@taskforcehq/taskforce 0.3.301 → 0.3.303
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Taskforce.module.css +37 -2
- package/dist/TaskforceCore.filter-persistence.test.js +1 -1
- package/dist/TaskforceCore.js +72 -33
- package/dist/TaskforceCore.test.js +848 -130
- package/dist/components/features/TaskSettings.js +14 -82
- package/dist/components/features/TaskSettings.test.js +33 -70
- package/dist/components/features/settings/TaxonomyLibraryManager.js +8 -2
- package/dist/components/features/settings/TaxonomyLibraryManager.test.js +1 -1
- package/dist/components/task/TaskActionHeader.js +6 -3
- package/dist/components/task/TaskCard.js +6 -3
- package/dist/components/task/TaskForm.js +2 -2
- package/dist/components/task/TaskForm.test.js +41 -2
- package/dist/components/task/TaskKanban.test.js +17 -0
- package/dist/components/ui/ReferenceBadgeButton.js +1 -1
- package/dist/components/views/PlansPage.d.ts +3 -1
- package/dist/components/views/PlansPage.js +109 -49
- package/dist/components/views/PlansPage.test.d.ts +1 -0
- package/dist/components/views/PlansPage.test.js +100 -0
- package/dist/components/views/StandaloneLayout.d.ts +1 -0
- package/dist/components/views/StandaloneLayout.js +473 -256
- package/dist/components/views/panels/PlanningDrawer.js +18 -1
- package/dist/components/views/standalone/modals/AccountHubModal.d.ts +48 -0
- package/dist/components/views/standalone/modals/AccountHubModal.js +36 -0
- package/dist/components/views/standalone/modals/AccountHubModal.test.d.ts +1 -0
- package/dist/components/views/standalone/modals/AccountHubModal.test.js +26 -0
- package/dist/components/views/standalone/modals/CreateWorkspaceConfirmModal.d.ts +9 -0
- package/dist/components/views/standalone/modals/CreateWorkspaceConfirmModal.js +8 -0
- package/dist/components/views/standalone/modals/EditProfileModal.d.ts +26 -0
- package/dist/components/views/standalone/modals/EditProfileModal.js +10 -0
- package/dist/components/views/standalone/modals/HelpModal.d.ts +9 -0
- package/dist/components/views/standalone/modals/HelpModal.js +8 -0
- package/dist/components/views/standalone/modals/ScheduleWarningModal.d.ts +13 -0
- package/dist/components/views/standalone/modals/ScheduleWarningModal.js +6 -0
- package/dist/components/views/standalone/modals/SyncStatusModal.d.ts +61 -0
- package/dist/components/views/standalone/modals/SyncStatusModal.js +38 -0
- package/dist/components/views/standalone/modals/TeamManagementModal.d.ts +64 -0
- package/dist/components/views/standalone/modals/TeamManagementModal.js +10 -0
- package/dist/components/views/standalone/modals/types.d.ts +2 -0
- package/dist/components/views/standalone/modals/types.js +1 -0
- package/dist/components/views/teamManagementAccess.d.ts +1 -1
- package/dist/components/views/teamManagementAccess.js +2 -2
- package/dist/components/views/teamManagementAccess.test.js +3 -3
- package/dist/config/deployment.js +2 -2
- package/dist/config/deployment.test.js +5 -3
- package/dist/core/AiProfileService.js +7 -2
- package/dist/core/AiProfiles.test.js +19 -0
- package/dist/core/EntitlementsPolicy.test.js +2 -2
- package/dist/core/GlobalSettingsService.js +78 -18
- package/dist/core/PlanEntitlementService.d.ts +29 -5
- package/dist/core/PlanEntitlementService.js +297 -219
- package/dist/core/SignupMonetizationSettings.test.js +173 -49
- package/dist/core/SyncReconciliationService.d.ts +2 -0
- package/dist/core/SyncReconciliationService.js +3 -0
- package/dist/core/SystemAdmin.test.js +186 -96
- package/dist/core/TaskAuditTimeline.test.js +40 -0
- package/dist/core/Taskforce.d.ts +100 -10
- package/dist/core/Taskforce.ids.test.js +133 -0
- package/dist/core/Taskforce.js +459 -127
- package/dist/core/Taskforce.mcpAuth.test.js +0 -2
- package/dist/core/UserProfileAvatarDrafts.test.d.ts +1 -0
- package/dist/core/UserProfileAvatarDrafts.test.js +111 -0
- package/dist/core/taskReferencePolicy.d.ts +28 -0
- package/dist/core/taskReferencePolicy.js +189 -0
- package/dist/core/types.d.ts +13 -12
- package/dist/hooks/tasks/useTaskFormActions.js +3 -0
- package/dist/hooks/useSyncOrchestrator.js +17 -3
- package/dist/hooks/useSyncOrchestrator.retry-closure.test.js +97 -5
- package/dist/hooks/useTaskData.js +3 -2
- package/dist/hooks/useTaskData.test.js +66 -0
- package/dist/hooks/useTaskforce.d.ts +8 -0
- package/dist/hooks/useTaskforce.js +72 -19
- package/dist/hooks/useTaskforce.sync-behavior.test.js +185 -6
- package/dist/mcp/aiProfileBootstrap.d.ts +29 -0
- package/dist/mcp/aiProfileBootstrap.js +80 -0
- package/dist/mcp/aiProfileBootstrap.test.d.ts +1 -0
- package/dist/mcp/aiProfileBootstrap.test.js +68 -0
- package/dist/mcp/clientIntegrations.d.ts +2 -8
- package/dist/mcp/clientIntegrations.js +21 -40
- package/dist/mcp/clientIntegrations.test.js +28 -2
- package/dist/mcp/clientProfileDefaults.d.ts +12 -0
- package/dist/mcp/clientProfileDefaults.js +37 -0
- package/dist/mcp/runtime.d.ts +10 -7
- package/dist/mcp/runtime.js +131 -48
- package/dist/mcp/runtime.test.js +321 -83
- package/dist/migrations/billingSchemaParity.test.js +3 -0
- package/dist/migrations/taskSchemaMigrations.js +68 -1
- package/dist/qaOpen.test.d.ts +1 -0
- package/dist/qaOpen.test.js +56 -0
- package/dist/server/index.cookieProxy.test.js +2 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +17 -1
- package/dist/server/index.test.js +15 -1
- package/dist/server/mockStripe.d.ts +1 -0
- package/dist/server/mockStripe.js +2 -0
- package/dist/server/routes/admin.js +105 -45
- package/dist/server/routes/auth.d.ts +6 -0
- package/dist/server/routes/auth.js +505 -30
- package/dist/server/routes/billing.js +517 -24
- package/dist/server/routes/billing.test.js +967 -45
- package/dist/server/routes/documents.js +6 -1
- package/dist/server/routes/shared.d.ts +1 -1
- package/dist/server/routes/shared.js +16 -6
- package/dist/server/routes/sync.integration.test.js +290 -0
- package/dist/server/routes/sync.js +234 -1922
- package/dist/server/routes/tasks.js +18 -4
- package/dist/server/routes.js +29 -22
- package/dist/server/routes.test.js +639 -82
- package/dist/shared/runtimeContract.d.ts +1 -1
- package/dist/sync/cloudSyncApi.d.ts +1 -0
- package/dist/sync/collaborationSyncPayload.d.ts +17 -0
- package/dist/sync/collaborationSyncPayload.js +131 -0
- package/dist/sync/collaborationSyncPayload.test.d.ts +1 -0
- package/dist/sync/collaborationSyncPayload.test.js +104 -0
- package/dist/sync/collaborationSyncState.d.ts +15 -0
- package/dist/sync/collaborationSyncState.js +60 -0
- package/dist/sync/contentSyncPayload.d.ts +45 -0
- package/dist/sync/contentSyncPayload.js +104 -0
- package/dist/sync/contentSyncPayload.test.d.ts +1 -0
- package/dist/sync/contentSyncPayload.test.js +104 -0
- package/dist/sync/contentSyncState.d.ts +98 -0
- package/dist/sync/contentSyncState.js +1004 -0
- package/dist/sync/planningSyncPayload.d.ts +9 -0
- package/dist/sync/planningSyncPayload.js +82 -0
- package/dist/sync/planningSyncPayload.test.d.ts +1 -0
- package/dist/sync/planningSyncPayload.test.js +68 -0
- package/dist/sync/syncApplyHandlers.d.ts +83 -0
- package/dist/sync/syncApplyHandlers.js +445 -0
- package/dist/sync/syncService.d.ts +1 -0
- package/dist/sync/syncService.js +21 -8
- package/dist/sync/taskSyncPayload.d.ts +33 -0
- package/dist/sync/taskSyncPayload.js +126 -0
- package/dist/sync/taskSyncPayload.test.d.ts +1 -0
- package/dist/sync/taskSyncPayload.test.js +54 -0
- package/dist/sync/workspacePullFeed.d.ts +38 -0
- package/dist/sync/workspacePullFeed.js +349 -0
- package/dist/sync/workspacePullFeed.test.d.ts +1 -0
- package/dist/sync/workspacePullFeed.test.js +278 -0
- package/dist/sync/workspaceSyncModel.d.ts +4 -1
- package/dist/sync/workspaceSyncModel.js +9 -2
- package/dist/sync/workspaceSyncModel.test.js +29 -0
- package/dist/test/setup.js +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/ui/assets/{AgentsModule-Bdq3T1Ts.js → AgentsModule-CpsTmrIW.js} +1 -1
- package/dist/ui/assets/{AnnotatedAttachmentWorkspace-jKUVo-PJ.js → AnnotatedAttachmentWorkspace-C_TmXZwA.js} +1 -1
- package/dist/ui/assets/{DocumentWorkspace-DuQa-uIC.js → DocumentWorkspace-C3GyzrWm.js} +2 -2
- package/dist/ui/assets/{InitiativesModule-C8Pi2VTk.js → InitiativesModule-4-Rh2K2n.js} +1 -1
- package/dist/ui/assets/PlansPage-BP7AYOqr.js +1 -0
- package/dist/ui/assets/TaskSettings-BOC5F6Ag.js +8 -0
- package/dist/ui/assets/{TaskSettings-BwB9NtmJ.css → TaskSettings-CnIBL_Eb.css} +1 -1
- package/dist/ui/assets/{WorkflowsModule-b6TLuHwJ.js → WorkflowsModule-CGk9s3NJ.js} +1 -1
- package/dist/ui/assets/index-CLIMgR6g.js +6 -0
- package/dist/ui/assets/index-DneETxcu.css +1 -0
- package/dist/ui/assets/{vendor-icons-QZyhEwgT.js → vendor-icons-pWocEipT.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/utils/accountProfileSummaryCache.d.ts +31 -0
- package/dist/utils/accountProfileSummaryCache.js +97 -0
- package/dist/utils/accountProfileSummaryCache.test.d.ts +1 -0
- package/dist/utils/accountProfileSummaryCache.test.js +63 -0
- package/dist/utils/taskActivity.js +17 -4
- package/dist/utils/taskActivity.test.js +27 -0
- package/dist/utils/taskNormalization.js +10 -2
- package/dist/utils/taskReferences.d.ts +11 -1
- package/dist/utils/taskReferences.js +33 -1
- package/package.json +4 -3
- package/scripts/qa-open-lib.mjs +175 -0
- package/scripts/qa-open-lib.mjs.d.ts +49 -0
- package/scripts/qa-open.mjs +352 -0
- package/dist/ui/assets/PlansPage-B6BDECSi.js +0 -1
- package/dist/ui/assets/TaskSettings-DUJgRTPU.js +0 -8
- package/dist/ui/assets/index-BiiF1cLQ.css +0 -1
- 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-BOC5F6Ag.js","assets/vendor-react-CKJs5o3c.js","assets/vendor-icons-pWocEipT.js","assets/vendor-markdown-BUxTU7dS.js","assets/vendor-dnd-DRzYolkg.js","assets/vendor-router-BbWMxlnO.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-C_TmXZwA.js","assets/AnnotatedAttachmentWorkspace-BaS2VwIr.css","assets/DocumentWorkspace-C3GyzrWm.js","assets/DocumentWorkspace-C_8T8oz-.css","assets/WorkflowsModule-CGk9s3NJ.js","assets/AgentsModule-CpsTmrIW.js","assets/InitiativesModule-4-Rh2K2n.js","assets/PlansPage-BP7AYOqr.js","assets/PlansPage-BlVC_lRq.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as a,j as t,R as pt,a as Ai,b as Yh}from"./vendor-react-CKJs5o3c.js";import{I as $s,C as Ii,a as Dc,b as ao,c as Ol,F as Jh,A as Xh,R as bp,T as Hl,L as _p,d as Ti,e as Qh,X as Di,f as rf,g as of,h as Wa,i as ji,j as ap,k as Pc,P as eg,D as pm,l as tg,B as eu,U as Eo,m as sr,n as ng,S as ag,G as sg,o as rg,p as cf,q as og,r as Cp,s as lf,t as ig,u as cg,v as Nc,w as df,x as lg,y as uf,z as dg,E as ug,H as pg,M as mm,J as fm,K as mg,N as fg,Z as hg,O as gg,Q as yg,V as kg,W as Sg,Y as vg,_ as wg,$ as bg,a0 as _g}from"./vendor-icons-pWocEipT.js";import{M as Cg,r as xg,a as Ag}from"./vendor-markdown-BUxTU7dS.js";import{u as pf,a as xp,b as Ig,D as mf,c as Tg,S as ff,v as hf,P as gf,d as yf,C as Mp,e as Ng,p as jg,f as hm,s as Rg,K as Dg,g as Kl,h as Pg,i as ku,j as Eg}from"./vendor-dnd-DRzYolkg.js";import{u as kf,a as Sf,b as Lg,M as Mg,N as gm,B as Bg}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 i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).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 jc="default",Su="General",Ss="task",Wg=2,Fg=[{value:jc,label:Su,icon:"Inbox"}],vf=[{value:Ss,label:"Task",icon:"CheckSquare",color:"blue-500"}],Og=[{value:Wg,label:"Medium",color:"blue-500",icon:"Minus"}];function $g(){return Fg.map(e=>({...e}))}function Ug(){return vf.map(e=>({...e}))}function zg(e){const n=String(e||"").trim().toLowerCase();return vf.find(s=>s.value===n)}function wf(){return Og.map(e=>({...e}))}const Hg="default",Gg=[{value:Hg,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 bf(){return Gg.map(e=>({...e}))}const Vg={categories:$g(),types:Ug(),priorities:wf(),approaches:bf(),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},Zg=["light","dawn","dark","midnight"],iu="dark",qg=[{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"}],Kg=new Set(Zg),Yg=new Set(qg.filter(e=>e.family==="light").map(e=>e.id));function Jg(e){return typeof e=="string"&&Kg.has(e)}function xc(e){if(typeof e!="string")return null;const n=e.trim().toLowerCase();return Jg(n)?n:null}function _f(e){const n=xc(e);return n!==null&&Yg.has(n)}function Ap(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 Ec(e,n){const s=Ap(typeof n=="object"&&n!==null?n.referenceNumber:n);return s?`${e}${s}`:""}function Bp(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?Ap(l[1]):null}function Yl(e,n){return n?typeof n.referenceLabel=="string"&&n.referenceLabel.trim().length>0?n.referenceLabel.trim():Ec(e,n.referenceNumber):""}const Wp="T-",ym="LT-";function Xg(e){return Ec(Wp,e)}function Cf(e){return typeof e=="number"||e===null||e===void 0?Ec(ym,e):Ec(ym,{referenceNumber:e.localReferenceNumber??null})}function xf(e){return Bp(Wp,e)}function Ar(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const n=Yl(Wp,e);return n||Cf(e.localReferenceNumber)}function Qg(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function Af(e){return{label:Ar(e),isProvisional:Qg(e)}}wf();const ey={low:1,medium:2,high:3,critical:4,"on-hold":1},ty={1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function ny(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 cu(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)):ey[String(e||"").trim().toLowerCase()]??2}function ay(e,n){return ty[String(e)]||n}function so(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?Xg(n):Cf(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:cu(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:ny(e.status)}}function sy(e,n,s){if(!e||typeof e!="object")return{tasks:n,archivedTasks:s};const r=so(e),o=String(r.id||"").trim();if(!o)return{tasks:n,archivedTasks:s};const l=!!r.isArchived,i=l?{...r,isArchived:!0}:{...r,isArchived:!1},p=b=>[...b].sort((_,k)=>{const g=Date.parse(String(_.updatedAt||_.createdAt||"")),C=Date.parse(String(k.updatedAt||k.createdAt||""));if(Number.isFinite(g)&&Number.isFinite(C)&&g!==C)return C-g;if(Number.isFinite(g)!==Number.isFinite(C))return Number.isFinite(C)?1:-1;const M=Date.parse(String(k.createdAt||""))-Date.parse(String(_.createdAt||""));return Number.isFinite(M)&&M!==0?M:String(_.id).localeCompare(String(k.id))}),h=n.filter(b=>b.id!==o),w=s.filter(b=>b.id!==o);return l?w.push(i):h.push(i),{tasks:p(h),archivedTasks:p(w)}}function ry(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 sp(e,n){return n.some(s=>String(s)===String(e))}function oy(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 iy={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"}},cy={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"}},ly={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"}},If=["en-US","es-419","pt-BR"],lu="en-US",rp={"en-US":iy,"es-419":cy,"pt-BR":ly},Tf={en:"en-US",es:"es-419",pt:"pt-BR"};let Ni=lu;function dy(e){return e.split(".").filter(Boolean)}function op(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 Nf(e){if(!e)return lu;const n=If.find(r=>r.toLowerCase()===e.toLowerCase());if(n)return n;const s=e.split("-")[0]?.toLowerCase()||"";return Tf[s]||lu}function ip(e,n){return n?e.replace(/\{([^}]+)\}/g,(s,r)=>{const o=n[r];return o==null?"":String(o)}):e}function jf(){return Ni}function uy(){return[...If]}function Rf(e){const n=Nf(e);return Ni=n,n}function py(e){const n=typeof navigator<"u"?navigator.language:null;return Ni=Nf(n),Ni}function Te(e,n){const s=dy(e),r=op(rp[Ni],s);if(r)return ip(r,n);const o=Ni.split("-")[0]?.toLowerCase()||"",l=Tf[o];if(l&&l!==Ni){const p=op(rp[l],s);if(p)return ip(p,n)}const i=op(rp[lu],s);return i?ip(i,n):e}const my="default",Lo="bootstrap";function fy(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 Fp(e){const n=String(e||"").trim().toLowerCase();return n?`${(n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${fy(n)}`:Lo}function Df(e){const n=String(e||"").trim().toLowerCase();if(!n)return Lo;const s=n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return s?s.slice(0,96):Lo}function Pf(e){const n=String(e||"").trim();return n?Fp(n):Lo}function hy(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?Lo:Pf(e.projectRoot)}function gy(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const s=String(e.workspaceId||"").trim();return s&&!Op(s)?Fp(`cloud-workspace:${s}`):Lo}return Pf(e.projectRoot)}function Op(e){return String(e||"").trim().toLowerCase()===my}const yy={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function ky(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function Sy(e){return yy[ky(e)]}function km(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 vy(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 wy(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=>({...zg(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:km(r.aliases),options:Array.isArray(r.options)?r.options.map(o=>({...o,aliases:km(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 Gl={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 vu(e){const n=String(e||"").trim().toLowerCase();return n==="production"||n==="staging"||n==="performance"?n:null}function by(e){return vu(e)||"production"}function Sm(e){return Gl[by(String(e||""))]}function _y(e){const n=String(e||"").trim().toLowerCase();if(!n)return null;for(const[s,r]of Object.entries(Gl))if(new URL(r.appBaseUrl).hostname.toLowerCase()===n||new URL(r.mcpBaseUrl).hostname.toLowerCase()===n)return s;return null}function $p(e){const n=String(e||"").trim();if(!n)return null;try{return _y(new URL(n).hostname)}catch{return null}}function Cy(e){const n=$p(e);return n?Gl[n].mcpBaseUrl:null}function Si(e,n){return String(e[n]||"").trim()}function vm(e,n,s){e.push(n),s?.(n)}function xy(e,n){const s=[],r=Si(e,"ENV"),o=vu(r);if(o)return vm(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:Si(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:Si(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:Si(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:Si(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:Si(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:Si(e,"TASKFORCE_BASE_URL")}];for(const i of l){if(!i.value)continue;const p=$p(i.value);if(p)return vm(s,`[Taskforce compat] ${i.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 Cr(e,n){return String(e[n]||"").trim()}function Ay(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function bc(e){return String(e||"").trim().replace(/\/+$/,"")}function Iy(e){return String(e||"").trim().replace(/\/+$/,"")}function Xr(...e){for(const n of e)if(String(n||"").trim())return String(n||"").trim();return""}function Ty(e,n={}){const s=[],r=j=>{s.push(j),n.onWarning?.(j)},o=Ay(Cr(e,"TASKFORCE_RUNTIME_MODE")),l=vu(Cr(e,"TASKFORCE_CLOUD_ENVIRONMENT")),i=l?{cloudEnvironment:l}:xy(e,r),p=l||i.cloudEnvironment,h=bc(String(n.requestBaseUrl||"")),w=bc(Xr(Cr(e,"VITE_TASKFORCE_BASE_URL"),Cr(e,"TASKFORCE_BASE_URL"))),b=bc(Cr(e,"VITE_TASKFORCE_API_BASE_URL")),_=bc(Cr(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),k=bc(Xr(Cr(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),Cr(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),g=bc(Cr(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),C=Iy(Cr(e,"VITE_TASKFORCE_WS_BASE_URL")),M=p?Gl[p].appBaseUrl:"",S=p?Gl[p].mcpBaseUrl:"",P=Xr(g,_,b,w,M),Z=Xr(k,S,P),$=Xr(h,w,b,_,P),ce=Xr(h,b,w,P),q=Xr(_,w,b,P),K=o==="local"?Xr(C,h,b,w,g,_,M,P):Xr(h,C,ce,$,P);return{runtimeMode:o,cloudEnvironment:p,cloudBaseUrl:P,cloudMcpBaseUrl:Z,baseUrl:$,apiBaseUrl:ce,cloudAuthBaseUrl:q,wsBaseUrl:K,cloudAuthViaLocalProxy:o==="local"||!!g,warnings:s}}function Up(e){return Ty({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 du="unassigned",Ef="agent",Ny="user",jy=/^[0-9a-f]{8,}$/i;function Lf(e){const n=String(e||"").trim().toLowerCase();return n===Ef||n==="ai"||n.startsWith("ai-profile-")}function Mf(e){const n=String(e||"").trim().toLowerCase();return!n||n===du||n==="none"||n==="null"||n===Ny}function uu(e){return Lf(e)?"agent":Mf(e)?"unassigned":"member"}function Ry(e){const n=String(e.displayName||"").trim(),s=String(e.email||"").trim().toLowerCase();return n||s||String(e.userId||"").trim()||"Workspace member"}function _i(){return[{value:du,label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)",kind:"unassigned"}]}function Dy(e){const n=new Map;for(const s of e){const r=String(s.userId||"").trim();r&&n.set(r,{value:r,label:Ry(s),icon:"User",color:"#22c55e",kind:"member"})}return Vl(Array.from(n.values()))}function Vl(e){const n=new Map;for(const r of _i())n.set(r.value,r);for(const r of Array.isArray(e)?e:[]){const o=String(r?.value||"").trim();!o||o===du||o===Ef||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=[du];return Array.from(n.values()).sort((r,o)=>{const l=s.indexOf(r.value),i=s.indexOf(o.value);return l>=0||i>=0?l<0?1:i<0?-1:l-i:r.label.localeCompare(o.label,void 0,{sensitivity:"base"})})}function Py(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(uu(s)==="agent"){const l=String(s).toLowerCase().startsWith("ai-profile-")&&r.split(" ").every(i=>jy.test(i));return Vl([...e,{value:s,label:l?"AI":o||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return uu(s)==="member"?Vl([...e,{value:s,label:o||s,icon:"User",color:"#22c55e",kind:"member"}]):e}function Bf(e){const n=Array.isArray(e)?e.filter(Boolean):[];return Vl(n)}function _c(e,n){const s=String(e||"").trim(),o=Bf(n).find(l=>l.value===s);return o?o.label:Lf(s)?"AI":Mf(s)?"Unassigned":s||"Unassigned"}const Wf="taskforce.workspaceContext.v2",Ey="taskforce.uiState.app.v1",Ly="taskforce.bootstrapDebug.v1";function My(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(Ly)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Hn(e,n){if(!My())return;console.info("[Taskforce Bootstrap]",e,n&&typeof n=="object"?n:{})}function Ff(e){const n=Fp(e);return`${Wf}.${n}`}function By(e){const n=Df(e);return`${Wf}.${n}`}function Vd(e){if(typeof window>"u")return"";try{const n=Ff(e),s=String(window.localStorage.getItem(n)||"").trim();if(s&&s.length<=120&&!/\s/.test(s))return s;const r=By(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 Wy(e,n){if(typeof window>"u")return;const s=String(e||"").trim();try{if(!s||Op(s))return;const r=Ff(n),o=String(window.localStorage.getItem(r)||"").trim();if(!s&&o&&o.toLowerCase()!=="default")return;window.localStorage.setItem(r,s)}catch{}}function Of(e){const n=Df(e);return`${Ey}.${n}`}function wm(e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Of(e));if(!n)return null;const s=JSON.parse(n);return s&&typeof s=="object"?s:null}catch{return null}}function Fy(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Of(n),JSON.stringify(e))}catch{}}const Ip="taskforce.localMutationActorUserId.v1";function $f(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function Oy(e){const n=String(e||"").trim().toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"}function Dl(e){if(!(typeof window>"u"))try{const n=String(e||"").trim();if(!n||n==="anonymous"){window.sessionStorage.removeItem(Ip);return}window.sessionStorage.setItem(Ip,n)}catch{}}function Uf(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Ip)||"").trim()}catch{return""}}function $y(e,n){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!Oy(window.location.hostname))return!1;try{return new URL(n,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function Uy(e,n,s){if(!$y(e,n))return s;const r=Uf();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 zy(e,n){if(!e.startsWith("/"))return e;const s=$f(n);return s?`${s}${e}`:e}async function cp(e,n,s){const r=zy(e,s),o=$f(s).length>0,l=Uy(e,r,n),i=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;Hn("taskforce_api_auth_fallback_retry",{path:e,primaryUrl:r,fallbackUrl:e,status:p.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)});try{const w=await fetch(e,l);return Hn("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())-i)}),w}catch{return Hn("taskforce_api_auth_fallback_failed",{path:e,primaryUrl:r,fallbackUrl:e,status:p.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),p}}catch(p){if(!o||!e.startsWith("/"))throw p;Hn("taskforce_api_network_fallback_retry",{path:e,primaryUrl:r,fallbackUrl:e,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i),error:p instanceof Error?p.message:String(p)});const h=await fetch(e,l);return Hn("taskforce_api_network_fallback_completed",{path:e,primaryUrl:r,fallbackUrl:e,fallbackStatus:h.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),h}}function Hy(e){const n=Number(e?.status);return Number.isFinite(n)&&n>0?Math.floor(n):0}async function Mc(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 i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>0)l=i*1e3;else{const p=Date.parse(o);if(Number.isFinite(p)){const h=p-Date.now();h>0&&(l=h)}}}return{ok:n.ok,status:n.status,data:r,retryAfterMs:l}}catch(n){return{ok:!1,status:Hy(n),data:{}}}}async function Gy(e){return Mc(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function Vy(e,n){return Mc(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function bm(e,n){return Mc(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n})}))}async function Zy(e,n){return Mc(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function qy(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 Mc(fetch(`${r}${o}${s.toString()}`,{method:"GET",credentials:"include"}))}async function Ky(e,n){return Mc(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 _m(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 i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:r});if(i.ok){const w=await i.json().catch(()=>({}));return{ok:!0,status:i.status,data:w,failures:l}}const p=await i.text().catch(()=>"");let h={};if(p)try{h=JSON.parse(p)}catch{h={error:p.slice(0,400)}}else i.statusText&&(h={error:`${i.status} ${i.statusText}`});return l.push(`${o}:${i.status}`),{ok:!1,status:i.status,data:h,failures:l}}catch{l.push(`${o}:network`)}return{ok:!1,status:0,data:{},failures:l}}const Tp="V1:AESGCM:",zp="AES-GCM",Yy=12;async function zf(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:zp},!1,["encrypt","decrypt"])}async function Cm(e,n){if(!e)return e;const s=crypto.getRandomValues(new Uint8Array(Yy)),r=await zf(n),l=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:zp,iv:s},r,l),p=Buffer.from(i).toString("base64"),h=Buffer.from(s).toString("base64");return`${Tp}${h}:${p}`}async function xm(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"),i=Buffer.from(o,"base64"),p=await zf(n);try{const h=await crypto.subtle.decrypt({name:zp,iv:l},p,i);return new TextDecoder("utf-8").decode(h)}catch(h){throw new Error(`Failed to decrypt document: ${h.message}`)}}var Ac={};function Ir(e){return e&&typeof e=="object"?e:{}}function no(e){const n=Number(e||0);return n===0||n===429||n>=500}function Jy(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 Xy(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 bm(e.resolveCloudAuthUrl,e.workspaceId);if(n.ok)return{success:!0,provisioned:!1};const s=Ir(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 Zy(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!r.ok){const o=Ir(r.data);return{success:!1,statusCode:r.status,error:Jy(o,r.status)}}if(n=await bm(e.resolveCloudAuthUrl,e.workspaceId),!n.ok){const o=Ir(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:no(n.status),error:String(o.error||`Workspace sync handshake failed (${n.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:n.status,transient:no(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 Qy(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 ek(e){const n=e.payload.changes.length,s=e.payload.deleteTaskIds.size,r=await Qy(e.workspaceId,e.payload.changes);let o=0,l=e.payload.changes;if(typeof process<"u"&&Ac?.TASKFORCE_SYNC_KEY){const b=Ac.TASKFORCE_SYNC_KEY,_=[];for(const k of l)k.op==="document-upsert"&&typeof k.content=="string"?_.push({...k,content:await Cm(k.content,b)}):k.op==="asset-upsert"&&typeof k.contentBase64=="string"&&k.contentBase64.length>0?_.push({...k,contentBase64:await Cm(k.contentBase64,b)}):_.push(k);l=_}const i=async()=>{const b=Date.now(),_=await Ky(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,idempotencyKey:r,changes:l,repairMode:e.repairMode===!0});return o+=Date.now()-b,_};let p=await i();if(!p.ok&&(p.status===403||p.status===409)&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(p=await i()),!p.ok){const b=Ir(p.data);return{success:!1,status:p.status,error:typeof b.error=="string"?b.error:void 0,code:typeof b.code=="string"?b.code:void 0,retryAfterMs:p.retryAfterMs,transient:no(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 h=Ir(p.data),w=Array.isArray(h.emittedEventIds)?Array.from(new Set(h.emittedEventIds.map(b=>String(b||"").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 tk(e){let n=e.cursor,s=!0,r=0,o=0,l=0,i=0;const p=new Set;let h=!1,w=!1;const b=new Set,_=new Set,k=new Set;let g=null;const C=Number.isFinite(Number(e.maxPages))?Math.max(1,Math.floor(Number(e.maxPages))):20;try{for(;s&&r<C;){const M=async()=>{const K=Date.now(),j=await qy(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:n,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0});return l+=Date.now()-K,j};let S=await M();if(!S.ok&&S.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(S=await M()),!S.ok)return{success:!1,kind:"pull_http",status:S.status,retryAfterMs:S.retryAfterMs,transient:no(S.status),cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),serverDiagnostics:null};const P=S.data||{},Z=Array.isArray(P?.changes)?P.changes:[],$=P?.diagnostics&&typeof P.diagnostics=="object"?P.diagnostics:null;g=$;const ce=Array.isArray(P?.workspaceMembers),q=ce?P.workspaceMembers:void 0;for(const K of Z){if(K.op==="upsert"){K?.archived===!0||K?.task?.isArchived===!0?w=!0:h=!0;continue}if(K.op==="annotated-attachment-session-upsert"){const ye=String(K?.session?.id||"").trim();ye&&k.add(ye);continue}if(K.op==="document-upsert"){if(typeof K.content=="string"&&typeof process<"u"&&Ac?.TASKFORCE_SYNC_KEY)try{K.content=await xm(K.content,Ac.TASKFORCE_SYNC_KEY)}catch{const ye=String(K.path||"").trim();ye&&b.add(ye)}continue}if(K.op==="asset-upsert"){if(typeof K.contentBase64=="string"&&typeof process<"u"&&Ac?.TASKFORCE_SYNC_KEY)try{K.contentBase64=await xm(K.contentBase64,Ac.TASKFORCE_SYNC_KEY)}catch{const ye=String(K.path||"").trim();ye&&b.add(ye)}continue}if(K.op!=="delete")continue;const j=String(K.taskId||"").trim();j&&p.add(j)}if(e.onPagePulled&&e.onPagePulled(),Z.length>0||ce){const K=Date.now(),j=await _m(e.workspaceId,Z,{...ce?{workspaceMembers:q}:{},repairMode:e.repairMode===!0}),ye=j.failures;if(!j.ok){i+=Date.now()-K;const X=Ir(j.data);if(ye.some(te=>te.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:ye,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),serverDiagnostics:$};const pe=ye.some(te=>{if(te.endsWith(":network"))return!0;const D=te.split(":").pop()||"",B=Number.parseInt(D,10);return Number.isFinite(B)&&(B===429||B>=500)});return{success:!1,kind:"apply_all_candidates",status:j.status||void 0,transient:pe,error:String(X.error||"").trim()||void 0,failures:ye,hasTransientApplyFailure:pe,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(_),serverDiagnostics:g}}const U=Ir(j.data);if(U.success===!1)return i+=Date.now()-K,{success:!1,kind:"apply_payload",transient:!1,error:String(U.error||"Workspace sync apply failed."),cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(_),serverDiagnostics:g};if(i+=Date.now()-K,o+=Z.length,Array.isArray(U.emittedEventIds))for(const X of U.emittedEventIds)_.add(String(X));e.onChangesApplied&&e.onChangesApplied(Z.length)}P&&"nextCursor"in P&&(P.nextCursor===null||typeof P.nextCursor=="string")&&(n=P.nextCursor),s=!!P?.hasMore,r+=1}if(e.bootstrap){const M=Date.now(),S=await _m(e.workspaceId,[],{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(k)}}),P=S.failures;if(!S.ok){i+=Date.now()-M;const Z=Ir(S.data);if(P.some(q=>q.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:P,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(_),serverDiagnostics:g};const ce=P.some(q=>{if(q.endsWith(":network"))return!0;const K=q.split(":").pop()||"",j=Number.parseInt(K,10);return Number.isFinite(j)&&(j===429||j>=500)});return{success:!1,kind:"apply_all_candidates",status:S.status||void 0,transient:ce,error:String(Z.error||"").trim()||void 0,failures:P,hasTransientApplyFailure:ce,cursor:n,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(_),serverDiagnostics:g}}i+=Date.now()-M}return{success:!0,syncedAt:new Date().toISOString(),cursor:n||null,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(_),serverDiagnostics:g}}catch(M){return{success:!1,kind:"exception",status:0,transient:!0,error:String(M?.message||M||"Workspace sync pull failed unexpectedly."),cursor:n||null,pages:r,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:p,pulledActiveUpserts:h,pulledArchivedUpserts:w,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(_),serverDiagnostics:null}}}async function nk(e){const n=await Gy(e.resolveCloudAuthUrl);if(!n.ok){const k=Number(n.status||0);return{success:!1,error:`Sync pull failed (${n.status})`,statusCode:n.status,retryAfterMs:n.retryAfterMs,transient:no(k)}}const s=Ir(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),i=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(i)||p>i))return await e.applyRemoteSettings(r),{success:!0,mode:"pulled",updatedAt:o};const h=l||new Date().toISOString(),w=await Vy(e.resolveCloudAuthUrl,{settings:e.buildLocalSettings(),updatedAt:h});if(!w.ok){const k=Number(w.status||0);return{success:!1,error:`Sync push failed (${w.status})`,statusCode:w.status,retryAfterMs:w.retryAfterMs,transient:no(k)}}const b=Ir(w.data);return{success:!0,mode:"pushed",updatedAt:typeof b.updatedAt=="string"&&b.updatedAt.trim().length>0?b.updatedAt.trim():h}}function ak(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 sk=["chat_app","ide","coding_tool","agent","other"],bL=["chat_app","ide","coding_tool","agent","other","unclassified"],rk={chat_app:"Chat app",ide:"IDE",coding_tool:"Coding tool",agent:"Agent",other:"Other"},ok={chat_app:"Chat Apps",ide:"IDEs",coding_tool:"Coding Tools",agent:"Agents",other:"Other",unclassified:"Unclassified"};function ik(e){return typeof e=="string"&&sk.includes(e)}function Hf(e){if(typeof e!="string")return null;const n=e.trim();return ik(n)?n:null}function _L(e){return rk[e]}function CL(e){return e??"unclassified"}function xL(e){return ok[e]}function Zd(e){if(e==null)return;const n=String(e).trim();return n.length>0?n:void 0}function qd(e){if(e===void 0)return;if(e===null)return null;const n=String(e).trim();return n.length>0?n:null}function ck(e){return typeof e=="boolean"?e:void 0}function Kd(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 lk(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(i=>String(i??"")),r):(l==null||(r[o]=String(l)),r),{});return Object.keys(s).length>0?s:{}}function dk(e){return Array.isArray(e)?e:void 0}function uk(e){return Array.isArray(e)?e:void 0}function pk(e){return Array.isArray(e)?e:void 0}function mk(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:Kd(n.priority,{min:1})??void 0,complexity:Kd(n.complexity,{min:1,nullable:!0}),type:String(n.type||"").trim(),category:String(n.category||"").trim(),approach:Zd(n.approach),canceledReason:n.canceledReason===void 0?void 0:n.canceledReason||null,createdAt:String(n.createdAt||"").trim(),updatedAt:Zd(n.updatedAt),completedAt:n.completedAt===void 0?void 0:n.completedAt||null,isArchived:ck(n.isArchived),taxonomies:lk(n.taxonomies),createdBy:Zd(n.createdBy),assignee:Zd(n.assignee),scheduledDate:qd(n.scheduledDate),dueDate:qd(n.dueDate),scheduledWeekKey:qd(n.scheduledWeekKey),orderInDay:Kd(n.orderInDay,{min:0,nullable:!0}),workstreamId:qd(n.workstreamId),referenceNumber:Kd(n.referenceNumber,{min:1,nullable:!0}),comments:dk(n.comments),attachments:uk(n.attachments),checklistItems:pk(n.checklistItems)}}function Am(e){return mk(e)}function Im(e){return[...e].sort((n,s)=>{const r=String(n?.id||"").trim(),o=String(s?.id||"").trim();return r.localeCompare(o)})}function fk(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 et=String(d?.id||"").trim();if(!et)return!1;const gt=String(d?.updatedAt||d?.createdAt||"").trim();return r.get(et)!==gt},l=Im(e.tasks||[]),i=Im(e.archivedTasks||[]),p=new Map,h=l.filter(d=>!s.has(String(d?.id||"").trim())&&o(d)).map(d=>{const et=String(d?.id||"").trim(),gt=String(d?.updatedAt||d?.createdAt||"").trim();return et&&p.set(et,gt),{op:"upsert",archived:!1,task:Am(d)}}),w=i.filter(d=>!s.has(String(d?.id||"").trim())&&o(d)).map(d=>{const et=String(d?.id||"").trim(),gt=String(d?.updatedAt||d?.createdAt||"").trim();return et&&p.set(et,gt),{op:"upsert",archived:!0,task:Am(d)}}),b=new Set;for(const d of e.tasks||[]){const et=String(d?.id||"").trim();et&&b.add(et)}for(const d of e.archivedTasks||[]){const et=String(d?.id||"").trim();et&&b.add(et)}const _=Array.from(e.lastPushedTaskIds).filter(d=>!b.has(d)).map(d=>({op:"delete",taskId:d})),k=Array.from(s).map(d=>({op:"delete",taskId:d})),g=new Set([..._.map(d=>String(d.taskId)),...k.map(d=>String(d.taskId))]),C=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),M=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,P=!S||S.size===0,Z=(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=>P?!0:S.get(d.initiative.id)!==d.initiative.updatedAt),$=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),ce=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)),q=e.lastPushedWorkstreamWatermarks,K=!q||q.size===0,j=(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=>K?!0:q.get(d.workstream.id)!==d.workstream.updatedAt),ye=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)),X=e.lastPushedAiProfileWatermarks,Ne=!X||X.size===0,pe=(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:Hf(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=>Ne?!0:X.get(d.profile.id)!==d.profile.updatedAt),te=new Set((Array.isArray(e.documents)?e.documents:[]).map(d=>String(d?.path||"").trim()).filter(d=>d.length>0)),D=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!te.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)),oe=e.lastPushedDocumentWatermarks,xe=!oe||oe.size===0,ie=(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=>xe?!0:oe.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)),Ze=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!ae.has(d))),Le=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,Oe=!Ce||Ce.size===0,R=(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=>Oe?!0:Ce.get(d.path)!==d.updatedAt),W=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],F=new Set(W.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),V=new Set([...Array.from(e.lastPushedDocumentReviewSessionIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!F.has(d)),...W.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),E=new Map(W.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),y=e.lastPushedDocumentReviewSessionWatermarks,x=!y||y.size===0,H=W.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=>x?!0:y.get(d.session.id)!==d.session.updatedAt),I=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],Ie=new Set(I.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),L=new Set([...Array.from(e.lastPushedDocumentReviewCommentIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!Ie.has(d)),...I.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),le=new Map(I.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),ne=e.lastPushedDocumentReviewCommentWatermarks,de=!ne||ne.size===0,G=I.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=>de?!0:ne.get(d.comment.id)!==d.comment.updatedAt),ee=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],be=new Set(ee.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),$e=new Set([...Array.from(e.lastPushedAnnotatedAttachmentSessionIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!be.has(d)),...ee.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),fe=new Map(ee.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),De=e.lastPushedAnnotatedAttachmentSessionWatermarks,Ke=!De||De.size===0,nt=ee.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=>Ke?!0:De.get(d.session.id)!==d.session.updatedAt);return{changes:[...Z,...j,...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}]:[],...pe,...ie,...Array.from(D).map(d=>({op:"document-delete",path:d,deletedAt:n})),...R,...Array.from(Ze).map(d=>({op:"asset-delete",path:d,deletedAt:n})),...H,...Array.from(V).map(d=>({op:"document-review-session-delete",sessionId:d,deletedAt:n})),...G,...Array.from(L).map(d=>({op:"document-review-comment-delete",commentId:d,deletedAt:n})),...nt,...Array.from($e).map(d=>({op:"annotated-attachment-session-delete",sessionId:d,deletedAt:n})),...h,...w,...Array.from(g).map(d=>({op:"delete",taskId:d}))],currentTaskIds:new Set(Array.from(b).filter(d=>!s.has(d))),deleteTaskIds:g,currentInitiativeIds:C,currentInitiativeWatermarks:M,currentWorkstreamIds:$,currentWorkstreamWatermarks:ce,currentAiProfileIds:ye,currentAiProfileWatermarks:U,currentDocumentPaths:te,deleteDocumentPaths:D,currentDocumentWatermarks:B,currentAssetPaths:ae,deleteAssetPaths:Ze,currentAssetWatermarks:Le,currentDocumentReviewSessionIds:F,deleteDocumentReviewSessionIds:V,currentDocumentReviewSessionWatermarks:E,currentDocumentReviewCommentIds:Ie,deleteDocumentReviewCommentIds:L,currentDocumentReviewCommentWatermarks:le,currentAnnotatedAttachmentSessionIds:be,deleteAnnotatedAttachmentSessionIds:$e,currentAnnotatedAttachmentSessionWatermarks:fe,pushedWatermarks:p}}function hk(e){const n=(e.tasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),s=(e.archivedTasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),r=e.pendingDeletedTaskIds?Array.from(e.pendingDeletedTaskIds).sort():[],o=(e.initiatives||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,p)=>i.id.localeCompare(p.id)),l=(e.workstreams||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),initiativeId:typeof i.initiativeId=="string"?i.initiativeId.trim():"",title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,p)=>i.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(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),name:String(i.name||"").trim(),username:String(i.username||"").trim()})).filter(i=>i.id.length>0).sort((i,p)=>i.id.localeCompare(p.id)):[],documents:Array.isArray(e.documents)?e.documents.map(i=>({path:String(i.path||"").trim(),updatedAt:String(i.updatedAt||"").trim(),length:typeof i.content=="string"?i.content.length:0})).filter(i=>i.path.length>0).sort((i,p)=>i.path.localeCompare(p.path)):[],assets:Array.isArray(e.assets)?e.assets.map(i=>({path:String(i.path||"").trim(),updatedAt:String(i.updatedAt||"").trim(),length:typeof i.contentBase64=="string"?i.contentBase64.length:0,kind:i.kind==="image"?"image":"file"})).filter(i=>i.path.length>0).sort((i,p)=>i.path.localeCompare(p.path)):[],documentReviewSessions:Array.isArray(e.documentReviewSessions)?e.documentReviewSessions.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),assetId:String(i.assetId||"").trim(),status:i.status==="resolved"?"resolved":"open",deletedAt:String(i.deletedAt||"").trim(),commentCount:Array.isArray(i.comments)?i.comments.length:0})).filter(i=>i.id.length>0).sort((i,p)=>i.id.localeCompare(p.id)):[],documentReviewComments:Array.isArray(e.documentReviewComments)?e.documentReviewComments.map(i=>({id:String(i.id||"").trim(),sessionId:String(i.sessionId||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),deletedAt:String(i.deletedAt||"").trim(),bodyLength:String(i.body||"").length})).filter(i=>i.id.length>0).sort((i,p)=>i.id.localeCompare(p.id)):[],annotatedAttachmentSessions:Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),taskId:String(i.taskId||"").trim(),baseImageAssetId:String(i.baseImageAssetId||"").trim(),deletedAt:String(i.deletedAt||"").trim(),annotationCount:Array.isArray(i.annotations)?i.annotations.length:0})).filter(i=>i.id.length>0).sort((i,p)=>i.id.localeCompare(p.id)):[],active:n,archived:s,pendingDeletes:r})}function tu(){return{version:2,enabled:!1,phase:"idle",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null}}function Do(e){const n=String(e||"").trim();return n.length>0?n:null}function gk(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 yk(e){const n=tu();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:Do(s.pullCursor),lastPullAt:Do(s.lastPullAt),lastPushAt:Do(s.lastPushAt),lastSyncedAt:Do(s.lastSyncedAt),lastErrorMessage:o};l.phase=gk(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||Do(s.pullCursor)!==l.pullCursor||Do(s.lastPullAt)!==l.lastPullAt||Do(s.lastPushAt)!==l.lastPushAt||Do(s.lastSyncedAt)!==l.lastSyncedAt||o!==l.lastErrorMessage;return{state:l,changed:p}}const kk="taskforce.sync.lease.v1",Sk="taskforce.sync.lease.v1",vk=2500,wk=9e3;function Pl(e){const n=String(e||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function Yd(e){const n=String(e||"").trim();return n.length>0?n:null}function lp(e){return`${kk}.${e}`}function bk(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(),i=String(n?.expiresAt||"").trim();return!s||!r||!l||!i||o!=="pull"&&o!=="push"&&o!=="repair"?null:{ownerId:s,workspaceId:r,operation:o,heartbeatAt:l,expiresAt:i}}catch{return null}}function _k(e,n,s,r){return{ownerId:e,workspaceId:n,operation:s,heartbeatAt:new Date(r).toISOString(),expiresAt:new Date(r+wk).toISOString()}}function Ck(e,n=Date.now()){if(!e)return!0;const s=Date.parse(e.expiresAt);return!Number.isFinite(s)||s<=n}function Tm(e,n){const s={...e,...n,version:2,phase:n.phase||e.phase,pullCursor:n.pullCursor===void 0?e.pullCursor:Yd(n.pullCursor),lastPullAt:n.lastPullAt===void 0?e.lastPullAt:Yd(n.lastPullAt),lastPushAt:n.lastPushAt===void 0?e.lastPushAt:Yd(n.lastPushAt),lastSyncedAt:n.lastSyncedAt===void 0?e.lastSyncedAt:Yd(n.lastSyncedAt),lastErrorMessage:n.lastErrorMessage===void 0?e.lastErrorMessage:n.lastErrorMessage??null};return s.enabled||(s.phase="idle",s.pullCursor=null),s}function xk(e){const{currentWorkspaceId:n,setWorkspaceCloudSyncEnabled:s,setWorkspaceSyncPhase:r,setWorkspaceLastPullAt:o,setWorkspaceLastPushAt:l,setWorkspaceLastErrorMessage:i}=e,[p,h]=a.useState(null),w=a.useRef(null),b=a.useRef(null),_=a.useRef(0),k=a.useRef(!1),g=a.useRef(!1),C=a.useRef(""),M=a.useRef(""),S=a.useRef(new Set),P=a.useRef(new Set),Z=a.useRef(null),$=a.useRef(tu()),ce=a.useRef(""),q=a.useRef(null),K=a.useRef(null),j=a.useRef(null),ye=a.useRef(null);if(!ce.current){const R=Date.now().toString(36),W=Math.random().toString(36).slice(2,10);ce.current=`sync-lease-${R}-${W}`}const U=a.useCallback(()=>{_.current=0,b.current=null,w.current!==null&&typeof window<"u"&&(window.clearTimeout(w.current),w.current=null),h(null)},[]),X=a.useCallback((R,W)=>{if(typeof window>"u")return;const F=Math.max(1,_.current+1);_.current=F;const V=ak(F),E=Number(W?.minDelayMs),y=Number.isFinite(E)&&E>0?Math.max(V,Math.floor(E)):V,x=Date.now()+y;b.current=x,h(new Date(x).toISOString()),w.current!==null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{w.current=null,b.current=null,h(null),R()},y)},[]),Ne=a.useCallback(()=>{const R=b.current;return typeof R=="number"&&Number.isFinite(R)&&R>Date.now()},[]),pe=a.useCallback(R=>{if(typeof window>"u")return null;const W=String(R||"").trim();return Pl(W)?bk(window.localStorage.getItem(lp(W))):null},[]),te=a.useCallback(R=>{const W=String(R||"").trim();if(W)try{ye.current?.postMessage({workspaceId:W})}catch{}},[]),D=a.useCallback((R,W)=>{if(typeof window>"u")return null;const F=String(R||"").trim();if(!Pl(F))return null;const V=_k(ce.current,F,W,Date.now());try{window.localStorage.setItem(lp(F),JSON.stringify(V))}catch{return null}return te(F),V},[te]),B=a.useCallback(()=>{j.current!==null&&typeof window<"u"&&(window.clearInterval(j.current),j.current=null)},[]),oe=a.useCallback((R,W)=>{if(typeof window>"u")return;const F=String(R||q.current||"").trim();if(!F)return;const V=pe(F),E=V?.ownerId===ce.current;if(!(!W?.force&&V&&!E)){B();try{window.localStorage.removeItem(lp(F))}catch{}q.current=null,K.current=null,te(F)}},[te,pe,B]),xe=a.useCallback((R,W)=>{typeof window>"u"||(B(),j.current=window.setInterval(()=>{const F=String(q.current||"").trim(),V=K.current;if(!F||!V){B();return}if(pe(F)?.ownerId!==ce.current){B(),q.current=null,K.current=null;return}D(F,V)},vk),q.current=R,K.current=W)},[pe,B,D]),ie=a.useCallback(async(R,W)=>{if(typeof window>"u")return!0;const F=String(R||"").trim();if(!Pl(F))return!1;const V=pe(F);if(V?.ownerId===ce.current)return D(F,W)?(xe(F,W),!0):!1;if(V&&!Ck(V)||!D(F,W))return!1;const x=pe(F);return!x||x.ownerId!==ce.current?!1:(xe(F,W),!0)},[pe,xe,D]),ae=a.useCallback(R=>{oe(R,{force:!0})},[oe]),Ze=a.useCallback(R=>{const W=$.current,F=Tm(W,{enabled:!!R.enabled,phase:R.phase||W.phase,pullCursor:R.pullCursor,lastPullAt:R.lastPullAt,lastPushAt:R.lastPushAt,lastSyncedAt:R.lastSyncedAt,lastErrorMessage:R.lastErrorMessage});$.current=F,Z.current=F.pullCursor,s(F.enabled),r(F.phase),o(F.lastPullAt),l(F.lastPushAt),i(F.lastErrorMessage??null)},[s,r,o,l,i]),Le=a.useCallback(async R=>{const W=Tm($.current,R);$.current=W,Z.current=W.pullCursor;const F=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n,stateKey:"workspace-sync",patch:W})}),V=await F.json().catch(()=>({}));if(!F.ok||V?.success===!1)throw new Error(V?.error||`Failed to persist workspace sync state (${F.status})`);return Ze(W),W},[Ze,n]),Ce=a.useCallback(async()=>{if(!Pl(n)){const R=tu();$.current=R,Ze(R);return}try{const R=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const W=await R.json().catch(()=>({})),F=yk(W?.state&&typeof W.state=="object"?W.state:null);$.current=F.state,Ze(F.state),F.changed&&Le(F.state)}catch{}},[Ze,n,Le]),Oe=a.useCallback(async(R,W)=>{if(!Pl(n))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!R.enabled)return await Le({enabled:!1,phase:"idle",pullCursor:null}),{success:!0};if(!W.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!W.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const F=await W.ensureCloudWorkspaceReadyForSync();return F.success?(await Le({enabled:!0,phase:F.provisioned?"provision-local":"attach-cloud",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}),{success:!0}):{success:!1,error:F.error||"Workspace sync handshake failed."}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[n,Le]);return a.useEffect(()=>{C.current="",M.current="",S.current=new Set,P.current=new Set,Z.current=null,$.current=tu(),k.current=!1,g.current=!1,oe(),U()},[U,n,oe]),a.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const R=new BroadcastChannel(Sk);return ye.current=R,()=>{R.close(),ye.current===R&&(ye.current=null)}},[]),a.useEffect(()=>()=>{w.current!==null&&typeof window<"u"&&(window.clearTimeout(w.current),w.current=null),oe()},[oe]),{workspaceRetryAt:p,isWorkspaceRetryPending:Ne,workspacePushInFlightRef:k,workspacePullInFlightRef:g,workspaceLastPushedSignatureRef:C,workspacePendingSignatureRef:M,workspaceLastPushedTaskIdsRef:S,workspaceDeletedTaskIdsRef:P,workspacePullCursorRef:Z,clearWorkspaceRetry:U,scheduleWorkspaceRetry:X,persistWorkspaceSyncPatch:Le,loadWorkspaceSyncState:Ce,applyWorkspaceSyncStateSnapshot:Ze,saveWorkspaceCloudSyncSettings:Oe,acquireWorkspaceSyncLease:ie,releaseWorkspaceSyncLease:oe,forceClearWorkspaceSyncLease:ae,readWorkspaceSyncLease:pe}}class Ak{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 i=Math.floor(o);if(this.activeEpoch&&this.activeEpoch!==r)return this.activeEpoch=r,this.lastSeq=i,s&&this.rememberEventId(s),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=r,this.lastSeq=i,s&&this.rememberEventId(s),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const p=this.lastSeq;if(typeof p=="number"){if(i<=p){this.telemetry.outOfOrderDiscarded+=i===p?0:1,this.telemetry.duplicateDiscarded+=i===p?1:0;const h=i<p;return h&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:i===p?"duplicate":"out-of-order",shouldRecover:h}}if(i>p+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=i,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 Gf(e){const{enabled:n,workspaceId:s,websocketUrl:r,reconnectBaseMs:o=400,reconnectMaxMs:l=1e4,degradeAfterAttempts:i=5,replayLimit:p=200,onSignal:h,onTelemetry:w,userId:b}=e,[_,k]=a.useState("degraded-fallback"),g=a.useRef(null),C=a.useRef(null),M=a.useRef(0),S=a.useRef(""),P=a.useRef(!1),Z=a.useRef(null),$=a.useRef(null),ce=a.useRef(new Ak),q=a.useRef(h),K=a.useRef(w);a.useEffect(()=>{q.current=h},[h]),a.useEffect(()=>{K.current=w},[w]);const[j,ye]=a.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),U=a.useMemo(()=>String(s||"").trim(),[s]),X=a.useMemo(()=>String(r||"").trim(),[r]);return a.useEffect(()=>{let Ne=!1;const pe=()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null)},te=()=>{const Ce=g.current;if(g.current=null,Ce)try{Ce.close()}catch{}},D=Ce=>Ce==="taskforce:replay-gap"||Ce==="taskforce:replay-reset"?4:Ce==="taskforce:mutation"||Ce==="taskforce:replay"?3:1,B=Ce=>{const Oe=$.current;if(Oe){const R=D(Oe.type),W=D(Ce.type);if(W<R||W===R&&Oe.eventId&&!Ce.eventId)return}$.current=Ce,Z.current!==null&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{Z.current=null;const R=q.current;if(!$.current||typeof R!="function")return;const W=$.current;$.current=null,R(W)},80)},oe=Ce=>{try{const Oe=JSON.parse(String(Ce.data||""));return!Oe||typeof Oe!="object"?null:Oe}catch{return null}},xe=Ce=>{const Oe=typeof Ce.serverEpoch=="string"?Ce.serverEpoch.trim():"",R=Number(Ce.seq);!Oe||!Number.isFinite(R)||R<0||(S.current=`${Oe}:${Math.floor(R)}`,P.current=!1)},ie=()=>{const Ce=ce.current.getTelemetry();ye(Ce);const Oe=K.current;typeof Oe=="function"&&Oe(Ce)},ae=Ce=>{const Oe={type:"taskforce:replay",workspaceId:U,limit:p},R=S.current;R&&(Oe.cursor=R),Ce.send(JSON.stringify(Oe))},Ze=()=>{if(!n||Ne)return;pe(),M.current+=1;const Ce=M.current,Oe=Math.max(50,Math.floor(o)),R=Math.max(Oe,Math.floor(l)),W=Math.min(R,Oe*Math.pow(2,Math.max(0,Ce-1)));k(Ce>=i?"degraded-fallback":"reconnecting"),C.current=window.setTimeout(()=>{Ne||(C.current=null,Le())},W)},Le=()=>{if(!n||Ne||!U||!X)return;te();let Ce;try{Ce=new WebSocket(X)}catch{Ze();return}g.current=Ce,Ce.addEventListener("open",()=>{M.current=0,k("connected"),Ce.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:U,userId:b||void 0})),ae(Ce)}),Ce.addEventListener("message",Oe=>{const R=oe(Oe);if(!R||typeof R.type!="string")return;const W=typeof R.workspaceId=="string"?R.workspaceId.trim():U;if(!(!W||W!==U)){if(R.type==="taskforce:update"){B({type:"taskforce:update",workspaceId:U});return}if(R.type==="taskforce:mutation"){const F=ce.current.process({eventId:R.eventId,serverEpoch:R.serverEpoch,seq:R.seq});if(!F.accepted){ie(),F.shouldRecover&&(S.current="",P.current||(P.current=!0,B({type:"taskforce:replay-gap",workspaceId:U})));return}xe(R),ie(),B({type:R.type,workspaceId:U,eventId:typeof R.eventId=="string"?R.eventId.trim():void 0});return}if(R.type==="taskforce:replay"){const F=Array.isArray(R.events)?R.events:[];let V=0;for(const E of F)ce.current.process({eventId:E.eventId,serverEpoch:E.serverEpoch,seq:E.seq}).accepted&&(V+=1,xe(E));P.current=!1,ie(),(V>0||R.truncated===!0)&&B({type:"taskforce:replay",workspaceId:U}),R.truncated===!0&&ae(Ce);return}if(R.type==="taskforce:replay-gap"||R.type==="taskforce:replay-reset"){if(S.current="",P.current)return;P.current=!0,B({type:R.type,workspaceId:U})}}}),Ce.addEventListener("close",Oe=>{if(g.current===Ce&&(g.current=null),!Ne&&n){const R=Number(Oe?.code||0),W=String(Oe?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${U} user=${String(b||"anonymous").trim()||"anonymous"} code=${R}${W?` reason=${W}`:""}`)}Ze()}),Ce.addEventListener("error",()=>{try{Ce.close()}catch{}})};return!n||!U||!X?(k("degraded-fallback"),pe(),te(),()=>{pe(),te()}):(k("reconnecting"),Le(),()=>{Ne=!0,pe(),Z.current!==null&&(window.clearTimeout(Z.current),Z.current=null),$.current=null,te()})},[n,U,X,o,l,i,p,b]),{connectionState:_,telemetry:j}}const Np="taskforce:context-assets-mutated";function Ik(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Np,{detail:e}))}const Vf="taskforce.userGlobalSyncMeta.v1",Tk="taskforce.syncDebug.v1",Nk=12e4,Zf="taskforce.syncWatermarks.v3",jk=7200*1e3,Nm="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function Po(e){const n=String(e||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function Rk(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(Tk)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function ks(e,n){if(!Rk())return;console.info("[Taskforce Sync]",e,n&&typeof n=="object"?n:{})}function Dk(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:Hf(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 jm(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Vf);if(!e)return{};const n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}}function Pk(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Vf,JSON.stringify(e))}catch{}}function Ek(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function Lk(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 Mk(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 Bk(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 Wk(e,n){if(typeof window>"u")return null;try{const s=`${Zf}.${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>jk)return null;const i=typeof o.taxonomyStateFingerprint=="string"?o.taxonomyStateFingerprint:"";return{taskWatermarks:!n||!i||i===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 Rm(e,n){if(!(typeof window>"u"))try{const s=`${Zf}.${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 Dm={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1};function Fk(e){const{currentWorkspaceId:n,cloudAuthConfigured:s,runtimeMode:r,authSessionResolved:o,isAuthenticated:l,authUserId:i,projectName:p,resolveCloudAuthUrl:h,resolveWebSocketUrl:w,realtimeSyncEnabled:b,tasks:_,archivedTasks:k,initiatives:g,workstreams:C,taxonomies:M,taxonomyState:S,setupState:P,globalTheme:Z,locale:$,globalWeekStartsOn:ce,themeUseGlobalDefault:q,setTasks:K,setArchivedTasks:j,setAuthBlocked:ye,setIsAuthenticated:U,checkAuthSession:X,setGlobalTheme:Ne,setCurrentTheme:pe,setSetupState:te,setLocale:D,setGlobalWeekStartsOn:B,fetchPlanningEntities:oe}=e,xe=a.useMemo(()=>Ek(S),[S]),[ie,ae]=a.useState("disconnected"),[Ze,Le]=a.useState(null),[Ce,Oe]=a.useState(null),[R,W]=a.useState(null),[F,V]=a.useState(null),[E,y]=a.useState(null),[x,H]=a.useState(!1),[I,Ie]=a.useState("idle"),[L,le]=a.useState(!1),[ne,de]=a.useState(0),[G,ee]=a.useState([]),[be,$e]=a.useState(""),fe=a.useRef(_||[]),De=a.useRef(k||[]),Ke=a.useRef(g||[]),nt=a.useRef(C||[]),dt=a.useRef([]),[d,et]=a.useState([]),[gt,O]=a.useState(""),[Ye,wt]=a.useState(null),[St,At]=a.useState(null),[zt,Ht]=a.useState(0),[sn,Jt]=a.useState(null),Xt=a.useRef([]),[gn,Mn]=a.useState([]),[un,yn]=a.useState(""),an=a.useRef([]),[Tn,Rt]=a.useState([]),[we,Lt]=a.useState(""),Qt=a.useRef([]),Dt=a.useRef([]),[He,Nn]=a.useState([]),[Y,Ae]=a.useState(""),_e=a.useRef([]),[Pe,qe]=a.useState(Dm),[Je,at]=a.useState("degraded-fallback"),[Xe,ct]=a.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),vt=a.useRef(!1),Ot=a.useRef(null),Pt=a.useRef(0),xt=a.useRef(!1),Et=a.useRef(new Set),xn=a.useRef(""),Gt=a.useRef(""),Jn=a.useRef(""),kn=a.useRef(""),yt=a.useRef(""),Gn=a.useRef(""),se=a.useRef(!1),je=a.useRef(null),Me=a.useRef(new Set),Ee=a.useRef([]),Fe=a.useRef(()=>Promise.resolve(!1)),tt=a.useRef(async()=>{}),An=a.useRef(null),Mt=a.useRef(null),fa=a.useRef("idle"),Bn=a.useCallback(()=>{Ot.current!==null&&(window.clearTimeout(Ot.current),Ot.current=null)},[]),bn=a.useCallback(T=>{if(typeof window>"u")return;Bn();const ge=Math.max(1,Math.floor(Pt.current)+1);Pt.current=ge;const Ue=1500*2**Math.max(0,ge-1),Re=Number.isFinite(Number(T))?Math.max(0,Math.floor(Number(T))):0,J=Math.max(Math.min(12e4,Ue),Re);Ot.current=window.setTimeout(()=>{Ot.current=null,tt.current({preferCloudOnFirstSync:!1})},J)},[Bn]);a.useEffect(()=>{Gt.current="",Jn.current="",kn.current="",yt.current="",Gn.current="",Ya.current="",ca.current=!1,ee([]),$e(""),Xt.current=[],et([]),O(""),Mn([]),yn(""),Qt.current=[],Dt.current=[],Rt([]),Lt(""),_e.current=[],Nn([]),Ae(""),qe(Dm),y(null),V(null),de(0),Me.current=new Set,Ee.current=[],on.current=new Map,jn.current=new Set,Vn.current=new Map,_n.current=new Set,$n.current=new Map,Wn.current=new Set,vn.current=new Map,cn.current=new Set,Rn.current=new Map,In.current=new Set,rt.current=new Map,wn.current=new Set,nn.current=new Map,Sa.current=new Set,Xn.current=new Map,Fa.current=new Set,Oa.current=new Map,Fa.current=new Set,Oa.current=new Map;const T=Wk(n,xe);T&&(on.current=T.taskWatermarks,Vn.current=T.initiativeWatermarks,$n.current=T.workstreamWatermarks,Rn.current=T.documentWatermarks,rt.current=T.assetWatermarks,nn.current=T.documentReviewSessionWatermarks,Xn.current=T.documentReviewCommentWatermarks,Oa.current=T.annotatedAttachmentSessionWatermarks)},[n,xe]);const fn=a.useCallback(T=>{qe(ge=>ge[T]?ge:{...ge,[T]:!0})},[]),rn=Object.values(Pe).every(Boolean),{workspaceRetryAt:Kt,isWorkspaceRetryPending:kt,workspacePushInFlightRef:$t,workspacePullInFlightRef:Yt,workspaceLastPushedSignatureRef:Sn,workspacePendingSignatureRef:ft,workspaceLastPushedTaskIdsRef:mt,workspaceDeletedTaskIdsRef:oa,workspacePullCursorRef:en,clearWorkspaceRetry:tn,scheduleWorkspaceRetry:It,persistWorkspaceSyncPatch:Tt,loadWorkspaceSyncState:ia,applyWorkspaceSyncStateSnapshot:ya,saveWorkspaceCloudSyncSettings:Ia,acquireWorkspaceSyncLease:ha,releaseWorkspaceSyncLease:ka,forceClearWorkspaceSyncLease:aa}=xk({currentWorkspaceId:n,setWorkspaceCloudSyncEnabled:H,setWorkspaceSyncPhase:Ie,setWorkspaceLastPullAt:Oe,setWorkspaceLastPushAt:W,setWorkspaceLastErrorMessage:y}),on=a.useRef(new Map),jn=a.useRef(new Set),Vn=a.useRef(new Map),_n=a.useRef(new Set),$n=a.useRef(new Map),Wn=a.useRef(new Set),vn=a.useRef(new Map),cn=a.useRef(new Set),Rn=a.useRef(new Map),In=a.useRef(new Set),rt=a.useRef(new Map),wn=a.useRef(new Set),nn=a.useRef(new Map),Sa=a.useRef(new Set),Xn=a.useRef(new Map),Fa=a.useRef(new Set),Oa=a.useRef(new Map),vs=a.useRef(!1),ss=a.useRef(!1),Ya=a.useRef(""),ca=a.useRef(!1),ln=3e4,rr=b?3e4:15e3,la=a.useMemo(()=>{const T=Ce?Date.parse(Ce):NaN,ge=R?Date.parse(R):NaN;return Number.isFinite(T)&&Number.isFinite(ge)?T>=ge?Ce:R:Number.isFinite(T)?Ce:Number.isFinite(ge)?R:null},[Ce,R]),va=a.useMemo(()=>x?L||I==="provision-local"||I==="attach-cloud"?"syncing":Kt||E||I==="error"?"attention":"healthy":"off",[x,L,I,Kt,E]),Un=a.useMemo(()=>Lk(x,I,L,Kt,E),[x,I,L,Kt,E]),wa=a.useMemo(()=>Mk(x,I,Kt,E),[x,I,Kt,E]),Ls=a.useCallback(T=>{const ge=String(T||"").trim();if(!ge)return null;const Re=jm()[ge]?.updatedAt;return typeof Re=="string"&&Re.trim().length>0?Re.trim():null},[]),rs=a.useCallback((T,ge)=>{const Ue=String(T||"").trim(),Re=String(ge||"").trim();if(!Ue||!Re)return;const J=jm();J[Ue]={updatedAt:Re},Pk(J)},[]),sa=a.useCallback(()=>{const T=P?.mode==="operations"?"operations":"core";return{theme:Z,operatingMode:T,localization:{locale:$,weekStartsOn:ce}}},[Z,P?.mode,$,ce]),os=a.useCallback(async T=>{if(!(!T||typeof T!="object")){xt.current=!0;try{const ge={},Ue=xc(T.theme);if(Ue&&(Ne(Ue),q&&pe(Ue),ge.theme=Ue),(T.operatingMode==="core"||T.operatingMode==="operations")&&(te(Re=>Re&&{...Re,mode:T.operatingMode}),ge.setup={mode:T.operatingMode}),T.localization&&typeof T.localization=="object"){const Re={};if(typeof T.localization.locale=="string"&&T.localization.locale.trim().length>0){const Be=Rf(T.localization.locale.trim());D(Be)}const J=String(T.localization.weekStartsOn||"").trim().toLowerCase();(J==="sunday"||J==="monday")&&(B(J),Re.weekStartsOn=J),Object.keys(Re).length>0&&(ge.schedulePreferences=Re)}Object.keys(ge).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ge)})}finally{xt.current=!1}}},[q,Ne,pe,te,D,B]),ba=a.useCallback(async T=>{const ge=T?.preferCloudOnFirstSync!==!1;if(!s)return;if(r!=="local"||!l){Bn(),Pt.current=0,ae("disconnected");return}const Ue=String(i||"").trim();if(!Ue||Ue==="anonymous"){Bn(),Pt.current=0,ae("disconnected");return}if(!vt.current){ae("syncing"),Le(null),vt.current=!0;try{const Re=await nk({resolveCloudAuthUrl:h,userId:Ue,preferCloudOnFirstSync:ge,getLocalUpdatedAt:Ls,buildLocalSettings:sa,applyRemoteSettings:os});if(!Re.success){ae("error"),Re.transient?(Le(Re.error||"Sync failed temporarily. Retrying automatically."),bn(Re.retryAfterMs)):(Bn(),Pt.current=0,Le(Re.error||"Sync failed."));return}Bn(),Pt.current=0;const J=String(Re.updatedAt||"").trim()||new Date().toISOString();rs(Ue,J),ae("idle"),Le(null),Et.current.add(Ue),Re.mode==="pulled"&&(xn.current="")}catch{ae("error"),Le("Sync failed temporarily. Retrying automatically."),bn()}finally{vt.current=!1}}},[s,r,l,i,h,Ls,sa,os,rs,Bn,bn]);a.useEffect(()=>{tt.current=ba},[ba]),a.useEffect(()=>()=>{Bn()},[Bn]);const is=a.useCallback(()=>{y(null),V(null)},[]),cs=a.useCallback(T=>{y(Nm),V(new Date().toISOString()),ae("error"),Le(Nm),ks("workspace_sync_window_contention",{workspaceId:n,operation:T})},[n]),Da=a.useCallback(T=>{Tt(T).catch(()=>{})},[Tt]),Q=a.useCallback(T=>{It(()=>Fe.current(),{minDelayMs:T})},[It]);a.useEffect(()=>{if(I==="attach-cloud"||I==="provision-local"){fa.current=I,An.current===null&&(An.current=Date.now()),Mt.current=null;return}An.current=null,Mt.current=null},[I]),a.useEffect(()=>{if(!x||I!=="attach-cloud"&&I!=="provision-local")return;const T=window.setInterval(()=>{if(I!=="attach-cloud"&&I!=="provision-local"||Yt.current||$t.current)return;const ge=Math.max(An.current??0,Mt.current??0);if(ge>0&&Date.now()-ge<Nk)return;const Re=`Workspace sync ${I==="attach-cloud"?"initial cloud pull":"initial cloud upload"} stalled. Press Repair to restart sync for this workspace.`;y(Re),V(new Date().toISOString()),ae("error"),Le(Re),le(!1),Da({phase:"error",lastErrorMessage:Re}),ks("workspace_sync_bootstrap_timeout",{workspaceId:n,phase:I})},1e4);return()=>window.clearInterval(T)},[n,x,I,Da,Yt,$t]);const Ve=a.useCallback(async()=>Xy({cloudAuthConfigured:s,runtimeMode:r,isAuthenticated:l,resolveCloudAuthUrl:h,workspaceId:n,workspaceName:p||n}),[s,r,l,h,n,p]);a.useEffect(()=>{fe.current=_||[]},[_]),a.useEffect(()=>{De.current=k||[]},[k]),a.useEffect(()=>{Ke.current=g||[]},[g]),a.useEffect(()=>{nt.current=C||[]},[C]);const Vt=a.useRef(!1),bt=a.useCallback(T=>{const ge=T?.forceAllAiProfiles===!0;return fk({tasks:fe.current,archivedTasks:De.current,lastPushedTaskIds:mt.current,pendingDeletedTaskIds:oa.current,initiatives:Ke.current,workstreams:nt.current,taxonomies:M||[],taxonomyState:S,lastPushedInitiativeIds:jn.current,lastPushedInitiativeWatermarks:Vn.current,lastPushedWorkstreamIds:_n.current,lastPushedWorkstreamWatermarks:$n.current,aiProfiles:Xt.current,lastPushedAiProfileIds:ge?new Set:Wn.current,lastPushedAiProfileWatermarks:ge?new Map:vn.current,documents:dt.current,assets:an.current,documentReviewSessions:Qt.current,documentReviewComments:Dt.current,annotatedAttachmentSessions:_e.current,lastPushedDocumentPaths:cn.current,lastPushedDocumentWatermarks:Rn.current,lastPushedAssetPaths:In.current,lastPushedAssetWatermarks:rt.current,lastPushedDocumentReviewSessionIds:wn.current,lastPushedDocumentReviewSessionWatermarks:nn.current,lastPushedDocumentReviewCommentIds:Sa.current,lastPushedDocumentReviewCommentWatermarks:Xn.current,lastPushedAnnotatedAttachmentSessionIds:Fa.current,lastPushedAnnotatedAttachmentSessionWatermarks:Oa.current,lastPushedWatermarks:on.current})},[M,S]),dn=a.useCallback((T,ge)=>{r==="local"&&fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({...ge,workspaceId:T})}).catch(Ue=>{ks("sync_event_post_failed",{workspaceId:T,eventType:ge.eventType,status:ge.status,error:String(Ue?.message||Ue||"")})})},[r]),ot=a.useCallback(()=>hk({workspaceId:n,tasks:fe.current,archivedTasks:De.current,pendingDeletedTaskIds:oa.current,initiatives:Ke.current,workstreams:nt.current,taxonomies:M||[],aiProfiles:Xt.current,documents:dt.current,assets:an.current,documentReviewSessions:Qt.current,documentReviewComments:Dt.current,annotatedAttachmentSessions:_e.current}),[n,M]),da=a.useMemo(()=>{const T=[];for(const ge of _||[]){const Ue=Array.isArray(ge.attachments)?ge.attachments.length:0;Ue>0&&T.push(`${ge.id}:${Ue}`)}return T.join("|")},[_]),_a=a.useCallback(T=>{if(!T)return!1;if(ca.current)return ca.current=!1,Ya.current=T,Sn.current=T,de(0),!0;const ge=Ya.current;return ge?T===ge?(Sn.current=T,de(0),!0):(Ya.current="",!1):!1},[]),Zn=a.useCallback(async()=>{if(r==="local"&&Po(n)&&!(s&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const ge=await T.json().catch(()=>({})),Ue=Array.isArray(ge?.documents)?ge.documents.map(J=>({path:String(J?.path||"").trim(),updatedAt:String(J?.updatedAt||"").trim(),content:typeof J?.content=="string"?J.content:"",assetId:typeof J?.assetId=="string"&&J.assetId.trim().length>0?J.assetId.trim():void 0,documentId:typeof J?.documentId=="string"&&J.documentId.trim().length>0?J.documentId.trim():null,referenceNumber:Number.isFinite(Number(J?.referenceNumber))?Math.max(1,Math.floor(Number(J.referenceNumber))):null,version:Number.isFinite(Number(J?.version))?Math.max(1,Math.floor(Number(J.version))):null,taskId:typeof J?.taskId=="string"&&J.taskId.trim().length>0?J.taskId.trim():null,logicalName:typeof J?.logicalName=="string"&&J.logicalName.trim().length>0?J.logicalName.trim():null,caption:typeof J?.caption=="string"&&J.caption.trim().length>0?J.caption.trim():null,originalFilename:typeof J?.originalFilename=="string"&&J.originalFilename.trim().length>0?J.originalFilename.trim():null,linkRole:J?.linkRole==="reference"?"reference":"attachment"})).filter(J=>J.path.length>0):[],Re=typeof ge?.fingerprint=="string"?ge.fingerprint:JSON.stringify(Ue.map(J=>`${J.path}:${J.updatedAt}:${J.content.length}`).sort());if(Re===Gt.current)return;Gt.current=Re,dt.current=Ue,ee(Ue),$e(Re)}catch(T){ks("documents_snapshot_refresh_failed",{workspaceId:n,error:String(T?.message||T||"")})}finally{fn("documents")}},[r,n,s,o,l,fn]),zn=a.useCallback(async()=>{if(r!=="local"){Jt("runtime-not-local");return}if(!Po(n)){Jt("workspace-id-invalid");return}if(s&&(!o||!l)){Jt(o?"auth-required":"auth-unresolved");return}Jt(null);try{const T=await fetch(`/api/taskforce/sync/workspace/ai-profiles?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!T.ok){At(`HTTP ${T.status}`),wt(new Date().toISOString());return}const ge=await T.json().catch(()=>({})),Ue=Array.isArray(ge?.aiProfiles)?ge.aiProfiles:[];Ht(Ue.length);const Re=Array.isArray(ge?.aiProfiles)?ge.aiProfiles.map(Be=>Dk(Be)).filter(Be=>Be.id.length>0&&Be.workspaceId.length>0):[];At(null),wt(new Date().toISOString());const J=typeof ge?.fingerprint=="string"?ge.fingerprint:JSON.stringify(Re.map(Be=>`${Be.id}:${Be.updatedAt}:${Be.name}:${Be.username}`).sort());if(J===Jn.current)return;Jn.current=J,Xt.current=Re,et(Re),O(J)}catch(T){At(String(T?.message||T||"unknown-error")),wt(new Date().toISOString()),ks("ai_profiles_snapshot_refresh_failed",{workspaceId:n,error:String(T?.message||T||"")})}finally{fn("aiProfiles")}},[r,n,s,o,l,fn]),ga=a.useCallback(async()=>{if(r==="local"&&Po(n)&&!(s&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const ge=await T.json().catch(()=>({})),Ue=Array.isArray(ge?.assets)?ge.assets.map(J=>({path:String(J?.path||"").trim(),updatedAt:String(J?.updatedAt||"").trim(),contentBase64:typeof J?.contentBase64=="string"?J.contentBase64:"",assetId:typeof J?.assetId=="string"&&J.assetId.trim().length>0?J.assetId.trim():void 0,kind:J?.kind==="image"?"image":"file",mimeType:typeof J?.mimeType=="string"&&J.mimeType.trim().length>0?J.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(J?.referenceNumber))?Math.max(1,Math.floor(Number(J.referenceNumber))):null,taskId:typeof J?.taskId=="string"&&J.taskId.trim().length>0?J.taskId.trim():null,logicalName:typeof J?.logicalName=="string"&&J.logicalName.trim().length>0?J.logicalName.trim():null,caption:typeof J?.caption=="string"&&J.caption.trim().length>0?J.caption.trim():null,originalFilename:typeof J?.originalFilename=="string"&&J.originalFilename.trim().length>0?J.originalFilename.trim():null,linkRole:J?.linkRole==="reference"?"reference":J?.linkRole==="image"?"image":"attachment"})).filter(J=>J.path.length>0&&J.contentBase64.length>0):[],Re=typeof ge?.fingerprint=="string"?ge.fingerprint:JSON.stringify(Ue.map(J=>`${J.path}:${J.updatedAt}:${J.contentBase64.length}`).sort());if(Re===kn.current)return;kn.current=Re,an.current=Ue,Mn(Ue),yn(Re)}catch(T){ks("assets_snapshot_refresh_failed",{workspaceId:n,error:String(T?.message||T||"")})}finally{fn("assets")}},[r,n,s,o,l,fn]),qn=a.useCallback(async()=>{if(r==="local"&&Po(n)&&!(s&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const ge=await T.json().catch(()=>({})),Ue=Array.isArray(ge?.sessions)?ge.sessions.map(Be=>({id:String(Be?.id||"").trim(),assetId:String(Be?.assetId||"").trim(),documentId:typeof Be?.documentId=="string"&&Be.documentId.trim().length>0?Be.documentId.trim():null,documentVersion:Number.isFinite(Number(Be?.documentVersion))?Math.max(1,Math.floor(Number(Be.documentVersion))):null,title:typeof Be?.title=="string"&&Be.title.trim().length>0?Be.title.trim():null,status:Be?.status==="resolved"?"resolved":"open",comments:Array.isArray(Be?.comments)?Be.comments:[],createdByActorId:typeof Be?.createdByActorId=="string"&&Be.createdByActorId.trim().length>0?Be.createdByActorId.trim():null,updatedByActorId:typeof Be?.updatedByActorId=="string"&&Be.updatedByActorId.trim().length>0?Be.updatedByActorId.trim():null,createdAt:String(Be?.createdAt||"").trim(),updatedAt:String(Be?.updatedAt||Be?.createdAt||"").trim(),deletedAt:typeof Be?.deletedAt=="string"&&Be.deletedAt.trim().length>0?Be.deletedAt.trim():null})).filter(Be=>Be.id.length>0&&Be.assetId.length>0):[],Re=Array.isArray(ge?.comments)?ge.comments.map(Be=>({id:String(Be?.id||"").trim(),sessionId:String(Be?.sessionId||"").trim(),body:typeof Be?.body=="string"?Be.body:"",anchor:Be?.anchor??null,order:Number.isFinite(Number(Be?.order))?Math.max(0,Math.floor(Number(Be.order))):0,authorActorId:typeof Be?.authorActorId=="string"&&Be.authorActorId.trim().length>0?Be.authorActorId.trim():null,createdAt:String(Be?.createdAt||"").trim(),updatedAt:String(Be?.updatedAt||Be?.createdAt||"").trim(),deletedAt:typeof Be?.deletedAt=="string"&&Be.deletedAt.trim().length>0?Be.deletedAt.trim():null})).filter(Be=>Be.id.length>0&&Be.sessionId.length>0):Bk(Ue),J=typeof ge?.fingerprint=="string"?ge.fingerprint:JSON.stringify([...Ue.map(Be=>`${Be.id}:${Be.updatedAt}:${Be.status}:${Be.deletedAt||""}:${Be.comments.length}`).sort(),...Re.map(Be=>`${Be.id}:${Be.sessionId}:${Be.updatedAt}:${Be.deletedAt||""}`).sort()]);if(J===yt.current)return;yt.current=J,Qt.current=Ue,Dt.current=Re,Rt(Ue),Lt(J)}catch(T){ks("document_review_sessions_snapshot_refresh_failed",{workspaceId:n,error:String(T?.message||T||"")})}finally{fn("documentReviewSessions")}},[r,n,s,o,l,fn]),Ja=a.useCallback(async()=>{if(r==="local"&&Po(n)&&!(s&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const ge=await T.json().catch(()=>({})),Ue=Array.isArray(ge?.sessions)?ge.sessions.map(J=>({id:String(J?.id||"").trim(),workspaceId:String(J?.workspaceId||"").trim(),taskId:String(J?.taskId||"").trim(),baseImageAssetId:String(J?.baseImageAssetId||"").trim(),title:typeof J?.title=="string"&&J.title.trim().length>0?J.title.trim():null,globalInstruction:typeof J?.globalInstruction=="string"&&J.globalInstruction.trim().length>0?J.globalInstruction.trim():null,annotations:Array.isArray(J?.annotations)?J.annotations:[],createdByActorId:typeof J?.createdByActorId=="string"&&J.createdByActorId.trim().length>0?J.createdByActorId.trim():null,updatedByActorId:typeof J?.updatedByActorId=="string"&&J.updatedByActorId.trim().length>0?J.updatedByActorId.trim():null,createdAt:String(J?.createdAt||"").trim(),updatedAt:String(J?.updatedAt||J?.createdAt||"").trim(),deletedAt:typeof J?.deletedAt=="string"&&J.deletedAt.trim().length>0?J.deletedAt.trim():null})).filter(J=>J.id.length>0&&J.workspaceId.length>0&&J.taskId.length>0&&J.baseImageAssetId.length>0):[],Re=typeof ge?.fingerprint=="string"?ge.fingerprint:JSON.stringify(Ue.map(J=>`${J.id}:${J.updatedAt}:${J.taskId}:${J.baseImageAssetId}:${J.annotations.length}:${J.deletedAt||""}`).sort());if(Re===Gn.current)return;Gn.current=Re,_e.current=Ue,Nn(Ue),Ae(Re)}catch(T){ks("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:n,error:String(T?.message||T||"")})}finally{fn("annotatedAttachmentSessions")}},[r,n,s,o,l,fn]),Ms=a.useCallback(()=>{cn.current=new Set(dt.current.map(T=>String(T?.path||"").trim()).filter(T=>T.length>0)),Rn.current=new Map(dt.current.map(T=>[String(T?.path||"").trim(),String(T?.updatedAt||"").trim()]).filter(([T])=>T.length>0)),In.current=new Set(an.current.map(T=>String(T?.path||"").trim()).filter(T=>T.length>0)),rt.current=new Map(an.current.map(T=>[String(T?.path||"").trim(),String(T?.updatedAt||"").trim()]).filter(([T])=>T.length>0)),wn.current=new Set(Qt.current.map(T=>String(T?.id||"").trim()).filter(T=>T.length>0)),nn.current=new Map(Qt.current.map(T=>[String(T?.id||"").trim(),String(T?.updatedAt||T?.createdAt||"").trim()]).filter(([T])=>T.length>0)),Sa.current=new Set(Dt.current.map(T=>String(T?.id||"").trim()).filter(T=>T.length>0)),Xn.current=new Map(Dt.current.map(T=>[String(T?.id||"").trim(),String(T?.updatedAt||T?.createdAt||"").trim()]).filter(([T])=>T.length>0)),Fa.current=new Set(_e.current.map(T=>String(T?.id||"").trim()).filter(T=>T.length>0)),Oa.current=new Map(_e.current.map(T=>[String(T?.id||"").trim(),String(T?.updatedAt||T?.createdAt||"").trim()]).filter(([T])=>T.length>0))},[]),Tr=a.useCallback(async()=>{const[T,ge]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(T.ok){const Ue=await T.json().catch(()=>({})),Re=Array.isArray(Ue?.tasks)?Ue.tasks.map(J=>so(J)):[];K(Re)}if(ge.ok){const Ue=await ge.json().catch(()=>({})),Re=Array.isArray(Ue?.archived)?Ue.archived.map(J=>({...so(J),isArchived:!0})):[];j(Re)}await oe().catch(()=>{ks("refresh_planning_entities_failed",{workspaceId:n})})},[n,oe,j,K]),ls=a.useCallback(async(T,ge)=>{tn(),le(!1),ae("error");const Ue="Session expired. Sign in again to resume cloud sync.";Le(Ue),y(Ue),V(new Date().toISOString()),dn(n,{eventType:T==="handshake"?"handshake":T,status:"error",statusCode:ge,errorMessage:Ue}),ye(!0),U(!1),await X()},[tn,dn,n,ye,U,X]),or=a.useCallback(async()=>{if(!Po(n)){const Ue="Workspace sync blocked: local workspace ID is unresolved.";return y(Ue),V(new Date().toISOString()),Le(Ue),ae("error"),!1}const T=await Ve();if(T.success)return!0;if(T.statusCode===401)return await ls("handshake",401),!1;const ge=T.error||"Workspace sync handshake failed.";return y(ge),V(new Date().toISOString()),Le(ge),ae("error"),dn(n,{eventType:"handshake",status:"error",statusCode:T.statusCode,errorMessage:ge}),T.transient||no(T.statusCode)?Q(T.retryAfterMs):I==="active"&&Da({phase:"error",lastErrorMessage:ge}),!1},[n,Ve,ls,dn,Q,I,Da]),ua=a.useCallback(async(T,ge)=>{if(!s||r!=="local"||!x||!Po(n))return!1;if(ss.current===!0&&ge?.repairMode!==!0||I==="attach-cloud")return ft.current=T,!1;if(!l&&!await X()||_a(T))return!1;if($t.current||Yt.current)return ft.current=T,!1;if(!await ha(n,"push"))return ft.current=T,cs("push"),!1;$t.current=!0,le(!0),ae("syncing"),Le(null);const Re=Date.now(),J=ge?.forceAllAiProfiles===!0||Vt.current===!0;try{if(await Zn(),await zn(),await ga(),await qn(),!await or())return!1;const ht=bt({forceAllAiProfiles:J});de(ht.changes.length);const Nt=await ek({resolveCloudAuthUrl:h,workspaceId:n,payload:ht,ensureCloudWorkspaceReadyForSync:Ve,repairMode:ge?.repairMode===!0||ss.current===!0});if(!Nt.success){if(Nt.status===401)return await ls("push",401),!1;let Kn=Nt.error?`Workspace sync push failed (${Nt.status||0}): ${Nt.error}`:`Workspace sync push failed (${Nt.status||0})`;return Nt.status===413&&(Kn="Workspace sync failed because the payload is too large. This usually happens when one or more attachments exceed the project limit."),ae("error"),Le(Kn),y(Kn),V(new Date().toISOString()),dn(n,{eventType:"push",status:"error",statusCode:Nt.status,errorMessage:Kn,requestMs:Nt.requestMs}),ft.current=T,Nt.transient||no(Nt.status)?Q(Nt.retryAfterMs):I==="active"&&Da({phase:"error",lastErrorMessage:Kn}),!1}Sn.current=T,mt.current=Nt.currentTaskIds,jn.current=new Set(Nt.currentInitiativeIds),Vn.current=new Map(Nt.currentInitiativeWatermarks),_n.current=new Set(Nt.currentWorkstreamIds),$n.current=new Map(Nt.currentWorkstreamWatermarks),Wn.current=new Set(Nt.currentAiProfileIds),vn.current=new Map(Nt.currentAiProfileWatermarks),cn.current=new Set(Nt.currentDocumentPaths),Rn.current=new Map(Nt.currentDocumentWatermarks),In.current=new Set(Nt.currentAssetPaths),rt.current=new Map(Nt.currentAssetWatermarks),wn.current=new Set(Nt.currentDocumentReviewSessionIds),nn.current=new Map(Nt.currentDocumentReviewSessionWatermarks),Sa.current=new Set(Nt.currentDocumentReviewCommentIds),Xn.current=new Map(Nt.currentDocumentReviewCommentWatermarks),Fa.current=new Set(Nt.currentAnnotatedAttachmentSessionIds),Oa.current=new Map(Nt.currentAnnotatedAttachmentSessionWatermarks),J&&(Vt.current=!1);for(const[Kn,Dn]of Nt.pushedWatermarks)on.current.set(Kn,Dn);if(Nt.deleteTaskIds.size>0)for(const Kn of Nt.deleteTaskIds)oa.current.delete(Kn),on.current.delete(Kn);if(Rm(n,{taskWatermarks:on.current,initiativeWatermarks:Vn.current,workstreamWatermarks:$n.current,documentWatermarks:Rn.current,assetWatermarks:rt.current,documentReviewSessionWatermarks:nn.current,documentReviewCommentWatermarks:Xn.current,annotatedAttachmentSessionWatermarks:Oa.current,taxonomyStateFingerprint:xe}),Array.isArray(Nt.emittedEventIds)&&Nt.emittedEventIds.length>0){for(const Kn of Nt.emittedEventIds){const Dn=String(Kn||"").trim();!Dn||Me.current.has(Dn)||(Me.current.add(Dn),Ee.current.push(Dn))}for(;Ee.current.length>2048;){const Kn=Ee.current.shift();Kn&&Me.current.delete(Kn)}}tn(),is();const ds=Nt.syncedAt||new Date().toISOString();return W(ds),de(0),ae("idle"),Da({phase:"active",lastPushAt:ds,lastSyncedAt:ds,lastErrorMessage:null}),dn(n,{eventType:I==="provision-local"?"bootstrap":"push",status:"success",changeCount:Nt.changeCount,requestMs:Nt.requestMs}),!0}catch(Be){const ht="Workspace sync push failed.";return ae("error"),Le(ht),y(ht),V(new Date().toISOString()),ft.current=T,Q(),dn(n,{eventType:"push",status:"error",errorMessage:`${ht} ${String(Be?.message||"").trim()}`.trim()}),ks("push_failed_exception",{workspaceId:n,elapsedMs:Date.now()-Re}),!1}finally{$t.current=!1,le(Yt.current),ka(n);const Be=ft.current;Be&&Be!==Sn.current&&!Yt.current&&(ft.current="",window.setTimeout(()=>{ua(Be)},120))}},[s,r,x,n,I,l,X,is,Zn,zn,ga,qn,or,bt,h,Ve,_a,ls,tn,Tt,dn,Q,ha,ka,cs,$t,Yt,Da]),Qn=a.useCallback(async T=>{if(!s||r!=="local"||!x||!Po(n)||ss.current===!0&&T?.repairMode!==!0||I==="provision-local"||kt()||!l&&!await X()||Yt.current||$t.current)return!1;if(!await ha(n,"pull"))return cs("pull"),!1;Yt.current=!0,le(!0),ae("syncing"),Le(null);const Ue=Date.now();try{if(!await or())return!1;const J=I==="attach-cloud",Be=J?null:en.current,ht=await tk({resolveCloudAuthUrl:h,workspaceId:n,cursor:Be,bootstrap:J,ensureCloudWorkspaceReadyForSync:Ve,maxPages:20,repairMode:T?.repairMode===!0||ss.current===!0,onPagePulled:()=>{Mt.current=Date.now()},onChangesApplied:()=>{Mt.current=Date.now()}});if(!ht.success){if(ht.kind==="pull_http"&&ht.status===401)return await ls("pull",401),!1;if(ht.kind==="apply_auth")return await ls("apply",401),!1;let Dn=ht.kind==="apply_payload"||ht.kind==="apply_all_candidates"||ht.kind==="exception"?String(ht.error||"Workspace sync apply failed."):`Workspace sync pull failed (${ht.status||0})`;return ht.status===413&&(Dn="Local sync failed because the downloaded payload is too large. This usually happens when the workspace contains massive attachments."),ae("error"),Le(Dn),y(Dn),V(new Date().toISOString()),dn(n,{eventType:ht.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:ht.status,errorMessage:Dn,requestMs:ht.pullRequestMs,details:{pages:ht.pages,applyMs:ht.applyMs,...ht.serverDiagnostics?{serverPullDiagnostics:ht.serverDiagnostics}:{}}}),ht.transient||ht.hasTransientApplyFailure||no(ht.status)?Q(ht.retryAfterMs):Da({phase:"error",lastErrorMessage:Dn}),!1}if(Array.isArray(ht.emittedEventIds))for(const Dn of ht.emittedEventIds)Dn&&(Me.current.add(Dn),setTimeout(()=>{Me.current.delete(Dn)},6e4));ht.pulledDeleteTaskIds.size>0&&(K(Dn=>Dn.filter(Ws=>!ht.pulledDeleteTaskIds.has(String(Ws.id||"")))),j(Dn=>Dn.filter(Ws=>!ht.pulledDeleteTaskIds.has(String(Ws.id||"")))));const Nt=Array.isArray(ht.documentDecryptFailures)?ht.documentDecryptFailures.filter(Dn=>String(Dn||"").trim().length>0):[];if(Nt.length>0&&ks("pull_document_decrypt_failures",{workspaceId:n,failureCount:Nt.length}),en.current=ht.cursor||null,ht.appliedChanges>0&&(ht.pulledActiveUpserts||ht.pulledArchivedUpserts))try{await Tr()}catch{ks("pull_local_refresh_failed",{workspaceId:n,appliedChanges:ht.appliedChanges})}tn(),is();const ds=ht.syncedAt||new Date().toISOString();if(Oe(ds),de(0),ae("idle"),I==="attach-cloud"&&(ca.current=!0,ft.current=""),await Tt({phase:"active",pullCursor:en.current,lastPullAt:ds,lastSyncedAt:ds,lastErrorMessage:null}),dn(n,{eventType:I==="attach-cloud"?"bootstrap":"pull",status:"success",changeCount:ht.appliedChanges,requestMs:ht.pullRequestMs,details:{pages:ht.pages,applyMs:ht.applyMs,...ht.serverDiagnostics?{serverPullDiagnostics:ht.serverDiagnostics}:{}}}),I==="attach-cloud")return await Zn(),await ga(),await qn(),await Ja(),Ms(),!0;const Kn=ft.current||ot();return Kn&&Kn!==Sn.current&&(ft.current="",window.setTimeout(()=>{ua(Kn)},120)),!0}catch(Re){const J=String(Re?.message||"").trim(),Be=J?`Workspace sync pull failed. ${J}`:"Workspace sync pull failed.";return ae("error"),Le(Be),y(Be),V(new Date().toISOString()),Q(),dn(n,{eventType:"pull",status:"error",errorMessage:Be,requestMs:Date.now()-Ue}),ks("pull_failed_exception",{workspaceId:n,elapsedMs:Date.now()-Ue,error:J||null}),!1}finally{Yt.current=!1,le($t.current),ka(n)}},[s,r,x,n,I,kt,l,X,is,or,h,Ve,ls,Tr,Zn,ga,qn,Ja,tn,Tt,dn,ot,ua,Ms,Q,ha,ka,cs,$t,Yt,Da]),Bs=a.useCallback(T=>{if(!s||r!=="local"||!x||I==="provision-local")return;const ge=String(T?.eventId||"").trim();ge&&Me.current.delete(ge)||Yt.current||(kt()&&tn(),je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{je.current=null,Qn()},180))},[s,r,x,I,kt,tn,Yt,Qn]),oo=w("/taskforce-ws"),Nr=String(i||"").trim(),Ut=Gf({enabled:!!(b&&s&&r==="local"&&x&&o&&l&&Nr&&Nr!=="anonymous"&&oo),workspaceId:n,websocketUrl:oo,onSignal:Bs,onTelemetry:ct,userId:Nr||void 0});a.useEffect(()=>{at(Ut.connectionState)},[Ut.connectionState]),a.useEffect(()=>()=>{je.current!==null&&(window.clearTimeout(je.current),je.current=null)},[]),a.useCallback(async()=>{const[T,ge]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(!T.ok||!ge.ok)return{tasks:[],archived:[],error:"Failed to read local workspace snapshot before sync bootstrap."};const Ue=await T.json().catch(()=>({})),Re=await ge.json().catch(()=>({}));return{tasks:Array.isArray(Ue?.tasks)?Ue.tasks:[],archived:Array.isArray(Re?.archived)?Re.archived:[]}},[]);const Pa=a.useCallback(async T=>Ia(T,{cloudAuthConfigured:s,isAuthenticated:l,ensureCloudWorkspaceReadyForSync:Ve}),[Ia,s,l,Ve]),Ca=a.useCallback(async()=>{await ba({preferCloudOnFirstSync:!1})},[ba]),ws=a.useCallback(async()=>{if(tn(),!s||r!=="local"||!x||!l&&!await X())return!1;if(Vt.current=!0,I==="provision-local"){const Re=ot();return Re?ua(Re,{forceAllAiProfiles:!0}):!1}const T=await Qn();if(I==="attach-cloud")return T;const ge=ot(),Ue=Vt.current===!0;if(!Ue&&_a(ge))return T;if(ge){ft.current=ge;const Re=await ua(ge,{forceAllAiProfiles:Ue});return T||Re}return T},[tn,s,r,x,l,X,I,ot,_a,ua,Qn]),ir=a.useCallback(async()=>{if(!await ha(n,"repair")&&(aa(n),!await ha(n,"repair"))){cs("repair");return}tn(),is(),An.current=null,Mt.current=null,en.current=null,Ya.current="",ca.current=!1,ft.current="",Sn.current="",on.current=new Map,jn.current=new Set,Vn.current=new Map,_n.current=new Set,$n.current=new Map,Wn.current=new Set,vn.current=new Map,cn.current=new Set,Rn.current=new Map,In.current=new Set,rt.current=new Map,wn.current=new Set,nn.current=new Map,Sa.current=new Set,Xn.current=new Map,Vt.current=!1,vs.current=!1,Rm(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:xe});try{if(!x)return;ss.current=!0;const ge=I==="provision-local"?"provision-local":I==="attach-cloud"?"attach-cloud":fa.current==="provision-local"||fa.current==="attach-cloud"?fa.current:Ce?"attach-cloud":"provision-local";if(await Tt({phase:ge,pullCursor:null,lastErrorMessage:null}),ge==="provision-local"){const Ue=ot();if(!Ue)return;await ua(Ue,{forceAllAiProfiles:!0,repairMode:!0});return}await Qn({repairMode:!0})}finally{ss.current=!1,ka(n)}},[ha,tn,is,n,aa,x,I,Tt,ot,Ce,Qn,ua,ka,cs]),Bo=a.useCallback(()=>({workspaceId:n,enabled:x,phase:I,status:va,summary:Un,lastSuccessfulSyncAt:la,lastPullAt:Ce,lastPushAt:R,lastErrorAt:F,pendingChanges:ne,lastErrorMessage:E,recommendedAction:wa,documentSnapshotCount:G.length,aiProfileSnapshotCount:d.length,aiProfileSnapshotRawCount:zt,aiProfileSnapshotLastFetchAt:Ye,aiProfileSnapshotLastFetchError:St,aiProfileSnapshotLastSkipReason:sn,assetSnapshotCount:gn.length,documentReviewSessionSnapshotCount:Tn.length,documentReviewSessionSnapshotFingerprint:we,annotatedAttachmentSessionSnapshotCount:He.length,annotatedAttachmentSessionSnapshotFingerprint:Y,lastPushedAiProfileCount:Wn.current.size,lastPushedAiProfileWatermarkCount:vn.current.size,forceFullAiProfilePushQueued:Vt.current===!0}),[n,x,I,va,Un,la,Ce,R,F,ne,E,wa,G.length,d.length,zt,Ye,St,sn,gn.length,Tn.length,we,He.length,Y]);return a.useEffect(()=>{Fe.current=ws},[ws]),a.useEffect(()=>{if(!s||r!=="local"||!x||!o||!l)return;Zn(),zn(),ga(),qn(),Ja();const T=ht=>{const Nt=ht.detail;(String(Nt?.workspaceId||"").trim()||"default")===n&&(Zn(),zn(),ga(),qn(),Ja())};window.addEventListener(Np,T);const ge=window.setInterval(()=>{Zn()},ln),Ue=window.setInterval(()=>{zn()},ln),Re=window.setInterval(()=>{ga()},ln),J=window.setInterval(()=>{qn()},ln),Be=window.setInterval(()=>{Ja()},ln);return()=>{window.removeEventListener(Np,T),window.clearInterval(ge),window.clearInterval(Ue),window.clearInterval(Re),window.clearInterval(J),window.clearInterval(Be)}},[s,r,x,o,l,n,Zn,zn,ga,qn,Ja,ln]),a.useEffect(()=>{!s||r!=="local"||!x||!o||!l||da&&(ga(),Zn(),zn(),qn(),Ja())},[s,r,x,o,l,da,ga,Zn,zn,qn,Ja]),a.useEffect(()=>{if(!s||r!=="local"||!x||!o||I==="attach-cloud"||!rn)return;const T=ot();if(_a(T)||!T||T===Sn.current)return;const ge=bt();if(de(ge.changes.length),$t.current||Yt.current){ft.current=T;return}const Ue=window.setTimeout(()=>{ua(T)},1500);return()=>window.clearTimeout(Ue)},[s,r,x,o,I,rn,ot,_a,bt,gt,be,un,we,Y,ua,$t,Yt]),a.useEffect(()=>{s&&r==="local"&&x||(tn(),le(!1))},[s,r,x,tn]),a.useEffect(()=>{if(!s||r!=="local"||!x||!o||I==="provision-local"||kt())return;Qn();const T=window.setInterval(()=>{Qn()},rr);return()=>window.clearInterval(T)},[s,r,x,o,I,kt,Qn,rr]),a.useEffect(()=>{r!=="local"||!l||!i||i==="anonymous"||ba({preferCloudOnFirstSync:!0})},[r,l,i,ba]),a.useEffect(()=>{if(r!=="local"||!l||!i||i==="anonymous"||!Et.current.has(i)||xt.current)return;const T=sa(),ge=JSON.stringify(T);if(!xn.current){xn.current=ge;return}if(ge===xn.current)return;xn.current=ge,rs(i,new Date().toISOString());const Ue=window.setTimeout(()=>{ba({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(Ue)},[r,l,i,sa,rs,ba]),a.useEffect(()=>{!s||r!=="local"||!x||!o||!l||I==="provision-local"||I==="attach-cloud"||vs.current||(vs.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 T=>{if(!T.ok)return;const ge=await T.json().catch(()=>({}));ge?.applied>0&&(ks("startup_repair_applied",{workspaceId:n,applied:ge.applied,skipped:ge.skipped,failed:ge.failed}),Zn(),zn(),ga(),qn())}).catch(()=>{}))},[s,r,x,o,l,I,n,Zn,zn,ga,qn]),{userGlobalSyncStatus:ie,setUserGlobalSyncStatus:ae,userGlobalSyncError:Ze,setUserGlobalSyncError:Le,workspaceLastPullAt:Ce,workspaceLastPushAt:R,workspaceLastErrorAt:F,workspaceLastErrorMessage:E,workspaceLastSuccessfulSyncAt:la,workspaceCloudSyncEnabled:x,workspaceSyncPhase:I,workspaceSyncStatus:va,workspaceSyncSummary:Un,workspaceSyncRecommendedAction:wa,workspaceSyncBusy:L,workspaceSyncPendingChanges:ne,syncInFlightRef:se,workspaceRetryAt:Kt,isWorkspaceRetryPending:kt,workspacePushInFlightRef:$t,workspacePullInFlightRef:Yt,workspaceLastPushedSignatureRef:Sn,workspacePendingSignatureRef:ft,workspaceLastPushedTaskIdsRef:mt,workspaceDeletedTaskIdsRef:oa,workspacePullCursorRef:en,clearWorkspaceRetry:tn,persistWorkspaceSyncPatch:Tt,loadWorkspaceSyncState:ia,applyWorkspaceSyncStateSnapshot:ya,syncUserGlobalSettings:ba,buildWorkspaceSyncSignature:ot,pushWorkspaceChangesToCloud:ua,pullWorkspaceChangesFromCloud:Qn,saveWorkspaceCloudSyncSettings:Pa,retryUserGlobalSettingsSync:Ca,retryWorkspaceCloudSync:ws,resetWorkspaceSyncCursorAndPull:ir,getWorkspaceSyncDiagnostics:Bo}}function Ok(e,n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:e==="error"?3600:2600}function $k(){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,i="info",p)=>{if(!l)return;s.current!==null&&(window.clearTimeout(s.current),s.current=null),n({message:l,tone:i,ttlMs:p});const h=Ok(i,p);s.current=window.setTimeout(()=>{s.current=null,n(null)},h)},[]);return a.useEffect(()=>()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null)},[]),{uiNotice:e,pushNotice:o,clearNotice:r}}function Uk({storagePath:e}){const[n,s]=a.useState("antigravity"),[r,o]=a.useState([]),[l,i]=a.useState(".agent/workflows"),[p,h]=a.useState(null),[w,b]=a.useState(null),_=a.useRef(null);a.useEffect(()=>{const M=r.find(S=>S.id===n);M&&i(M.directory)},[n,r]);const k=a.useCallback(()=>{typeof window>"u"||(_.current!==null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{_.current=null,b(null)},5e3))},[]),g=a.useCallback(async()=>{const M=await fetch("/api/taskforce/environments");if(!M.ok)return;const S=await M.json().catch(()=>({}));S.environments&&o(S.environments)},[]),C=a.useCallback(async(M,S)=>{h("workflows"),b(null);try{const Z=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:M,workflowNames:S,variables:{STORAGE_PATH:e.replace(/\/$/,"")||".Taskforce"}})})).json();Z.success?b({type:"success",message:`Successfully exported ${Z.count} workflows to ${M}`}):b({type:"error",message:Z.error||"Export failed"})}catch{b({type:"error",message:"Network error exporting workflows"})}finally{h(null),k()}},[k,e]);return a.useEffect(()=>()=>{_.current!==null&&typeof window<"u"&&(window.clearTimeout(_.current),_.current=null)},[]),{exportEnvironment:n,setExportEnvironment:s,availableEnvironments:r,loadAvailableEnvironments:g,exportWorkflowsPath:l,setExportWorkflowsPath:i,exportingResource:p,exportResult:w,handleExportWorkflows:C}}function zk(e){const{resolveCloudAuthUrl:n,currentWorkspaceId:s,normalizedCloudAuthBaseUrl:r,normalizedCloudMcpBaseUrl:o,mergedConfig:l,availableWorkspaces:i,currentTheme:p,configLoaded:h,globalTheme:w,themeUseGlobalDefault:b,keyShortcut:_,jsonBackupEnabled:k,globalJsonBackupEnabled:g,globalWeekStartsOn:C,locale:M,supportedLocales:S,jsonBackupUseGlobalDefault:P,manualComplexityEnabled:Z,checklistDropdownEnabled:$,showTaskCardStatusLabel:ce,exportWorkflowsPath:q,exportingResource:K,exportResult:j,pathSaved:ye,settingsSection:U,exportEnvironment:X,setupState:Ne,buildInfo:pe,saveSetupMode:te,saveWorkspaceProfile:D,setCurrentTheme:B,handleSaveTheme:oe,handleSaveGlobalTheme:xe,setKeyShortcut:ie,handleJsonBackupEnabledChange:ae,handleSaveGlobalJsonBackupEnabled:Ze,handleSaveGlobalWeekStartsOn:Le,handleSaveLocale:Ce,handleManualComplexityEnabledChange:Oe,handleChecklistDropdownEnabledChange:R,handleShowTaskCardStatusLabelChange:W,handleResetProjectToGlobal:F,handleSaveSettings:V,setExportWorkflowsPath:E,setExportEnvironment:y,availableWorkflows:x,initiativeTemplates:H,availableEnvironments:I,fetchWorkflows:Ie,fetchInitiativeTemplates:L,createInitiativeFromTemplate:le,fetchWorkflowTemplate:ne,fetchWorkflowOverrideNames:de,saveWorkflowTemplateDraft:G,resetWorkflowTemplateDraft:ee,handleExportWorkflows:be,setShowFolderBrowser:$e,setBrowserTarget:fe,fetchFolders:De,activeCategories:Ke,pathValidation:nt,taxonomyDisplayLabels:dt,handleUpdateCategory:d,handleRemoveCategory:et,handleSaveCategory:gt,handleAddPath:O,handleRemovePath:Ye,handleUpdateCategoryIcon:wt,handleUpdateCategoryColor:St,activeTypes:At,handleSaveType:zt,handleRemoveType:Ht,handleUpdateType:sn,taxonomies:Jt,handleUpdateTaxonomies:Xt,priorities:gn,handleUpdatePriorities:Mn,analyzeSystemTaxonomyPack:un,handleApplySystemTaxonomyPack:yn,handleUpdateTaxonomyDisplayLabels:an,projectRoot:Tn,projectName:Rt,mcpHostRoot:we,serverHostRoot:Lt,mcpScriptPath:Qt,tenantId:Dt,runtimeMode:He,workspaceSwitchingEnabled:Nn,deleteWorkspace:Y,setMcpHostRoot:Ae,isAuthenticated:_e}=e,Pe=a.useCallback(async(Je,at)=>{const Xe=n(Je),ct=new Headers(at?.headers||void 0);if(Je.startsWith("/api/taskforce/settings/mcp/")){const Ot=String(s||"").trim();Ot&&Ot!=="default"&&!ct.has("x-taskforce-workspace-id")&&ct.set("x-taskforce-workspace-id",Ot)}const vt={...at,headers:ct,credentials:at?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(Xe))try{new URL(Xe,window.location.origin).origin!==window.location.origin&&vt.mode===void 0&&(vt.mode="cors")}catch{}return fetch(Xe,vt)},[s,n]),qe=i.find(Je=>Je.id===s);return{fetchCloudAuthApi:Pe,currentTheme:p,configLoaded:h,globalTheme:w,themeUseGlobalDefault:b,keyShortcut:_,jsonBackupEnabled:k,globalJsonBackupEnabled:g,globalWeekStartsOn:C,locale:M,supportedLocales:S,jsonBackupUseGlobalDefault:P,manualComplexityEnabled:Z,checklistDropdownEnabled:$,showTaskCardStatusLabel:ce,exportWorkflowsPath:q,exportingResource:K,exportResult:j,pathSaved:ye,initialSection:U,exportEnvironment:X,setupState:Ne,buildInfo:pe,onSaveSetupMode:te,onSaveWorkspaceProfile:D,onThemeChange:B,onSaveTheme:oe,onSaveGlobalTheme:xe,onKeyShortcutChange:ie,onJsonBackupEnabledChange:ae,onSaveGlobalJsonBackupEnabled:Ze,onSaveGlobalWeekStartsOn:Le,onSaveLocale:Ce,onManualComplexityEnabledChange:Oe,onChecklistDropdownEnabledChange:R,onShowTaskCardStatusLabelChange:W,onResetProjectToGlobal:F,onSaveSettings:V,onExportWorkflowsPathChange:E,onExportEnvironmentChange:y,availableWorkflows:x,initiativeTemplates:H,availableEnvironments:I,onRefreshWorkflows:Ie,onRefreshInitiativeTemplates:L,onCreateInitiativeFromTemplate:le,onFetchWorkflowTemplate:ne,onFetchWorkflowOverrideNames:de,onSaveWorkflowTemplateDraft:G,onResetWorkflowTemplateDraft:ee,onExportWorkflows:be,onShowFolderBrowserChange:$e,onBrowserTargetChange:fe,onFetchFolders:De,categories:Ke,pathValidation:nt,taxonomyDisplayLabels:dt,onUpdateCategory:d,onRemoveCategory:et,onSaveCategory:gt,onAddPath:O,onRemovePath:Ye,onUpdateCategoryIcon:wt,onUpdateCategoryColor:St,types:At,onSaveType:zt,onRemoveType:Ht,onUpdateType:sn,taxonomies:Jt,onUpdateTaxonomies:Xt,priorities:gn,onUpdatePriorities:Mn,onAnalyzeSystemTaxonomyPack:un,onApplySystemTaxonomyPack:yn,onUpdateTaxonomyDisplayLabels:an,projectRoot:Tn,projectName:Rt,mcpHostRoot:we,serverHostRoot:Lt,mcpScriptPath:Qt,tenantId:Dt,workspaceId:s,runtimeMode:He,cloudAuthBaseUrl:r||l.cloudAuthBaseUrl,cloudMcpBaseUrl:o||void 0,workspaceSwitchingEnabled:Nn,currentWorkspaceRole:qe?.role||"member",currentWorkspaceName:String(qe?.name||""),onDeleteWorkspace:Y,onMcpHostRootChange:Ae,isAuthenticated:_e}}function Hk(e){const{keyShortcut:n,themeUseGlobalDefault:s,runtimeMode:r,jsonBackupUseGlobalDefault:o,globalTheme:l,globalJsonBackupEnabled:i,setCurrentTheme:p,setThemeUseGlobalDefault:h,setGlobalTheme:w,setJsonBackupEnabled:b,setJsonBackupUseGlobalDefault:_,setGlobalJsonBackupEnabled:k,setGlobalWeekStartsOn:g,setLocale:C,setManualComplexityEnabled:M,setChecklistDropdownEnabled:S,setShowTaskCardStatusLabel:P,setShowChecklist:Z}=e,$=a.useCallback(async()=>{try{const D=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:n})});if(!D.ok)throw new Error(`Failed to save global settings (${D.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[n]),ce=a.useCallback(async D=>{p(D),h(!1);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:D})});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,h]),q=a.useCallback(async D=>{w(D),s&&p(D);try{const B=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:D})});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]),K=a.useCallback(async D=>{if(r==="cloud")return b(!1),_(!1),!1;b(D),_(!1);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:D})});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,b,_]),j=a.useCallback(async D=>{if(r==="cloud")return k(!1),o&&b(!1),!1;k(D),o&&b(D);try{const B=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:D})});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,k,o,b]),ye=a.useCallback(async D=>{g(D);try{const B=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:D}})});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}},[g]),U=a.useCallback(async D=>{const B=Rf(D);return C(B),!0},[C]),X=a.useCallback(async D=>{M(D);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:D})});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}},[M]),Ne=a.useCallback(async D=>{S(D),D||Z(!1);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:D})});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,Z]),pe=a.useCallback(async D=>{P(D);try{const B=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:D})});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}},[P]),te=a.useCallback(async()=>{h(!0),_(!0),p(l),b(i),M(!1),S(!0),P(!0),Z(!1);try{const D=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(!D.ok)throw new Error(`Failed to save config (${D.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[h,_,p,l,b,i,M,S,P,Z]);return{handleSaveSettings:$,handleSaveTheme:ce,handleSaveGlobalTheme:q,handleJsonBackupEnabledChange:K,handleSaveGlobalJsonBackupEnabled:j,handleSaveGlobalWeekStartsOn:ye,handleSaveLocale:U,handleManualComplexityEnabledChange:X,handleChecklistDropdownEnabledChange:Ne,handleShowTaskCardStatusLabelChange:pe,handleResetProjectToGlobal:te}}function Gk(e){const{activeCategories:n,activeTab:s,activeTypes:r,archivedTasks:o,browserTarget:l,category:i,configLoaded:p,customCategories:h,refreshTaskCollections:w,fetchTasks:b,filterCategories:_,getCategoryPaths:k,normalizePath:g,pathValidation:C,setBrowserTarget:M,setCategory:S,setCustomCategories:P,setCustomTypes:Z,setFilterCategories:$,setPathValidation:ce,setPriorities:q,setShowFolderBrowser:K,setTaxonomies:j,tasks:ye}=e,U=a.useCallback(async(E,y)=>{const x=await E.json().catch(()=>({}));return String(x?.error||y)},[]),X=a.useCallback(()=>[...ye,...o],[o,ye]),Ne=a.useCallback(E=>E.priorities.find(y=>y.value===2)?.value||E.priorities[0]?.value||2,[]),pe=a.useCallback(async E=>{if(E.length!==0)try{const y=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:E})});if(y.ok){const x=await y.json();ce(H=>({...H,...x.results}))}}catch(y){console.error("[Taskforce] Failed to validate paths:",y)}},[ce]);a.useEffect(()=>{if(s!=="settings"||!p)return;const E=[];n.forEach(x=>{k(x).forEach(I=>{E.includes(I)||E.push(I)})});const y=E.filter(x=>!C[x]);y.length>0&&pe(y)},[n,s,p,k,C,pe]);const te=a.useCallback(async(E,y)=>{if(p){P(x=>(x.length>0?x:n).map(I=>I.value===E.value?E:I)),y&&y!==E.label&&(i===y&&S(E.label),_.includes(y)&&$(x=>x.map(H=>H===y?E.label:H)));try{const I={categories:(h.length>0?h:n).map(Ie=>Ie.value===E.value?E:Ie)};y&&y!==E.label&&(I.reassignFrom=y,I.reassignTo=E.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)}),y&&await b()}catch(x){console.error("[Taskforce] Failed to update category",x)}}},[n,i,p,h,b,_,S,P,$]),D=a.useCallback(async E=>{if(!p)return;const y=E.trim().toLowerCase().replace(/\s+/g,"-");if(n.some(H=>H.value===y))return;const x={value:y,label:E.trim(),color:"blue-200",icon:"Folder"};P(H=>[...H.length>0?H:n,x]);try{const I=[...h.length>0?h:n,x];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:I})})}catch(H){console.error("[Taskforce] Failed to create category",H)}},[n,p,h,P]),B=a.useCallback((E,y)=>{if(!y.trim())return;const x=n.find(L=>L.value===E);if(!x)return;const H=k(x),I=y.trim();if(H.includes(I))return;const Ie=[...H,I];te({...x,path:void 0,paths:Ie}),pe(Ie)},[n,k,te,pe]),oe=a.useCallback((E,y)=>{const x=n.find(H=>H.value===E);x&&te({...x,icon:y})},[n,te]),xe=a.useCallback((E,y)=>{const x=n.find(H=>H.value===E);x&&te({...x,color:y})},[n,te]),ie=a.useCallback((E,y)=>{const x=n.find(Ie=>Ie.value===E);if(!x)return;const I=k(x).filter(Ie=>Ie!==y);te({...x,path:void 0,paths:I})},[n,k,te]),ae=a.useCallback(E=>{const y=g(E);if(l&&typeof l=="object"&&l.type==="category"){const x=n.find(H=>H.value===l.value);if(x){const H=k(x);if(!H.includes(y)){const I=[...H,y];te({...x,path:void 0,paths:I})}}}K(!1),M(null)},[n,l,k,te,g,M,K]),Ze=a.useCallback(async E=>{if(!p)return;const y=jc,x=n.find(L=>L.value===y),H=x?{...x}:{value:y,label:Su,icon:"Inbox"},I=H.label,Ie=n.find(L=>L.value===E);P(L=>{let ne=(L.length>0?L:n).filter(de=>de.value!==E);return ne.some(de=>de.value===y)||(ne=[H,...ne]),ne}),Ie&&((i===Ie.label||i===Ie.value)&&S(y),(_.includes(Ie.label)||_.includes(Ie.value))&&$(L=>{const le=L.filter(ne=>ne!==Ie.label&&ne!==Ie.value);return le.includes(y)?le:[...le,y]}));try{let L=(h.length>0?h:n).filter(le=>le.value!==E);L.some(le=>le.value===y)||(L=[H,...L]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:L,reassignFrom:Ie?.label||E,reassignTo:I})}),await b()}catch(L){console.error("[Taskforce] Failed to remove category",L)}},[n,i,p,h,b,_,S,P,$]),Le=a.useCallback(async E=>{if(!E.trim())return;const y=E.trim().toLowerCase().replace(/\s+/g,"-");if(r.some(H=>H.value===y))return;const x=[...r,{value:y,label:E.trim(),status:"active"}];Z(x);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:x})})}catch(H){console.error("Failed to save type",H)}},[r,Z]),Ce=a.useCallback(async E=>{const y=r.map(x=>x.value===E?{...x,status:"retired"}:x);Z(y);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:y})}),await b()}catch(x){console.error("Failed to save type",x)}},[r,b,Z]),Oe=a.useCallback(async(E,y)=>{const x=r.find(L=>L.value===E);if(!x)return;const H=typeof y.label=="string"?y.label.trim():x.label;if(!H)return;const I=r.map(L=>L.value===E?{...L,...y,label:H}:L);if(JSON.stringify(I)!==JSON.stringify(r)){Z(I);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:I})})}catch(L){console.error("Failed to update type",L)}}},[r,Z]),R=a.useCallback(async E=>{if(p){j(E);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:E})})}catch(y){console.error("[Taskforce] Failed to save taxonomies",y)}}},[p,j]),W=a.useCallback(async E=>{if(p){q(E);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:E})})}catch(y){console.error("[Taskforce] Failed to save priorities",y)}}},[p,q]),F=a.useCallback(E=>{const y=X(),x=new Set(E.categories.map(ne=>ne.value)),H=new Set(E.types.map(ne=>ne.value)),I=new Set(E.priorities.map(ne=>Number(ne.value))),Ie=Array.from(new Set(y.map(ne=>String(ne.category||"").trim()).filter(ne=>ne.length>0&&!x.has(ne)))).sort(),L=Array.from(new Set(y.map(ne=>String(ne.type||"").trim()).filter(ne=>ne.length>0&&!H.has(ne)))).sort(),le=Array.from(new Set(y.map(ne=>Number(ne.priority)).filter(ne=>Number.isFinite(ne)&&ne>0&&!I.has(ne)))).sort((ne,de)=>ne-de);return{unmatchedCategoryValues:Ie,unmatchedTypeValues:L,incompatiblePriorityValues:le}},[X]),V=a.useCallback(async E=>{if(!p)return{success:!1,error:"Settings are still loading."};const{pack:y,sections:x,remapExistingValuesToDefault:H,workspaceIdOverride:I}=E,Ie=String(I||"").trim(),L=Ie.length>0,le=L?[]:X(),ne=G=>{if(!Ie)return G;const ee=G.includes("?")?"&":"?";return`${G}${ee}workspaceId=${encodeURIComponent(Ie)}`},de=()=>{const G={"Content-Type":"application/json"};return Ie&&(G["x-taskforce-workspace-id"]=Ie),G};try{if(x.categories){const G=new Set(y.categories.map($e=>$e.value)),ee=H?[...y.categories]:[...y.categories,...n.filter($e=>!G.has($e.value)).map($e=>({...$e,disabled:!0}))];L||P(ee);const be=await fetch(ne("/api/taskforce/categories"),{method:"POST",headers:de(),body:JSON.stringify({categories:ee})});if(!be.ok)return{success:!1,error:await U(be,"Failed to apply category library pack.")}}if(x.types){const G=new Set(y.types.map(fe=>fe.value)),ee=y.types.find(fe=>fe.value===Ss)?.value||y.types[0]?.value||Ss;if(H){const fe=le.filter(De=>De.type&&!G.has(String(De.type))).map(De=>({id:De.id,type:ee}));if(fe.length>0){const De=await fetch(ne("/api/taskforce/bulk-update-fields"),{method:"POST",headers:de(),body:JSON.stringify({updates:fe})});if(!De.ok)return{success:!1,error:await U(De,"Failed to remap task types to the pack default.")}}}const be=H?[...y.types]:[...y.types,...r.filter(fe=>!G.has(fe.value)).map(fe=>({...fe,status:"retired"}))];L||Z(be);const $e=await fetch(ne("/api/taskforce/types"),{method:"POST",headers:de(),body:JSON.stringify({types:be})});if(!$e.ok)return{success:!1,error:await U($e,"Failed to apply task type library pack.")}}if(x.priorities){const G=new Set(y.priorities.map(fe=>fe.value)),ee=Array.from(new Set(le.map(fe=>Number(fe.priority)).filter(fe=>Number.isFinite(fe)&&fe>0&&!G.has(fe)))).sort((fe,De)=>fe-De);if(ee.length>0&&!H)return{success:!1,error:`This workspace still uses priority levels ${ee.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(ee.length>0){const fe=Ne(y),De=le.filter(Ke=>ee.includes(Number(Ke.priority))).map(Ke=>({id:Ke.id,priority:fe}));if(De.length>0){const Ke=await fetch(ne("/api/taskforce/bulk-update-fields"),{method:"POST",headers:de(),body:JSON.stringify({updates:De})});if(!Ke.ok)return{success:!1,error:await U(Ke,"Failed to remap task priorities to the pack default.")}}}const be=y.priorities.map(fe=>({...fe,value:Number(fe.value)}));L||q(be);const $e=await fetch(ne("/api/taskforce/priorities"),{method:"POST",headers:de(),body:JSON.stringify({priorities:be})});if(!$e.ok)return{success:!1,error:await U($e,"Failed to apply priority library pack.")}}return L||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,X,Ne,U,w,P,Z,q]);return{getCategoryPaths:k,validatePaths:pe,handleUpdateCategory:te,handleSaveCategory:D,handleAddPath:B,handleUpdateCategoryIcon:oe,handleUpdateCategoryColor:xe,handleRemovePath:ie,handleSelectPath:ae,handleRemoveCategory:Ze,handleSaveType:Le,handleRemoveType:Ce,handleUpdateType:Oe,handleUpdateTaxonomies:R,handleUpdatePriorities:W,analyzeSystemTaxonomyPack:F,handleApplySystemTaxonomyPack:V}}function Vk({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:n}){const[s,r]=a.useState([]),[o,l]=a.useState([]),i=a.useCallback(async()=>{if(!(e||n))try{const k=await fetch("/api/taskforce/workflow-templates");if(k.ok){const g=await k.json();r(g.templates||[])}}catch{}},[e,n]),p=a.useCallback(async()=>{try{const k=await fetch("/api/taskforce/initiative-templates");if(!k.ok)return[];const g=await k.json(),C=Array.isArray(g?.templates)?g.templates:[];return l(C),C}catch{return[]}},[]),h=a.useCallback(async k=>{if(!k)return null;const g=[`/api/taskforce/workflow-template/${encodeURIComponent(k)}`,`/api/taskforce/workflow-templates/${encodeURIComponent(k)}`];try{for(const C of g){const M=await fetch(C);if(!M.ok)continue;const S=await M.json();if(S?.template)return S.template}return null}catch{return null}},[]),w=a.useCallback(async()=>{try{const k=await fetch("/api/taskforce/workflow-editor/overrides");if(!k.ok)return[];const g=await k.json();return Array.isArray(g?.names)?g.names:[]}catch{return[]}},[]),b=a.useCallback(async(k,g)=>{try{const C=await fetch("/api/taskforce/workflow-editor/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:k,draft:g})}),M=await C.json().catch(()=>({}));return!C.ok||!M.success?{success:!1,error:M.error||`Save failed (${C.status})`}:(i(),{success:!0})}catch(C){return{success:!1,error:C.message}}},[i]),_=a.useCallback(async k=>{try{const g=await fetch(`/api/taskforce/workflow-editor/reset/${encodeURIComponent(k)}`,{method:"POST"}),C=await g.json().catch(()=>({}));return!g.ok||!C.success?{success:!1,error:C.error||`Reset failed (${g.status})`}:(i(),{success:!0})}catch(g){return{success:!1,error:g.message}}},[i]);return{availableWorkflows:s,initiativeTemplates:o,fetchWorkflows:i,fetchInitiativeTemplates:p,fetchWorkflowTemplate:h,fetchWorkflowOverrideNames:w,saveWorkflowTemplateDraft:b,resetWorkflowTemplateDraft:_}}function Zk(){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 qk(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 Kk({tasks:e,archivedTasks:n,setTasks:s,setArchivedTasks:r,setLoadingTasks:o,getCurrentWorkspaceId:l,workspaceResetKey:i,shouldDeferProtectedApiCalls:p,shouldBlockProtectedApiCalls:h,handleUnauthorized:w,authRequiredForApi:b}){const _=a.useRef(new Map),k=a.useRef(!1),g=a.useRef([]),C=a.useRef([]),M=a.useRef(!1),S=a.useRef(!1),P=a.useRef(null),Z=a.useRef(null);a.useEffect(()=>{g.current=e},[e]),a.useEffect(()=>{C.current=n},[n]);const $=a.useCallback(D=>`${D.updatedAt||D.createdAt||""}|${D.status}|${D.priority}|${D.title}`,[]),ce=a.useCallback((D,B)=>B.aborted?D===B.reason?!0:D instanceof DOMException?D.name==="AbortError":String(D?.name||"").toLowerCase()==="aborterror":!1,[]),[q,K]=a.useState([]),j=a.useRef(new Map),ye=a.useCallback(D=>{!D.length||typeof window>"u"||(K(B=>Array.from(new Set([...B,...D]))),D.forEach(B=>{const oe=j.current.get(B);oe&&window.clearTimeout(oe);const xe=window.setTimeout(()=>{j.current.delete(B),K(ie=>ie.filter(ae=>ae!==B))},4e3);j.current.set(B,xe)}))},[]);a.useEffect(()=>()=>{typeof window>"u"||(j.current.forEach(D=>window.clearTimeout(D)),j.current.clear())},[]),a.useEffect(()=>{_.current=new Map,k.current=!1,M.current=!1,S.current=!1,P.current?.abort("workspace-reset"),P.current=null,Z.current?.abort("workspace-reset"),Z.current=null,typeof window<"u"&&(j.current.forEach(D=>window.clearTimeout(D)),j.current.clear()),K([])},[i]);const U=a.useCallback(async(D=!1,B)=>{if(!(B?.ignoreAuthGuard===!0)&&(p||h))return;D||o(!0);const xe=String(l()||"").trim();P.current?.abort("superseded");const ie=new AbortController;P.current=ie;try{const ae=await fetch("/api/taskforce/tasks",{signal:ie.signal});if(ae.status===401){w(),s([]),D||o(!1);return}if(ae.ok){const Le=((await ae.json()).tasks||[]).map(W=>so(W));if(String(l()||"").trim()!==xe)return;const Oe=new Map,R=[];for(const W of Le){const F=$(W);if(Oe.set(W.id,F),!k.current)continue;const V=_.current.get(W.id);(!V||V!==F)&&R.push(W.id)}_.current=Oe,k.current?ye(R):k.current=!0,s(Le)}}catch(ae){if(ce(ae,ie.signal))return;console.error("[Taskforce] Failed to fetch tasks:",ae)}finally{const ae=P.current===ie;ae&&(P.current=null),!D&&ae&&o(!1)}},[$,l,ye,w,s,o,b,p,h]),X=a.useCallback(async(D=!1,B)=>{if(!(B?.ignoreAuthGuard===!0)&&(p||h))return;const xe=String(l()||"").trim();Z.current?.abort("superseded");const ie=new AbortController;Z.current=ie;try{const ae=await fetch("/api/taskforce/archive",{signal:ie.signal});if(ae.ok){const Ze=await ae.json();if(String(l()||"").trim()!==xe)return;const Ce=(Ze.archived||[]).map(Oe=>({...so(Oe),isArchived:!0}));r(Ce)}}catch(ae){if(ce(ae,ie.signal))return;console.error("[Taskforce] Failed to fetch archive:",ae)}finally{Z.current===ie&&(Z.current=null)}},[l,ce,r,p,h]),Ne=a.useCallback(async D=>{const B=D?.isSilent!==!1,oe=D?.ignoreAuthGuard===!0;await Promise.all([U(B,{ignoreAuthGuard:oe}),X(B,{ignoreAuthGuard:oe})])},[X,U]),pe=a.useCallback(async()=>{await qk(M,S,async()=>{await Ne({isSilent:!0})})},[Ne]),te=a.useCallback(D=>{const B=sy(D,g.current,C.current);g.current=B.tasks,C.current=B.archivedTasks,s(B.tasks),r(B.archivedTasks)},[s,r]);return{tasksRef:g,archivedTasksRef:C,recentlyChangedTaskIds:q,markRecentlyChangedTasks:ye,fetchTasks:U,fetchArchive:X,refreshTaskCollections:Ne,refreshTaskCollectionsFromInvalidation:pe,mergeTaskFromServer:te,getTaskRevisionKey:$}}function Yk(e){const{editingTaskId:n,relationshipTasks:s,initiatives:r=[],workstreams:o=[],supplementalTasks:l=[],setComments:i}=e,p=a.useMemo(()=>{if(l.length===0)return s;const _=new Map;return s.forEach(k=>_.set(k.id,k)),l.forEach(k=>_.set(k.id,k)),Array.from(_.values())},[s,l]),h=a.useMemo(()=>{if(n)return p.find(_=>_.id===n)},[p,n]);a.useEffect(()=>{n&&i(h?.comments||[])},[n,h?.id,h?.updatedAt,h?.comments,i]);const w=a.useMemo(()=>{if(h?.workstreamId)return o.find(_=>_.id===h.workstreamId)},[h,o]),b=a.useMemo(()=>{if(w?.initiativeId)return r.find(_=>_.id===w.initiativeId)},[w,r]);return{currentTask:h,currentTaskWorkstream:w,currentTaskInitiative:b}}const Hp="WS-",Gp="IN-";function eo(e){return Ec(Hp,e)}function qf(e){return Bp(Hp,e)}function Vp(e){return Yl(Hp,e)}function ar(e){return Ec(Gp,e)}function Jk(e){return Bp(Gp,e)}function Xk(e){return Yl(Gp,e)}function dp(e,n){const s=String(n||"").trim();if(!s)return null;const r=Jk(s);return e.find(o=>o.id===s||ar(o)===s||r!==null&&o.referenceNumber===r)||null}function Qk(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 eS(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 tS(e){const{activeCategories:n,activeTypes:s,activeTab:r,attachments:o,checklistItems:l,comments:i,description:p,editingTaskId:h,flushPendingAutoSave:w,getPreferredCategoryValue:b,lastUsedCategory:_,newCommentText:k,relationshipTasks:g,workstreams:C,showArchive:M,taxonomies:S,setActiveTab:P,setApproach:Z,setAssignee:$,setAttachments:ce,setAttachmentsDirty:q,setCategory:K,setChecklistItems:j,setComments:ye,setComplexity:U,setDescription:X,setDueDate:Ne,setEditingTaskId:pe,setError:te,setFormTaxonomies:D,setIsOpen:B,setNewCommentText:oe,setPendingNavigation:xe,setWorkstreamInput:ie,setPriority:ae,setScheduledDate:Ze,setShowArchive:Le,setStatus:Ce,setTaskReturnTrail:Oe,setTitle:R,setType:W,setUnsavedModalOpen:F,taskReturnTrail:V,title:E}=e,y=a.useCallback(()=>s.find(ee=>String(ee.value||"").trim().length>0)?.value||Ss,[s]),x=a.useCallback(ee=>{if(h){w(),ee();return}if(!(E.trim()!==""||p.trim()!==""||l.length>0||k.trim()!==""||i.length>0||o.length>0)){ee();return}xe(()=>ee),F(!0)},[o,i.length,p,h,w,l,k,xe,F,E]),H=a.useCallback(()=>{B(!1)},[B]),I=a.useCallback(()=>{pe(null),R(""),X("");const ee=_,be=n.some($e=>$e.label===ee||$e.value===ee);if(ee&&be){const $e=n.find(fe=>fe.label===ee||fe.value===ee);K($e?.value||ee)}else K(b(n));W(y()),ae(2),U(3),Ce("task"),Z("default"),$("unassigned"),Ze(""),Ne(""),ie(""),j([]),D(Qk(S)),ye([]),oe(""),ce([]),q(!1),te("")},[n,b,y,_,Z,$,ce,q,K,j,ye,U,X,Ne,pe,te,D,oe,ae,Ze,Ce,R,W,S]),Ie=a.useCallback(ee=>{const be=ee.trim();if(!be)return null;const $e=xf(be);if($e){const Ke=g.find(nt=>nt.referenceNumber===$e);if(Ke)return Ke}const fe=g.find(Ke=>Ke.id===be);if(fe)return fe;const De=g.find(Ke=>Ar(Ke)===be);return De||null},[g]),L=a.useCallback(ee=>{const be=ee.trim();if(!be)return null;const $e=be.toLowerCase(),fe=qf(be);if(fe){const nt=C.find(dt=>dt.referenceNumber===fe);if(nt)return nt}const De=C.find(nt=>nt.id===be);if(De)return De;const Ke=C.find(nt=>nt.title.trim().toLowerCase()===$e);return Ke||null},[C]),le=a.useCallback((ee,be)=>{be?.preserveReturnTrail||Oe([]),pe(ee.id),R(ee.title),X(ee.description||""),K(ee.category||b(n)),W(ee.type||y()),ae(typeof ee.priority=="number"?ee.priority:2),U(typeof ee.complexity=="number"?ee.complexity:3),Ce(ee.status||"task"),Z(ee.approach||"default"),$(ee.assignee||"unassigned"),Ze(ee.scheduledDate||""),Ne(ee.dueDate||"");const $e=ee.workstreamId&&C.find(fe=>fe.id===ee.workstreamId)||null;ie($e?eo($e)||$e.id:""),j(ee.checklistItems||[]),ye(ee.comments||[]),D(ee.taxonomies||{}),ee.taxonomies?.approach&&Z(ee.taxonomies.approach),ce(ee.attachments||[]),q(!1),P("add")},[n,b,y,P,Z,$,ce,q,K,j,ye,U,X,Ne,pe,D,ae,Ze,Ce,Oe,R,W,C]),ne=a.useCallback(ee=>{const be=g.find($e=>$e.id===ee);be&&(r==="add"&&h&&h!==be.id&&Oe($e=>$e[$e.length-1]===h?$e:[...$e,h]),be.isArchived&&!M&&Le(!0),le(be,{preserveReturnTrail:!0}))},[r,h,le,g,Le,Oe,M]),de=a.useCallback(()=>{if(r!=="add"||!h||V.length===0)return!1;const ee=[...V];for(;ee.length>0;){const be=ee.pop();if(!be)continue;const $e=g.find(fe=>fe.id===be);if($e)return $e.isArchived&&!M&&Le(!0),Oe(ee),le($e,{preserveReturnTrail:!0}),!0}return Oe([]),!1},[r,h,le,g,Le,Oe,M,V]),G=a.useCallback(()=>{Oe([])},[Oe]);return{handleNavigation:x,handleClose:H,resetForm:I,resolveTaskIdInput:Ie,resolveWorkstreamIdInput:L,handleEdit:le,handleOpenTaskById:ne,returnToPreviousTask:de,clearReturnToParentTask:G}}function nS(e){return e.map(n=>({...n}))}function aS(e){return e.map(n=>({...n}))}function sS(e){return e.map(n=>({...n}))}const rS={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"}]},oS=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",isDefaultStarter:!0,categories:[{value:jc,label:Su,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"}]},rS];function Kf(){return oS.map(e=>({...e,categories:nS(e.categories),types:aS(e.types),priorities:sS(e.priorities)}))}const Ic=[{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"}],to=Ic.map(({value:e,label:n,icon:s,color:r})=>({value:e,label:n,icon:s,color:r}));function $l(e){const n=String(e||"task").trim().toLowerCase();return n==="completed"?Ic.find(s=>s.value==="done")||Ic[0]:Ic.find(s=>s.value===n)||Ic[0]}const Yf=["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"],Ri=Yf.reduce((e,n)=>(e[n]=$s[n]||Ii,e),{}),AL=Yf,pu=Object.fromEntries(Kf().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),[])),iS={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"},Pm={"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"},IL=["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 Aa(e){if(e)return Pm[e]?Pm[e]:e}function cS(e){const n=String(e||"").trim().toLowerCase();return Aa(pu[n]?.color)||Aa("violet-200")||"#9c7aeb"}function TL(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 lS(e){const n=String(e||"").trim().toUpperCase();return Aa(iS[n])||"var(--text-muted)"}function dS(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 Jl(e,n){const s=e.filter(o=>o.status!=="retired"),r=e.filter(o=>o.status==="retired"&&n.some(l=>dS(l,o.id)));return[...s,...r.filter(o=>!s.some(l=>l.id===o.id))]}function Jf(e,n=[]){return Jl(e,n).filter(s=>s.sortEnabled===!0).map(s=>({value:`taxonomy:${s.id}`,label:s.status==="retired"?`${s.label} (Retired)`:s.label}))}function Em(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 vi(e,n){return new Date(n.createdAt).getTime()-new Date(e.createdAt).getTime()}function mu(e,n,s,r,o=[]){let l=0;if(s==="created")return l=vi(e,n),r==="desc"?l:-l;if(s==="updated"){const i=e.updatedAt||e.createdAt,p=n.updatedAt||n.createdAt;return l=new Date(p).getTime()-new Date(i).getTime(),r==="desc"?l:-l}if(s==="priority"){const i=cu(e.priority),p=cu(n.priority);return l=i!==p?p-i:vi(e,n),r==="desc"?l:-l}if(s==="complexity"){const i=typeof e.complexity=="number"?e.complexity:3,p=typeof n.complexity=="number"?n.complexity:3;return l=i!==p?p-i:vi(e,n),r==="desc"?l:-l}if(s.startsWith("taxonomy:")){const i=s.slice(9),p=o.find(b=>b.id===i);if(!p)return l=vi(e,n),r==="desc"?l:-l;const h=Em(e,p),w=Em(n,p);return h===null&&w===null?vi(e,n):h===null?1:w===null?-1:h!==w?r==="desc"?w-h:h-w:vi(e,n)}return l=vi(e,n),r==="desc"?l:-l}function uS(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 Zp(e,n){const s=e.options.filter(o=>o.status!=="retired"),r=e.options.filter(o=>o.status==="retired"&&n.some(l=>uS(l,e.id,o.value)));return[...s,...r.filter(o=>!s.some(l=>String(l.value)===String(o.value)))]}function pS({tasks:e,archivedTasks:n,activeCategories:s,activeTypes:r,priorities:o,taxonomies:l,configLoaded:i,referenceDataLoaded:p,assigneeOptionsLoaded:h,assigneeOptions:w}){const b=a.useMemo(()=>Bf(w),[w]),_=a.useMemo(()=>Jl(l,[...e,...n]).filter(L=>L.filterEnabled!==!1).map(L=>({...L,options:Zp(L,[...e,...n])})),[n,e,l]),k=a.useMemo(()=>b.map(L=>L.value),[b]),[g,C]=a.useState(""),[M,S]=a.useState([]),[P,Z]=a.useState([]),[$,ce]=a.useState([]),[q,K]=a.useState(!1),[j,ye]=a.useState(to.map(L=>L.value)),[U,X]=a.useState(k),[Ne,pe]=a.useState(!0),[te,D]=a.useState({}),[B,oe]=a.useState("created"),[xe,ie]=a.useState("desc"),ae=a.useCallback(()=>{ie(L=>L==="asc"?"desc":"asc")},[]),[Ze,Le]=a.useState("category"),[Ce,Oe]=a.useState("show"),[R,W]=a.useState({}),F=a.useCallback((L,le)=>le.length===0?!0:le.every(ne=>L.includes(ne)),[]),V=a.useCallback((L,le)=>L.length===le.length&&L.every((ne,de)=>ne===le[de]),[]);a.useEffect(()=>{Ze==="approach"&&Le("status")},[Ze]),a.useEffect(()=>{if(!(!i||!p)&&h&&!q&&s.length>0&&r.length>0&&o.length>0){S(s.map(le=>le.value)),Z(o.map(le=>le.value)),ce(r.map(le=>le.value)),X(k),pe(!0);const L={};_.forEach(le=>{L[le.id]=le.options.map(ne=>ne.value)}),D(L),K(!0)}},[i,p,h,s,r,o,_,q,k]),a.useEffect(()=>{if(!q||!h)return;const L=new Set(k),le=U.filter(G=>L.has(G)),ne=Ne?k:le.length>0||U.length===0?le:k;(ne.length!==U.length||ne.some((G,ee)=>G!==U[ee]))&&X(ne)},[k,U,Ne,q,h]),a.useEffect(()=>{if(!q||!h)return;const L=U.filter(ne=>k.includes(ne)),le=k.length>0&&k.every(ne=>L.includes(ne));le!==Ne&&pe(le)},[k,U,Ne,q,h]),a.useEffect(()=>{if(!i||!p||!q||s.length===0)return;const L=oy(M,s);(L.length!==M.length||L.some((ne,de)=>ne!==M[de]))&&S(L)},[i,p,s,q,M]),a.useEffect(()=>{if(!i||!p||!q||o.length===0||P.length===0)return;const L=ry(P,o),le=Array.from(new Set(P.map(de=>Number(de)).filter(de=>Number.isFinite(de))));(L.length!==le.length||L.some((de,G)=>de!==le[G]))&&Z(L)},[i,p,q,o,P]),a.useEffect(()=>{if(!i||!p||!q||r.length===0)return;const L=new Set(r.map(de=>de.value)),le=$.filter(de=>L.has(de)),ne=le.length>0||$.length===0?le:r.map(de=>de.value);V(ne,$)||ce(ne)},[r,i,$,q,V,p]),a.useEffect(()=>{if(!i||!p||!q)return;const L={};_.forEach(ee=>{const be=ee.options.map(De=>De.value);if(be.length===0)return;const $e=Array.isArray(te[ee.id])?te[ee.id]:[],fe=$e.filter(De=>be.includes(De));L[ee.id]=fe.length>0||$e.length===0?fe:be});const le=Object.keys(te).sort(),ne=Object.keys(L).sort(),de=le.length!==ne.length||le.some((ee,be)=>ee!==ne[be]),G=ne.some(ee=>!V(te[ee]||[],L[ee]||[]));(de||G)&&D(L)},[i,te,_,q,V,p]);const E=a.useCallback(()=>{C(""),S(s.map(le=>le.value)),Z(o.map(le=>le.value)),ce(r.map(le=>le.value)),ye(to.map(le=>le.value)),X(k),pe(!0);const L={};_.forEach(le=>{L[le.id]=le.options.map(ne=>ne.value)}),D(L),oe("created"),ie("desc")},[s,o,r,_,k]),y=a.useCallback(L=>{X(le=>{const ne=typeof L=="function"?L(le):L,de=Array.from(new Set(ne.filter(ee=>typeof ee=="string"&&ee.trim().length>0))),G=k.length>0&&k.every(ee=>de.includes(ee));return pe(G),de})},[k]),x=a.useMemo(()=>{const L=F(M,s.map(G=>G.value)),le=F($,r.map(G=>G.value)),ne=F(Array.from(new Set(P.map(G=>Number(G)).filter(G=>Number.isFinite(G)))),o.map(G=>Number(G.value)).filter(G=>Number.isFinite(G))),de=F(j,to.map(G=>G.value));return e.filter(G=>{const ee=Ar(G).toLowerCase(),be=G.title.toLowerCase().includes(g.toLowerCase())||(G.description?.toLowerCase()||"").includes(g.toLowerCase())||G.id.toLowerCase().includes(g.toLowerCase())||ee.includes(g.toLowerCase()),$e=!q||L||M.includes(G.category),fe=!q||ne||sp(G.priority,P),De=!q||le||$.includes(G.type||Ss),Ke=!q||de||j.includes(G.status),nt=!q||Ne||U.includes(G.assignee||"unassigned"),dt=Object.entries(te).every(([d,et])=>{const gt=_.find(wt=>wt.id===d);if(!gt)return!0;const O=gt?.options.every(wt=>et.includes(wt.value))??!0;if(O)return!0;const Ye=G.taxonomies?.[d];return Ye?Array.isArray(Ye)?Ye.some(wt=>et.includes(wt)):et.includes(Ye):O||et.includes("")});return be&&$e&&fe&&De&&Ke&&nt&&dt}).sort((G,ee)=>mu(G,ee,B,xe,l))},[e,n,g,M,P,$,j,U,Ne,te,B,xe,q,_,s,r,o,F,l]),H=a.useMemo(()=>{const L=F(M,s.map(G=>G.value)),le=F($,r.map(G=>G.value)),ne=F(Array.from(new Set(P.map(G=>Number(G)).filter(G=>Number.isFinite(G)))),o.map(G=>Number(G.value)).filter(G=>Number.isFinite(G))),de=F(j,to.map(G=>G.value));return e.filter(G=>{const ee=!q||L||M.includes(G.category),be=!q||ne||sp(G.priority,P),$e=!q||le||$.includes(G.type||Ss),fe=!q||de||j.includes(G.status),De=!q||Ne||U.includes(G.assignee||"unassigned"),Ke=Object.entries(te).every(([nt,dt])=>{const d=_.find(O=>O.id===nt);if(!d)return!0;const et=d?.options.every(O=>dt.includes(O.value))??!0;if(et)return!0;const gt=G.taxonomies?.[nt];return gt?Array.isArray(gt)?gt.some(O=>dt.includes(O)):dt.includes(gt):et||dt.includes("")});return ee&&be&&$e&&fe&&De&&Ke})},[e,n,M,P,$,j,U,Ne,te,q,_,s,r,o,F]),I=a.useMemo(()=>{const L=s.every(de=>M.includes(de.value)),le=F($,r.map(de=>de.value)),ne=F(Array.from(new Set(P.map(de=>Number(de)).filter(de=>Number.isFinite(de)))),o.map(de=>Number(de.value)).filter(de=>Number.isFinite(de)));return n.filter(de=>{const G=Ar(de).toLowerCase(),ee=de.title.toLowerCase().includes(g.toLowerCase())||(de.description?.toLowerCase()||"").includes(g.toLowerCase())||de.id.toLowerCase().includes(g.toLowerCase())||G.includes(g.toLowerCase()),be=!q||L||M.includes(de.category),$e=!q||ne||sp(de.priority,P),fe=!q||le||$.includes(de.type||Ss),De=!q||Ne||U.includes(de.assignee||"unassigned"),Ke=Object.entries(te).every(([nt,dt])=>{const d=_.find(O=>O.id===nt);if(!d)return!0;const et=d?.options.every(O=>dt.includes(O.value))??!0;if(et)return!0;const gt=de.taxonomies?.[nt];return gt?Array.isArray(gt)?gt.some(O=>dt.includes(O)):dt.includes(gt):et||dt.includes("")});return ee&&be&&$e&&fe&&De&&Ke}).sort((de,G)=>mu(de,G,B,xe,l))},[n,g,M,P,$,U,Ne,te,B,xe,q,s,r,o,_,F,l]),Ie=a.useMemo(()=>{const L={};return x.forEach(le=>{const ne=s.find(G=>G.value===le.category),de=ne?ne.label:le.category||"General";L[de]||(L[de]=[]),L[de].push(le)}),L},[x,s]);return{searchQuery:g,setSearchQuery:C,filterCategories:M,setFilterCategories:S,filterPriorities:P,setFilterPriorities:Z,filterTypes:$,setFilterTypes:ce,filterStatus:j,setFilterStatus:ye,filterAssignees:U,setFilterAssignees:y,filterAssigneesAllSelected:Ne,setFilterAssigneesAllSelected:pe,filterTaxonomies:te,setFilterTaxonomies:D,hasInitedFilters:q,setHasInitedFilters:K,sortBy:B,setSortBy:oe,sortOrder:xe,setSortOrder:ie,toggleSortOrder:ae,groupBy:Ze,setGroupBy:Le,emptyColumnMode:Ce,setEmptyColumnMode:Oe,collapsedCategories:R,setCollapsedCategories:W,clearFilters:E,filteredTasks:x,searchAgnosticTasks:H,filteredArchive:I,groupedTasks:Ie}}const mS=pS;function fS(e){const{activeCategories:n,activeTab:s,apiEndpoint:r,approach:o,assignee:l,attachments:i,attachmentsDirty:p,category:h,checklistItems:w,comments:b,complexity:_,description:k,dueDate:g,editingTaskId:C,fetchTasks:M,formTaxonomies:S,getPreferredCategoryValue:P,mergeTaskFromServer:Z,workstreamInput:$,priority:ce,pushNotice:q,queueWorkspaceSyncFromAuthoritativeTaskState:K,relationshipTasks:j,resetForm:ye,resolveWorkstreamIdInput:U,scheduledDate:X,setActiveTab:Ne,setAttachmentsDirty:pe,setComments:te,setError:D,setLastUsedCategory:B,setLoading:oe,setNewCommentText:xe,status:ie,title:ae,taxonomies:Ze,type:Le}=e,[Ce,Oe]=a.useState(null),[R,W]=a.useState("idle"),[F,V]=a.useState(null),E=a.useRef(null),y=a.useCallback(()=>JSON.stringify({title:ae.trim(),description:k||"",category:typeof h=="string"?h:h.label||P(n),type:typeof Le=="string"?Le:Le.label||Ss,priority:Number(ce),complexity:Number(_)||3,approach:o||"default",assignee:l||"agent",scheduledDate:X||"",dueDate:g||"",workstreamInput:$.trim(),checklistItems:w,comments:b,taxonomies:S,attachments:i}),[n,o,l,i,h,w,b,_,k,g,S,P,ce,X,ae,Le,$]),x=a.useCallback(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),H=a.useCallback(async G=>{const ee=G?.quiet??!1,be=G?.source??"manual";if(!ae.trim())return D("Title is required"),C&&W(be==="autosave"?"error":"idle"),!1;const $e=Ze.filter(fe=>fe.isRequired).filter(fe=>{const De=S[fe.id];return Array.isArray(De)?De.filter(Ke=>String(Ke).trim().length>0).length===0:typeof De!="string"&&typeof De!="number"||String(De).trim().length===0}).map(fe=>fe.label);if($e.length>0)return D(`Required taxonomy values are missing: ${$e.join(", ")}`),C&&W(be==="autosave"?"error":"idle"),!1;if(C&&j.find(De=>De.id===C)?.isArchived)return D("Archived tasks are read-only. Unarchive first to make changes."),W(be==="autosave"?"error":"idle"),!1;oe(!0),D(""),C&&W("saving");try{const fe=C?`/api/taskforce/task/${C}`:r.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),De=C?"PATCH":"POST",Ke=typeof h=="string"?h:h.label||P(n),nt=typeof Le=="string"?Le:Le.label||Ss,dt=$.trim()?U($):null,d={title:ae,description:k||null,category:Ke||P(n),type:nt,priority:ce,complexity:Number(_)||3,status:C?void 0:ie,completedAt:C?void 0:ie==="done"?new Date().toISOString():null,approach:o||"default",assignee:l||"agent",scheduledDate:X||null,dueDate:g||null,workstreamId:$.trim()?dt?.id||$.trim():null,checklistItems:w,comments:b,taxonomies:S,...C?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};(!C||p)&&(d.attachments=i),C&&(d.saveSource=be);const et=await fetch(fe,{method:De,headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!et.ok){const Ye=(await et.json()).message||`Failed to ${C?"update":"save"} task`;return D(Ye),ee||q(Ye,"error"),oe(!1),C&&W("error"),!1}const gt=await et.json().catch(()=>null);return C&>&&typeof gt=="object"&&(Z(gt),K()),B(Ke),pe(!1),oe(!1),C&&W("saved"),!0}catch{return D("Failed to connect to server"),ee||q("Failed to connect to server","error"),oe(!1),C&&W("error"),!1}},[n,r,o,l,i,p,h,w,b,_,k,g,C,S,P,Z,$,ce,q,K,U,pe,D,B,oe,X,ie,ae,Ze,Le]),I=a.useCallback(async()=>{await H({source:"manual"})&&(C||q("Task added successfully","success"),s==="add"&&!C&&(ye(),Ne("tasks"),await M()))},[s,C,M,q,ye,H,Ne]);a.useEffect(()=>{if(x(),!C){V(null),W("idle");return}V(y()),W("idle")},[x,C]);const Ie=a.useCallback(async()=>{if(x(),!C||F===null)return;const G=y();if(G===F||!ae.trim()||g&&X&&g<X)return;await H({quiet:!0,source:"autosave"})&&V(G)},[y,x,g,C,F,H,X,ae]);a.useEffect(()=>{if(!C||F===null)return;const G=y();if(G!==F){if(!ae.trim()){W("idle");return}if(g&&X&&g<X){W("error");return}return W(ee=>ee==="error"?"error":"idle"),x(),E.current=window.setTimeout(async()=>{await H({quiet:!0,source:"autosave"})&&V(G)},700),()=>{x()}}},[y,x,g,C,F,H,X,ae]);const L=a.useCallback(async G=>{if(G.preventDefault(),g&&X&&g<X){Oe({dueDate:g,scheduledDate:X});return}await I()},[g,I,X]),le=a.useCallback(async()=>{Oe(null),await I()},[I]),ne=a.useCallback(()=>{Oe(null)},[]),de=a.useCallback(async G=>{if(!C||!G.trim())return;const ee=G.trim();try{const be=await fetch(`/api/taskforce/task/${C}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:ee,author:"user"})});if(!be.ok){const De=(await be.json().catch(()=>({}))).error||"Failed to add comment.";D(De),q(De,"error");return}const $e=await be.json().catch(()=>null);if(xe(""),$e&&typeof $e=="object"){const fe=so($e);te(fe.comments||[]),Z($e),V(y()),W("saved")}else await M(!0);K()}catch(be){console.error("Failed to add comment",be),D("Failed to add comment."),q("Failed to add comment.","error")}},[C,M,y,Z,q,K,te,D,xe]);return{autoSaveState:R,flushAutoSave:Ie,scheduleWarningPrompt:Ce,saveTask:H,handleSubmit:L,confirmScheduleWarning:le,cancelScheduleWarning:ne,handleAddComment:de}}function hS(e){const{editingTaskId:n,fetchTasks:s,mergeTaskFromServer:r,workstreamInput:o,pushNotice:l,queueWorkspaceSyncFromAuthoritativeTaskState:i,relationshipTasks:p,resolveWorkstreamIdInput:h,setError:w}=e;return{handleSetWorkstreamForCurrentTask:a.useCallback(async _=>{if(!n)return;const k=p.find(S=>S.id===n);if(!k)return;const g=typeof _=="string"?_.trim():_===null?"":o.trim(),C=g?h(g):null,M=g.length>0?C?.id||g:null;if((k.workstreamId||null)===M){l(M?"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:M})});if(!S.ok){const $=(await S.json().catch(()=>({}))).error||"Failed to set workstream.";w($),l($,"error");return}w(""),l(M?"Workstream set":"Workstream removed","info");const P=await S.json().catch(()=>null);P?(r(P),i()):(await s(!0),i())}catch{w("Failed to set workstream."),l("Failed to set workstream.","error")}},[n,s,r,o,l,i,p,h,w])}}function gS({tasks:e,archivedTasks:n,editingTaskId:s,setTasks:r,setArchivedTasks:o,setDeletedTasks:l,setError:i,resetForm:p,setActiveTab:h,fetchTasks:w,fetchArchive:b,fetchDeletedTasks:_,mergeTaskFromServer:k,pushNotice:g,cloudAuthConfigured:C,runtimeMode:M,isAuthenticated:S,workspaceCloudSyncEnabled:P,buildWorkspaceSyncSignature:Z,pushWorkspaceChangesToCloud:$,workspacePendingSignatureRef:ce,workspaceDeletedTaskIdsRef:q}){const[K,j]=a.useState(null),ye=a.useRef(null),U=a.useCallback((R=0)=>{C&&M==="local"&&S&&P&&(typeof window>"u"||window.setTimeout(()=>{const W=Z();W&&(ce.current=W,$(W))},Math.max(0,R)))},[C,M,S,P,Z,ce,$]),X=a.useCallback(async(R,W)=>{let F=await fetch(`/api/taskforce/deleted${R}`,W);return F.status===404&&(F=await fetch(`/api/taskforce/trash${R}`,W)),F},[]),Ne=async(R,W=!1,F={})=>{if(!F.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const V=W||n.some(E=>E.id===R);try{const E=await fetch(`/api/taskforce/task/${R}`,{method:"DELETE"});if(!E.ok){const I=(await E.json().catch(()=>({}))).error||"Failed to delete task.";return i(I),g(I,"error"),!1}const y=await E.json().catch(()=>({})),x=y?.deleted&&typeof y.deleted=="object"&&y.deleted.taskSnapshot?{...y.deleted,taskSnapshot:so(y.deleted.taskSnapshot)}:null;if(window.location.search.includes(R)){const H=new URL(window.location.href);H.searchParams.delete("task"),window.history.pushState({},"",H.toString())}if(V?o(H=>H.filter(I=>I.id!==R)):r(H=>H.filter(I=>I.id!==R)),x?l(H=>[x,...H.filter(I=>I.taskId!==R)]):await _(!0),q.current.add(R),C&&M==="local"&&S&&P){const H=Z();ce.current=H,$(H)}return s===R&&(p(),h("tasks")),i(""),g("Task moved to Trash.","info"),!0}catch(E){return console.error("Failed to delete task:",E),i("Failed to delete task."),g("Failed to delete task.","error"),!1}},pe=a.useCallback(async R=>{try{const W=await X(`/${R}/restore`,{method:"POST"});if(!W.ok){const E=(await W.json().catch(()=>({}))).error||"Failed to restore deleted task.";return i(E),g(E,"error"),null}const F=await W.json().catch(()=>null);return F?k(F):await w(!0),l(V=>V.filter(E=>E.id!==R&&E.taskId!==R)),q.current.delete(R),U(),i(""),g("Task restored from Trash.","info"),F?so(F):null}catch(W){return console.error("Failed to restore deleted task:",W),i("Failed to restore deleted task."),g("Failed to restore deleted task.","error"),null}},[w,k,g,U,X,l,i]),te=a.useCallback(async R=>{try{const W=await X(`/${R}`,{method:"DELETE"});if(!W.ok){const V=(await W.json().catch(()=>({}))).error||"Failed to permanently delete deleted task.";return i(V),g(V,"error"),!1}return l(F=>F.filter(V=>V.id!==R&&V.taskId!==R)),U(),i(""),g("Deleted task permanently removed.","info"),!0}catch(W){return console.error("Failed to permanently delete deleted task:",W),i("Failed to permanently delete deleted task."),g("Failed to permanently delete deleted task.","error"),!1}},[g,U,X,l,i]),D=a.useCallback(async()=>{try{const R=await X("/empty",{method:"POST"});if(!R.ok){const E=(await R.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return i(E),g(E,"error"),null}const W=await R.json().catch(()=>({})),F=Number(W?.deleted||0);return l([]),U(),i(""),g(F===1?"Deleted task permanently removed.":`${F} deleted tasks permanently removed.`,"info"),F}catch(R){return console.error("Failed to empty deleted tasks:",R),i("Failed to permanently delete deleted tasks."),g("Failed to permanently delete deleted tasks.","error"),null}},[g,U,X,l,i]),B=a.useCallback(async(R,W)=>{const F=e,V=n;r(E=>E.map(y=>y.id===R?{...y,...W}:y)),o(E=>E.map(y=>y.id===R?{...y,...W}:y));try{const E=await fetch(`/api/taskforce/task/${R}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!E.ok){const H=(await E.json().catch(()=>({}))).error||`Failed to update task ${R}.`;i(H),g(H,"error"),r(F),o(V);return}const y=await E.json().catch(()=>null);k(y),U(W.attachments!==void 0?150:0),i("")}catch(E){console.error("Failed to update task",E);const y=`Failed to update task ${R}.`;i(y),g(y,"error"),r(F),o(V)}},[e,n,g,k,U]);return{copiedId:K,handleDelete:Ne,handleUpdateTask:B,handleToggleComplete:async R=>{const W=R.status==="done"?"task":"done";try{const F=W==="done"?new Date().toISOString():void 0,V=await fetch(`/api/taskforce/task/${R.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:W,completedAt:F})});if(!V.ok){const x=(await V.json().catch(()=>({}))).error||"Failed to update task status.";i(x),g(x,"error"),await w(!0);return}const E=await V.json().catch(()=>null);E?(k(E),U()):(await w(!0),U()),i("")}catch(F){console.error("Failed to toggle complete",F),i("Failed to update task status."),g("Failed to update task status.","error"),w()}},handleToggleCancel:async R=>{const W=R.status==="cancelled"?"task":"cancelled";try{const F=await fetch(`/api/taskforce/task/${R.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:W})});if(!F.ok){const y=(await F.json().catch(()=>({}))).error||"Failed to update task status.";i(y),g(y,"error"),await w(!0);return}const V=await F.json().catch(()=>null);V?(k(V),U()):(await w(!0),U()),i("")}catch(F){console.error("Failed to toggle cancel",F),i("Failed to update task status."),g("Failed to update task status.","error"),w()}},handleToggleInProgress:async R=>{const W=R.status==="in-progress"?"task":"in-progress";r(F=>F.map(V=>V.id===R.id?{...V,status:W}:V));try{const F=await fetch(`/api/taskforce/task/${R.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:W})});if(!F.ok){await w(!0);return}const V=await F.json().catch(()=>null);k(V),U()}catch{w()}},handleToggleReview:async R=>{const W=R.status==="review"?"task":"review";r(F=>F.map(V=>V.id===R.id?{...V,status:W}:V));try{const F=await fetch(`/api/taskforce/task/${R.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:W})});if(!F.ok){await w(!0);return}const V=await F.json().catch(()=>null);k(V),U()}catch{w()}},handleArchiveTask:async R=>{try{const F=R.status==="cancelled"?"cancel":"complete",V=await fetch(`/api/taskforce/task/${R.id}/${F}`,{method:"POST"});if(V.ok){const E=await V.json().catch(()=>null),y=[];if(E&&typeof E=="object"&&y.push(E),y.length>0){for(const H of y)k(H);U()}else b();const x=new Set(y.map(H=>String(H?.id||"").trim()).filter(H=>H.length>0));s&&x.has(s)&&(p(),h("tasks"))}else{const y=(await V.json().catch(()=>({}))).error||"Failed to archive task.";i(y),g(y,"error")}}catch(W){console.error("Failed to archive",W),i("Failed to archive task."),g("Failed to archive task.","error")}},handleBulkArchive:async()=>{const R=e.filter(W=>W.status==="done"||W.status==="cancelled");if(R.length!==0&&confirm(`Archive ${R.length} completed/cancelled tasks?`))try{const W=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:R.map(F=>F.id)})});if(W.ok){const F=await W.json(),V=Array.isArray(F?.results?.archived)?F.results.archived:[];if(V.length>0){for(const E of V)k(E);U()}else r(E=>E.filter(y=>!["done","cancelled"].includes(y.status))),b();g(`${F.archived||R.length} tasks archived`,"info"),i("")}else{const V=(await W.json().catch(()=>({}))).error||"Failed to bulk archive tasks.";i(V),g(V,"error")}}catch(W){console.error("Failed to bulk archive",W),i("Failed to bulk archive tasks."),g("Failed to bulk archive tasks.","error")}},handleUnarchive:async R=>{try{const W=await fetch(`/api/taskforce/task/${R}/unarchive`,{method:"POST"});if(W.ok){const F=await W.json().catch(()=>null);F?(k(F),U()):(o(V=>V.filter(E=>E.id!==R)),await w(!0),U()),i(""),g("Task restored from archive.","info")}}catch(W){console.error("Failed to unarchive",W),i("Failed to unarchive task."),g("Failed to unarchive task.","error")}},handleRestoreDeletedTask:pe,handlePermanentlyDeleteDeletedTask:te,handleEmptyDeletedTasks:D,handleCopyId:(R,W)=>{R.stopPropagation(),navigator.clipboard.writeText(W),j(W),ye.current!==null&&window.clearTimeout(ye.current),ye.current=window.setTimeout(()=>{ye.current=null,j(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:U}}const yS=gS;function Jd(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function kS(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 SS({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")&&!Jd(l)?n(l):l;if(l instanceof URL)return s!=="cloud"?l:l.origin===window.location.origin&&l.pathname.startsWith("/api/taskforce")?Jd(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 i=new URL(l.url,window.location.origin);if(i.origin===window.location.origin&&i.pathname.startsWith("/api/taskforce"))return Jd(i.pathname)?l:n(`${i.pathname}${i.search}${i.hash}`)}return l};return window.fetch=((l,i)=>{const p=o(l),h=kS(p);if(!!!(h&&h.pathname.startsWith("/api/taskforce")&&!Jd(h.pathname)))return r(p,i);const b=String(e.current||"").trim();if(typeof Request<"u"&&p instanceof Request){const k=new Headers(p.headers);i?.headers&&new Headers(i.headers).forEach((M,S)=>k.set(S,M)),b&&b!=="default"&&!k.has("x-taskforce-workspace-id")&&(k.set("x-taskforce-workspace-id",b),k.set("x-taskforce-workspace-authoritative","1"));const g=new Request(p,{...i,headers:k});return r(g)}const _=new Headers(i?.headers);return b&&b!=="default"&&!_.has("x-taskforce-workspace-id")&&(_.set("x-taskforce-workspace-id",b),_.set("x-taskforce-workspace-authoritative","1")),r(p,{...i,headers:_})}),()=>{window.fetch=r}},[e,n,s])}function vS(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 wS(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function bS(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}const _S={},Qr=Up(_S),up=(()=>{const e=Qr.baseUrl,n=Qr.cloudAuthBaseUrl;if(n)return n;const s=Qr.apiBaseUrl;return s||e||"https://app.taskforcehq.ai"})(),wi=12e3;function CS({config:e={},initialTaskId:n,onTaskCountChange:s,onClose:r}){const o={...Vg,...e},{categories:l,types:i,apiEndpoint:p,apiBaseUrl:h,cloudAuthBaseUrl:w,cloudMcpBaseUrl:b,wsBaseUrl:_,shortcut:k}=o,g=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",C=g==="localhost"||g==="127.0.0.1"||g==="::1",M=typeof window<"u"&&!C,[S,P]=a.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[Z,$]=a.useState(!1),ce=a.useCallback(m=>typeof m=="string"?m.trim().replace(/\/+$/,""):"",[]);a.useEffect(()=>{if(typeof window>"u"){$(!0);return}let m=!1;return(async()=>{try{const A=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!A.ok)return;const N=await A.json().catch(()=>({})),z=N?.config&&typeof N.config=="object"?N.config:{};if(m)return;const me=String(z.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",Se=String(z.workspaceMode||"").trim(),_t=Se==="single-local"||Se==="multi-cloud"?Se:me==="cloud"?"multi-cloud":"single-local";P({cloudEnvironment:typeof z.cloudEnvironment=="string"?String(z.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:ce(z.cloudBaseUrl),cloudMcpBaseUrl:ce(z.cloudMcpBaseUrl),baseUrl:ce(z.baseUrl),apiBaseUrl:ce(z.apiBaseUrl),cloudAuthBaseUrl:ce(z.cloudAuthBaseUrl),wsBaseUrl:ce(z.wsBaseUrl),cloudAuthViaLocalProxy:!!z.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:_t,workspaceSwitchingEnabled:typeof z.workspaceSwitchingEnabled=="boolean"?!!z.workspaceSwitchingEnabled:_t==="multi-cloud"})}catch{}finally{m||$(!0)}})(),()=>{m=!0}},[ce]);const q=typeof window>"u"?"":C?up:"",K=ce(Qr.baseUrl),j=ce(Qr.apiBaseUrl),ye=ce(Qr.cloudBaseUrl),U=ce(Qr.cloudMcpBaseUrl),X=ce(Qr.cloudAuthBaseUrl),Ne=ce(Qr.wsBaseUrl),pe=ce(h),te=ce(w),D=ce(b),B=pe||j||K,oe=S.apiBaseUrl||S.baseUrl,xe=B||oe||"",ie=te||X||K,ae=S.cloudAuthBaseUrl||S.baseUrl,Le=((C?ae||ie:ie||ae)||xe||q).trim().replace(/\/+$/,""),Ce=ce(Cy(S.cloudMcpBaseUrl||S.cloudAuthBaseUrl||S.cloudBaseUrl||D||te||U||X||ye||Le)),Oe=(S.cloudMcpBaseUrl||D||Ce||S.cloudBaseUrl||U||ye||Le||q).trim().replace(/\/+$/,""),R=!!Le&&!xe,W=Z&&(!!(Le||xe)||M),F=W&&!R,V=!!(Le||xe||M),E=M?"cloud":"local",y=E==="local"&&C&&V?Uf():"",x=y.length>0,H=a.useCallback(m=>!m||/^https?:\/\//i.test(m)||!xe||!m.startsWith("/")?m:`${xe}${m}`,[xe]),I=a.useCallback(m=>{if(!m||/^https?:\/\//i.test(m)||!m.startsWith("/"))return m;const A=m.startsWith("/api/taskforce/auth/")||m.startsWith("/api/taskforce/account/")||m.startsWith("/api/taskforce/billing/")||m.startsWith("/api/taskforce/sync/")||m.startsWith("/api/taskforce/settings/mcp/");if(!M&&A&&(!Z||S.cloudAuthViaLocalProxy))return m;const N=Le||xe;if(N){const z=`${N}${m}`;if(typeof window<"u"&&!M&&A)try{if(new URL(z,window.location.origin).origin===window.location.origin)return`${up}${m}`}catch{return`${up}${m}`}return z}return m},[Z,S.cloudAuthViaLocalProxy,Le,xe,M]),Ie=a.useCallback(m=>{const A=String(m||"").trim()||"/taskforce-ws",N=A.startsWith("/")?A:`/${A}`,z=String(_||S.wsBaseUrl||Ne||xe||"").trim().replace(/\/+$/,""),ke=typeof window<"u"?window.location.origin:"",me=z||ke;if(!me)return"";try{const Se=new URL(N,me);return Se.protocol==="https:"&&(Se.protocol="wss:"),Se.protocol==="http:"&&(Se.protocol="ws:"),Se.toString()}catch{return""}},[_,S.wsBaseUrl,Ne,xe]),[L,le]=a.useState("tasks"),[ne,de]=a.useState(!1),[G,ee]=a.useState(!1),[be,$e]=a.useState("open"),[fe,De]=a.useState(xc(o.theme)||iu),[Ke,nt]=a.useState(xc(o.theme)||iu),[dt,d]=a.useState(!0),[et]=a.useState(".taskforce"),gt=!1,[O,Ye]=a.useState(!1),[wt,St]=a.useState([]),[At,zt]=a.useState([]),[Ht,sn]=a.useState(""),[Jt,Xt]=a.useState(null),[gn,Mn]=a.useState(null),[un,yn]=a.useState(""),[an,Tn]=a.useState(""),Rt=a.useMemo(()=>hy({projectRoot:un,runtimeMode:E}),[un,E]),[we,Lt]=a.useState(""),[Qt,Dt]=a.useState(""),[He,Nn]=a.useState(()=>E),Y=Sy(He),Ae=S.workspaceMode==="single-local"||S.workspaceMode==="multi-cloud"?S.workspaceMode:Y.workspaceMode,_e=typeof S.workspaceSwitchingEnabled=="boolean"?S.workspaceSwitchingEnabled:Y.workspaceSwitchingEnabled,[Pe,qe]=a.useState(!1),[Je,at]=a.useState(!1),[Xe,ct]=a.useState(x),[vt,Ot]=a.useState(x?y:"anonymous"),[Pt,xt]=a.useState(""),[Et,xn]=a.useState(""),[Gt,Jn]=a.useState(""),[kn,yt]=a.useState(""),[Gn,se]=a.useState(!0),[je,Me]=a.useState(null),[Ee,Fe]=a.useState(()=>{if(E==="local")return"default";const m=Vd(Rt);return m&&m.toLowerCase()!=="default"?m:"default"}),tt=a.useMemo(()=>gy({projectRoot:un,runtimeMode:He,workspaceId:Ee}),[un,He,Ee]),[An,Mt]=a.useState([]),[fa,Bn]=a.useState(()=>_i()),[bn,fn]=a.useState(!1),[rn,Kt]=a.useState(x),[kt,$t]=a.useState("idle"),[Yt,Sn]=a.useState(null),[ft,mt]=a.useState(null),oa=a.useRef(null),en=a.useRef(0),tn=a.useRef(x),It=a.useRef(Ee),Tt=a.useRef(null),ia=a.useRef(0),[ya,Ia]=a.useState(0),ha=a.useRef(null),ka=a.useRef(null),aa=a.useRef(null),on=a.useRef(null),jn=a.useRef(null),Vn=a.useRef(null),_n=a.useCallback((m,A)=>{const N=String(m||"").trim();if(!N)return;const z=String(It.current||"").trim();z&&z!==N&&(ia.current+=1,Ia(ia.current)),It.current=N,A?.clearExplicitSelection!==!1&&(Tt.current=null),Fe(N)},[]);a.useEffect(()=>{It.current=Ee},[Ee]);const $n=a.useCallback((m,A)=>{const N=String(m||"").trim();N&&Fe(z=>{const ke=String(Tt.current||"").trim();let me=N;if(ke&&ke!==N)me=ke;else{const Se=String(z||"").trim();A?.preserveNonDefaultDefault&&N==="default"&&Se&&Se.toLowerCase()!=="default"&&(me=Se)}return It.current=me,me})},[]),Wn=a.useCallback(()=>({workspaceId:String(It.current||"default").trim()||"default",epoch:ia.current}),[]),vn=a.useCallback(m=>(String(It.current||"default").trim()||"default")!==m.workspaceId||ia.current!==m.epoch,[]),cn=a.useCallback(m=>ia.current!==m.epoch,[]),Rn=a.useCallback(m=>m instanceof DOMException?m.name==="AbortError":String(m?.name||"").toLowerCase()==="aborterror",[]),In=a.useCallback(()=>{[ha,ka,aa,on,jn,Vn].forEach(m=>{m.current?.abort("workspace-transition"),m.current=null}),Gr.current=null},[]),rt=a.useMemo(()=>vS({shouldGateProtectedApiCalls:F,runtimeMode:He,authSessionResolved:rn,authRequiredForApi:Pe,isAuthenticated:Xe}),[F,He,rn,Pe,Xe]),wn=rt.shouldDeferProtectedApiCalls,nn=rt.shouldBlockProtectedApiCalls,[Sa,Xn]=a.useState(null),[Fa,Oa]=a.useState(null),[vs,ss]=a.useState(!1),[Ya,ca]=a.useState("unknown"),[ln,rr]=a.useState(null),[la,va]=a.useState(o.shortcut||"Alt+T"),[Un,wa]=a.useState(o.priorities||[]),[Ls]=a.useState(bf()),[rs,sa]=a.useState(""),[os,ba]=a.useState(!1),[is,cs]=a.useState(!1),[Da,Q]=a.useState(!0),[Ve,Vt]=a.useState(()=>py()),bt=a.useMemo(()=>uy(),[]),[dn,ot]=a.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[da,_a]=a.useState(!1),[Zn,zn]=a.useState(!0),[ga,qn]=a.useState(!0),[Ja,Ms]=a.useState(""),[Tr,ls]=a.useState(null);SS({currentWorkspaceIdRef:It,resolveApiUrl:H,runtimeMode:He});const{availableWorkflows:or,initiativeTemplates:ua,fetchWorkflows:Qn,fetchInitiativeTemplates:Bs,fetchWorkflowTemplate:oo,fetchWorkflowOverrideNames:Nr,saveWorkflowTemplateDraft:Ge,resetWorkflowTemplateDraft:Ut}=Vk({shouldDeferProtectedApiCalls:wn,shouldBlockProtectedApiCalls:nn}),{zenMode:Pa,setZenModeState:Ca,toggleZenMode:ws}=Zk(),{exportEnvironment:ir,setExportEnvironment:Bo,availableEnvironments:T,loadAvailableEnvironments:ge,exportWorkflowsPath:Ue,setExportWorkflowsPath:Re,exportingResource:J,exportResult:Be,handleExportWorkflows:ht}=Uk({storagePath:et}),[Nt,ds]=a.useState(!1),[Kn,Dn]=a.useState(null),{uiNotice:Ws,pushNotice:Us,clearNotice:zs}=$k(),[Wo,jr]=a.useState([]),Pi=a.useRef(null),[Fo,cr]=a.useState(0),bu=a.useCallback(m=>!m||!un?m:m.startsWith(un)?m.slice(un.length).replace(/^[/\\]+/,""):m,[un]),[xa,bs]=a.useState([]),[us,io]=a.useState([]),[lr,Ei]=a.useState([]),[_s,Oo]=a.useState([]),[Rr,co]=a.useState([]),[$o,lo]=a.useState(!1),[ps,Li]=a.useState(null),[Dr,Bc]=a.useState(!1),[Pr,Uo]=a.useState([]),[$a,Mi]=a.useState(!1),[dr,Wc]=a.useState({}),uo=a.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});a.useEffect(()=>{uo.current={authSessionResolved:rn,configLoaded:$a,workspaceBootstrapPending:bn}},[rn,$a,bn]);const Ua=a.useCallback(m=>{$t(m),m!=="ready"&&(Sn(null),mt(Date.now()))},[]),ea=a.useCallback(m=>{const A=uo.current;A.authSessionResolved&&A.configLoaded&&!A.workspaceBootstrapPending||($t("stalled"),Sn(m),mt(N=>N??Date.now()))},[]),ms=a.useCallback(async(m,A,N=wi,z)=>{const ke=new AbortController,me=z?.signal,Se=Number(N)>0?Number(N):wi,_t=typeof window<"u"?window.setTimeout(()=>ke.abort("bootstrap-timeout"),Se):null,Ft=()=>{ke.abort(me?.reason||"external-abort")};me&&(me.aborted?Ft():me.addEventListener("abort",Ft,{once:!0}));try{return await fetch(m,{...A||{},signal:ke.signal})}catch(Wt){if(Wt instanceof DOMException?Wt.name==="AbortError":String(Wt?.name||"").toLowerCase()==="aborterror"){const Zt=new Error(`Startup checks timed out after ${Se}ms.`);throw Zt.name="BootstrapTimeoutError",Zt}throw Wt}finally{me&&me.removeEventListener("abort",Ft),_t!==null&&typeof window<"u"&&window.clearTimeout(_t)}},[]),Hs=a.useCallback(m=>String(m?.name||"")==="BootstrapTimeoutError",[]),[po,zo]=a.useState([]),[Cs,Er]=a.useState({}),[Ea,ta]=a.useState(o.taxonomies||[]),Cn=a.useMemo(()=>(Pr.length>0?Pr:l||[]).map(A=>typeof A=="string"?{value:A.toLowerCase().replace(/\s+/g,"-"),label:A}:A).sort((A,N)=>A.label.localeCompare(N.label)),[Pr,l]),xs=a.useMemo(()=>({categories:Cn,types:po,priorities:Un,taxonomies:Ea,displayLabels:Cs}),[Cn,po,Un,Ea,Cs]);a.useMemo(()=>Cn.filter(m=>!m.disabled),[Cn]);const za=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",[]),Xa=po.length>0?po:i,[Xl,ur]=a.useState(!1),[Fs,Ha]=a.useState(""),pa="Authentication required. Sign in to continue.",[Ho,Gs]=a.useState(!1),[pr,fs]=a.useState(!1),As=a.useCallback(()=>{at(He==="cloud"),ct(!1),xn(""),Jn(""),yt(""),Ha(pa)},[pa,He]),{recentlyChangedTaskIds:Lr,fetchTasks:mo,fetchArchive:mr,refreshTaskCollections:Bi,refreshTaskCollectionsFromInvalidation:fr,mergeTaskFromServer:Is}=Kk({tasks:xa,archivedTasks:us,setTasks:bs,setArchivedTasks:io,setLoadingTasks:lo,getCurrentWorkspaceId:()=>It.current,workspaceResetKey:`${Ee}:${ya}`,shouldDeferProtectedApiCalls:wn,shouldBlockProtectedApiCalls:nn,handleUnauthorized:As,authRequiredForApi:Pe});a.useEffect(()=>{ya!==0&&(In(),Gr.current=null,uc.current="",kr.current="",pc.current="",Ba.current="",ri.current="",oi.current="",ci(!1),Gs(!1),Bn(_i()),fs(!1),co([]),bs([]),io([]),Ei([]),Oo([]),lo(!1),Za.current!==null&&typeof window<"u"&&(window.clearTimeout(Za.current),Za.current=null),ts.current!==null&&typeof window<"u"&&(window.clearTimeout(ts.current),ts.current=null))},[In,io,lo,bs,ya]);const Ta=a.useCallback(async(m=!1,A)=>{if(!(A?.ignoreAuthGuard===!0)&&(wn||nn))return;m||lo(!0);const z=Wn(),ke=new AbortController;jn.current=ke;try{let me=await fetch("/api/taskforce/deleted",{signal:ke.signal});if(me.status===404&&(me=await fetch("/api/taskforce/trash",{signal:ke.signal})),me.status===401){As(),co([]);return}if(me.status===404){co([]);return}if(me.ok){const Se=await me.json();if(vn(z))return;const _t=Array.isArray(Se?.deleted)?Se.deleted.map(Ft=>{const Wt=Ft?.taskSnapshot&&typeof Ft.taskSnapshot=="object"?so(Ft.taskSnapshot):null;return Wt?{...Ft,taskSnapshot:Wt}:null}).filter(Ft=>!!Ft):[];co(_t)}}catch(me){if(Rn(me))return;console.error("[Taskforce] Failed to fetch deleted tasks:",me)}finally{jn.current===ke&&(jn.current=null),m||lo(!1)}},[Wn,As,Rn,vn,wn,nn]),pn=a.useCallback(async m=>{if(!(m?.ignoreAuthGuard===!0)&&(wn||nn))return;const N=Wn(),z=new AbortController;Vn.current=z;try{const[ke,me]=await Promise.all([fetch("/api/taskforce/initiatives",{signal:z.signal}),fetch("/api/taskforce/workstreams",{signal:z.signal})]);if(ke.status===401||me.status===401){As(),Ei([]),Oo([]);return}const[Se,_t]=await Promise.all([ke.ok?ke.json().catch(()=>[]):[],me.ok?me.json().catch(()=>[]):[]]);if(vn(N))return;Ei(Array.isArray(Se)?Se.filter(Ft=>!!(Ft&&typeof Ft=="object"&&typeof Ft.id=="string")):[]),Oo(Array.isArray(_t)?_t.filter(Ft=>!!(Ft&&typeof Ft=="object"&&typeof Ft.id=="string")):[])}catch(ke){if(Rn(ke))return;console.error("[Taskforce] Failed to fetch planning entities:",ke)}finally{Vn.current===z&&(Vn.current=null)}},[Wn,As,Rn,vn,wn,nn]),Pn=a.useCallback(async(m=!1,A)=>{await mo(m,A)},[mo]),La=a.useCallback(async(m=!1,A)=>{await mr(m,A)},[mr]),hr=a.useCallback(async m=>{const A=m?.isSilent!==!1,N=m?.ignoreAuthGuard===!0;await Promise.all([Bi({isSilent:A,ignoreAuthGuard:N}),Ta(A,{ignoreAuthGuard:N}),pn({ignoreAuthGuard:N})])},[Ta,pn,Bi]),Go=a.useCallback(async()=>{await fr(),await Ta(!0),await pn()},[Ta,pn,fr]),Yn=a.useCallback(async m=>{const A=m?.force===!0;if(Ua("auth"),!Z)return tn.current;if(!W)return Nn("local"),qe(!1),ct(!1),Ot("anonymous"),xt(""),Dl(null),xn(""),Jn(""),yt(""),Vo("disconnected"),Vs(null),se(!0),Mt([]),Me(null),Bn(_i()),at(!1),Kt(!0),tn.current=!1,en.current=Date.now(),!1;const N=I("/api/taskforce/auth/session"),z=Date.now();if(!A&&oa.current)return oa.current;if(!A&&rn&&z-en.current<1500)return tn.current;const ke=(async()=>{const me=typeof performance<"u"?performance.now():Date.now(),Se=new AbortController,_t=typeof window<"u"?window.setTimeout(()=>Se.abort(),8e3):null;try{const Ft=await fetch(N,{method:"GET",credentials:"include",mode:"cors",signal:Se.signal});if(Ft.status===429)return Kt(!0),tn.current;if(!Ft.ok)return C&&Dl(null),Kt(!0),tn.current=!1,!1;const Wt=await Ft.json(),Bt=!!Wt.authRequiredForApi,Zt=!!Wt.authenticated,ys=Zt?Wt.betaAccess!==!1:!0,Kr=typeof Wt.workspaceId=="string"&&Wt.workspaceId.trim().length>0?Wt.workspaceId.trim():"",qa=typeof Wt.userId=="string"&&Wt.userId.trim().length>0?Wt.userId.trim():"anonymous",as=typeof Wt.email=="string"&&Wt.email.trim().length>0?Wt.email.trim().toLowerCase():"",En=typeof Wt.displayName=="string"?Wt.displayName.trim():"",Ro=typeof Wt.avatarUrl=="string"?Wt.avatarUrl.trim():"",wc=He==="local",Hd=He==="local"||R;return qe(R||wc?!1:Bt),ct(Zt),Ot(Zt?qa:"anonymous"),xt(Zt?Kr:""),C&&Dl(Zt?qa:null),xn(Zt?as:""),Jn(Zt?En:""),yt(Zt?Ro:""),Zt&&Ha(_r=>_r===pa?"":_r),Vo(Zt?"idle":"disconnected"),Vs(null),se(ys),Hd||$n(Kr||Vd(Rt)||"default"),at(R||wc?!1:Bt&&!Zt),Kt(!0),tn.current=Zt,Hn("auth_session_resolved",{authenticated:Zt,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-me)}),Zt&&Ua("ready"),Zt}catch{return C&&Dl(null),Kt(!0),tn.current=!1,Hn("auth_session_failed",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-me)}),ea("Unable to verify your session."),tn.current}finally{_t!==null&&typeof window<"u"&&window.clearTimeout(_t),en.current=Date.now(),oa.current=null}})();return oa.current=ke,ke},[Z,W,rn,I,R,pa,He,$n,Rt,Ua,ea]),{userGlobalSyncStatus:_u,setUserGlobalSyncStatus:Vo,userGlobalSyncError:Ma,setUserGlobalSyncError:Vs,workspaceLastPullAt:Mr,workspaceLastPushAt:Zo,workspaceLastErrorAt:Cu,workspaceLastErrorMessage:Ql,workspaceLastSuccessfulSyncAt:fo,workspaceCloudSyncEnabled:Wi,workspaceSyncPhase:ed,workspaceSyncStatus:td,workspaceSyncSummary:nd,workspaceSyncRecommendedAction:Fc,workspaceSyncBusy:ad,workspaceSyncPendingChanges:Oc,workspacePendingSignatureRef:ho,workspaceDeletedTaskIdsRef:qo,loadWorkspaceSyncState:Br,applyWorkspaceSyncStateSnapshot:$c,syncUserGlobalSettings:Zs,buildWorkspaceSyncSignature:Wr,pushWorkspaceChangesToCloud:ma,saveWorkspaceCloudSyncSettings:Ko,retryUserGlobalSettingsSync:Uc,retryWorkspaceCloudSync:Fi,resetWorkspaceSyncCursorAndPull:Oi,getWorkspaceSyncDiagnostics:gr}=Fk({currentWorkspaceId:Ee,cloudAuthConfigured:V,runtimeMode:He,authSessionResolved:rn,isAuthenticated:Xe,authUserId:vt,projectName:an,resolveCloudAuthUrl:I,resolveWebSocketUrl:Ie,realtimeSyncEnabled:vs,tasks:xa,archivedTasks:us,initiatives:lr,workstreams:_s,taxonomies:Ea,taxonomyState:Ho?xs:void 0,setupState:Sa,globalTheme:Ke,locale:Ve,globalWeekStartsOn:dn,themeUseGlobalDefault:dt,setTasks:bs,setArchivedTasks:io,setAuthBlocked:at,setIsAuthenticated:ct,checkAuthSession:Yn,setGlobalTheme:nt,setCurrentTheme:De,setSetupState:Xn,setLocale:Vt,setGlobalWeekStartsOn:ot,fetchPlanningEntities:pn}),$i=a.useCallback((m=Xa)=>m.find(A=>String(A.value||"").trim().length>0)?.value||Ss,[Xa]),[go,Fr]=a.useState(()=>za(Cn)),[Or,Na]=a.useState(()=>$i(Xa)),[qs,sd]=a.useState(2),[rd,Ga]=a.useState(3),[Ui,zi]=a.useState("task"),[Yo,zc]=a.useState("default"),[Hc,$r]=a.useState("unassigned"),[Hi,od]=a.useState(""),[Gi,Jo]=a.useState(""),[yo,Vi]=a.useState(""),[lt,Gc]=a.useState(""),[Zi,Ks]=a.useState(""),[qi,Ki]=a.useState([]),[Yi,Vc]=a.useState([]),[id,Qa]=a.useState(""),[ra,Xo]=a.useState({}),xu=a.useRef(null),[Zc,Ur]=a.useState(!1),[Qo,cd]=a.useState("");a.useEffect(()=>{if(ps)return;const m=String(Or||"").trim();Xa.some(N=>String(N.value||"").trim()===m)||Na($i(Xa))},[Xa,ps,$i,Or]);const{searchQuery:hs,setSearchQuery:ld,filterCategories:ei,setFilterCategories:Ji,filterPriorities:ko,setFilterPriorities:So,filterTypes:vo,setFilterTypes:qc,filterStatus:ti,setFilterStatus:dd,filterAssignees:Kc,setFilterAssignees:ni,filterAssigneesAllSelected:Ys,setFilterAssigneesAllSelected:es,filterTaxonomies:zr,setFilterTaxonomies:wo,hasInitedFilters:Xi,setHasInitedFilters:Qi,sortBy:ai,setSortBy:ec,sortOrder:Yc,setSortOrder:Jc,toggleSortOrder:ud,groupBy:tc,setGroupBy:yr,emptyColumnMode:nc,setEmptyColumnMode:ac,collapsedCategories:pd,setCollapsedCategories:Au,clearFilters:Xc,filteredTasks:Va,searchAgnosticTasks:md,filteredArchive:fd,groupedTasks:hd}=mS({tasks:xa,archivedTasks:us,activeCategories:Cn,activeTypes:Xa,priorities:Un,taxonomies:Ea,configLoaded:$a,referenceDataLoaded:Ho,assigneeOptionsLoaded:pr,assigneeOptions:fa}),[si,sc]=a.useState("tasks"),[Qc,el]=a.useState(!1),[rc,gd]=a.useState(!1),[yd,tl]=a.useState(!1),[nl,oc]=a.useState([]),[kd,ic]=a.useState(!1),cc=a.useRef(null),Za=a.useRef(null),ts=a.useRef(null),lc=a.useRef(!1),al=a.useRef(rn),dc=a.useRef(Pe),Sd=a.useRef(Xe),Hr=a.useRef(!1),uc=a.useRef(""),kr=a.useRef(""),pc=a.useRef(""),Ba=a.useRef(""),ri=a.useRef(""),oi=a.useRef(""),ii=a.useRef(!1),Gr=a.useRef(null),Sr=a.useRef(!1),[sl,ci]=a.useState(!1),{handleSaveSettings:rl,handleSaveTheme:mc,handleSaveGlobalTheme:Iu,handleJsonBackupEnabledChange:ol,handleSaveGlobalJsonBackupEnabled:Tu,handleSaveGlobalWeekStartsOn:Nu,handleSaveLocale:il,handleManualComplexityEnabledChange:ju,handleChecklistDropdownEnabledChange:cl,handleShowTaskCardStatusLabelChange:bo,handleResetProjectToGlobal:Ru}=Hk({keyShortcut:la,themeUseGlobalDefault:dt,runtimeMode:He,jsonBackupUseGlobalDefault:Da,globalTheme:Ke,globalJsonBackupEnabled:is,setCurrentTheme:De,setThemeUseGlobalDefault:d,setGlobalTheme:nt,setJsonBackupEnabled:ba,setJsonBackupUseGlobalDefault:Q,setGlobalJsonBackupEnabled:cs,setGlobalWeekStartsOn:ot,setLocale:Vt,setManualComplexityEnabled:_a,setChecklistDropdownEnabled:zn,setShowTaskCardStatusLabel:qn,setShowChecklist:Ur});a.useEffect(()=>{He==="cloud"&&Rt!==Lo&&Wy(Ee,Rt)},[He,Ee,Rt]),a.useEffect(()=>{al.current=rn,dc.current=Pe,Sd.current=Xe},[rn,Pe,Xe]);const ll=a.useCallback(m=>{if(!m)return;const A=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"?sc(m.activeWorkspaceModule):m.groupBy==="docs"&&sc("docs"),m.groupBy&&m.groupBy!=="docs"&&yr(m.groupBy),(m.emptyColumnMode==="show"||m.emptyColumnMode==="collapse"||m.emptyColumnMode==="hide")&&ac(m.emptyColumnMode),typeof m.zenMode=="boolean"&&Ca(m.zenMode),typeof m.searchQuery=="string"&&ld(m.searchQuery),Array.isArray(m.filterCategories)&&Ji(m.filterCategories),Array.isArray(m.filterPriorities)&&So(m.filterPriorities),Array.isArray(m.filterTypes)&&qc(m.filterTypes),Array.isArray(m.filterStatus)&&dd(m.filterStatus),Array.isArray(m.filterAssignees)&&ni(m.filterAssignees),typeof m.filterAssigneesAllSelected=="boolean"&&es(m.filterAssigneesAllSelected),m.filterTaxonomies&&typeof m.filterTaxonomies=="object"&&wo(m.filterTaxonomies),(m.sortBy==="created"||m.sortBy==="priority"||m.sortBy==="updated"||m.sortBy==="complexity")&&ec(m.sortBy),(m.sortOrder==="asc"||m.sortOrder==="desc")&&Jc(m.sortOrder),typeof m.hasInitedFilters=="boolean"?Qi(m.hasInitedFilters):A&&Qi(!0),typeof m.showChecklist=="boolean"&&Ur(m.showChecklist),typeof m.lastCategory=="string"&&cd(m.lastCategory),typeof m.exportEnvironment=="string"&&m.exportEnvironment.trim().length>0&&Bo(m.exportEnvironment.trim())},[]),_o=a.useCallback(async m=>{const A=String(m||It.current||Ee||"default").trim()||"default",N=`${He}:${tt}:${A}`;try{const z=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(A)}`,{method:"GET",credentials:"include"}),ke=z.ok?await z.json().catch(()=>({})):{},me=ke?.state&&typeof ke.state=="object"?ke.state:null,Se=wm(tt),_t=me||Se?{...Se||{},...me||{}}:null;if(It.current!==A)return;ll(_t),uc.current=N}catch{const z=wm(tt);It.current===A&&(ll(z),uc.current=N)}finally{if(It.current!==A)return;ii.current=!0,ci(!0)}},[ll,Ee,He,tt]);a.useEffect(()=>{const m=`${He}:${tt}:${Ee}`;Hr.current&&uc.current!==m&&(ci(!1),_o(Ee))},[Ee,_o,He,tt]),a.useEffect(()=>{if(!sl)return;if(ii.current){ii.current=!1;return}const m={groupBy:tc,activeWorkspaceModule:si,emptyColumnMode:nc,zenMode:Pa,searchQuery:hs,filterCategories:ei,filterPriorities:ko,filterTypes:vo,filterStatus:ti,filterAssignees:Kc,filterAssigneesAllSelected:Ys,filterTaxonomies:zr,sortBy:ai,sortOrder:Yc,hasInitedFilters:Xi,showChecklist:Zc,lastCategory:Qo||"",exportEnvironment:ir};Fy(m,tt);const A=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:It.current,patch:m})})}catch{}},250);return()=>window.clearTimeout(A)},[sl,tc,si,nc,Pa,hs,ei,ko,vo,ti,Kc,Ys,zr,ai,Yc,Xi,Zc,Qo,ir,tt]);const vd=a.useCallback(m=>{const A=m.runtimeMode==="cloud"?"cloud":"local",N=!!m.authRequiredForApi,z=typeof m.userId=="string"&&m.userId.trim().length>0?m.userId.trim():"anonymous",ke=A==="cloud"&&z!=="anonymous";if(Nn(A),qe(N),ke&&(ct(!0),Ot(z),at(!1),rn||Kt(!0)),typeof m.workspaceId=="string"&&m.workspaceId.trim().length>0){const Zt=m.workspaceId.trim();A==="local"?_n(Zt):$n(Zt,{preserveNonDefaultDefault:!0})}at(A==="cloud"&&N?!(ke||Xe):!1),m.setupState&&typeof m.setupState=="object"?Xn(m.setupState):Xn(null),m.runtimeCapabilities&&typeof m.runtimeCapabilities=="object"?Oa(m.runtimeCapabilities):Oa(null),ss(!!m.realtimeSyncEnabled);const me=String(m.realtimeSyncFlagSource||"").trim().toLowerCase();ca(me==="env"||me==="settings"||me==="default"?me:"unknown"),typeof m.shortcut=="string"&&m.shortcut.trim().length>0&&va(m.shortcut);const Se=xc(m.theme);Se&&De(Se);const _t=xc(m.globalTheme);_t&&nt(_t),typeof m.themeUseGlobalDefault=="boolean"&&d(m.themeUseGlobalDefault);const Ft=m.runtimeMode==="cloud"?"cloud":"local";typeof m.projectRoot=="string"?yn(m.projectRoot):Ft==="cloud"&&yn(""),typeof m.tenantId=="string"?Dt(m.tenantId.trim()):Ft==="cloud"&&Dt("");const Wt=Ft==="cloud"?String(m.projectName||"").trim():m.projectName||m.paths?.projectName||"";(String(Wt||"").trim().length>0||Ft==="cloud")&&Tn(Wt),typeof m.mcpScript=="string"?Lt(m.mcpScript):Ft==="cloud"&&Lt(""),typeof m.hostRoot=="string"?Ms(m.hostRoot):Ft==="cloud"&&Ms(""),typeof m.jsonBackupEnabled=="boolean"&&ba(m.jsonBackupEnabled),typeof m.globalJsonBackupEnabled=="boolean"&&cs(m.globalJsonBackupEnabled),typeof m.jsonBackupUseGlobalDefault=="boolean"&&Q(m.jsonBackupUseGlobalDefault);const Bt=m?.schedulePreferences?.weekStartsOn;(Bt==="sunday"||Bt==="monday")&&ot(Bt),typeof m.manualComplexityEnabled=="boolean"&&_a(m.manualComplexityEnabled),typeof m.checklistDropdownEnabled=="boolean"?zn(m.checklistDropdownEnabled):zn(!0),typeof m.showTaskCardStatusLabel=="boolean"?qn(m.showTaskCardStatusLabel):qn(!0)},[$n,rn,_n,Xe]),wd=a.useCallback(async()=>{const m=typeof performance<"u"?performance.now():Date.now();try{const A=await ms("/api/taskforce/version",void 0,wi);if(!A.ok)return;const N=await A.json().catch(()=>({}));N?.build&&typeof N.build=="object"&&rr({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}),Hn("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-m)})}catch(A){Hs(A)&&ea("Startup checks timed out.")}},[ms,Hs,ea]),Vr=a.useCallback(async m=>{const A=m?.ignoreAuthGuard===!0,N=m?.force===!0;if(!A&&(wn||nn))return;const z=Wn();if(!N&&Gr.current?.workspaceId===z.workspaceId){await Gr.current.promise;return}Gs(!1);const ke=new AbortController;ka.current=ke;const me=(async()=>{const Se=typeof performance<"u"?performance.now():Date.now();await Promise.allSettled([(async()=>{const _t=await fetch("/api/taskforce/taxonomy-state",{signal:ke.signal});if(!_t.ok)return;const Ft=await _t.json().catch(()=>({}));if(!vy(Ft)){const[Zt,ys,Kr,qa]=await Promise.all([fetch("/api/taskforce/categories",{signal:ke.signal}),fetch("/api/taskforce/types",{signal:ke.signal}),fetch("/api/taskforce/priorities",{signal:ke.signal}),fetch("/api/taskforce/taxonomies",{signal:ke.signal})]),[as,En,Ro,wc]=await Promise.all([Zt.ok?Zt.json().catch(()=>({})):Promise.resolve({}),ys.ok?ys.json().catch(()=>({})):Promise.resolve({}),Kr.ok?Kr.json().catch(()=>({})):Promise.resolve({}),qa.ok?qa.json().catch(()=>({})):Promise.resolve({})]);Ft.categories=as.categories,Ft.types=En.types,Ft.priorities=Ro.priorities,Ft.taxonomies=wc.taxonomies}const Bt=wy(Ft);vn(z)||(Bt.categories.length>0&&Uo(Bt.categories),Bt.types.length>0&&zo(Bt.types),Bt.priorities.length>0&&wa(Bt.priorities),ta(Bt.taxonomies),Er(Bt.displayLabels||{}))})(),(async()=>{await Qn()})(),(async()=>{await Bs()})(),(async()=>{await ge()})()]),!vn(z)&&(Gs(!0),Hn("reference_data_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-Se)}))})();Gr.current={workspaceId:z.workspaceId,promise:me};try{await me}catch(Se){if(!Rn(Se))throw Se}finally{Gr.current?.promise===me&&(Gr.current=null),ka.current===ke&&(ka.current=null)}},[Qn,Bs,Wn,Rn,vn,ge,wn,nn]),li=a.useCallback(async m=>{if(!(m?.ignoreAuthGuard===!0)&&(wn||nn))return;Ua("config");const N=Wn(),z=new AbortController;ha.current=z;const ke=typeof performance<"u"?performance.now():Date.now();try{const me=await ms("/api/taskforce/config",void 0,wi,{signal:z.signal});if(cn(N))return;if(me.status===401){As(),Mi(!0);return}let Se="";if(me.ok){const _t=await me.json();if(cn(N))return;Se=typeof _t?.workspaceId=="string"&&_t.workspaceId.trim().length>0?_t.workspaceId.trim():"",vd(_t)}if(cn(N)){const _t=String(It.current||"default").trim()||"default";if(!Se||_t!==Se)return}if(!Hr.current){const _t=Se||N.workspaceId;Hr.current=!0,await _o(_t)}if(cn(N)){const _t=String(It.current||"default").trim()||"default";if(!Se||_t!==Se)return}Mi(!0),Ua("ready"),Hn("bootstrap_config_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-ke)}),wd()}catch(me){if(Rn(me)||cn(N))return;Hr.current||(Hr.current=!0,await _o(N.workspaceId)),Hs(me)?ea("Startup checks timed out."):ea("Unable to finish startup checks."),Mi(!0)}finally{ha.current===z&&(ha.current=null)}},[vd,wd,ms,Wn,As,Rn,Hs,cn,vn,_o,Ua,ea,wn,nn]),na=a.useCallback(async m=>{await li(m),await Vr(m)},[li,Vr]),di=a.useCallback(async()=>{await Yn(),await na()},[Yn,na]),Fn=a.useCallback(async()=>{if(!_e)return Mt([]),Sr.current=!1,{success:!0,workspaces:[]};const m=Wn(),A=new AbortController;aa.current=A;const N=typeof performance<"u"?performance.now():Date.now();try{const z=await ms("/api/taskforce/workspaces",{method:"GET",credentials:"include"},wi,{signal:A.signal});if(cn(m))return{success:!1,error:"Workspace changed while loading workspaces."};if(z.status===401)return Mt([]),Sr.current=!1,{success:!1,error:"Authentication required."};const ke=await z.json().catch(()=>({}));if(cn(m))return{success:!1,error:"Workspace changed while loading workspaces."};if(!z.ok||ke?.success===!1)return Mt([]),Sr.current=!1,{success:!1,error:ke?.error||`Failed to load workspaces (${z.status})`};const me=Array.isArray(ke?.workspaces)?ke.workspaces:[];return Mt(me),Sr.current=!0,He!=="local"&&typeof ke?.currentWorkspaceId=="string"&&ke.currentWorkspaceId.trim().length>0&&$n(ke.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),Hn("workspace_list_loaded",{workspaceCount:me.length,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-N)}),{success:!0,workspaces:me}}catch(z){return Rn(z)?{success:!1,error:"Workspace list request aborted."}:(Hs(z)&&ea("Startup checks timed out."),Mt([]),Sr.current=!1,{success:!1,error:"Failed to load workspaces."})}finally{aa.current===A&&(aa.current=null)}},[$n,ms,Wn,Rn,cn,Hs,vn,ea,He,_e]),Co=a.useCallback(async()=>{const m=Wn(),A=new AbortController;on.current=A,fs(!1);try{const[N,z]=await Promise.all([ms("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},wi,{signal:A.signal}),rn&&Xe?ms("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},wi,{signal:A.signal}).catch(()=>null):Promise.resolve(null)]);if(vn(m))return{success:!1,error:"Workspace changed while loading assignee options."};if(N.status===401)return Bn(_i()),fs(!0),{success:!1,error:"Authentication required."};const ke=await N.json().catch(()=>({}));if(vn(m))return{success:!1,error:"Workspace changed while loading assignee options."};if(!N.ok)return Bn(_i()),fs(!0),{success:!1,error:ke?.error||`Failed to load assignee options (${N.status})`};const me=Array.isArray(ke?.assignees)?ke.assignees:[],Se=me.map(Bt=>{const Zt=String(Bt?.value||"").trim(),ys=String(Bt?.kind||"").trim().toLowerCase();return Zt?ys==="agent"||ys==="ai"?{value:Zt,label:String(Bt?.label||Zt).trim()||Zt,icon:String(Bt?.icon||"Bot"),color:String(Bt?.color||"#8b5cf6"),kind:"agent"}:ys==="member"||ys==="human"?{value:Zt,label:String(Bt?.label||Zt).trim()||Zt,icon:String(Bt?.icon||"User"),color:String(Bt?.color||"#22c55e"),kind:"member"}:null:null}).filter(Bt=>!!Bt),_t=me.map(Bt=>({userId:String(Bt?.userId||"").trim(),email:String(Bt?.email||"").trim().toLowerCase(),displayName:typeof Bt?.displayName=="string"?Bt.displayName:null,status:typeof Bt?.status=="string"?Bt.status:null,disabled:Bt?.disabled===!0})).filter(Bt=>Bt.userId&&String(Bt.status||"active").trim().toLowerCase()==="active"&&Bt.disabled!==!0);let Ft=_t;if(z?.ok){const Bt=await z.json().catch(()=>({})),Zt=Array.isArray(Bt?.users)?Bt.users:[],ys=String(vt||"").trim(),Kr=Zt.find(En=>String(En?.userId||"").trim()===ys),qa=String(Kr?.role||"").trim().toLowerCase();qa==="owner"||qa==="admin"||qa==="member"||qa==="read-only"?Me(qa):!_e&&Zt.length===0&&Me(null);const as=Zt.map(En=>({userId:String(En?.userId||"").trim(),email:String(En?.email||"").trim().toLowerCase(),displayName:typeof En?.displayName=="string"?En.displayName:null,status:typeof En?.status=="string"?En.status:null,disabled:En?.disabled===!0})).filter(En=>En.userId&&String(En.status||"active").trim().toLowerCase()==="active"&&En.disabled!==!0).map(En=>({userId:En.userId,email:En.email,displayName:En.displayName??null}));Ft=Array.from(new Map([..._t,...as].map(En=>[String(En.userId||"").trim(),En])).values()).filter(En=>String(En.userId||"").trim().length>0)}else!_e&&!_t.length&&Me(null);const Wt=Vl([...Se,...Dy(Ft).filter(Bt=>Bt.kind==="member")]);return vn(m)?{success:!1,error:"Workspace changed while loading assignee options."}:(Bn(Wt),fs(!0),{success:!0})}catch(N){return Rn(N)?{success:!1,error:"Assignee options request aborted."}:(vn(m)||(Bn(_i()),fs(!0)),{success:!1,error:"Failed to load assignee options."})}finally{on.current===A&&(on.current=null)}},[rn,vt,ms,Wn,Rn,Xe,vn,_e]);a.useEffect(()=>{if(!$a||bn)return;const m=`${He}:${Xe?"auth":"guest"}:${Ee}`;pr&&kr.current===m||(kr.current=m,Co())},[pr,$a,Ee,Co,Xe,He,bn]);const bd=a.useMemo(()=>_e?An.find(A=>A.id===Ee)?.role??null:je,[An,Ee,je,_e]);a.useEffect(()=>{Xe||Me(null)},[Xe]);const vr=a.useCallback(async(m,A)=>{if(!_e)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 z=await fetch("/api/taskforce/session/workspace",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:N})}),ke=await z.json().catch(()=>({}));if(!z.ok||ke?.success===!1)return{success:!1,error:ke?.error||`Failed to switch workspace (${z.status})`,code:ke?.code};Tt.current=N,_n(N,{clearExplicitSelection:!1}),In(),fn(!0),Ua("workspace");const me=await Yn({force:!0});return A?.hydrate===!1?await Fn():(pc.current=`${He}:${N}:${Rt}`,kr.current=`${He}:${me?"auth":"guest"}:${N}`,Ba.current=N,ne&&L==="tasks"&&(ri.current=`${N}:${L}:${G?"archive":"active"}:${be}`),ne&&L==="settings"&&(oi.current=`${N}:${L}:${gn}`),await Promise.all([na(),Fn(),hr({isSilent:!1}),Co(),Br()])),Tt.current===N&&(Tt.current=null),{success:!0}}catch{return Tt.current===N&&(Tt.current=null),{success:!1,error:"Failed to switch workspace."}}finally{fn(!1)}},[In,L,Yn,_n,Co,na,Fn,ne,Br,Ua,hr,He,gn,G,be,Rt,_e]),Ts=a.useCallback(async m=>{Ua("workspace"),fn(!0);const A=typeof performance<"u"?performance.now():Date.now();try{if(!_e){const Wt=String(Ee||"").trim()||"default";return _n(Wt),Hn("workspace_resolved",{workspaceId:Wt,workspaceSetupRequired:!1,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-A)}),{success:!0,workspaceSetupRequired:!1,workspaceId:Wt}}const N=String(m?.preferredWorkspaceId||"").trim(),z=Vd(Rt),ke=await Fn();if(!ke.success)return{success:!1,workspaceSetupRequired:!1,error:ke.error||"Failed to load workspaces after authentication."};const me=Array.isArray(ke.workspaces)?ke.workspaces:[];if(me.length===0)return _n("default"),Hn("workspace_resolved",{workspaceId:"default",workspaceSetupRequired:!0,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-A)}),{success:!0,workspaceSetupRequired:!0};const Se=new Set(me.map(Wt=>String(Wt.id||"").trim()).filter(Boolean)),_t=(N&&Se.has(N)?N:"")||(z&&Se.has(z)?z:"")||String(me[0]?.id||"").trim();if(!_t)return _n("default"),{success:!0,workspaceSetupRequired:!0};if(String(It.current||"").trim()!==_t){const Wt=await vr(_t,{hydrate:!1});if(!Wt.success)return{success:!1,workspaceSetupRequired:!1,error:Wt.error||"Failed to set workspace after authentication.",code:Wt.code}}else _n(_t);return Hn("workspace_resolved",{workspaceId:_t,workspaceSetupRequired:!1,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-A)}),{success:!0,workspaceSetupRequired:!1,workspaceId:_t}}catch{return ea("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{fn(!1)}},[_n,Fn,Ua,ea,Rt,vr,_e]),dl=a.useCallback(async()=>{Sn(null),Ua("auth");const m=await Yn({force:!0});if(_e&&m){const A=await Ts();if(!A.success||A.workspaceSetupRequired){await na({ignoreAuthGuard:!0});return}}await na({ignoreAuthGuard:!0})},[Yn,na,Ua,Ts,_e]),Du=a.useCallback(async(m,A)=>{if(!_e)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 z=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:N,description:typeof A=="string"?A:void 0})}),ke=await z.json().catch(()=>({}));if(!z.ok||ke?.success===!1)return{success:!1,error:ke?.error||`Failed to create workspace (${z.status})`,code:ke?.code};const me=ke?.workspace;if(await Fn(),me?.id){const Se=await vr(me.id);if(!Se.success)return{success:!1,error:Se.error||"Workspace created but failed to activate.",code:Se.code}}return{success:!0,workspace:me}}catch{return{success:!1,error:"Failed to create workspace."}}},[Fn,vr,_e]),ui=a.useCallback(async m=>{if(!_e)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const A=String(m||"").trim();if(!A)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const N=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(A)}`,{method:"DELETE",credentials:"include"}),z=await N.json().catch(()=>({}));if(!N.ok||z?.success===!1)return{success:!1,error:z?.error||`Failed to delete workspace (${N.status})`,code:z?.code};await Yn({force:!0}),await Promise.all([na(),Fn()]);const ke=typeof z?.nextWorkspaceId=="string"?z.nextWorkspaceId.trim():"";return ke&&_n(ke),{success:!0,nextWorkspaceId:ke||void 0,workspaceSetupRequired:z?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(z?.cleanupWarnings)?z.cleanupWarnings.map(me=>String(me||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[Yn,_n,na,Fn,_e]),Pu=a.useCallback(async m=>{const A=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:A}})}),z=await N.json().catch(()=>({}));return!N.ok||z?.success===!1?!1:(await di(),!0)}catch{return!1}},[di]),Js=a.useCallback(async m=>{const A=String(m?.name||"").trim();if(!A)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":He},credentials:"include",body:JSON.stringify({workspaceId:m.workspaceId,name:A,description:typeof m.description=="string"?m.description:void 0,allowCreate:!0})}),z=await N.json().catch(()=>({}));if(!N.ok||z?.success===!1)return{success:!1,error:z?.error||`Failed to save workspace (${N.status})`,code:z?.code};const ke=String(z?.workspace?.id||"").trim();if(ke&&(_n(ke),await new Promise(me=>window.setTimeout(me,0)),He==="cloud"&&Xe&&ke!==Ee)){const me=await vr(ke);if(!me.success)return{success:!1,error:me.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await di(),{success:!0,workspaceId:ke||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[_n,di,He,Xe,Ee,vr]),Eu=a.useCallback(async(m,A)=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const N=m.trim().toLowerCase(),z=A;if(!N||!z)return{success:!1,error:"Email and password are required."};try{const ke=await fetch(I("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:N,password:z})}),me=await ke.json().catch(()=>({}));if(!ke.ok||!me?.success)return{success:!1,error:me?.error||"Sign in failed.",code:me?.code};Ha(""),await Yn({force:!0});const Se=await Ts();return Se.success?Se.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([na({ignoreAuthGuard:!0}),Pn(!0,{ignoreAuthGuard:!0})]),Zs({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:Se.error||"Unable to resolve workspace after sign in.",code:Se.code}}catch{return{success:!1,error:"Sign in failed."}}},[Yn,na,Pn,Ts,Zs,I,V]),ul=a.useCallback(async(m,A,N)=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const z=m.trim().toLowerCase(),ke=A;if(!z||!ke)return{success:!1,error:"Email and password are required."};try{const me=await fetch(I("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:z,password:ke,...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()}:{}})}),Se=await me.json().catch(()=>({}));return!me.ok||!Se?.success?{success:!1,error:Se?.error||"Create account failed.",code:Se?.code}:{success:!0,workspaceSetupRequired:!!Se?.workspaceSetupRequired,planSelectionRequired:Se?.planSelectionRequired===!0,checkoutPending:Se?.checkoutPending===!0,commercialState:typeof Se?.commercialState=="string"?Se.commercialState:null,verificationRequired:!!Se?.verificationRequired,verificationToken:typeof Se?.verificationToken=="string"?Se.verificationToken:void 0,emailSent:Se?.emailSent!==!1,emailError:typeof Se?.emailError=="string"?Se.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[I,V]),pi=a.useCallback(async m=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const A=String(m.displayName||"").trim(),N=typeof m.avatarDraftId=="string"?m.avatarDraftId.trim():"",z=m.clearAvatar===!0;if(!A)return{success:!1,error:"Display name is required."};try{const ke=await fetch(I("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:A,...N?{avatarDraftId:N}:{},...z?{clearAvatar:!0}:{}})}),me=await ke.json().catch(()=>({}));if(!ke.ok||!me?.success)return{success:!1,error:me?.error||"Failed to update profile.",code:me?.code};const Se={userId:typeof me?.profile?.userId=="string"?me.profile.userId:vt,email:typeof me?.profile?.email=="string"?me.profile.email:Et,displayName:typeof me?.profile?.displayName=="string"?me.profile.displayName:null,avatarUrl:typeof me?.profile?.avatarUrl=="string"?me.profile.avatarUrl:null};return Jn(Se.displayName||""),yt(Se.avatarUrl||""),{success:!0,profile:Se}}catch{return{success:!1,error:"Failed to update profile."}}},[I,V,Et,vt]),Lu=a.useCallback(async m=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const A=m.trim().toLowerCase();if(!A)return{success:!1,error:"Email is required."};try{const N=await fetch(I("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:A})}),z=await N.json().catch(()=>({}));return!N.ok||!z?.success?{success:!1,error:z?.error||"Failed to request verification email.",code:z?.code}:{success:!0,verificationToken:z?.verificationToken??null,emailSent:z?.emailSent!==!1,emailError:typeof z?.emailError=="string"?z.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[I,V]),pl=a.useCallback(async m=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const A=m.trim();if(!A)return{success:!1,error:"Token is required."};try{const N=await fetch(I("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:A})}),z=await N.json().catch(()=>({}));return!N.ok||!z?.success?{success:!1,error:z?.error||"Verification failed.",code:z?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[I,V]),_d=a.useCallback(async m=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const A=m.trim().toLowerCase();if(!A)return{success:!1,error:"Email is required."};try{const N=await fetch(I("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:A})}),z=await N.json().catch(()=>({}));return!N.ok||!z?.success?{success:!1,error:z?.error||"Failed to request password reset.",code:z?.code}:{success:!0,resetToken:z?.resetToken??null,emailSent:z?.emailSent!==!1,emailError:typeof z?.emailError=="string"?z.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[I,V]),ml=a.useCallback(async(m,A)=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const N=m.trim(),z=A;if(!N||!z)return{success:!1,error:"Token and password are required."};try{const ke=await fetch(I("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:N,password:z})}),me=await ke.json().catch(()=>({}));return!ke.ok||!me?.success?{success:!1,error:me?.error||"Failed to reset password.",code:me?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[I,V]),xo=a.useCallback(async m=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const A=m.trim();if(!A)return{success:!1,error:"Token is required."};try{const N=await fetch(I("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:A})}),z=await N.json().catch(()=>({}));return!N.ok||!z?.success?{success:!1,error:z?.error||"Invite inspection failed.",code:z?.code,state:z?.state}:{success:!0,state:z?.state,email:typeof z?.email=="string"?z.email:void 0,workspaceId:typeof z?.workspaceId=="string"?z.workspaceId:void 0,inviteeKind:z?.inviteeKind==="existing_user"?"existing_user":"new_user",passwordRequired:z?.passwordRequired===!0}}catch{return{success:!1,error:"Invite inspection failed."}}},[I,V]),ns=a.useCallback(async(m,A)=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const N=m.trim(),z=A;if(!N||!z)return{success:!1,error:"Token and password are required."};try{const ke=await fetch(I("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:N,password:z})}),me=await ke.json().catch(()=>({}));if(!ke.ok||!me?.success)return{success:!1,error:me?.error||"Invite acceptance failed.",code:me?.code};Ha(""),await Yn({force:!0});const Se=typeof me?.workspaceId=="string"?me.workspaceId:null,_t=await Ts({preferredWorkspaceId:Se});return _t.success?_t.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([na({ignoreAuthGuard:!0}),Pn(!0,{ignoreAuthGuard:!0})]),Zs({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:_t.error||"Unable to resolve workspace after invite acceptance.",code:_t.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[Yn,na,Pn,Ts,Zs,I,V]),Ao=a.useCallback(async m=>{if(!V)return{success:!1,error:"Cloud auth endpoint is not configured."};const A=m.trim();if(!A)return{success:!1,error:"Token is required."};try{const N=await fetch(I("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:A})}),z=await N.json().catch(()=>({}));if(!N.ok||!z?.success)return{success:!1,error:z?.error||"Invite join failed.",code:z?.code};Ha(""),await Yn();const ke=typeof z?.workspaceId=="string"?z.workspaceId:null,me=await Ts({preferredWorkspaceId:ke});return me.success?me.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([na({ignoreAuthGuard:!0}),Pn(!0,{ignoreAuthGuard:!0})]),Zs({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:me.error||"Unable to resolve workspace after invite join.",code:me.code}}catch{return{success:!1,error:"Invite join failed."}}},[Yn,na,Pn,Ts,Zs,I,V]),Mu=a.useCallback(async()=>{try{V&&await fetch(I("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if(oa.current=null,tn.current=!1,en.current=Date.now(),ct(!1),Kt(!0),Ot("anonymous"),xt(""),Dl(null),xn(""),Jn(""),yt(""),Vo("disconnected"),Vs(null),se(!0),at(He==="cloud"&&Pe),Fe(m=>{const A=String(m||"").trim();let N="default";return A&&A.toLowerCase()!=="default"?N=A:He!=="local"&&(N=Vd(Rt)||"default"),It.current=N,N}),Mt([]),Sr.current=!1,Me(null),He==="local"){await Promise.allSettled([na({ignoreAuthGuard:!0}),Pn(!0,{ignoreAuthGuard:!0}),pn({ignoreAuthGuard:!0}),Vr({ignoreAuthGuard:!0,force:!0})]);return}bs([]),Ei([]),Oo([])}},[Pe,I,V,Rt,He,na,pn,Vr,Pn]),fl=a.useCallback(async m=>{try{const A=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),N=await A.json().catch(()=>({}));return!A.ok||!N?.success?{success:!1,error:N?.error||`Create failed (${A.status})`}:(await Pn(!0),{success:!0,result:N?.results})}catch(A){return{success:!1,error:A.message}}},[Pn]),Bu=a.useCallback(async m=>{const A=await fetch("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m||{})}),N=await A.json().catch(()=>({}));if(!A.ok)throw new Error(N?.error||`Failed to create initiative (${A.status})`);return await pn(),N},[pn]),hl=a.useCallback(async(m,A)=>{const N=await fetch(`/api/taskforce/initiative/${encodeURIComponent(m)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(A||{})}),z=await N.json().catch(()=>({}));if(!N.ok)throw new Error(z?.error||`Failed to update initiative (${N.status})`);return await pn(),z},[pn]),Wu=a.useCallback(async m=>{const A=await fetch(`/api/taskforce/initiative/${encodeURIComponent(m)}/archive`,{method:"POST"}),N=await A.json().catch(()=>({}));if(!A.ok)throw new Error(N?.error||`Failed to archive initiative (${A.status})`);return await pn(),N},[pn]),Ns=a.useCallback(async m=>{const A=await fetch(`/api/taskforce/initiative/${encodeURIComponent(m)}/unarchive`,{method:"POST"}),N=await A.json().catch(()=>({}));if(!A.ok)throw new Error(N?.error||`Failed to unarchive initiative (${A.status})`);return await pn(),N},[pn]),Fu=a.useCallback(async m=>{const A=await fetch("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m||{})}),N=await A.json().catch(()=>({}));if(!A.ok)throw new Error(N?.error||`Failed to create workstream (${A.status})`);return await pn(),N},[pn]),js=a.useCallback(async(m,A)=>{const N=await fetch(`/api/taskforce/workstream/${encodeURIComponent(m)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(A||{})}),z=await N.json().catch(()=>({}));if(!N.ok)throw new Error(z?.error||`Failed to update workstream (${N.status})`);return await pn(),z},[pn]),Cd=a.useCallback(async m=>{const A=await fetch(`/api/taskforce/workstream/${encodeURIComponent(m)}/archive`,{method:"POST"}),N=await A.json().catch(()=>({}));if(!A.ok)throw new Error(N?.error||`Failed to archive workstream (${A.status})`);return await pn(),N},[pn]),xd=a.useCallback(async m=>{const A=await fetch(`/api/taskforce/workstream/${encodeURIComponent(m)}/unarchive`,{method:"POST"}),N=await A.json().catch(()=>({}));if(!A.ok)throw new Error(N?.error||`Failed to unarchive workstream (${A.status})`);return await pn(),N},[pn]),mi=a.useRef(!1),wr=a.useRef(!1);a.useEffect(()=>{de(!0),!mi.current&&(mi.current=!0,Yn())},[Yn]),a.useEffect(()=>{Z&&Yn()},[Z,Yn]),a.useEffect(()=>{if(He!=="local"||!W||typeof window>"u")return;const m=()=>{Yn()},A=()=>{document.visibilityState==="visible"&&m()};window.addEventListener("focus",m),window.addEventListener("online",m),document.addEventListener("visibilitychange",A);const N=window.setInterval(m,3e4);return()=>{window.removeEventListener("focus",m),window.removeEventListener("online",m),document.removeEventListener("visibilitychange",A),window.clearInterval(N)}},[He,W,Yn]),a.useEffect(()=>{wn||nn||wr.current||(wr.current=!0,(async()=>{if(He==="cloud"&&rn&&Xe){const m=await Ts();if(!m.success||m.workspaceSetupRequired){await li(),Vr();return}}await li(),await Promise.all([(async()=>{const m=typeof performance<"u"?performance.now():Date.now();await Pn(!1),Hn("bootstrap_tasks_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-m)})})(),Vr(),pn()]),typeof window<"u"&&(ts.current!==null&&window.clearTimeout(ts.current),ts.current=window.setTimeout(()=>{ts.current=null;const m=typeof performance<"u"?performance.now():Date.now();La(!0).then(()=>{Hn("bootstrap_archive_loaded_deferred",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-m)})})},1500))})())},[wn,nn,He,rn,Xe,Ts,li,Pn,La,Vr,pn]),a.useEffect(()=>{if(wn||nn||bn||Rt===Lo||!wr.current)return;const m=`${He}:${Ee}:${Rt}`;pc.current!==m&&(pc.current=m,na())},[Ee,wn,nn,bn,He,Rt,na]),a.useEffect(()=>{if(wn||nn||bn)return;const m=Ee;Ba.current!==m&&(Ba.current=m,Br())},[wn,nn,Ee,Br,bn]),a.useEffect(()=>{if(He!=="cloud"||!rn||!Xe){He!=="cloud"&&Mt([]),Sr.current=!1;return}bn||!wr.current||Sr.current||Fn()},[He,rn,Xe,Fn,bn]),a.useEffect(()=>{s&&s(xa.length)},[xa.length,s]),a.useEffect(()=>{if(n&&xa.length>0){const m=xa.find(A=>A.id.endsWith(n)||A.id===n);m&&(Ld(m),To("add"))}},[n,xa]);const fc=a.useRef(!1);a.useEffect(()=>{if(!$a)return;if(!fc.current&&Cn.length>0){fc.current=!0;const A=Qo,N=Cn.some(z=>z.label===A||z.value===A);if(A&&N){const z=Cn.find(ke=>ke.label===A||ke.value===A);Fr(z?.value||A)}else Fr(za(Cn));return}const m=Cn.some(A=>A.value===go);Cn.length>0&&!m&&Fr(za(Cn))},[$a,Cn,go,za,Qo]),a.useEffect(()=>{if(!$a||Cn.length===0)return;const m=z=>!Cn.some(ke=>ke.value===z.category),A=xa.some(m),N=us.some(m);if(A||N){const z=za(Cn);A&&bs(ke=>ke.map(me=>m(me)?{...me,category:z}:me)),N&&io(ke=>ke.map(me=>m(me)?{...me,category:z}:me))}},[$a,Cn,xa,us,za]),a.useEffect(()=>()=>{ts.current!==null&&typeof window<"u"&&(window.clearTimeout(ts.current),ts.current=null),Za.current!==null&&typeof window<"u"&&(window.clearTimeout(Za.current),Za.current=null)},[]),a.useEffect(()=>{},[hr]);const hc=a.useCallback(async()=>{await Go()},[Go]),gl=String(Ee||"").trim(),br=String(vt||"").trim(),fi=Ie("/taskforce-ws"),Ad=!!(V&&He==="cloud"&&rn&&Xe&&br&&br!=="anonymous"&&gl&&!Op(gl)&&fi),Id=a.useCallback(()=>{He==="cloud"&&(Go(),!(typeof window>"u")&&(Za.current!==null&&window.clearTimeout(Za.current),Za.current=window.setTimeout(()=>{Za.current=null,Go()},250)))},[He,Go]);Gf({enabled:Ad,workspaceId:gl,websocketUrl:fi,onSignal:Id,userId:br||void 0}),a.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||wS({isOpen:ne,authBlocked:Je,authRequiredForApi:Pe,isAuthenticated:Xe,canCallProtectedApi:rt.canCallProtectedApi}))return;let m=!1;const A=async()=>{if(!(m||document.visibilityState!=="visible")&&!bS({shouldGateProtectedApiCalls:F,authSessionResolved:al.current,authRequiredForApi:dc.current,isAuthenticated:Sd.current}))try{const ke=await fetch("/api/taskforce/data-version");if(!ke.ok)return;const me=await ke.json(),Se=Number(me?.dataVersion);if(!Number.isFinite(Se))return;if(cc.current===null){cc.current=Se;return}Se!==cc.current&&(cc.current=Se,await hc())}catch{}},N=()=>{document.visibilityState==="visible"&&A()},z=window.setInterval(A,3e3);return document.addEventListener("visibilitychange",N),A(),()=>{m=!0,window.clearInterval(z),document.removeEventListener("visibilitychange",N)}},[ne,Pn,La,Je,Pe,Xe,rt,F,hc]);const gc=a.useMemo(()=>{const m=new Map;for(const A of us)m.set(A.id,A);for(const A of xa)m.set(A.id,A);return Array.from(m.values())},[xa,us]),yc=a.useMemo(()=>Rr.map(m=>({...m.taskSnapshot,isDeleted:!0,deletedRecordId:m.id})),[Rr]);a.useEffect(()=>{if(!(wn||nn)&&ne&&!bn){if(L==="tasks"){const m=`${Ee}:${L}:${G?"archive":"active"}:${be}`;if(!lc.current){lc.current=!0,ri.current=m;return}if(ri.current===m)return;ri.current=m,Pn(),(G||be==="archived")&&La(!0),be==="deleted"&&Ta();return}if(L==="settings"){const m=`${Ee}:${L}:${gn}`;if(oi.current===m)return;oi.current=m,na(),(gn==="commands"||gn==="resources")&&Qn()}}},[Ee,ne,L,gn,G,be,Pn,La,Ta,na,Qn,wn,nn,bn]);const Zr=a.useCallback(async(m="")=>{try{const A=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(m)}`);if(A.ok){const N=await A.json();St(N.folders||[]),zt(N.files||[]),sn(m)}}catch(A){console.error("[Taskforce] Failed to fetch folders:",A)}},[]),hi=a.useCallback(m=>{const A=[];if(m.path&&A.push(m.path),m.paths&&m.paths.length>0)for(const N of m.paths)A.includes(N)||A.push(N);return A},[]),{validatePaths:gs,handleUpdateCategory:Io,handleSaveCategory:gi,handleAddPath:yl,handleUpdateCategoryIcon:Td,handleUpdateCategoryColor:kl,handleRemovePath:Ou,handleSelectPath:Sl,handleRemoveCategory:vl,handleSaveType:Nd,handleRemoveType:jd,handleUpdateType:kc,handleUpdateTaxonomies:Rd,handleUpdatePriorities:Xs,analyzeSystemTaxonomyPack:$u,handleApplySystemTaxonomyPack:Dd}=Gk({activeCategories:Cn,activeTab:L,activeTypes:Xa,archivedTasks:us,browserTarget:Jt,category:go,configLoaded:$a,customCategories:Pr,refreshTaskCollections:hr,fetchTasks:Pn,filterCategories:ei,getCategoryPaths:hi,normalizePath:bu,pathValidation:dr,setBrowserTarget:Xt,setCategory:Fr,setCustomCategories:Uo,setCustomTypes:zo,setFilterCategories:Ji,setPathValidation:Wc,setPriorities:wa,setShowFolderBrowser:Ye,setTaxonomies:ta,tasks:xa}),Pd=a.useCallback(async m=>{const A=Cs,N={...A,...m};Er(N);try{const z=await fetch("/api/taskforce/taxonomy-display-labels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLabels:m})});if(!z.ok)throw new Error(`Failed to save taxonomy display labels (${z.status})`);const ke=await z.json().catch(()=>({}));ke?.displayLabels&&typeof ke.displayLabels=="object"&&Er({...N,...ke.displayLabels})}catch(z){console.error("[Taskforce] Failed to update taxonomy display labels",z),Er(A)}},[Cs]),To=a.useCallback(m=>{L==="tasks"&&Pi.current&&cr(Pi.current.scrollTop),le(m)},[L]),Qs=a.useRef(async()=>{}),{handleNavigation:Uu,handleClose:zu,resetForm:wl,resolveWorkstreamIdInput:Ed,handleEdit:Ld,handleOpenTaskById:Rs,returnToPreviousTask:Md,clearReturnToParentTask:yi}=tS({activeCategories:Cn,activeTypes:Xa,activeTab:L,attachments:nl,checklistItems:qi,comments:Yi,description:Zi,editingTaskId:ps,flushPendingAutoSave:()=>Qs.current(),getPreferredCategoryValue:za,lastUsedCategory:Qo,newCommentText:id,relationshipTasks:gc,workstreams:_s,showArchive:G,taxonomies:Ea,setActiveTab:To,setApproach:zc,setAssignee:$r,setAttachments:oc,setAttachmentsDirty:ic,setCategory:Fr,setChecklistItems:Ki,setComments:Vc,setComplexity:Ga,setDescription:Ks,setDueDate:Jo,setEditingTaskId:Li,setError:Ha,setFormTaxonomies:Xo,setIsOpen:de,setNewCommentText:Qa,setPendingNavigation:Dn,setWorkstreamInput:Vi,setPriority:sd,setScheduledDate:od,setShowArchive:ee,setStatus:zi,setTaskReturnTrail:jr,setTitle:Gc,setType:Na,setUnsavedModalOpen:ds,taskReturnTrail:Wo,title:lt}),{copiedId:er,handleDelete:bl,handleUpdateTask:_l,handleToggleComplete:Cl,handleToggleCancel:qr,handleToggleInProgress:tr,handleToggleReview:No,handleArchiveTask:Sc,handleBulkArchive:xl,handleUnarchive:Hu,handleRestoreDeletedTask:Bd,handlePermanentlyDeleteDeletedTask:ki,handleEmptyDeletedTasks:Gu,handleCopyId:Al,queueWorkspaceSyncFromAuthoritativeTaskState:Wd}=yS({tasks:xa,archivedTasks:us,editingTaskId:ps,setTasks:bs,setArchivedTasks:io,setDeletedTasks:co,setError:Ha,resetForm:wl,setActiveTab:To,fetchTasks:Pn,fetchArchive:La,fetchDeletedTasks:Ta,mergeTaskFromServer:Is,pushNotice:Us,cloudAuthConfigured:V,runtimeMode:He,isAuthenticated:Xe,workspaceCloudSyncEnabled:Wi,buildWorkspaceSyncSignature:Wr,pushWorkspaceChangesToCloud:ma,workspacePendingSignatureRef:ho,workspaceDeletedTaskIdsRef:qo}),{autoSaveState:Il,flushAutoSave:Tl,scheduleWarningPrompt:Fd,handleSubmit:Os,confirmScheduleWarning:Od,cancelScheduleWarning:$d,handleAddComment:Ud}=fS({activeCategories:Cn,activeTab:L,apiEndpoint:p,approach:Yo,assignee:Hc,attachments:nl,attachmentsDirty:kd,category:go,checklistItems:qi,comments:Yi,complexity:rd,description:Zi,dueDate:Gi,editingTaskId:ps,fetchTasks:Pn,formTaxonomies:ra,getPreferredCategoryValue:za,mergeTaskFromServer:Is,workstreamInput:yo,priority:qs,pushNotice:Us,queueWorkspaceSyncFromAuthoritativeTaskState:Wd,relationshipTasks:gc,resetForm:wl,resolveWorkstreamIdInput:Ed,scheduledDate:Hi,setActiveTab:To,setAttachmentsDirty:ic,setComments:Vc,setError:Ha,setLastUsedCategory:cd,setLoading:ur,setNewCommentText:Qa,status:Ui,title:lt,taxonomies:Ea,type:Or});a.useEffect(()=>{Qs.current=Tl},[Tl]);const{handleSetWorkstreamForCurrentTask:Vu}=hS({editingTaskId:ps,mergeTaskFromServer:Is,workstreamInput:yo,pushNotice:Us,queueWorkspaceSyncFromAuthoritativeTaskState:Wd,relationshipTasks:gc,resolveWorkstreamIdInput:Ed,setError:Ha,fetchTasks:Pn}),{currentTask:Zu,currentTaskWorkstream:qu,currentTaskInitiative:Ku}=Yk({editingTaskId:ps,relationshipTasks:gc,initiatives:lr,workstreams:_s,supplementalTasks:yc,setComments:Vc}),jo=zk({resolveCloudAuthUrl:I,currentWorkspaceId:Ee,normalizedCloudAuthBaseUrl:Le,normalizedCloudMcpBaseUrl:Oe,mergedConfig:o,availableWorkspaces:An,currentTheme:fe,configLoaded:$a,globalTheme:Ke,themeUseGlobalDefault:dt,keyShortcut:la,jsonBackupEnabled:os,globalJsonBackupEnabled:is,globalWeekStartsOn:dn,locale:Ve,supportedLocales:bt,jsonBackupUseGlobalDefault:Da,manualComplexityEnabled:da,checklistDropdownEnabled:Zn,showTaskCardStatusLabel:ga,exportWorkflowsPath:Ue,exportingResource:J,exportResult:Be,pathSaved:gt,settingsSection:gn,exportEnvironment:ir,setupState:Sa,buildInfo:ln,saveSetupMode:Pu,saveWorkspaceProfile:Js,setCurrentTheme:De,handleSaveTheme:mc,handleSaveGlobalTheme:Iu,setKeyShortcut:va,handleJsonBackupEnabledChange:ol,handleSaveGlobalJsonBackupEnabled:Tu,handleSaveGlobalWeekStartsOn:Nu,handleSaveLocale:il,handleManualComplexityEnabledChange:ju,handleChecklistDropdownEnabledChange:cl,handleShowTaskCardStatusLabelChange:bo,handleResetProjectToGlobal:Ru,handleSaveSettings:rl,setExportWorkflowsPath:Re,setExportEnvironment:Bo,availableWorkflows:or,initiativeTemplates:ua,availableEnvironments:T,fetchWorkflows:Qn,fetchInitiativeTemplates:Bs,createInitiativeFromTemplate:fl,fetchWorkflowTemplate:oo,fetchWorkflowOverrideNames:Nr,saveWorkflowTemplateDraft:Ge,resetWorkflowTemplateDraft:Ut,handleExportWorkflows:ht,setShowFolderBrowser:Ye,setBrowserTarget:Xt,fetchFolders:Zr,activeCategories:Cn,pathValidation:dr,taxonomyDisplayLabels:Cs,handleUpdateCategory:Io,handleRemoveCategory:vl,handleSaveCategory:gi,handleAddPath:yl,handleRemovePath:Ou,handleUpdateCategoryIcon:Td,handleUpdateCategoryColor:kl,activeTypes:Xa,handleSaveType:Nd,handleRemoveType:jd,handleUpdateType:kc,taxonomies:Ea,handleUpdateTaxonomies:Rd,priorities:Un,handleUpdatePriorities:Xs,analyzeSystemTaxonomyPack:$u,handleApplySystemTaxonomyPack:Dd,handleUpdateTaxonomyDisplayLabels:Pd,projectRoot:un,projectName:an,mcpHostRoot:rs,serverHostRoot:Ja,mcpScriptPath:we,tenantId:Qt,runtimeMode:He,workspaceSwitchingEnabled:_e,deleteWorkspace:ui,setMcpHostRoot:sa,isAuthenticated:Xe});a.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:xa,archivedTasks:us,runtimeMode:He,currentWorkspaceId:Ee,isAuthenticated:Xe,workspaceCloudSyncEnabled:Wi,realtimeSyncEnabled:vs,fetchTasks:Pn,fetchArchive:La,retryWorkspaceCloudSync:Fi,resetWorkspaceSyncCursorAndPull:Oi,getSyncDiagnostics:gr,__dispatch:{handleUpdateTask:_l,handleToggleComplete:Cl,handleArchiveTask:Sc,handleToggleCancel:qr,handleToggleInProgress:tr,handleToggleReview:No,handleSubmit:Os,handleDelete:bl}})},[xa,us,He,Ee,Xe,Wi,vs,Pn,La,Fi,Oi,gr,_l,Cl,Sc,qr,tr,No,Os,bl]);const vc=Ws&&Ws.tone!=="error"?{message:Ws.message,type:"info"}:null,Nl=String(_||S.wsBaseUrl||xe||"").trim().replace(/\/+$/,"");return{config:{...o,cloudEnvironment:S.cloudEnvironment||o.cloudEnvironment||"",apiBaseUrl:xe||o.apiBaseUrl,cloudAuthBaseUrl:Le||o.cloudAuthBaseUrl,wsBaseUrl:Nl||o.wsBaseUrl},isOpen:ne,setIsOpen:de,activeTab:L,setActiveTab:To,currentTheme:fe,setCurrentTheme:De,configLoaded:$a,storagePath:et,saveSettings:rl,pathSaved:gt,keyShortcut:la,setKeyShortcut:va,globalWeekStartsOn:dn,locale:Ve,supportedLocales:bt,saveLocale:il,jsonBackupEnabled:os,setJsonBackupEnabled:ba,manualComplexityEnabled:da,checklistDropdownEnabled:Zn,showTaskCardStatusLabel:ga,setManualComplexityEnabled:_a,mcpHostRoot:rs,setMcpHostRoot:sa,settingsSection:gn,setSettingsSection:Mn,runtimeMode:He,workspaceMode:Ae,workspaceSwitchingEnabled:_e,cloudAuthConfigured:V,authRequiredForApi:Pe,authBlocked:Je,isAuthenticated:Xe,authUserId:vt,authUserEmail:Et,authUserDisplayName:Gt,authUserAvatarUrl:kn,authWorkspaceId:Pt,userGlobalSyncStatus:_u,workspaceLastPullAt:Mr,workspaceLastPushAt:Zo,workspaceLastErrorAt:Cu,userGlobalSyncError:Ma,workspaceLastErrorMessage:Ql,workspaceLastSuccessfulSyncAt:fo,workspaceSyncPhase:ed,workspaceSyncStatus:td,workspaceSyncSummary:nd,workspaceSyncRecommendedAction:Fc,workspaceSyncBusy:ad,workspaceSyncPendingChanges:Oc,retryUserGlobalSettingsSync:Uc,retryWorkspaceCloudSync:Fi,resetWorkspaceSyncCursorAndPull:Oi,getWorkspaceSyncDiagnostics:gr,hasBetaAccess:Gn,realtimeSyncEnabled:vs,realtimeSyncFlagSource:Ya,currentWorkspaceId:Ee,currentWorkspaceRole:bd,availableWorkspaces:An,assigneeOptions:fa,workspaceCloudSyncEnabled:Wi,saveWorkspaceCloudSyncSettings:Ko,applyWorkspaceSyncStateSnapshot:$c,authSessionResolved:rn,workspaceBootstrapPending:bn,bootstrapPhase:kt,bootstrapError:Yt,bootstrapStartedAt:ft,setupState:Sa,runtimeCapabilities:Fa,refreshSetupContext:di,retryBootstrapChecks:dl,saveWorkspaceProfile:Js,fetchWorkspaces:Fn,createWorkspace:Du,deleteWorkspace:ui,switchWorkspace:vr,loginWithCredentials:Eu,registerWithCredentials:ul,updateCurrentUserProfile:pi,requestEmailVerification:Lu,confirmEmailVerification:pl,requestPasswordReset:_d,confirmPasswordReset:ml,inspectInviteAcceptance:xo,acceptInviteWithToken:ns,joinInviteWithToken:Ao,logout:Mu,showFolderBrowser:O,setShowFolderBrowser:Ye,folders:wt,files:At,currentBrowsePath:Ht,fetchFolders:Zr,browserTarget:Jt,setBrowserTarget:Xt,groupBy:tc,setGroupBy:yr,activeWorkspaceModule:si,setActiveWorkspaceModule:sc,emptyColumnMode:nc,setEmptyColumnMode:ac,zenMode:Pa,setZenMode:ws,handleSelectPath:Sl,handleAddPath:yl,handleRemovePath:Ou,tasks:xa,loadingTasks:$o,archivedTasks:us,initiatives:lr,workstreams:_s,deletedTasks:Rr,activeCategories:Cn,activeTypes:Xa,priorities:Un,taxonomyDisplayLabels:Cs,approaches:Ls,taxonomies:Ea,searchQuery:hs,setSearchQuery:ld,filterCategories:ei,setFilterCategories:Ji,filterTypes:vo,setFilterTypes:qc,filterPriorities:ko,setFilterPriorities:So,filterStatus:ti,setFilterStatus:dd,filterAssignees:Kc,setFilterAssignees:ni,filterTaxonomies:zr,setFilterTaxonomies:wo,sortBy:ai,setSortBy:ec,sortOrder:Yc,setSortOrder:Jc,toggleSortOrder:ud,showArchive:G,setShowArchive:ee,taskScope:be,setTaskScope:$e,clearFilters:Xc,filteredTasks:Va,searchAgnosticTasks:md,filteredArchive:fd,groupedTasks:hd,collapsedCategories:pd,setCollapsedCategories:Au,fetchTasks:Pn,fetchArchive:La,fetchDeletedTasks:Ta,fetchPlanningEntities:pn,fetchAssigneeOptions:Co,createInitiative:Bu,updateInitiative:hl,archiveInitiative:Wu,unarchiveInitiative:Ns,createWorkstream:Fu,updateWorkstream:js,archiveWorkstream:Cd,unarchiveWorkstream:xd,handleEdit:Ld,handleDelete:bl,handleCopyId:Al,handleToggleComplete:Cl,handleToggleCancel:qr,handleToggleInProgress:tr,handleToggleReview:No,handleArchiveTask:Sc,handleBulkArchive:xl,handleUnarchive:Hu,handleRestoreDeletedTask:Bd,handlePermanentlyDeleteDeletedTask:ki,handleEmptyDeletedTasks:Gu,handleUpdateTask:_l,editingTaskId:ps,loading:Xl,error:Fs,title:lt,setTitle:Gc,description:Zi,setDescription:Ks,checklistItems:qi,setChecklistItems:Ki,category:go,setCategory:Fr,type:Or,setType:Na,priority:qs,setPriority:sd,complexity:rd,setComplexity:Ga,status:Ui,setStatus:zi,approach:Yo,setApproach:zc,assignee:Hc,setAssignee:$r,scheduledDate:Hi,setScheduledDate:od,dueDate:Gi,setDueDate:Jo,workstreamInput:yo,setWorkstreamInput:Vi,formTaxonomies:ra,setFormTaxonomies:Xo,comments:Yi,newCommentText:id,setNewCommentText:Qa,attachments:nl,setAttachments:oc,attachmentsDirty:kd,setAttachmentsDirty:ic,descriptionFocused:rc,setDescriptionFocused:gd,showMarkdownHelp:Dr,setShowMarkdownHelp:Bc,showChecklist:Zc,setShowChecklist:Ur,showComments:Qc,setShowComments:el,isCapturingScreenshot:yd,setIsCapturingScreenshot:tl,handleSubmit:Os,resetForm:wl,handleAddComment:Ud,handleSetWorkstreamForCurrentTask:Vu,handleOpenTaskById:Rs,returnToPreviousTask:Md,autoSaveState:Il,unsavedModalOpen:Nt,setUnsavedModalOpen:ds,pendingNavigation:Kn,handleNavigation:Uu,handleClose:zu,uiNotice:Ws,pushNotice:Us,clearNotice:zs,successBanner:vc,taskReturnTrail:Wo,clearReturnToParentTask:yi,copiedId:er,recentlyChangedTaskIds:Lr,scheduleWarningPrompt:Fd,confirmScheduleWarning:Od,cancelScheduleWarning:$d,tasksScrollRef:Pi,setTasksScrollPos:cr,exportEnvironment:ir,setExportEnvironment:Bo,exportWorkflowsPath:Ue,setExportWorkflowsPath:Re,exportResult:Be,exportingResource:J,handleUpdateCategory:Io,handleRemoveCategory:vl,handleSaveCategory:gi,handleUpdateCategoryIcon:Td,handleUpdateCategoryColor:kl,handleSaveType:Nd,handleRemoveType:jd,handleUpdateType:kc,handleUpdateTaxonomies:Rd,handleUpdatePriorities:Xs,handleUpdateTaxonomyDisplayLabels:Pd,pathValidation:dr,validatePaths:gs,getCategoryPaths:hi,customCategories:Pr,setCustomCategories:Uo,projectRoot:un,projectName:an,mcpScriptPath:we,serverHostRoot:Ja,commentsEndRef:xu,currentTask:Zu,currentTaskWorkstream:qu,currentTaskInitiative:Ku,availableWorkflows:or,initiativeTemplates:ua,availableEnvironments:T,fetchWorkflows:Qn,fetchInitiativeTemplates:Bs,createInitiativeFromTemplate:fl,fetchWorkflowTemplate:oo,fetchWorkflowOverrideNames:Nr,saveWorkflowTemplateDraft:Ge,resetWorkflowTemplateDraft:Ut,onExportWorkflows:ht,settingsModel:jo}}const xS="modulepreload",AS=function(e){return"/taskforce/"+e},Lm={},Mo=function(n,s,r){let o=Promise.resolve();if(s&&s.length>0){let h=function(w){return Promise.all(w.map(b=>Promise.resolve(b).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),p=i?.nonce||i?.getAttribute("nonce");o=h(s.map(w=>{if(w=AS(w),w in Lm)return;Lm[w]=!0;const b=w.endsWith(".css"),_=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${w}"]${_}`))return;const k=document.createElement("link");if(k.rel=b?"stylesheet":xS,b||(k.as="script"),k.crossOrigin="",k.href=w,p&&k.setAttribute("nonce",p),document.head.appendChild(k),b)return new Promise((g,C)=>{k.addEventListener("load",g),k.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${w}`)))})}))}function l(i){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=i,window.dispatchEvent(p),!p.defaultPrevented)throw i}return o.then(i=>{for(const p of i||[])p.status==="rejected"&&l(p.reason);return n().catch(l)})},IS="_filterGlow_19036_13",TS="_floatingButton_19036_23",NS="_badge_19036_54",jS="_configBadge_19036_71",RS="_configBadgeActive_19036_81",DS="_configBadgeRevoked_19036_87",PS="_configBadgeExpired_19036_93",ES="_header_19036_103",LS="_headerTitle_19036_118",MS="_brandIcon_19036_135",BS="_brandCloudSuffix_19036_141",WS="_projectSlash_19036_146",FS="_projectName_19036_153",OS="_taskCountBadge_19036_172",$S="_taskCountBadgeIcon_19036_189",US="_taskCountBadgeAlert_19036_193",zS="_headerActions_19036_199",HS="_sortDirectionBtn_19036_206",GS="_sortDirectionBtnWidget_19036_213",VS="_form_19036_221",ZS="_topRow_19036_233",qS="_field_19036_239",KS="_labelRow_19036_245",YS="_label_19036_245",JS="_manageLink_19036_259",XS="_input_19036_278",QS="_select_19036_279",ev="_textarea_19036_280",tv="_taskIdInlineLink_19036_314",nv="_readOnly_19036_333",av="_selectWithConfig_19036_341",sv="_configBtn_19036_351",rv="_configBtnActive_19036_381",ov="_hasPath_19036_389",iv="_pathIndicator_19036_394",cv="_formActions_19036_400",lv="_hasCancel_19036_407",dv="_submitBtn_19036_411",uv="_cancelBtn_19036_427",pv="_successMessage_19036_459",mv="_successIcon_19036_465",fv="_spinner_19036_485",hv="_spin_19036_485",gv="_boardRefreshIndicator_19036_489",yv="_destructiveBtn_19036_519",kv="_warningBtn_19036_542",Sv="_viewTab_19036_565",vv="_deleteBtn_19036_576",wv="_loading_19036_586",bv="_emptyState_19036_592",_v="_taskList_19036_602",Cv="_taskIdBadge_19036_608",xv="_taskIdBadgeLabel_19036_630",Av="_copiedId_19036_649",Iv="_highlight_19036_655",Tv="_modal_19036_667",Nv="_priorityEmoji_19036_675",jv="_metaItem_19036_679",Rv="_taskFormDateInput_19036_693",Dv="_metaBadge_19036_703",Pv="_complexityPill_19036_718",Ev="_complexityDots_19036_722",Lv="_dot_19036_728",Mv="_dotFilled_19036_736",Bv="_typePill_19036_742",Wv="_type_bug_19036_746",Fv="_type_feature_19036_750",Ov="_type_chore_19036_754",$v="_type_refactor_19036_758",Uv="_type_documentation_19036_762",zv="_type_research_19036_766",Hv="_type_security_19036_774",Gv="_approachPill_19036_779",Vv="_approach_evaluate_19036_784",Zv="_approach_collaborate_19036_790",qv="_approach_plan_19036_796",Kv="_approachActive_19036_802",Yv="_statusActionsGroup_19036_807",Jv="_statusActionsGroupCompact_19036_813",Xv="_statusSelectWrap_19036_817",Qv="_statusTaxonomyDropdownWrap_19036_823",ew="_statusTaxonomyDropdown_19036_823",tw="_statusTaxonomyDropdownCompact_19036_831",nw="_statusTaxonomyDropdownIconOnly_19036_835",aw="_taxonomyDropdownButton_19036_840",sw="_taxonomyDropdownButtonContent_19036_857",rw="_statusTaxonomyDropdownIconOnlyPanel_19036_861",ow="_actionBtn_19036_867",iw="_startWorkBtn_19036_891",cw="_workingBtn_19036_900",lw="_pulse_19036_1",dw="_reviewBtn_19036_906",uw="_reviewActiveBtn_19036_916",pw="_reviewPill_19036_922",mw="_archiveTaskBtn_19036_929",fw="_bulkArchiveBtn_19036_938",hw="_bulkDeleteBtn_19036_960",gw="_completeBtn_19036_1001",yw="_completeActiveBtn_19036_1011",kw="_deleteActiveBtn_19036_1017",Sw="_disabledBtn_19036_1023",vw="_archiveList_19036_1030",ww="_archiveHeader_19036_1038",bw="_settingsTab_19036_1049",_w="_settingsTabs_19036_1061",Cw="_settingsLayout_19036_1075",xw="_settingsSidebar_19036_1082",Aw="_settingsSidebarHeader_19036_1092",Iw="_settingsSidebarNav_19036_1101",Tw="_settingsSidebarBtn_19036_1110",Nw="_settingsSidebarBtnActive_19036_1134",jw="_settingsSidebarGroup_19036_1141",Rw="_settingsSidebarGroupBtn_19036_1147",Dw="_settingsSidebarGroupLabel_19036_1151",Pw="_settingsSidebarGroupChevron_19036_1155",Ew="_settingsSidebarSubnav_19036_1161",Lw="_settingsSidebarSubBtn_19036_1168",Mw="_appScrollbar_19036_1191",Bw="_settingsTabBtn_19036_1195",Ww="_settingsTabBtnActive_19036_1221",Fw="_settingsContent_19036_1227",Ow="_settingsToast_19036_1275",$w="_settingsToastSuccess_19036_1292",Uw="_settingsToastError_19036_1298",zw="_inputWithPrefix_19036_1304",Hw="_pathHint_19036_1311",Gw="_settingGroup_19036_1324",Vw="_settingTitle_19036_1330",Zw="_settingTitleRow_19036_1339",qw="_settingTitleActionBtn_19036_1346",Kw="_themeOptions_19036_1366",Yw="_buttonGrid_19036_1371",Jw="_themeBtn_19036_1383",Xw="_activeTheme_19036_1407",Qw="_pathInputGroup_19036_1415",eb="_saveSettingsBtn_19036_1424",tb="_shortcutInputWrapper_19036_1445",nb="_inputIcon_19036_1450",ab="_settingHelper_19036_1459",sb="_browseBtn_19036_1466",rb="_inlineCategoryManager_19036_1485",ob="_categoryManager_19036_1496",ib="_categoryList_19036_1502",cb="_categoryChip_19036_1514",lb="_categoryChipLabel_19036_1527",db="_chipActionBtn_19036_1535",ub="_removeCategoryBtn_19036_1555",pb="_addCategoryForm_19036_1575",mb="_addCategoryBtn_19036_1580",fb="_filesList_19036_1605",hb="_helpLink_19036_1632",gb="_inlineCode_19036_1653",yb="_codeBlock_19036_1664",kb="_taskChildrenSummaryBadges_19036_1688",Sb="_taskChildrenProgressBar_19036_1696",vb="_taskChildrenProgressBarSegmentDone_19036_1707",wb="_taskChildrenProgressBarSegmentReview_19036_1713",bb="_taskChildrenProgressBarSegmentInProgress_19036_1719",_b="_taskChildrenProgressBarSegmentBlocked_19036_1725",Cb="_taskChildrenProgressText_19036_1731",xb="_taskChildUnlinkBtn_19036_1740",Ab="_aboutText_19036_1758",Ib="_versionInfo_19036_1765",Tb="_filterBar_19036_1773",Nb="_kanbanHintText_19036_1787",jb="_searchContainer_19036_1793",Rb="_searchIcon_19036_1800",Db="_searchInput_19036_1808",Pb="_searchActive_19036_1834",Eb="_searchCount_19036_1839",Lb="_clearSearchBtn_19036_1855",Mb="_filterRow_19036_1877",Bb="_sortLabel_19036_1883",Wb="_archiveToggle_19036_1891",Fb="_filterContainer_19036_1928",Ob="_filterButton_19036_1933",$b="_filterActive_19036_1958",Ub="_filterDropdown_19036_1964",zb="_filterOption_19036_1979",Hb="_filterDivider_19036_2009",Gb="_filterSelect_19036_2015",Vb="_filterToggleBtn_19036_2056",Zb="_inProgressToggle_19036_2078",qb="_activeInProgress_19036_2096",Kb="_activeFilter_19036_2105",Yb="_resetFiltersBtn_19036_2115",Jb="_categoryChip_disabled_19036_2148",Xb="_categoryVisibilityToggle_19036_2158",Qb="_editCategoryInput_19036_2171",e_="_categoryChipActionBtn_19036_2182",t_="_categoryChipActionBtn_active_19036_2200",n_="_categoryGroup_19036_2205",a_="_categoryHeader_19036_2213",s_="_categoryTitle_19036_2227",r_="_categoryCount_19036_2237",o_="_categoryItems_19036_2243",i_="_priorityItem_low_19036_2252",c_="_priorityItem_medium_19036_2256",l_="_priorityItem_high_19036_2260",d_="_priorityItem_critical_19036_2264",u_="_priorityPill_low_19036_2268",p_="_priorityPill_medium_19036_2274",m_="_priorityPill_high_19036_2280",f_="_priorityPill_critical_19036_2286",h_="_selectPriority_low_19036_2301",g_="_selectPriority_medium_19036_2306",y_="_selectPriority_high_19036_2311",k_="_selectPriority_critical_19036_2316",S_="_levelSelect_19036_2325",v_="_levelOption_19036_2338",w_="_levelOptionFilled_19036_2355",b_="_levelOption_priority_low_19036_2362",__="_levelOption_priority_medium_19036_2367",C_="_levelOption_priority_high_19036_2372",x_="_levelOption_priority_critical_19036_2377",A_="_levelOption_complexity_tiny_19036_2384",I_="_levelOption_complexity_low_19036_2389",T_="_levelOption_complexity_medium_19036_2394",N_="_levelOption_complexity_high_19036_2399",j_="_levelOption_complexity_epic_19036_2404",R_="_levelOptionActive_19036_2411",D_="_levelOptionSelected_19036_2416",P_="_levelLabel_19036_2424",E_="_fadeIn_19036_1",L_="_closeConfigBtn_19036_2449",M_="_configItem_19036_2471",B_="_settingsLabel_19036_2477",W_="_settingsHint_19036_2486",F_="_pathList_19036_2493",O_="_pathChip_19036_2500",$_="_pathValid_19036_2513",U_="_pathInvalid_19036_2518",z_="_pathValidIcon_19036_2523",H_="_pathInvalidIcon_19036_2528",G_="_pathText_19036_2533",V_="_removePathBtn_19036_2540",Z_="_pathCount_19036_2562",q_="_specialistSection_19036_2585",K_="_toggleHeading_19036_2593",Y_="_dropdownList_19036_2633",J_="_specialistBadge_19036_2642",X_="_iconGrid_19036_2672",Q_="_iconPickerBtn_19036_2683",eC="_iconPickerBtnActive_19036_2702",tC="_categorySubConfig_19036_2709",nC="_colorPickerRow_19036_2717",aC="_colorPickerGrid_19036_2723",sC="_colorSwatch_19036_2730",rC="_colorSwatchActive_19036_2749",oC="_categoryChipIcon_19036_2755",iC="_fieldIconWrapper_19036_2760",cC="_fieldIcon_19036_2760",lC="_field_dynamic_19036_2782",dC="_fieldIcon_dynamic_19036_2788",uC="_categoryTitleIcon_19036_2792",pC="_editActionsHeader_19036_2798",mC="_editActionsGroup_19036_2807",fC="_urlInputGroup_19036_2814",hC="_iconBtn_19036_2827",gC="_stickyActionHeader_19036_2848",yC="_taskHierarchyHeader_19036_2865",kC="_taskHierarchyBadgeRow_19036_2872",SC="_taskHierarchyDivider_19036_2880",vC="_taskHierarchyMeta_19036_2886",wC="_taskHierarchyAddBtn_19036_2899",bC="_taskHierarchyEditor_19036_2905",_C="_taskHierarchyInput_19036_2912",CC="_taskSaveStatus_19036_2921",xC="_taskSaveStatusCenter_19036_2932",AC="_taskSaveStatusError_19036_2940",IC="_headerSuccessFeedback_19036_2944",TC="_slideInUp_19036_1",NC="_successCheck_19036_2956",jC="_scaleIn_19036_1",RC="_primaryUpdateBtn_19036_2992",DC="_secondaryHeaderBtn_19036_3020",PC="_secondaryHeaderBtnDestructive_19036_3041",EC="_commentSection_19036_3054",LC="_attachmentCaptureContainer_19036_3090",MC="_capturePrompt_19036_3098",BC="_previewContainer_19036_3112",WC="_previewHeader_19036_3118",FC="_attachmentCapturePreview_19036_3128",OC="_actions_19036_3135",$C="_primaryButton_19036_3141",UC="_secondaryButton_19036_3156",zC="_iconButton_19036_3171",HC="_attachmentGrid_19036_3193",GC="_attachmentCard_19036_3200",VC="_attachmentPreviewContainer_19036_3214",ZC="_contextFileLink_19036_3235",qC="_attachmentActions_19036_3261",KC="_attachmentActionBtn_19036_3275",YC="_attachmentCaptionInput_19036_3297",JC="_hiddenInput_19036_3315",XC="_contextUploadPanel_19036_3319",QC="_contextUploadActions_19036_3327",ex="_contextDropzone_19036_3335",tx="_contextDropzoneActive_19036_3351",nx="_contextDropzonePulse_19036_1",ax="_contextLinkRow_19036_3359",sx="_contextNotice_19036_3365",rx="_documentAttachmentList_19036_3371",ox="_documentAttachmentItem_19036_3378",ix="_documentAttachmentRow_19036_3385",cx="_documentAttachmentLink_19036_3393",lx="_documentAttachmentMain_19036_3407",dx="_documentAttachmentText_19036_3414",ux="_documentAttachmentIcon_19036_3422",px="_documentAttachmentName_19036_3433",mx="_documentAttachmentType_19036_3442",fx="_documentAttachmentActions_19036_3455",hx="_documentAttachmentActionBtn_19036_3461",gx="_documentAttachmentCaptionInput_19036_3482",yx="_brokenImage_19036_3510",kx="_brokenImagePlaceholder_19036_3518",Sx="_regionOverlay_19036_3532",vx="_selectionBox_19036_3543",wx="_exportRow_19036_3551",bx="_exportItem_19036_3556",_x="_taxonomyDrillDown_19036_3565",Cx="_drillDownList_19036_3575",xx="_drillDownSection_19036_3583",Ax="_drillDownSectionHeader_19036_3589",Ix="_drillDownSectionTitle_19036_3596",Tx="_drillDownItem_19036_3605",Nx="_drillDownItemDimmed_19036_3627",jx="_drillDownItemActive_19036_3635",Rx="_drillDownItemInfo_19036_3640",Dx="_drillDownItemText_19036_3646",Px="_drillDownItemLabel_19036_3651",Ex="_drillDownItemSubtext_19036_3656",Lx="_addTaxonomyBtnSmall_19036_3661",Mx="_taxonomyDetailView_19036_3683",Bx="_slideIn_19036_1",Wx="_detailHeader_19036_3703",Fx="_detailTitle_19036_3712",Ox="_detailContent_19036_3719",$x="_createOverlay_19036_3726",Ux="_createDialog_19036_3738",zx="_zoomIn_19036_1",Hx="_dialogActions_19036_3766",Gx="_settingsGroup_19036_3784",Vx="_settingsItem_19036_3790",Zx="_settingLabelGroup_19036_3796",qx="_settingLabel_19036_3796",Kx="_settingDescription_19036_3808",Yx="_settingInput_19036_3815",Jx="_codeBlockWrapper_19036_3838",Xx="_codeHeader_19036_3847",Qx="_codeHeaderActions_19036_3858",eA="_codeLabel_19036_3865",tA="_copyBtn_19036_3888",nA="_copyBtnActive_19036_3909",aA="_copyBtnNeutralActive_19036_3915",sA="_headerDivider_19036_3933",rA="_groupByContainer_19036_3939",oA="_groupByLabel_19036_3947",iA="_groupBySelect_19036_3952",cA="_viewSwitcher_19036_3974",lA="_selectWithIcon_19036_3982",dA="_marginBottom16_19036_3986",uA="_headerDraggable_19036_3991",pA="_headerDragging_19036_3995",mA="_filterSelectSort_19036_4003",fA="_archiveRow_19036_4007",hA="_taskScopeToggle_19036_4013",gA="_taskScopeTabs_19036_4021",yA="_taskScopeTab_19036_4021",kA="_taskScopeTabActive_19036_4054",SA="_taskToolbarAction_19036_4066",vA="_overlayHighZ_19036_4082",wA="_savedText_19036_4092",bA="_shortcutInput_19036_1445",_A="_saveSettingsBtnWrapper_19036_4100",CA="_marginBottom12_19036_4104",xA="_exportRowGrid_19036_4108",AA="_settingSubtitleCustom_19036_4113",IA="_capitalize_19036_4119",TA="_marginTop12_19036_4123",NA="_marginTop16_19036_4127",jA="_labelGroupFlex_19036_4131",RA="_codeBlockWrapperCustom_19036_4137",DA="_kanbanWrapper_19036_4143",PA="_kanbanContainer_19036_4151",EA="_kanbanTopScroll_19036_4173",LA="_kanbanTopScrollSpacer_19036_4182",MA="_kanbanColumn_19036_4186",BA="_kanbanColumnSticky_19036_4202",WA="_kanbanColumnCollapsed_19036_4208",FA="_kanbanColumnPast_19036_4213",OA="_kanbanColumnSelectedDay_19036_4218",$A="_kanbanHeader_19036_4225",UA="_kanbanCount_19036_4235",zA="_kanbanHeaderDraggable_19036_4255",HA="_kanbanHeaderPanning_19036_4259",GA="_kanbanQuickAdd_19036_4263",VA="_kanbanColorDot_19036_4284",ZA="_kanbanDroppable_19036_4296",qA="_kanbanDroppableScroll_19036_4305",KA="_kanbanEmpty_19036_4315",YA="_kanbanCard_19036_4325",JA="_kanbanCardWrapper_19036_4335",XA="_taxonomyDropdownActive_19036_4343",QA="_kanbanCardWrapperRaised_19036_4347",eI="_kanbanCardTitle_19036_4351",tI="_kanbanBadges_19036_4355",nI="_kanbanBadge_19036_4355",aI="_headerFlex_19036_4371",sI="_marginBottom8_19036_4378",rI="_marginBottom20_19036_4382",oI="_configPanel_19036_4386",iI="_configPanelLarge_19036_4395",cI="_subLabelBlock_19036_4399",lI="_subLabelBlock12_19036_4406",dI="_flexBetween_19036_4410",uI="_flexBetweenCenter_19036_4417",pI="_deleteBtnSmall_19036_4422",mI="_deleteBtnMedium_19036_4428",fI="_trashIcon_19036_4435",hI="_gridConfig_19036_4439",gI="_flexColGap4_19036_4446",yI="_flexColGap4Center_19036_4452",kI="_flex1_19036_4459",SI="_flexCol_19036_4446",vI="_flexGrow1_19036_4469",wI="_inputLabel_19036_4473",bI="_inputLabelBlock_19036_4477",_I="_checkboxInput_19036_4483",CI="_configDividerMargin_19036_4489",xI="_configDividerMargin24_19036_4494",AI="_pathListMargin_19036_4499",II="_cancelBtnRed_19036_4503",TI="_code_19036_1664",NI="_workflowList_19036_4530",jI="_workflowActions_19036_4538",RI="_textBtn_19036_4547",DI="_workflowGrid_19036_4561",PI="_checkboxLabel_19036_4569",EI="_checkboxSmall_19036_4583",LI="_docWorkspace_19036_4596",MI="_docIndexPanel_19036_4605",BI="_docSpinning_19036_4617",WI="_docSpin_19036_4617",FI="_docViewerPanel_19036_4628",OI="_docViewerEmpty_19036_4636",$I="_marginTop24_19036_4651",UI="_settingSubTitle_19036_4655",zI="_dangerBtn_19036_4664",HI="_aiProfilesExplorer_19036_4680",GI="_aiProfilesListPane_19036_4687",VI="_aiProfilesList_19036_4687",ZI="_aiProfilesSection_19036_4697",qI="_aiProfilesSectionHeader_19036_4703",KI="_aiProfileGroup_19036_4711",YI="_aiProfileGroupSelected_19036_4730",JI="_aiProfileGroupDuplicate_19036_4739",XI="_aiProfileGroupHeader_19036_4744",QI="_aiProfileName_19036_4752",eT="_aiProfileMetaRow_19036_4757",tT="_aiProfileSurfaceBadge_19036_4767",nT="_aiProfileDuplicateBadge_19036_4777",aT="_aiProfileMergeSection_19036_4789",sT="_aiProfileMergeRow_19036_4796",rT="_aiProfileIdChip_19036_4803",oT="_aiProfileKeepBadge_19036_4815",iT="_aiProfileMergeActions_19036_4829",cT="_aiProfileDetailPane_19036_4836",lT="_aiProfileDetailCard_19036_4841",dT="_aiProfileDetailHero_19036_4850",uT="_aiProfileDetailIcon_19036_4856",pT="_aiProfileDetailHeading_19036_4870",mT="_aiProfileDetailTitleRow_19036_4875",fT="_aiProfileDetailTitle_19036_4875",hT="_aiProfileDetailMetaRow_19036_4889",gT="_aiProfileDetailHandle_19036_4897",yT="_aiProfileDetailSectionBadge_19036_4902",kT="_aiProfileDetailLinkedCount_19036_4916",ST="_aiProfileDetailDescription_19036_4921",vT="_aiProfileDetailGrid_19036_4928",wT="_aiProfileDetailStat_19036_4935",bT="_aiProfileDetailStatLabel_19036_4948",_T="_aiProfileDetailStatValue_19036_4958",CT="_aiProfileInstanceSection_19036_4965",xT="_aiProfileInstanceSectionHeader_19036_4971",AT="_aiProfileInstanceList_19036_4981",IT="_aiProfileInstanceCard_19036_4987",TT="_aiProfileInstanceTopRow_19036_4999",NT="_aiProfileInstanceName_19036_5006",jT="_aiProfileInstanceMeta_19036_5013",u={filterGlow:IS,floatingButton:TS,badge:NS,configBadge:jS,configBadgeActive:RS,configBadgeRevoked:DS,configBadgeExpired:PS,header:ES,headerTitle:LS,brandIcon:MS,brandCloudSuffix:BS,projectSlash:WS,projectName:FS,taskCountBadge:OS,taskCountBadgeIcon:$S,taskCountBadgeAlert:US,headerActions:zS,sortDirectionBtn:HS,sortDirectionBtnWidget:GS,form:VS,topRow:ZS,field:qS,labelRow:KS,label:YS,manageLink:JS,input:XS,select:QS,textarea:ev,taskIdInlineLink:tv,readOnly:nv,selectWithConfig:av,configBtn:sv,configBtnActive:rv,hasPath:ov,pathIndicator:iv,formActions:cv,hasCancel:lv,submitBtn:dv,cancelBtn:uv,successMessage:pv,successIcon:mv,spinner:fv,spin:hv,boardRefreshIndicator:gv,destructiveBtn:yv,warningBtn:kv,viewTab:Sv,deleteBtn:vv,loading:wv,emptyState:bv,taskList:_v,taskIdBadge:Cv,taskIdBadgeLabel:xv,copiedId:Av,highlight:Iv,modal:Tv,priorityEmoji:Nv,metaItem:jv,taskFormDateInput:Rv,metaBadge:Dv,complexityPill:Pv,complexityDots:Ev,dot:Lv,dotFilled:Mv,typePill:Bv,type_bug:Wv,type_feature:Fv,type_chore:Ov,type_refactor:$v,type_documentation:Uv,type_research:zv,"type_ui-ux":"_type_ui-ux_19036_770",type_security:Hv,approachPill:Gv,approach_evaluate:Vv,approach_collaborate:Zv,approach_plan:qv,approachActive:Kv,statusActionsGroup:Yv,statusActionsGroupCompact:Jv,statusSelectWrap:Xv,statusTaxonomyDropdownWrap:Qv,statusTaxonomyDropdown:ew,statusTaxonomyDropdownCompact:tw,statusTaxonomyDropdownIconOnly:nw,taxonomyDropdownButton:aw,taxonomyDropdownButtonContent:sw,statusTaxonomyDropdownIconOnlyPanel:rw,actionBtn:ow,startWorkBtn:iw,workingBtn:cw,pulse:lw,reviewBtn:dw,reviewActiveBtn:uw,reviewPill:pw,archiveTaskBtn:mw,bulkArchiveBtn:fw,bulkDeleteBtn:hw,completeBtn:gw,completeActiveBtn:yw,deleteActiveBtn:kw,disabledBtn:Sw,archiveList:vw,archiveHeader:ww,settingsTab:bw,settingsTabs:_w,settingsLayout:Cw,settingsSidebar:xw,settingsSidebarHeader:Aw,settingsSidebarNav:Iw,settingsSidebarBtn:Tw,settingsSidebarBtnActive:Nw,settingsSidebarGroup:jw,settingsSidebarGroupBtn:Rw,settingsSidebarGroupLabel:Dw,settingsSidebarGroupChevron:Pw,settingsSidebarSubnav:Ew,settingsSidebarSubBtn:Lw,appScrollbar:Mw,settingsTabBtn:Bw,settingsTabBtnActive:Ww,settingsContent:Fw,settingsToast:Ow,settingsToastSuccess:$w,settingsToastError:Uw,inputWithPrefix:zw,pathHint:Hw,settingGroup:Gw,settingTitle:Vw,settingTitleRow:Zw,settingTitleActionBtn:qw,themeOptions:Kw,buttonGrid:Yw,themeBtn:Jw,activeTheme:Xw,pathInputGroup:Qw,saveSettingsBtn:eb,shortcutInputWrapper:tb,inputIcon:nb,settingHelper:ab,browseBtn:sb,inlineCategoryManager:rb,categoryManager:ob,categoryList:ib,categoryChip:cb,categoryChipLabel:lb,chipActionBtn:db,removeCategoryBtn:ub,addCategoryForm:pb,addCategoryBtn:mb,filesList:fb,helpLink:hb,inlineCode:gb,codeBlock:yb,taskChildrenSummaryBadges:kb,taskChildrenProgressBar:Sb,taskChildrenProgressBarSegmentDone:vb,taskChildrenProgressBarSegmentReview:wb,taskChildrenProgressBarSegmentInProgress:bb,taskChildrenProgressBarSegmentBlocked:_b,taskChildrenProgressText:Cb,taskChildUnlinkBtn:xb,aboutText:Ab,versionInfo:Ib,filterBar:Tb,kanbanHintText:Nb,searchContainer:jb,searchIcon:Rb,searchInput:Db,searchActive:Pb,searchCount:Eb,clearSearchBtn:Lb,filterRow:Mb,sortLabel:Bb,archiveToggle:Wb,filterContainer:Fb,filterButton:Ob,filterActive:$b,filterDropdown:Ub,filterOption:zb,filterDivider:Hb,filterSelect:Gb,filterToggleBtn:Vb,inProgressToggle:Zb,activeInProgress:qb,activeFilter:Kb,resetFiltersBtn:Yb,categoryChip_disabled:Jb,categoryVisibilityToggle:Xb,editCategoryInput:Qb,categoryChipActionBtn:e_,categoryChipActionBtn_active:t_,categoryGroup:n_,categoryHeader:a_,categoryTitle:s_,categoryCount:r_,categoryItems:o_,priorityItem_low:i_,priorityItem_medium:c_,priorityItem_high:l_,priorityItem_critical:d_,priorityPill_low:u_,priorityPill_medium:p_,priorityPill_high:m_,priorityPill_critical:f_,selectPriority_low:h_,selectPriority_medium:g_,selectPriority_high:y_,selectPriority_critical:k_,"critical-glow":"_critical-glow_19036_1",levelSelect:S_,levelOption:v_,levelOptionFilled:w_,levelOption_priority_low:b_,levelOption_priority_medium:__,levelOption_priority_high:C_,levelOption_priority_critical:x_,levelOption_complexity_tiny:A_,levelOption_complexity_low:I_,levelOption_complexity_medium:T_,levelOption_complexity_high:N_,levelOption_complexity_epic:j_,levelOptionActive:R_,levelOptionSelected:D_,levelLabel:P_,fadeIn:E_,closeConfigBtn:L_,configItem:M_,settingsLabel:B_,settingsHint:W_,pathList:F_,pathChip:O_,pathValid:$_,pathInvalid:U_,pathValidIcon:z_,pathInvalidIcon:H_,pathText:G_,removePathBtn:V_,pathCount:Z_,specialistSection:q_,toggleHeading:K_,dropdownList:Y_,specialistBadge:J_,iconGrid:X_,iconPickerBtn:Q_,iconPickerBtnActive:eC,categorySubConfig:tC,colorPickerRow:nC,colorPickerGrid:aC,colorSwatch:sC,colorSwatchActive:rC,categoryChipIcon:oC,fieldIconWrapper:iC,fieldIcon:cC,field_dynamic:lC,fieldIcon_dynamic:dC,categoryTitleIcon:uC,editActionsHeader:pC,editActionsGroup:mC,urlInputGroup:fC,iconBtn:hC,stickyActionHeader:gC,taskHierarchyHeader:yC,taskHierarchyBadgeRow:kC,taskHierarchyDivider:SC,taskHierarchyMeta:vC,taskHierarchyAddBtn:wC,taskHierarchyEditor:bC,taskHierarchyInput:_C,taskSaveStatus:CC,taskSaveStatusCenter:xC,taskSaveStatusError:AC,headerSuccessFeedback:IC,slideInUp:TC,successCheck:NC,scaleIn:jC,primaryUpdateBtn:RC,secondaryHeaderBtn:DC,secondaryHeaderBtnDestructive:PC,commentSection:EC,attachmentCaptureContainer:LC,capturePrompt:MC,previewContainer:BC,previewHeader:WC,attachmentCapturePreview:FC,actions:OC,primaryButton:$C,secondaryButton:UC,iconButton:zC,attachmentGrid:HC,attachmentCard:GC,attachmentPreviewContainer:VC,contextFileLink:ZC,attachmentActions:qC,attachmentActionBtn:KC,attachmentCaptionInput:YC,hiddenInput:JC,contextUploadPanel:XC,contextUploadActions:QC,contextDropzone:ex,contextDropzoneActive:tx,contextDropzonePulse:nx,contextLinkRow:ax,contextNotice:sx,documentAttachmentList:rx,documentAttachmentItem:ox,documentAttachmentRow:ix,documentAttachmentLink:cx,documentAttachmentMain:lx,documentAttachmentText:dx,documentAttachmentIcon:ux,documentAttachmentName:px,documentAttachmentType:mx,documentAttachmentActions:fx,documentAttachmentActionBtn:hx,documentAttachmentCaptionInput:gx,brokenImage:yx,brokenImagePlaceholder:kx,regionOverlay:Sx,selectionBox:vx,exportRow:wx,exportItem:bx,taxonomyDrillDown:_x,drillDownList:Cx,drillDownSection:xx,drillDownSectionHeader:Ax,drillDownSectionTitle:Ix,drillDownItem:Tx,drillDownItemDimmed:Nx,drillDownItemActive:jx,drillDownItemInfo:Rx,drillDownItemText:Dx,drillDownItemLabel:Px,drillDownItemSubtext:Ex,addTaxonomyBtnSmall:Lx,taxonomyDetailView:Mx,slideIn:Bx,detailHeader:Wx,detailTitle:Fx,detailContent:Ox,createOverlay:$x,createDialog:Ux,zoomIn:zx,dialogActions:Hx,settingsGroup:Gx,settingsItem:Vx,settingLabelGroup:Zx,settingLabel:qx,settingDescription:Kx,settingInput:Yx,codeBlockWrapper:Jx,codeHeader:Xx,codeHeaderActions:Qx,codeLabel:eA,copyBtn:tA,copyBtnActive:nA,copyBtnNeutralActive:aA,headerDivider:sA,groupByContainer:rA,groupByLabel:oA,groupBySelect:iA,viewSwitcher:cA,selectWithIcon:lA,marginBottom16:dA,headerDraggable:uA,headerDragging:pA,filterSelectSort:mA,archiveRow:fA,taskScopeToggle:hA,taskScopeTabs:gA,taskScopeTab:yA,taskScopeTabActive:kA,taskToolbarAction:SA,overlayHighZ:vA,savedText:wA,shortcutInput:bA,saveSettingsBtnWrapper:_A,marginBottom12:CA,exportRowGrid:xA,settingSubtitleCustom:AA,capitalize:IA,marginTop12:TA,marginTop16:NA,labelGroupFlex:jA,codeBlockWrapperCustom:RA,kanbanWrapper:DA,kanbanContainer:PA,kanbanTopScroll:EA,kanbanTopScrollSpacer:LA,kanbanColumn:MA,kanbanColumnSticky:BA,kanbanColumnCollapsed:WA,kanbanColumnPast:FA,kanbanColumnSelectedDay:OA,kanbanHeader:$A,kanbanCount:UA,kanbanHeaderDraggable:zA,kanbanHeaderPanning:HA,kanbanQuickAdd:GA,kanbanColorDot:VA,kanbanDroppable:ZA,kanbanDroppableScroll:qA,kanbanEmpty:KA,kanbanCard:YA,kanbanCardWrapper:JA,taxonomyDropdownActive:XA,kanbanCardWrapperRaised:QA,kanbanCardTitle:eI,kanbanBadges:tI,kanbanBadge:nI,headerFlex:aI,marginBottom8:sI,marginBottom20:rI,configPanel:oI,configPanelLarge:iI,subLabelBlock:cI,subLabelBlock12:lI,flexBetween:dI,flexBetweenCenter:uI,deleteBtnSmall:pI,deleteBtnMedium:mI,trashIcon:fI,gridConfig:hI,flexColGap4:gI,flexColGap4Center:yI,flex1:kI,flexCol:SI,flexGrow1:vI,inputLabel:wI,inputLabelBlock:bI,checkboxInput:_I,configDividerMargin:CI,configDividerMargin24:xI,pathListMargin:AI,cancelBtnRed:II,code:TI,workflowList:NI,workflowActions:jI,textBtn:RI,workflowGrid:DI,checkboxLabel:PI,checkboxSmall:EI,docWorkspace:LI,docIndexPanel:MI,docSpinning:BI,docSpin:WI,docViewerPanel:FI,docViewerEmpty:OI,marginTop24:$I,settingSubTitle:UI,dangerBtn:zI,aiProfilesExplorer:HI,aiProfilesListPane:GI,aiProfilesList:VI,aiProfilesSection:ZI,aiProfilesSectionHeader:qI,aiProfileGroup:KI,aiProfileGroupSelected:YI,aiProfileGroupDuplicate:JI,aiProfileGroupHeader:XI,aiProfileName:QI,aiProfileMetaRow:eT,aiProfileSurfaceBadge:tT,aiProfileDuplicateBadge:nT,aiProfileMergeSection:aT,aiProfileMergeRow:sT,aiProfileIdChip:rT,aiProfileKeepBadge:oT,aiProfileMergeActions:iT,aiProfileDetailPane:cT,aiProfileDetailCard:lT,aiProfileDetailHero:dT,aiProfileDetailIcon:uT,aiProfileDetailHeading:pT,aiProfileDetailTitleRow:mT,aiProfileDetailTitle:fT,aiProfileDetailMetaRow:hT,aiProfileDetailHandle:gT,aiProfileDetailSectionBadge:yT,aiProfileDetailLinkedCount:kT,aiProfileDetailDescription:ST,aiProfileDetailGrid:vT,aiProfileDetailStat:wT,aiProfileDetailStatLabel:bT,aiProfileDetailStatValue:_T,aiProfileInstanceSection:CT,aiProfileInstanceSectionHeader:xT,aiProfileInstanceList:AT,aiProfileInstanceCard:IT,aiProfileInstanceTopRow:TT,aiProfileInstanceName:NT,aiProfileInstanceMeta:jT},RT="_standaloneWrapper_1mq9f_1",DT="_standalonePage_1mq9f_11",PT="_standaloneHeader_1mq9f_21",ET="_standaloneTitle_1mq9f_27",LT="_standaloneContent_1mq9f_31",MT="_workspaceToolRail_1mq9f_37",BT="_workspaceToolRailMain_1mq9f_54",WT="_workspaceToolRailBottom_1mq9f_62",FT="_workspaceToolRailDivider_1mq9f_72",OT="_workspaceToolButton_1mq9f_79",$T="_workspaceToolButtonActive_1mq9f_99",UT="_headerTitleWidget_1mq9f_123",hn={standaloneWrapper:RT,standalonePage:DT,standaloneHeader:PT,standaloneTitle:ET,standaloneContent:LT,workspaceToolRail:MT,workspaceToolRailMain:BT,workspaceToolRailBottom:WT,workspaceToolRailDivider:FT,workspaceToolButton:OT,workspaceToolButtonActive:$T,headerTitleWidget:UT},zT="_overlay_11v7l_1",HT="_browser_11v7l_16",GT="_header_11v7l_27",VT="_pathInfo_11v7l_36",ZT="_actions_11v7l_52",qT="_list_11v7l_57",KT="_item_11v7l_63",YT="_itemCurrent_11v7l_80",JT="_itemFile_11v7l_86",XT="_empty_11v7l_90",On={overlay:zT,browser:HT,header:GT,pathInfo:VT,actions:ZT,list:qT,item:KT,itemCurrent:YT,itemFile:JT,empty:XT},QT="_overlay_1hhtx_2",e0="_overlayHighZ_1hhtx_15",t0="_modal_1hhtx_20",n0="_draggableModal_1hhtx_46",a0="_draggableHeader_1hhtx_53",s0="_headerActions_1hhtx_61",r0="_modalContent_1hhtx_69",o0="_form_1hhtx_78",i0="_formActions_1hhtx_89",c0="_modalFooter_1hhtx_96",l0="_modalSizeSm_1hhtx_102",d0="_modalSizeMd_1hhtx_106",u0="_modalSizeLg_1hhtx_110",p0="_modalSizeXl_1hhtx_114",m0="_modalSizeFull_1hhtx_118",f0="_settingsViewModal_1hhtx_123",h0="_unsavedOverlay_1hhtx_142",g0="_unsavedModal_1hhtx_147",y0="_unsavedHeader_1hhtx_153",k0="_unsavedTitle_1hhtx_158",S0="_unsavedContent_1hhtx_162",v0="_unsavedText_1hhtx_166",w0="_unsavedActions_1hhtx_171",ut={overlay:QT,overlayHighZ:e0,modal:t0,draggableModal:n0,draggableHeader:a0,headerActions:s0,modalContent:r0,form:o0,formActions:i0,modalFooter:c0,modalSizeSm:l0,modalSizeMd:d0,modalSizeLg:u0,modalSizeXl:p0,modalSizeFull:m0,settingsViewModal:f0,unsavedOverlay:h0,unsavedModal:g0,unsavedHeader:y0,unsavedTitle:k0,unsavedContent:S0,unsavedText:v0,unsavedActions:w0};function b0(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 Ci({label:e,options:n,selected:s,onChange:r,variant:o="label",containerStyle:l}){const[i,p]=a.useState(!1),h=a.useRef(null);a.useEffect(()=>{const S=P=>{h.current&&!h.current.contains(P.target)&&p(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const w=S=>{s.includes(S)?r(s.filter(P=>P!==S)):r([...s,S])},b=n.length>0&&n.every(S=>{const P=o==="label"?S.label:S.value;return s.includes(P)}),_=!n.some(S=>{const P=o==="label"?S.label:S.value;return s.includes(P)}),k=()=>{r(b?[]:n.map(S=>o==="label"?S.label:S.value))},g=n.filter(S=>{const P=o==="label"?S.label:S.value;return s.includes(P)}).length,C=b0(e),M=b?`All ${C}`:_?`No ${C}`:g===1?`1 ${e}`:`${g} ${C}`;return t.jsxs("div",{className:u.filterContainer,ref:h,style:l,children:[t.jsxs("button",{className:`${u.filterButton} ${b?"":u.filterActive}`,onClick:()=>p(!i),title:`Filter by ${e}`,children:[t.jsx("span",{children:M}),t.jsx(Dc,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&t.jsxs("div",{className:`${u.filterDropdown} ${u.appScrollbar} tf-scrollbar`,children:[t.jsxs("div",{className:u.filterOption,onClick:k,children:[t.jsx("input",{type:"checkbox",checked:b,onChange:()=>{}}),t.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),t.jsx("div",{className:u.filterDivider}),n.map(S=>{const P=o==="label"?S.label:S.value,Z=s.includes(P);return t.jsxs("div",{className:u.filterOption,onClick:()=>w(P),children:[t.jsx("input",{type:"checkbox",checked:Z,onChange:()=>{}}),t.jsx("span",{children:S.label})]},S.value)})]})]})}const _0="_taskItem_x943c_1",C0="_compressed_x943c_20",x0="_taskHeader_x943c_25",A0="_taskReferenceCluster_x943c_30",I0="_taskMeta_x943c_34",T0="_taskTitle_x943c_40",N0="_taskItemRecentlyChanged_x943c_67",j0="_inProgress_x943c_128",R0="_onHold_x943c_139",D0="_readyForReview_x943c_150",P0="_completed_x943c_161",E0="_cancelled_x943c_172",L0="_archived_x943c_183",M0="_taskContent_x943c_193",B0="_kanbanCardOverlay_x943c_202",W0="_taskReferenceText_x943c_241",F0="_taskReferenceDivider_x943c_250",O0="_taskActions_x943c_257",$0="_taskMetaCompact_x943c_282",U0="_taskMetaRow_x943c_289",z0="_taskMetaBadgeGroup_x943c_297",H0="_taskDescription_x943c_303",G0="_taskLatestComment_x943c_362",V0="_taskCancellationReason_x943c_383",Z0="_archiveBadge_x943c_537",q0="_attachmentThumbnails_x943c_542",K0="_attachmentImageRow_x943c_549",Y0="_attachmentDocumentList_x943c_556",J0="_attachmentThumbnail_x943c_542",X0="_contextDocThumb_x943c_589",Q0="_contextDocMain_x943c_615",eN="_contextDocText_x943c_622",tN="_contextDocIcon_x943c_630",nN="_contextDocName_x943c_641",aN="_contextDocType_x943c_651",sN="_taskSpecialists_x943c_663",rN="_taxonomiesList_x943c_672",qt={taskItem:_0,compressed:C0,taskHeader:x0,taskReferenceCluster:A0,taskMeta:I0,taskTitle:T0,taskItemRecentlyChanged:N0,inProgress:j0,onHold:R0,readyForReview:D0,completed:P0,cancelled:E0,archived:L0,taskContent:M0,kanbanCardOverlay:B0,taskReferenceText:W0,taskReferenceDivider:F0,taskActions:O0,taskMetaCompact:$0,taskMetaRow:U0,taskMetaBadgeGroup:z0,taskDescription:H0,taskLatestComment:G0,taskCancellationReason:V0,archiveBadge:Z0,attachmentThumbnails:q0,attachmentImageRow:K0,attachmentDocumentList:Y0,attachmentThumbnail:J0,contextDocThumb:X0,contextDocMain:Q0,contextDocText:eN,contextDocIcon:tN,contextDocName:nN,contextDocType:aN,taskSpecialists:sN,taxonomiesList:rN},jp=({children:e,className:n,onTaskIdClick:s})=>{if(!e)return null;const r=i=>pt.Children.toArray(i).some(h=>pt.isValidElement(h)?String(h.props?.className||"").includes("task-list-item"):!1),o=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,l=i=>{if(!s)return i;if(typeof i=="string"){const w=Array.from(i.matchAll(o));if(!w.length)return i;const b=[];let _=0;for(let k=0;k<w.length;k+=1){const g=w[k],C=g[1],M=g.index??-1;M<_||(M>_&&b.push(i.slice(_,M)),b.push(t.jsx("button",{type:"button",className:u.taskIdInlineLink,onClick:S=>{S.preventDefault(),S.stopPropagation(),s(C)},children:C},`${C}-${M}-${k}`)),_=M+C.length)}return _<i.length&&b.push(i.slice(_)),b}if(Array.isArray(i))return i.map(l);if(!pt.isValidElement(i))return i;const p=typeof i.type=="string"?i.type:"";if(p==="code"||p==="pre"||p==="a")return i;const h=i.props?.children;return h===void 0?i:pt.cloneElement(i,{},pt.Children.map(h,l))};return t.jsx("div",{className:n,children:t.jsx(Cg,{remarkPlugins:[xg,Ag],components:{p:({children:i})=>t.jsx("p",{children:l(i)}),ul:({children:i})=>t.jsx("ul",{style:r(i)?{paddingLeft:0}:void 0,children:i}),li:({children:i,className:p})=>{const h=String(p||"").includes("task-list-item");return t.jsx("li",{className:p,style:h?{listStyle:"none"}:void 0,children:l(i)})},input:({type:i,checked:p})=>i!=="checkbox"?t.jsx("input",{type:i,checked:p,readOnly:!0}):t.jsx("input",{type:"checkbox",checked:!!p,readOnly:!0,style:{cursor:"default",marginRight:8}}),code:({children:i,className:p,...h})=>{const w=String(i||"").replace(/\n$/,"");return/language-(\w+)/.test(p||"")||w.includes(`
|
|
3
|
+
`)?t.jsx("pre",{className:u.codeBlock,children:t.jsx("code",{className:p,...h,children:w})}):t.jsx("code",{className:u.inlineCode,...h,children:w})}},children:e})})};function Xf({label:e,title:n,ariaLabel:s,copied:r=!1,disabled:o=!1,className:l="",onClick:i,children:p}){return t.jsxs("button",{type:"button",className:`${u.taskIdBadge} ${r?u.copiedId:""} ${l}`.trim(),onClick:i,disabled:o,title:n,"aria-label":s,children:[r?t.jsx(ao,{size:13}):t.jsx(Ol,{size:13}),t.jsx("span",{className:u.taskIdBadgeLabel,children:p??e})]})}function nu({copied:e,disabled:n=!1,label:s,onClick:r,title:o="Copy task reference",ariaLabel:l,className:i=""}){return t.jsx(Xf,{copied:e,disabled:n,label:"",onClick:r,title:o,ariaLabel:l,className:i,children:s})}const oN=(e,n=10)=>{const s=pu[e?.toLowerCase()]||{icon:"FileCode"},r=$s[s.icon]||Jh;return t.jsx(r,{size:n})},Xd=(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 Zl(e){return e.trim().replace(/\\/g,"/")}function Qf(e){return e.split("?")[0].split("#")[0]}function wu(e){return typeof e=="string"?e:String(e.path||"").trim()}function eh(e){const s=Qf(Zl(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 th(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?Zl(s):null}catch{return null}}function iN(e,n){const s=(n||(typeof e=="string"?"":e.fsPath||"")).trim();if(s)return Zl(s);const r=wu(e),o=th(r);return o?Zl(o):null}function cN(e,n){const s=String(typeof e=="string"?"":e.assetId||"").trim();if(s)return s;const r=wu(e);return eh(r)}function lN(e,n){const s=wu(e);return eh(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(),th(s)||"",s].some(o=>{if(!o)return!1;const l=Qf(Zl(o)).toLowerCase();return l.endsWith(".md")||l.endsWith(".markdown")})}function Rp(e,n){const s=wu(e),r=iN(e,n);if(!r||!lN(e,r))return!1;const o=cN(e),l=new CustomEvent("taskforce:open-markdown-document",{detail:{path:s,fsPath:r,...o?{assetId:o}:{}},cancelable:!0});return!window.dispatchEvent(l)}const dN="I-";function nh(e){return Yl(dN,e)}function uN(e){return e.trim().replace(/\\/g,"/")}function ah(e){return typeof e=="string"?e:String(e.path||"").trim()}function pN(e){return/\.(png|jpe?g|webp)(\?|#|$)/i.test(e)}function mN(e){return typeof e=="string"?uN(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function sh(e,n){if(typeof e=="string")return!1;const s=String(e.assetId||"").trim(),r=ah(e);return!!(s&&r&&pN(r))}function Dp(e,n){if(!sh(e))return!1;const s=e,r=String(n?.taskId||s.taskId||"").trim(),o=String(n?.taskReferenceLabel||"").trim(),l=String(s.assetId||"").trim(),i=nh(s),p=ah(e),h=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...r?{taskId:r}:{},...o?{taskReferenceLabel:o}:{},assetId:l,...i?{imageReferenceLabel:i}:{},path:p,displayName:mN(e)},cancelable:!0});return!window.dispatchEvent(h)}function Mm(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 i=String(e.taskReferenceLabel||"").trim(),p=s?n.find(w=>w.id===s):void 0,h=s?i||Ar(p)||s:void 0;return{...s?{taskId:s}:{},...h?{taskReferenceLabel:h}:{},assetId:r,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,path:o,displayName:l}}function fu(e){const n=String(e||"").trim().replace(/\\/g,"/");if(!n)return"";const s=n.split("/").filter(Boolean);return s[s.length-1]||""}function qp(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 rh(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 fN(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function Bm(e,n){const{stem:s,ext:r}=qp(fu(e)),o=rh(s,n),l=fN(o||s);return l?`${l}${r}`:fu(e)||"Untitled document"}function pp(e,n){const s=String(e||"").trim();if(!s)return!0;const r=fu(s),{stem:o}=qp(r),l=String(n||"").trim();if(l&&o.toLowerCase()===l.toLowerCase())return!0;const i=rh(o,n);return i?i!==o:!0}function hN(e){const n=String(e.logicalName||"").trim();if(n&&!pp(n,e.assetId))return n;const s=String(e.displayName||"").trim();if(s&&!pp(s,e.assetId))return s;const r=String(e.title||"").trim();if(r&&!pp(r,e.assetId))return r;const o=String(e.originalFilename||"").trim();if(o)return Bm(o,e.assetId);const l=String(e.fsPath||"").trim();return l?Bm(l,e.assetId):"Untitled document"}function gN(e){return hN(e)}function yN(e){const n=gN(e),s=String(e.originalFilename||e.fsPath||"").trim(),r=qp(fu(s)).ext;return r?n.toLowerCase().endsWith(r.toLowerCase())?n:`${n}${r}`:n}const kN="_taxonomyDropdown_tt12a_1",SN="_taxonomyDropdownActive_tt12a_6",vN="_taxonomyDropdownButton_tt12a_11",wN="_taxonomyDropdownOpen_tt12a_50",bN="_taxonomyDropdownButtonContent_tt12a_56",_N="_taxonomyDropdownIcon_tt12a_64",CN="_taxonomyDropdownLabel_tt12a_72",xN="_taxonomyDropdownChevron_tt12a_81",AN="_taxonomyDropdownChevronOpen_tt12a_87",IN="_taxonomyDropdownPanel_tt12a_91",TN="_taxonomyDropdownPanelPortal_tt12a_110",NN="_taxonomyDropdownOption_tt12a_129",jN="_taxonomyDropdownOptionHighlighted_tt12a_157",RN="_taxonomyDropdownOptionSelected_tt12a_163",Ka={taxonomyDropdown:kN,taxonomyDropdownActive:SN,taxonomyDropdownButton:vN,taxonomyDropdownOpen:wN,taxonomyDropdownButtonContent:bN,taxonomyDropdownIcon:_N,taxonomyDropdownLabel:CN,taxonomyDropdownChevron:xN,taxonomyDropdownChevronOpen:AN,taxonomyDropdownPanel:IN,taxonomyDropdownPanelPortal:TN,taxonomyDropdownOption:NN,taxonomyDropdownOptionHighlighted:jN,taxonomyDropdownOptionSelected:RN};function Bl({value:e,options:n,onChange:s,placeholder:r="Select...",required:o=!1,disabled:l=!1,className:i="",ariaLabelledBy:p,ariaLabel:h,hideSelectedLabel:w=!1,hideChevron:b=!1,panelClassName:_="",portalPanel:k=!1,panelMinWidth:g}){const[C,M]=a.useState(!1),[S,P]=a.useState(-1),[Z,$]=a.useState({}),ce=a.useRef(null),q=a.useRef(null),K=a.useRef(null),j=n.find(te=>String(te.value)===String(e));a.useEffect(()=>{if(!C)return;const te=D=>{const B=D.target,oe=!!ce.current?.contains(B),xe=!!K.current?.contains(B);!oe&&!xe&&(M(!1),P(-1))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[C]),a.useEffect(()=>{if(!C)P(-1);else{const te=n.findIndex(D=>String(D.value)===String(e));P(te>=0?te:0)}},[C,n,e]),a.useEffect(()=>{if(!C||!k)return;const te=()=>{const D=q.current;if(!D)return;const B=D.getBoundingClientRect(),oe=Math.max(g||0,B.width),xe=Math.max(8,B.right-oe),ie=B.bottom;$({position:"fixed",top:ie,left:xe,minWidth:oe,zIndex:2e3})};return te(),window.addEventListener("resize",te),window.addEventListener("scroll",te,!0),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0)}},[C,k,g]);const ye=()=>{l||M(!C)},U=te=>{s(te.value),M(!1),q.current?.focus()},X=te=>{if(!l)switch(te.key){case"Enter":case" ":te.preventDefault(),C?S>=0&&U(n[S]):M(!0);break;case"Escape":te.preventDefault(),M(!1),q.current?.focus();break;case"ArrowDown":te.preventDefault(),C?P(D=>D<n.length-1?D+1:0):M(!0);break;case"ArrowUp":te.preventDefault(),C?P(D=>D>0?D-1:n.length-1):M(!0);break;case"Home":te.preventDefault(),C&&P(0);break;case"End":te.preventDefault(),C&&P(n.length-1);break;case"Tab":M(!1);break}},Ne=(te,D)=>{const B=te.icon&&$s[te.icon]?$s[te.icon]:Ii,oe=te.color?Aa(te.color):"var(--text-secondary)",xe=D?.hideLabel===!0;return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`taxonomyDropdownIcon ${Ka.taxonomyDropdownIcon}`,style:{color:oe},children:t.jsx(B,{size:16})}),!xe&&t.jsx("span",{className:`taxonomyDropdownLabel ${Ka.taxonomyDropdownLabel}`,children:te.label})]})},pe=C?t.jsx("div",{ref:K,id:`taxonomy-listbox-${r.replace(/\s+/g,"-")}`,className:`taxonomyDropdownPanel ${Ka.taxonomyDropdownPanel} ${k?Ka.taxonomyDropdownPanelPortal:""} ${_}`,role:"listbox","aria-labelledby":p,"aria-label":h,style:k?Z:void 0,children:n.map((te,D)=>{const B=String(te.value)===String(e),oe=D===S;return t.jsx("div",{className:`taxonomyDropdownOption ${Ka.taxonomyDropdownOption} ${B?`taxonomyDropdownOptionSelected ${Ka.taxonomyDropdownOptionSelected}`:""} ${oe?`taxonomyDropdownOptionHighlighted ${Ka.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":B,onClick:()=>U(te),onMouseEnter:()=>P(D),style:(()=>{const xe=te.color,ie=Aa(xe),ae=!ie||ie.startsWith("var("),Ze=ae?"#8b5cf6":ie,Le=ae?"20":"30",Ce=ae?"05":"10";return{"--option-color":ie||"var(--text-primary)","--option-border":`${Ze}${Le}`,"--option-bg":`${Ze}${Ce}`}})(),children:Ne(te)},String(te.value))})}):null;return t.jsxs("div",{ref:ce,className:`taxonomyDropdown ${Ka.taxonomyDropdown} ${C?`taxonomyDropdownActive ${Ka.taxonomyDropdownActive}`:""} ${i}`,children:[t.jsxs("button",{ref:q,type:"button",className:`taxonomyDropdownButton ${Ka.taxonomyDropdownButton} ${C?`taxonomyDropdownOpen ${Ka.taxonomyDropdownOpen}`:""}`,onClick:ye,onKeyDown:X,disabled:l,role:"combobox","aria-haspopup":"listbox","aria-expanded":C,"aria-controls":`taxonomy-listbox-${r.replace(/\s+/g,"-")}`,"aria-labelledby":p,"aria-label":h,style:(()=>{if(!j)return{};const te=j.color,D=Aa(te),B=!D||D.startsWith("var("),oe=B?"#8b5cf6":D,xe=B?"30":"50",ie=B?"05":"10";return{"--field-color":D||"var(--text-primary)","--field-border":`${oe}${xe}`,"--field-bg":`${oe}${ie}`}})(),children:[t.jsx("span",{className:`taxonomyDropdownButtonContent ${Ka.taxonomyDropdownButtonContent}`,children:j?Ne(j,{hideLabel:w}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`taxonomyDropdownIcon ${Ka.taxonomyDropdownIcon}`,children:t.jsx(Ii,{size:16})}),t.jsx("span",{className:`taxonomyDropdownLabel ${Ka.taxonomyDropdownLabel}`,children:r})]})}),!b&&t.jsx(Dc,{size:16,className:`taxonomyDropdownChevron ${Ka.taxonomyDropdownChevron} ${C?`taxonomyDropdownChevronOpen ${Ka.taxonomyDropdownChevronOpen}`:""}`})]}),k?pe?Ai.createPortal(pe,document.body):null:pe]})}function oh({task:e,disabled:n=!1,compressed:s=!1,shortLabels:r=!1,showLabel:o=!0,onSetStatus:l,onArchiveTask:i}){const p=e?.status||"task",h=!!e&&(p==="done"||p==="cancelled"),w=Ic.map(b=>({...b,label:(s||r)&&b.shortLabel||b.label}));return t.jsxs("div",{className:`${u.statusActionsGroup} ${s?u.statusActionsGroupCompact:""}`,children:[h&&t.jsx("button",{type:"button",className:`${u.actionBtn} ${u.archiveTaskBtn}`,onClick:()=>e&&!n&&i?.(e),disabled:n,title:"Archive Now","aria-label":"Archive task",children:t.jsx(Xh,{size:s?12:16})}),t.jsx("div",{className:`${u.statusSelectWrap} ${u.statusTaxonomyDropdownWrap}`,children:t.jsx(Bl,{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:b=>{e&&l?.(e,b)}})})]})}function DN(e){return e==="title"?"TITLE":e==="description"?"DESCRIPTION":e==="assignee"?"ASSIGNED TO":e}function Es(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=>Es(l,n,s)).filter(Boolean);return o.length>0?o.join(", "):"none"}return typeof e=="object"?"updated":String(e)}function Wm(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 PN(e){const n=Wm(e?.from),s=Wm(e?.to),r=new Map(n.map(i=>[i.id||i.title,i])),o=new Map(s.map(i=>[i.id||i.title,i]));for(const[i,p]of o.entries()){const h=r.get(i);if(!h)return p.title?`Checklist item added: ${p.title}`:"Checklist item added";if(h.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[i,p]of r.entries())if(!o.has(i))return p.title?`Checklist item removed: ${p.title}`:"Checklist item removed";return n.length===s.length&&n.every(i=>o.has(i.id||i.title))&&n.some((p,h)=>{const w=s[h];return(p.id||p.title)!==(w?.id||w?.title)})?"Checklist reordered":"Checklist updated"}function ih(e,n,s){if(e==="checklistItems")return PN(n);const r=DN(e);if(e==="title")return`${r}: updated`;if(e==="description"){const o=Es(n?.from,e,s)!=="none",l=Es(n?.to,e,s)!=="none";return!o&&l?`${r}: added`:o&&!l?`${r}: cleared`:`${r}: updated`}return`${r}: ${Es(n?.from,e,s)} -> ${Es(n?.to,e,s)}`}function ch(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: ${Es(s.status.from,"status",n)} -> ${Es(s.status.to,"status",n)}`;if(e.action==="task-schedule-changed")return s.scheduledDate?`Scheduled: ${Es(s.scheduledDate.from,"scheduledDate",n)} -> ${Es(s.scheduledDate.to,"scheduledDate",n)}`:s.dueDate?`Due: ${Es(s.dueDate.from,"dueDate",n)} -> ${Es(s.dueDate.to,"dueDate",n)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&s.workstreamId)return`Workstream: ${Es(s.workstreamId.from,"workstreamId",n)} -> ${Es(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 ih(o,l,n)}return r.length>1?`${r.length} fields updated`:"Task updated"}function EN(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 LN(e,n){return e?e.type==="comment"?e.comment.text:ch(e.event,n):""}const{MessageSquare:MN,User:BN,Bot:WN,Gauge:FN,ClipboardList:ON,HelpCircle:Fm,File:$N}=$s,UN=({task:e,searchQuery:n="",copiedId:s=null,taxonomies:r=[],types:o=[],priorities:l=[],categories:i=[],assigneeOptions:p=[],taskWorkstream:h=null,taskInitiative:w=null,isOverlay:b=!1,isArchived:_=!1,readOnlyMode:k=null,isRecentlyChanged:g=!1,onClick:C,onCopyId:M,onToggleInProgress:S,onToggleReview:P,onToggleComplete:Z,onToggleCancel:$,onSetStatus:ce,onArchiveTask:q,onUnarchive:K,onDelete:j,deleteActionTitle:ye,onOpenTaskById:U,compressed:X=!1,showStatusLabel:Ne=!0})=>{const pe=Af(e),te=pe.label||(pe.isProvisional?"Pending":""),D=pe.isProvisional,B=!!pe.label,oe=Vp(h)||h?.id||"",xe=Xk(w)||w?.id||"",ie=l.find(O=>String(O.value)===String(e.priority)),ae=ie?ie.label.toLowerCase().replace(/\s+/g,"-"):String(e.priority),Ze=i.find(O=>O.value===e.category||O.label===e.category),Le=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),Ce=Number.isFinite(Le)?Math.max(1,Math.min(5,Math.round(Le))):3,Oe={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},R={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},W=Oe[Ce],F=`var(--complexity-${R[Ce]})`,V=ay(e.priority,ae),E=!!u[`priorityItem_${V}`],y=uu(e.assignee),x=_c(e.assignee,p),H=pt.useMemo(()=>EN(e),[e]),I=k||(e.isDeleted?"deleted":_?"archived":null),Ie=I!==null,L=pt.useMemo(()=>LN(H),[H]),le=Array.isArray(e.activity)&&e.activity.length>0?e.activity.length:e.comments?.length||0,ne=[qt.taskItem,e.status==="on-hold"?qt.onHold:"",e.status==="in-progress"?qt.inProgress:"",e.status==="review"?qt.readyForReview:"",e.status==="done"?qt.completed:"",e.status==="cancelled"?qt.cancelled:"",g?qt.taskItemRecentlyChanged:"",u[`priorityItem_${V}`]||"",b?qt.kanbanCardOverlay:"",_?qt.archived:"",X?qt.compressed:""].filter(Boolean).join(" "),de=Aa(ie?.color),G=o.find(O=>O.value===e.type),ee=Aa(G?.color)||cS(e.type),be=O=>{const Ye=typeof O=="string"?O:O.path,wt=typeof O=="string"?"":(O.fsPath||"").trim(),St=typeof O=="string"?"":(O.displayName||"").trim(),At=typeof O=="string"?"":(O.originalFilename||"").trim(),zt=typeof O=="string"?"":(O.caption||"").trim();return[wt,At,St,zt,Ye].some(sn=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(sn))},$e=O=>{const Ye=typeof O=="string"?O:O.path,wt=Ye.includes("/api/taskforce/documents/"),St=typeof O=="string"?"":(O.displayName||"").trim();if(wt&&typeof O!="string")return yN({displayName:O.displayName,originalFilename:O.originalFilename,fsPath:O.fsPath,assetId:O.assetId||null});const At=typeof O=="string"?"":(O.caption||"").trim();if(At)return At;if(St)return St;const zt=typeof O=="string"?"":(O.originalFilename||"").trim();return zt||Ye.split("?")[0].split("#")[0].split("/").pop()||"Context file"},fe=O=>{const Ye=typeof O=="string"?O:O.path,wt=typeof O=="string"?"":(O.fsPath||"").trim(),St=typeof O=="string"?"":(O.caption||"").trim(),At=typeof O=="string"?"":(O.originalFilename||"").trim(),zt=[];if(wt&&zt.push(wt),At&&zt.push(At),St&&zt.push(St),Ye.includes("/api/taskforce/context-link?path="))try{const sn=new URL(Ye,"http://localhost").searchParams.get("path");sn&&zt.push(sn)}catch{}zt.push(Ye);for(const Ht of zt){const Jt=Ht.split("?")[0].split("#")[0].split("/").pop()||"",Xt=Jt.lastIndexOf(".");if(Xt<=0||Xt===Jt.length-1)continue;const gn=Jt.slice(Xt+1);if(gn)return gn.slice(0,5).toUpperCase()}return"FILE"},De={"--task-change-glow-color":de||`var(--priority-${V})`,...de?{borderLeftColor:de,[`--priority-${V}`]:de}:{},...!E&&de?{borderLeft:`4px solid ${de}`}:{}},Ke=O=>O.replace(/\b\w/g,Ye=>Ye.toUpperCase()),nt=Jl(r,[e]),dt=e.checklistItems||[],d=dt.length,et=d>0?dt.filter(O=>O.isCompleted).length:0,gt=(O,Ye)=>{O.stopPropagation(),M?.(O,Ye)};return t.jsxs("div",{className:ne,onClick:()=>C?.(e),style:De,"data-task-card":"true",children:[t.jsxs("div",{className:qt.taskHeader,children:[t.jsxs("div",{className:qt.taskReferenceCluster,children:[w?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:qt.taskReferenceText,children:xe}),t.jsx("span",{className:qt.taskReferenceDivider,children:"/"})]}):null,h?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:qt.taskReferenceText,children:oe}),t.jsx("span",{className:qt.taskReferenceDivider,children:"/"})]}):null,te?t.jsx(nu,{copied:B&&s===pe.label,onClick:O=>gt(O,pe.label),disabled:!B,title:B?"Copy task reference":"Task reference pending sync",className:_?qt.archiveBadge:"",label:Xd(te,n)}):null,D?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:qt.taskActions,onClick:O=>O.stopPropagation(),children:Ie?K||j?t.jsxs(t.Fragment,{children:[K&&t.jsx("button",{type:"button",className:u.actionBtn,onClick:()=>K(e.id),title:I==="deleted"?"Restore deleted task":"Restore archived task",children:t.jsx(bp,{size:16})}),j&&t.jsx("button",{type:"button",className:`${u.actionBtn} ${u.deleteBtn}`,onClick:()=>j(e.id),title:ye||(I==="deleted"?"Delete Permanently":"Move to Trash"),children:t.jsx(Hl,{size:16})})]}):null:t.jsx(oh,{task:e,compressed:X,shortLabels:!0,showLabel:Ne,onSetStatus:(O,Ye)=>{if(ce){ce(O,Ye);return}if(Ye==="in-progress"){S?.(O);return}if(Ye==="review"){P?.(O);return}if(Ye==="done"){Z?.(O);return}Ye==="cancelled"&&$?.(O)},onArchiveTask:q})})]}),t.jsxs("div",{className:qt.taskContent,children:[Ie&&t.jsx("div",{className:`${qt.taskMeta} ${qt.taskMetaCompact}`}),t.jsxs("div",{children:[t.jsxs("div",{className:qt.taskTitle,style:X?{fontSize:"13px",lineHeight:"1.4"}:{},children:[I==="archived"&&"✓ ",I==="deleted"&&"Deleted: ",Xd(e.title,n)]}),e.description&&!Ie&&!X&&t.jsx("div",{className:qt.taskDescription,children:t.jsx(jp,{onTaskIdClick:U,children:e.description})})]}),e.attachments&&e.attachments.length>0&&!Ie&&!X&&t.jsxs("div",{className:qt.attachmentThumbnails,children:[t.jsx("div",{className:qt.attachmentImageRow,children:(e.attachments||[]).map((O,Ye)=>{const wt=typeof O=="string"?O:O.path;return be(O)?t.jsx("div",{className:qt.attachmentThumbnail,onClick:St=>{St.stopPropagation(),!Dp(typeof O=="string"?{path:wt}:O,{taskId:e.id,taskReferenceLabel:te})&&window.open(wt,"_blank")},children:t.jsx("img",{src:wt,alt:`Attachment ${Ye}`})},Ye):null})}),t.jsx("div",{className:qt.attachmentDocumentList,children:(e.attachments||[]).map((O,Ye)=>{const wt=typeof O=="string"?O:O.path,St=typeof O=="string"?void 0:O.fsPath,At=$e(O);if(be(O))return null;const zt=fe(O);return t.jsxs("button",{type:"button",className:qt.contextDocThumb,onClick:Ht=>{Ht.stopPropagation(),!Rp(O,St)&&window.open(wt,"_blank")},title:At,style:{"--context-doc-accent":lS(zt)},children:[t.jsxs("span",{className:qt.contextDocMain,children:[t.jsx("span",{className:qt.contextDocIcon,"aria-hidden":"true",children:t.jsx($N,{size:13})}),t.jsx("span",{className:qt.contextDocText,children:t.jsx("span",{className:qt.contextDocName,children:At})})]}),t.jsx("span",{className:qt.contextDocType,children:zt})]},Ye)})})]}),e.status==="cancelled"&&e.canceledReason&&!X&&t.jsxs("div",{className:qt.taskCancellationReason,children:[t.jsx("strong",{children:"Cancellation Reason:"})," ",Xd(e.canceledReason,n)]}),L&&!Ie&&!X&&t.jsxs("div",{className:qt.taskLatestComment,children:[t.jsx("strong",{children:"Latest Activity:"})," ",Xd(L.length>120?L.substring(0,120)+"...":L,n)]}),!Ie&&nt.length>0&&!X&&t.jsx("div",{className:`${qt.taskSpecialists} ${qt.taxonomiesList}`,children:nt.map(O=>{const Ye=e.taxonomies?.[O.id];return Ye?(Array.isArray(Ye)?Ye:[Ye]).map(St=>{const At=O.options.find(Xt=>Xt.value===St);if(!At)return null;const zt=$s[At.icon||"Layers"]||_p,Ht=Aa(At.color)||"var(--text-primary)",sn=O.status==="retired"?`${O.label} (Retired)`:O.label,Jt=At.status==="retired"?`${At.label} (Retired)`:At.label;return t.jsx("span",{className:u.specialistBadge,style:{borderColor:`${Ht}50`,backgroundColor:`${Ht}15`,color:Ht},title:`${sn}: ${Ke(Jt)}`,children:t.jsx(zt,{size:10})},`${O.id}-${St}`)}):null})}),t.jsx("div",{className:qt.taskMeta,children:Ie?t.jsx("span",{children:e.category}):t.jsx(t.Fragment,{children:t.jsxs("div",{className:qt.taskMetaRow,style:X?{marginBottom:0}:void 0,children:[t.jsxs("div",{className:qt.taskMetaBadgeGroup,children:[(()=>{const O=Aa(Ze?.color),Ye=Ze?.icon||"Folder",wt=$s[Ye]||Ti;return t.jsx("span",{className:u.metaBadge,title:Ke(e.category),style:{color:O||"var(--text-secondary)",backgroundColor:O?`${O}15`:"var(--bg-tertiary)",borderColor:O?`${O}40`:"transparent"},children:t.jsx(wt,{size:14})})})(),t.jsx("span",{className:`${u.metaBadge} ${u[`type_${e.type}`]||""}`,title:Ke(e.type||Ss),style:{color:`var(--type-color, ${ee})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${ee}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${ee}), transparent 75%)`},children:G?.icon?(()=>{const O=$s[G.icon]||Fm;return t.jsx(O,{size:14})})():oN(e.type,14)}),ie&&t.jsx("span",{className:u.metaBadge,style:{color:de||"var(--text-secondary)",backgroundColor:de?`${de}15`:"var(--bg-tertiary)",borderColor:de?`${de}40`:"var(--border-color)"},title:`${ie.label}`,children:(()=>{const O=ie.icon||"AlertCircle",Ye=$s[O]||Qh;return t.jsx(Ye,{size:14})})()}),le>0&&t.jsxs("span",{className:u.metaBadge,title:`${le} activity items`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[t.jsx(MN,{size:14}),t.jsx("span",{children:le})]}),d>0&&t.jsxs("span",{className:u.metaBadge,title:`${et}/${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(ON,{size:14}),t.jsx("span",{children:`${et}/${d}`})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsxs("span",{className:u.metaBadge,title:`AI-estimated complexity: ${W} (${Ce}/5)`,style:{color:F,backgroundColor:`color-mix(in srgb, ${F}, transparent 88%)`,borderColor:`color-mix(in srgb, ${F}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[t.jsx(FN,{size:14}),!X&&t.jsx("span",{children:W})]}),t.jsx("span",{className:u.metaBadge,title:`Assigned to: ${x}`,"aria-label":y==="unassigned"?"Unassigned":`Assigned to ${x}`,style:{backgroundColor:y==="agent"?"color-mix(in srgb, var(--color-violet-500, #8b5cf6), transparent 88%)":y==="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:y==="agent"?"var(--color-violet-500, #8b5cf6)":y==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",borderColor:y==="agent"?"color-mix(in srgb, var(--color-violet-500, #8b5cf6), transparent 72%)":y==="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:y==="agent"?t.jsx(WN,{size:X?14:16}):y==="member"?t.jsx(BN,{size:X?14:16}):t.jsx(Fm,{size:X?14:16})})]})]})})})]})]})},ql=pt.memo(UN),hu="168px";function lh(){return t.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:Te("standalone.filtersCaps")})}function xi({label:e,options:n,selected:s,onChange:r,variant:o="label"}){return t.jsx(Ci,{label:e,options:n,selected:s,onChange:r,variant:o,containerStyle:{flex:`0 0 ${hu}`,maxWidth:hu}})}function dh({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(Di,{size:12})," ",Te("standalone.clearFilters")]})}function Om({label:e,options:n,selected:s,onChange:r,allLabel:o,title:l}){const[i,p]=pt.useState(!1),h=pt.useRef(null),w=n.find(k=>k.value===s),b=w?.selectedLabel||w?.label||o;pt.useEffect(()=>{const k=g=>{h.current&&!h.current.contains(g.target)&&p(!1)};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[]);const _=k=>{r(k),p(!1)};return t.jsxs("div",{className:u.filterContainer,ref:h,style:{flex:`0 0 ${hu}`,maxWidth:hu},children:[t.jsxs("button",{type:"button",className:`${u.filterButton} ${s?u.filterActive:""}`,onClick:()=>p(k=>!k),title:l||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":i,children:[t.jsx("span",{children:b}),t.jsx(Dc,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&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(ao,{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(k=>{const g=k.value===s;return t.jsxs("button",{type:"button",className:u.filterOption,onClick:()=>_(k.value),"aria-selected":g,children:[t.jsx(ao,{size:14,style:{opacity:g?1:0}}),t.jsx("span",{style:{fontWeight:g?600:500},children:k.label})]},k.value)})]})]})}function uh({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 ph({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(Hl,{size:14}),o]})}const{Search:$m,ClipboardList:zN,ChevronRight:HN,ChevronDown:GN,Folder:VN,Archive:ZN,RotateCcw:qN,X:KN,Plus:YN,ArrowUpDown:JN,Trash2:XN}=$s,mh=a.forwardRef((e,n)=>{const{tasks:s,archivedTasks:r,categories:o,types:l,priorities:i,taxonomyDisplayLabels:p,assigneeOptions:h=[],workstreams:w=[],initiatives:b=[],searchQuery:_,filterCategories:k,filterTypes:g,filterPriorities:C,filterStatus:M,filterAssignees:S=[],filterTaxonomies:P,sortBy:Z,sortOrder:$,showArchive:ce,taskScope:q,collapsedCategories:K,loadingTasks:j,filteredTasks:ye,filteredArchive:U,groupedTasks:X,filteredDeletedTasks:Ne=[],groupedDeletedTasks:pe={},copiedId:te,recentlyChangedTaskIds:D=[],showTaskCardStatusLabel:B=!0,onSearchChange:oe,onFilterCategoriesChange:xe,onFilterTypesChange:ie,onFilterPrioritiesChange:ae,onFilterStatusChange:Ze,onFilterAssigneesChange:Le,onTaxonomyFilterChange:Ce,onSortByChange:Oe,onSortOrderChange:R,onShowArchiveChange:W,onTaskScopeChange:F,onClearFilters:V,onToggleCategory:E,onEditTask:y,onOpenTaskById:x,onCopyId:H,onToggleInProgress:I,onToggleReview:Ie,onToggleComplete:L,onToggleCancel:le,onSetStatus:ne,onArchiveTask:de,onBulkArchive:G,onUnarchive:ee,onDelete:be,onDeleteAllDeleted:$e,onFetchArchive:fe,onAddTaskToCategory:De,supplementalTasks:Ke=[],taxonomies:nt}=e,dt=new Set(D),d=pt.useMemo(()=>new Map(w.map(we=>[we.id,we])),[w]),et=pt.useMemo(()=>new Map(b.map(we=>[we.id,we])),[b]),gt=pt.useCallback(we=>{const Lt=we.workstreamId&&d.get(we.workstreamId)||null,Qt=Lt?.initiativeId&&et.get(Lt.initiativeId)||null;return{taskWorkstream:Lt,taskInitiative:Qt}},[et,d]),O=[...s,...r,...Ke],Ye=!!F,wt=F,St=q??(ce?"archived":"open"),At=Ye?St==="archived"?U:St==="deleted"?Ne:ye:ye,zt=Ye?St==="archived"?{Archived:U}:St==="deleted"?pe:X:X,Ht=Ye?St==="deleted"?"deleted":St==="archived"?"archived":null:null,sn=_?Te("taskList.noMatchingTasks"):St==="archived"?"No archived tasks found.":St==="deleted"?"No deleted tasks found.":Te("taskList.noActiveTasks"),Jt=o.filter(we=>!we.disabled),Xt=o.filter(we=>we.disabled&&O.some(Lt=>Lt.category===we.value)),gn=[...Jt,...Xt.filter(we=>!Jt.some(Lt=>Lt.value===we.value))].map(we=>({value:we.value,label:we.disabled?`${we.label} (Legacy)`:we.label})),Mn=l.filter(we=>we.status!=="retired"),un=l.filter(we=>we.status==="retired"&&O.some(Lt=>Lt.type===we.value)),yn=[...Mn,...un.filter(we=>!Mn.some(Lt=>Lt.value===we.value))].map(we=>({value:we.value,label:we.status==="retired"?`${we.label} (Retired)`:we.label})),Tn=Jl(nt,O).filter(we=>we.filterEnabled!==!1).map(we=>({...we,options:Zp(we,O)})),Rt=pt.useMemo(()=>[{value:"created",label:Te("taskList.sortCreated")},{value:"updated",label:Te("taskList.sortUpdated")},{value:"priority",label:Te("taskList.sortPriority")},...Jf(nt,O)],[O,Te,nt]);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($m,{size:16,className:u.searchIcon}),t.jsx("input",{type:"text",className:u.searchInput,placeholder:Te("taskList.searchPlaceholder"),value:_,onChange:we=>oe(we.target.value)}),_&&t.jsx("button",{className:u.clearSearchBtn,onClick:()=>oe(""),title:Te("taskList.clearSearchTitle"),children:t.jsx(KN,{size:14})})]}),t.jsxs("div",{className:u.filterRow,children:[t.jsx(Ci,{label:p?.category||Te("taskList.categoryLabel"),options:gn,selected:k,onChange:xe,variant:"value"}),t.jsx(Ci,{label:p?.type||Te("taskList.typeLabel"),options:yn,selected:g,onChange:ie,variant:"value"})]}),t.jsxs("div",{className:u.filterRow,children:[t.jsx(Ci,{label:p?.priority||Te("taskList.priorityLabel"),options:i,selected:C,onChange:ae,variant:"value"}),t.jsx(Ci,{label:Te("taskList.statusLabel"),options:to,selected:M,onChange:Ze,variant:"value"}),t.jsx(Ci,{label:Te("taskList.assigneeLabel"),options:h,selected:S,onChange:we=>Le?.(we),variant:"value"})]}),Tn.map(we=>t.jsx(Ci,{label:we.status==="retired"?`${we.label} (Retired)`:we.label,options:we.options.map(Lt=>({...Lt,label:Lt.status==="retired"?`${Lt.label} (Retired)`:Lt.label})),selected:P[we.id]||[],onChange:Lt=>Ce(we.id,Lt),variant:"value"},we.id)),t.jsxs("div",{className:u.filterRow,children:[t.jsxs("div",{className:u.sortLabel,children:[t.jsx(JN,{size:14,style:{marginRight:"4px"}})," ",Te("taskList.sortByLabel")]}),t.jsx("select",{value:Z,onChange:we=>Oe(we.target.value),className:`${u.filterSelect} ${u.filterSelectSort} `,children:Rt.map(we=>t.jsx("option",{value:we.value,children:we.label},we.value))}),t.jsx("button",{className:`${u.resetFiltersBtn} ${u.sortDirectionBtnWidget}`,onClick:R,title:Te($==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:$==="desc"?t.jsx(rf,{size:14}):t.jsx(of,{size:14})}),t.jsx("button",{className:u.resetFiltersBtn,onClick:V,title:Te("taskList.resetFiltersTitle"),children:t.jsx(qN,{size:14})})]}),t.jsxs("div",{className:`${u.filterRow} ${u.archiveRow} `,children:[St==="open"?t.jsxs("button",{className:`${u.bulkArchiveBtn} ${s.some(we=>we.status==="done"||we.status==="cancelled")?"":u.disabledBtn} `,onClick:()=>s.some(we=>we.status==="done"||we.status==="cancelled")&&G(),disabled:!s.some(we=>we.status==="done"||we.status==="cancelled"),title:s.some(we=>we.status==="done"||we.status==="cancelled")?Te("taskList.archiveAllTitle"):Te("taskList.noTasksToArchiveTitle"),children:[t.jsx(ZN,{size:12}),t.jsx("span",{children:Te("taskList.archiveFinished")})]}):St==="deleted"&&$e?t.jsx(ph,{className:`${u.bulkArchiveBtn} ${u.taskToolbarAction} ${u.bulkDeleteBtn} ${Ne.length===0?u.disabledBtn:""}`,onClick:()=>Ne.length>0&&$e(),disabled:Ne.length===0,title:Ne.length>0?"Empty trash":"Trash is already empty",children:"Empty Trash"}):t.jsx("div",{}),Ye?t.jsx(uh,{scope:St,onScopeChange:we=>{wt?.(we),we==="archived"?(W(!0),fe()):ce&&W(!1)},className:`${u.archiveToggle} ${u.taskScopeToggle}`}):t.jsxs("label",{className:u.archiveToggle,children:[t.jsx("input",{type:"checkbox","aria-label":"Archived",checked:ce,onChange:we=>{W(we.target.checked),we.target.checked&&fe()}}),t.jsx("span",{children:"Include Archive"})]})]})]}),j&&s.length===0?t.jsx("div",{className:u.loading,children:t.jsx(Wa,{size:24,className:u.spinner})}):At.length===0&&!j?t.jsxs("div",{className:u.emptyState,children:[_?t.jsx($m,{size:48}):St==="deleted"?t.jsx(XN,{size:48}):t.jsx(zN,{size:48}),t.jsx("p",{children:sn})]}):t.jsx("div",{className:u.taskList,style:{opacity:j?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(zt).map(([we,Lt])=>{if(Lt.length===0)return null;const Qt=K[we];return t.jsxs("div",{className:u.categoryGroup,children:[t.jsx("div",{className:u.categoryHeader,onClick:()=>E(we),children:t.jsxs("div",{className:u.categoryTitle,children:[Qt?t.jsx(HN,{size:16}):t.jsx(GN,{size:16}),(()=>{const Dt=o.find(Y=>Y.label===we),He=Dt?.icon&&Ri[Dt.icon]?Ri[Dt.icon]:VN,Nn=Aa(Dt?.color)||"var(--color-purple, #8b5cf6)";return t.jsx(He,{size:16,className:u.categoryTitleIcon,style:{color:Nn}})})(),we,t.jsxs("span",{className:u.categoryCount,children:["(",Lt.length,")"]}),De&&t.jsx("button",{className:u.kanbanQuickAdd,onClick:Dt=>{Dt.stopPropagation(),De(we)},title:Te("taskList.addTaskToCategoryTitle",{category:we}),style:{marginLeft:"auto"},disabled:Ht!==null,children:t.jsx(YN,{size:14})})]})}),!Qt&&t.jsx("div",{className:u.categoryItems,children:Lt.map(Dt=>(()=>{const{taskWorkstream:He,taskInitiative:Nn}=gt(Dt);return t.jsx(ql,{task:Dt,taskWorkstream:He,taskInitiative:Nn,searchQuery:_,copiedId:te,taxonomies:nt,types:l,priorities:i,assigneeOptions:h,onClick:y,onOpenTaskById:x,onCopyId:H,onToggleInProgress:I,onToggleReview:Ie,onToggleComplete:L,onToggleCancel:le,onSetStatus:ne,onArchiveTask:de,onUnarchive:Ht?ee:void 0,onDelete:Ht?be:void 0,categories:o,isRecentlyChanged:dt.has(Dt.id),readOnlyMode:Ht,showStatusLabel:B},Dt.id)})())})]},we)})}),!Ye&&ce&&U.length>0&&t.jsxs("div",{className:u.archiveList,children:[t.jsx("div",{className:u.archiveHeader,children:"Archived"}),U.map(we=>(()=>{const{taskWorkstream:Lt,taskInitiative:Qt}=gt(we);return t.jsx(ql,{task:we,taskWorkstream:Lt,taskInitiative:Qt,searchQuery:_,copiedId:te,isArchived:!0,types:l,assigneeOptions:h,onClick:y,onCopyId:H,onSetStatus:ne,onUnarchive:ee,onDelete:be,deleteActionTitle:"Delete Permanently",categories:o,showStatusLabel:B},we.id)})())]})]})});mh.displayName="TaskList";const QN="_formNotice_1infv_1",ej="_assigneeIndicator_1infv_12",tj="_assigneeIndicatorAgent_1infv_20",nj="_assigneeIndicatorUser_1infv_24",aj="_assigneeIndicatorUnassigned_1infv_28",sj="_markdownPreview_1infv_32",rj="_error_1infv_83",oj="_keyboardHint_1infv_92",ij="_taskFormLifecycle_1infv_109",cj="_taskFormMetaDivider_1infv_114",lj="_taskFormMetaGrid_1infv_121",dj="_compactMetaSection_1infv_127",uj="_createWorkstreamRow_1infv_133",pj="_createWorkstreamDropdown_1infv_139",mj="_compactMetaGrid_1infv_144",fj="_compactMetaField_1infv_150",hj="_compactMetaSpacer_1infv_154",gj="_compactMetaFieldHint_1infv_168",yj="_formFieldsetReset_1infv_172",kj="_taskFormDateRow_1infv_185",Sj="_taskFormDateLabel_1infv_192",vj="_taskFormDateValue_1infv_200",wj="_taskFormMetaStack_1infv_208",bj="_taskFormMetaActor_1infv_214",_j="_taskFormDateWarning_1infv_226",Cj="_taskFormDateError_1infv_232",xj="_helpHeader_1infv_238",Aj="_helpClose_1infv_249",Ij="_markdownHelp_1infv_263",Tj="_helpGrid_1infv_272",Nj="_helpGridItem_1infv_278",jj="_settingsHint_1infv_290",Rj="_sectionBlock_1infv_296",Dj="_softSectionSurface_1infv_306",Pj="_stackedList_1infv_313",Ej="_stackedListSpaced_1infv_318",Lj="_checklistRow_1infv_322",Mj="_checklistRowDragging_1infv_331",Bj="_checklistHandleBtn_1infv_335",Wj="_checklistCheckboxBtn_1infv_358",Fj="_checklistCheckboxBtnChecked_1infv_378",Oj="_checklistItemText_1infv_383",$j="_checklistItemTextCompleted_1infv_389",Uj="_checklistRemoveBtn_1infv_394",zj="_specialistChip_1infv_457",Hj="_specialistChipActive_1infv_480",Gj="_commentPanel_1infv_561",Vj="_commentThread_1infv_575",Zj="_emptyComments_1infv_584",qj="_comment_1infv_561",Kj="_activityEvent_1infv_602",Yj="_activityEventSystem_1infv_607",Jj="_commentAi_1infv_611",Xj="_commentUser_1infv_615",Qj="_commentHeader_1infv_619",eR="_activityEventHeader_1infv_636",tR="_commentAuthor_1infv_642",nR="_commentTime_1infv_650",aR="_commentText_1infv_654",sR="_activityEventText_1infv_690",rR="_activityEventChanges_1infv_699",oR="_activityEventChange_1infv_699",iR="_commentInputArea_1infv_717",cR="_commentInput_1infv_717",lR="_sendCommentBtn_1infv_749",dR="_taxonomyFieldsGrid_1infv_775",uR="_markdownPreviewContainer_1infv_782",pR="_descriptionSurface_1infv_787",We={formNotice:QN,assigneeIndicator:ej,assigneeIndicatorAgent:tj,assigneeIndicatorUser:nj,assigneeIndicatorUnassigned:aj,markdownPreview:sj,error:rj,keyboardHint:oj,taskFormLifecycle:ij,taskFormMetaDivider:cj,taskFormMetaGrid:lj,compactMetaSection:dj,createWorkstreamRow:uj,createWorkstreamDropdown:pj,compactMetaGrid:mj,compactMetaField:fj,compactMetaSpacer:hj,compactMetaFieldHint:gj,formFieldsetReset:yj,taskFormDateRow:kj,taskFormDateLabel:Sj,taskFormDateValue:vj,taskFormMetaStack:wj,taskFormMetaActor:bj,taskFormDateWarning:_j,taskFormDateError:Cj,helpHeader:xj,helpClose:Aj,markdownHelp:Ij,helpGrid:Tj,helpGridItem:Nj,settingsHint:jj,sectionBlock:Rj,softSectionSurface:Dj,stackedList:Pj,stackedListSpaced:Ej,checklistRow:Lj,checklistRowDragging:Mj,checklistHandleBtn:Bj,checklistCheckboxBtn:Wj,checklistCheckboxBtnChecked:Fj,checklistItemText:Oj,checklistItemTextCompleted:$j,checklistRemoveBtn:Uj,specialistChip:zj,specialistChipActive:Hj,commentPanel:Gj,commentThread:Vj,emptyComments:Zj,comment:qj,activityEvent:Kj,activityEventSystem:Yj,commentAi:Jj,commentUser:Xj,commentHeader:Qj,activityEventHeader:eR,commentAuthor:tR,commentTime:nR,commentText:aR,activityEventText:sR,activityEventChanges:rR,activityEventChange:oR,commentInputArea:iR,commentInput:cR,sendCommentBtn:lR,taxonomyFieldsGrid:dR,markdownPreviewContainer:uR,descriptionSurface:pR};function mp({label:e,value:n,options:s,onChange:r,type:o="priority",hideLabel:l=!1,showSelectedLabel:i=!0}){const p=s.find(h=>String(h.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}),i&&p&&t.jsx("span",{className:u.levelLabel,style:{color:Aa(p.color)||(o==="priority"?`var(--priority-${n})`:o==="complexity"?`var(--complexity-${n})`:"var(--text-secondary)"),backgroundColor:(Aa(p.color)?`${Aa(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((h,w)=>{const b=s.findIndex(g=>String(g.value)===String(n)),_=w<=b,k=String(h.value)===String(n);return t.jsx("button",{type:"button",className:`${u.levelOption} ${_?u.levelOptionFilled:""} ${_?u[`levelOption_${o}_${h.value}`]:""} ${k?u.levelOptionSelected:""}`,onClick:()=>r(h.value),title:h.label,style:{opacity:_?1:.15,backgroundColor:_?Aa(h.color)||(o==="priority"?`var(--priority-${h.value})`:o==="complexity"?`var(--complexity-${h.value})`:"var(--text-primary)"):void 0,color:_?o==="priority"&&String(h.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:_&&(o==="priority"&&(String(h.value).toLowerCase()==="critical"||h.value===4)||o==="complexity"&&(String(h.value).toLowerCase()==="epic"||h.value===5))?`0 0 12px ${o==="priority"?"rgba(239, 68, 68, 0.6)":"rgba(217, 70, 239, 0.6)"}`:void 0}},String(h.value))})})]})}const Um=new Map;function mR(e){const n=e instanceof Date?e:new Date(e);return Number.isNaN(n.getTime())?null:n}function fR(e,n){const s=Object.entries(n).sort(([r],[o])=>r.localeCompare(o));return JSON.stringify([e,s])}function Rc(e,n,s){const r=mR(e);if(!r)return"";const o=s??jf(),l=fR(o,n);let i=Um.get(l);return i||(i=new Intl.DateTimeFormat(o,n),Um.set(l,i)),i.format(r)}const hR="D-";function gR(e){return Yl(hR,e)}const fh=[".png",".jpg",".jpeg",".webp",".gif",".pdf",".txt",".md",".csv",".json",".doc",".docx",".html",".js",".ts",".tsx",".css",".py",".java",".go",".rs",".sh"].join(","),yR=new Set(["image/png","image/jpeg","image/webp"]),kR=new Set(fh.split(",").map(e=>e.trim().toLowerCase())),SR=10*1024*1024,vR=3500;function hh(e){const n=e.trim().toLowerCase(),s=n.lastIndexOf(".");return s===-1?"":n.slice(s)}function fp(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 wR(e){return`${e.name.trim().toLowerCase()}::${e.size}::${e.lastModified}`}function bR(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 El(e){return/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(e)}function _R(e){const n=e.types;if(!n)return null;for(const s of Array.from(n)){const r=String(s||"").trim().toLowerCase();if(yR.has(r))return r}return null}function zm(e,n){const s=e.includes("?")?"&":"?";return`${e}${s}download=1&filename=${encodeURIComponent(n)}`}function Hm(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 CR(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=hh(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 xR(e){const{taskId:n,taskReferenceLabel:s,workspaceId:r,contextFiles:o,onAddContextFile:l,onRemoveContextFile:i,onUpdateContextCaption:p}=e,h=a.useRef(null),[w,b]=a.useState(!1),[_,k]=a.useState(null),[g,C]=a.useState(""),[M,S]=a.useState(null),[P,Z]=a.useState(null),[$,ce]=a.useState(!1),[q,K]=a.useState(!1),[j,ye]=a.useState(0),U=a.useRef(new Set),X=a.useRef(new Set),Ne=y=>(y||"").trim(),pe=(y,x)=>{const H=[],I=Ne(y),Ie=Ne(x);return I&&H.push(`path:${I}`),Ie&&H.push(`fs:${Ie}`),H},te=a.useMemo(()=>{const y=new Set;return o.forEach(x=>{if(typeof x=="string"){pe(x).forEach(H=>y.add(H));return}pe(x.path,x.fsPath).forEach(H=>y.add(H))}),y},[o]);a.useEffect(()=>{U.current=new Set(te)},[te]);const D=(y,x)=>x.some(H=>y.has(H)),B=(y,x)=>x.forEach(H=>y.add(H)),oe=String(r||"").trim(),xe=(y="application/json")=>{const x={"Content-Type":y};return oe&&(x["x-taskforce-workspace-id"]=oe),x},ie=(y,x=!0,H=U.current)=>{const I=y.trim();if(!I||!/^https?:\/\//i.test(I))return"invalid";const L=I,le=pe(L);if(D(H,le))return"duplicate";const ne=I.split(/[\\/]/).pop()||I;return l({path:L,caption:ne,timestamp:new Date().toISOString()}),B(H,le),x&&C(""),S(null),"added"};a.useEffect(()=>{if(!P)return;const y=window.setTimeout(()=>{Z(null)},vR);return()=>window.clearTimeout(y)},[P]);const ae=async y=>{if(y.length===0)return;k(null),Z(null);const x=y,H=[],I=[],Ie=[],L=[],le=new Set(X.current);x.forEach(ee=>{const be=hh(ee.name);if(!kR.has(be)){H.push(ee.name);return}if(ee.size>SR){I.push(ee.name);return}const $e=wR(ee);if(le.has($e)){Ie.push(ee.name);return}le.add($e),L.push({file:ee,fingerprint:$e})});const ne=[];if(H.length>0&&ne.push(`${H.length} unsupported file${H.length===1?"":"s"} skipped: ${fp(H)}.`),I.length>0&&ne.push(`${I.length} file${I.length===1?"":"s"} over 10 MB skipped: ${fp(I)}.`),Ie.length>0&&ne.push(`${Ie.length} local duplicate file${Ie.length===1?"":"s"} skipped before upload: ${fp(Ie)}.`),L.length===0){ne.length>0&&Z(ne.join(" ")),h.current&&(h.current.value="");return}b(!0);const de=new Set(U.current);let G=0;try{for(const{file:be,fingerprint:$e}of L){let fe=null;const De=await fetch("/api/taskforce/context-upload/init",{method:"POST",headers:xe(),body:JSON.stringify({originalName:be.name,mimeType:be.type||"application/octet-stream",size:be.size,taskId:n||null,workspaceId:oe||null})});if(De.ok){const nt=await De.json();if(nt?.success&&typeof nt?.uploadUrl=="string"&&typeof nt?.path=="string"){if(!(await fetch(nt.uploadUrl,{method:String(nt.method||"PUT"),headers:nt.headers||{"Content-Type":be.type||"application/octet-stream"},body:be})).ok)throw new Error(`Upload failed for ${be.name}`);const d=await fetch("/api/taskforce/context-upload/finalize",{method:"POST",headers:xe(),body:JSON.stringify({relativePath:nt.relativePath,mimeType:be.type||"application/octet-stream",originalName:be.name,size:be.size,taskId:n||null,workspaceId:oe||null})});if(!d.ok){const et=await d.json().catch(()=>({}));throw new Error(et?.error||`Upload failed for ${be.name}`)}fe=await d.json().catch(()=>null)}else nt?.success&&typeof nt?.path=="string"&&(fe=nt)}if(!fe){const nt=await bR(be),dt=await fetch("/api/taskforce/context-upload",{method:"POST",headers:xe(),body:JSON.stringify({file:nt,originalName:be.name,taskId:n||null,workspaceId:oe||null})});if(!dt.ok)throw new Error(`Upload failed for ${be.name}`);fe=await dt.json()}if(!fe?.success||!fe?.path)throw new Error(`Upload failed for ${be.name}`);const Ke=pe(fe.path,fe.fsPath);if(D(de,Ke)){G+=1;continue}l({path:fe.path,fsPath:fe.fsPath,caption:typeof fe.caption=="string"&&fe.caption.trim().length>0?fe.caption:be.name,displayName:typeof fe.displayName=="string"?fe.displayName:void 0,originalFilename:typeof fe.originalFilename=="string"?fe.originalFilename:be.name,assetId:typeof fe.assetId=="string"?fe.assetId:void 0,referenceNumber:typeof fe.referenceNumber=="number"?fe.referenceNumber:null,referenceLabel:typeof fe.referenceLabel=="string"?fe.referenceLabel:void 0,taskId:typeof fe.taskId=="string"?fe.taskId:null,timestamp:new Date().toISOString()}),Ik({workspaceId:oe||"default",taskId:n||null,reason:"upload"}),B(de,Ke),X.current.add($e)}const ee=[...ne];G>0&&ee.push(`${G} duplicate file${G===1?"":"s"} skipped.`),Z(ee.length>0?ee.join(" "):null),U.current=de}catch(ee){k(ee instanceof Error?ee.message:"Failed to upload context file")}finally{b(!1),h.current&&(h.current.value="")}},Ze=async y=>{!y||y.length===0||await ae(Array.from(y))},Le=async()=>{if(k(null),Z(null),!navigator.clipboard||typeof navigator.clipboard.read!="function"){k("Clipboard image paste is not available in this browser.");return}try{const y=await navigator.clipboard.read(),x=[];for(const H of y){const I=_R(H);if(!I)continue;const Ie=await H.getType(I),L=I.toLowerCase()==="image/png"?"png":I.toLowerCase()==="image/webp"?"webp":"jpg";x.push(new globalThis.File([Ie],`pasted-image-${Date.now()}.${L}`,{type:I}))}if(x.length===0){k("Clipboard does not currently contain a supported image.");return}await ae(x)}catch(y){k(y?.message||"Failed to read an image from the clipboard.")}},Ce=y=>{const x=new Set,H=y.dataTransfer.getData("text/uri-list")||"",I=y.dataTransfer.getData("text/plain")||"",Ie=`${H}
|
|
4
|
+
${I}`.split(`
|
|
5
|
+
`).map(L=>L.trim()).filter(L=>!!L&&!L.startsWith("#"));for(const L of Ie){if(/^file:\/\//i.test(L)){try{const le=new URL(L),ne=decodeURIComponent(le.pathname||"").trim();ne&&x.add(ne)}catch{}continue}x.add(L)}return Array.from(x)},Oe=y=>{if(y.preventDefault(),y.stopPropagation(),K(!1),ye(0),k(null),S(null),Z(null),y.dataTransfer.files&&y.dataTransfer.files.length>0){Ze(y.dataTransfer.files);return}const x=Ce(y);if(x.length===0){S("Drop a file or URL.");return}const H=new Set(U.current);let I=0,Ie=0,L=0;x.forEach(ne=>{const de=ie(ne,!1,H);de==="duplicate"&&(I+=1),de==="added"&&(Ie+=1),de==="invalid"&&(L+=1)});const le=[];I>0&&le.push(`${I} duplicate link${I===1?"":"s"} skipped.`),L>0&&le.push(`${L} local path${L===1?"":"s"} skipped. Upload files to attach them, or drop an http(s) URL to link.`),Z(le.length>0?le.join(" "):Ie>0?null:P),U.current=H},R=y=>{y.preventDefault(),y.stopPropagation(),ye(x=>x+1),K(!0)},W=y=>{y.preventDefault(),y.stopPropagation(),ye(x=>{const H=Math.max(0,x-1);return H===0&&K(!1),H})},F=y=>{y.preventDefault(),y.stopPropagation(),y.dataTransfer.dropEffect="copy"},V=o.filter(y=>{const x=typeof y=="string"?y:y.path;return El(x)}),E=o.filter(y=>{const x=typeof y=="string"?y:y.path;return!El(x)});return t.jsxs("div",{className:u.specialistSection,children:[t.jsxs("div",{className:u.toggleHeading,onClick:()=>ce(!$),title:$?"Hide context documents":"Show context documents",children:[t.jsxs("label",{className:u.label,children:["Context Documents ",o.length>0&&`(${o.length})`]}),$?t.jsx(Dc,{size:14}):t.jsx(ji,{size:14})]}),$&&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:()=>h.current?.click(),disabled:w,children:[w?t.jsx(Wa,{size:12,className:u.spinner}):t.jsx(ap,{size:12}),w?"Uploading...":"Upload File"]}),t.jsxs("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{Le()},disabled:w,children:[t.jsx(Ol,{size:12}),"Paste Image from Clipboard"]})]}),t.jsx("input",{ref:h,type:"file",accept:fh,multiple:!0,className:u.hiddenInput,onChange:y=>{Ze(y.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:g,onChange:y=>{C(y.target.value),M&&S(null),P&&Z(null)}}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{if(!g.trim()){S("Enter an http(s) URL to link.");return}const y=ie(g,!0);if(y==="invalid"){S("Only external http(s) URLs can be linked here. Upload files to attach them.");return}y==="duplicate"?Z("Link already exists in task context."):y==="added"&&Z(null)},children:"Add URL"})]}),t.jsxs("div",{className:`${u.contextDropzone} ${q?u.contextDropzoneActive:""}`,onDragEnter:R,onDragLeave:W,onDragOver:F,onDrop:Oe,children:[t.jsx(ap,{size:14}),t.jsx("span",{children:"Drop files or URLs here"})]})]}),P&&t.jsx("div",{className:u.contextNotice,children:P}),M&&t.jsx("div",{className:u.error,children:M}),V.length>0&&t.jsx("div",{className:u.attachmentGrid,children:o.map((y,x)=>{const H=typeof y=="string"?y:y.path;if(!El(H))return null;const I=typeof y=="string"?void 0:y.fsPath,Ie=typeof y=="string"?"":y.caption||"",L=Hm(y),le=El(H),ne=/^https?:\/\//i.test(H),de=sh(y);return t.jsxs("div",{className:u.attachmentCard,children:[t.jsxs("div",{className:u.attachmentPreviewContainer,children:[le?t.jsx("img",{src:H,alt:Ie||`Context file ${x}`,onClick:()=>{Dp(y,{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:()=>{Rp(y,I)||window.open(H,"_blank")},title:"Open file",children:[t.jsx(ap,{size:16}),t.jsx("span",{children:Ie||I||H.split("/").pop()||"Context file"})]}),t.jsxs("div",{className:u.brokenImagePlaceholder,children:[t.jsx(Pc,{size:16}),t.jsx("span",{children:"Preview unavailable"})]}),t.jsxs("div",{className:u.attachmentActions,children:[de&&t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),Dp(y,{taskId:n,taskReferenceLabel:s})},title:"Annotate",children:t.jsx(eg,{size:12})}),I&&t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),navigator.clipboard.writeText(I)},title:`Copy path: ${I}`,children:t.jsx(Ol,{size:12})}),!ne&&t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),window.open(zm(H,Ie||L),"_blank")},title:"Download",children:t.jsx(pm,{size:12})}),t.jsx("button",{type:"button",className:u.attachmentActionBtn,onClick:G=>{G.stopPropagation(),i(x)},title:"Delete",children:t.jsx(Hl,{size:12})})]})]}),t.jsx("input",{type:"text",className:u.attachmentCaptionInput,placeholder:"Add a label...",value:Ie,onChange:G=>p(x,G.target.value)})]},x)})}),E.length>0&&t.jsx("div",{className:u.documentAttachmentList,children:o.map((y,x)=>{const H=typeof y=="string"?y:y.path;if(El(H))return null;const I=typeof y=="string"?void 0:y.fsPath,Ie=typeof y=="string"?"":y.caption||"",L=Hm(y),le=CR(y),ne=typeof y=="string"?"":gR(y),de=/^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:()=>{Rp(y,I)||window.open(H,"_blank")},title:L,children:[t.jsxs("span",{className:u.documentAttachmentMain,children:[t.jsx("span",{className:u.documentAttachmentIcon,"aria-hidden":"true",children:t.jsx(tg,{size:13})}),t.jsxs("span",{className:u.documentAttachmentText,children:[t.jsx("span",{className:u.documentAttachmentName,children:L}),ne&&t.jsx("span",{className:u.taskIdBadge,children:ne})]})]}),t.jsx("span",{className:u.documentAttachmentType,children:le})]}),t.jsxs("div",{className:u.documentAttachmentActions,children:[I&&t.jsx("button",{type:"button",className:u.documentAttachmentActionBtn,onClick:()=>{navigator.clipboard.writeText(I)},title:`Copy path: ${I}`,children:t.jsx(Ol,{size:12})}),!de&&t.jsx("button",{type:"button",className:u.documentAttachmentActionBtn,onClick:()=>{window.open(zm(H,Ie||L),"_blank")},title:"Download",children:t.jsx(pm,{size:12})}),t.jsx("button",{type:"button",className:u.documentAttachmentActionBtn,onClick:()=>i(x),title:"Delete",children:t.jsx(Hl,{size:12})})]})]}),t.jsx("input",{type:"text",className:u.documentAttachmentCaptionInput,placeholder:"Add a label...",value:Ie,onChange:G=>p(x,G.target.value)})]},x)})})]})]})}function AR({id:e,item:n,onToggle:s,onRemove:r}){const{attributes:o,listeners:l,setNodeRef:i,transform:p,transition:h,isDragging:w}=yf({id:e}),b={transform:Mp.Transform.toString(p),transition:h,opacity:w?.88:1};return t.jsxs("div",{ref:i,style:b,className:`${We.checklistRow} ${w?We.checklistRowDragging:""}`.trim(),children:[t.jsx("button",{type:"button",className:We.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...o,...l,children:t.jsx(sg,{size:14})}),t.jsx("button",{type:"button",className:`${We.checklistCheckboxBtn} ${n.isCompleted?We.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(ao,{size:14,strokeWidth:2.1}):null}),t.jsx("span",{className:`${We.checklistItemText} ${n.isCompleted?We.checklistItemTextCompleted:""}`.trim(),children:n.title}),t.jsx("button",{type:"button",className:We.checklistRemoveBtn,onClick:r,title:"Remove checklist item","aria-label":"Remove checklist item",children:t.jsx(Di,{size:15,strokeWidth:1.9})})]})}function hp(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 gh(e){const{editingTaskId:n,error:s,title:r,description:o,category:l,type:i,priority:p,complexity:h,manualComplexityEnabled:w=!1,assignee:b,scheduledDate:_,dueDate:k,workstreamInput:g="",checklistItems:C,comments:M,newCommentText:S,contextFiles:P,currentWorkspaceId:Z,apiBaseUrl:$,descriptionFocused:ce,showMarkdownHelp:q,showChecklist:K=!1,checklistEnabled:j=!0,showComments:ye,formTaxonomies:U,onTaxonomyChange:X,onOpenSettings:Ne,categories:pe,types:te,priorities:D,taxonomyDisplayLabels:B,assigneeOptions:oe,taxonomies:xe,workstreams:ie=[],copiedId:ae,onTitleChange:Ze,onDescriptionChange:Le,onCategoryChange:Ce,onTypeChange:Oe,onPriorityChange:R,onComplexityChange:W,onAssigneeChange:F,onScheduledDateChange:V,onDueDateChange:E,onWorkstreamInputChange:y=()=>{},onChecklistItemsChange:x,onNewCommentTextChange:H,onDescriptionFocusedChange:I,onShowMarkdownHelpChange:Ie,onShowChecklistChange:L=()=>{},onShowCommentsChange:le,onSubmit:ne,onAddComment:de,onAddContextFile:G,onRemoveContextFile:ee,onUpdateContextCaption:be,onCopyId:$e,onToggleInProgress:fe,onToggleReview:De,onToggleComplete:Ke,onToggleCancel:nt,onSetStatus:dt,onArchiveTask:d,onUnarchive:et,onOpenTaskById:gt,currentTask:O,commentsEndRef:Ye}=e,wt=Ar(O),St=pt.useMemo(()=>eS(xe,U),[xe,U]),At=pt.useMemo(()=>{const se=pe.find(tt=>tt.value===jc),je={value:jc,label:se?.label||Su,icon:se?.icon||"HelpCircle",color:se?.color||"var(--text-secondary)"},Me=pe.find(tt=>tt.value===l),Fe=pe.filter(tt=>!tt.disabled||tt.value===Me?.value).filter(tt=>tt.value!==jc).map(tt=>({value:tt.value,label:tt.disabled?`${tt.label} (Legacy)`:tt.label,icon:tt.icon,color:tt.color}));return[je,...Fe]},[pe,l]),zt=pt.useMemo(()=>{const se=te.find(Me=>Me.value===i);return te.filter(Me=>Me.status!=="retired"||Me.value===se?.value).map(Me=>({value:Me.value,label:Me.status==="retired"?`${Me.label} (Retired)`:Me.label,icon:Me.icon||"Box",color:Me.color||"violet-500"}))},[te,i]),Ht=se=>se&&Rc(se,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,sn=Ht(O?.createdAt),Jt=Ht(O?.updatedAt||O?.createdAt),Xt=Ht(O?.completedAt),gn=pt.useMemo(()=>{const se=new Date,je=se.getFullYear(),Me=String(se.getMonth()+1).padStart(2,"0"),Ee=String(se.getDate()).padStart(2,"0");return`${je}-${Me}-${Ee}`},[]),Mn=!!(k&&_&&k<_),un=!!(k&&k<gn&&(!O||O.status!=="done"&&O.status!=="cancelled")),yn=C.filter(se=>se.isCompleted).length,[an,Tn]=pt.useState(""),[Rt,we]=pt.useState(!1),Lt=!!O?.isArchived,Qt=!!O?.isDeleted,Dt=pt.useMemo(()=>ie.map(se=>{const je=Vp(se);return{value:je||se.id,label:je?`${je} · ${se.title}`:se.title,icon:"Folder",color:"var(--text-secondary)"}}),[ie]),He=pt.useMemo(()=>Dt.some(se=>String(se.value)===String(g||"").trim()),[g,Dt]);pt.useEffect(()=>{if(n){Rt&&we(!1);return}if(g.trim()){if(He&&Rt){we(!1);return}!He&&!Rt&&we(!0)}},[n,He,Rt,g]);const Nn=Lt||Qt,Y=pt.useRef(null),Ae=pf(xp(gf,{activationConstraint:{distance:6}}));pt.useLayoutEffect(()=>{const se=Y.current;if(!se)return;const je=()=>{se.scrollTop=0;const Ee=se.parentElement;Ee&&(typeof Ee.scrollTo=="function"?Ee.scrollTo({top:0,left:0,behavior:"auto"}):Ee.scrollTop=0)};je();const Me=window.requestAnimationFrame(je);return()=>window.cancelAnimationFrame(Me)},[n,O?.id]);const _e=()=>{const se=an.trim();if(!se)return;const je=new Date().toISOString();x([...C,{id:`checklist-draft-${je}-${C.length}`,taskId:n||"",title:se,isCompleted:!1,order:C.length,createdAt:je,updatedAt:je}]),Tn("")},Pe=pt.useCallback(se=>{const{active:je,over:Me}=se;if(!Me||je.id===Me.id)return;const Ee=C.findIndex(Mt=>Mt.id===je.id),Fe=C.findIndex(Mt=>Mt.id===Me.id);if(Ee<0||Fe<0)return;const tt=new Date().toISOString(),An=Ig(C,Ee,Fe).map((Mt,fa)=>({...Mt,order:fa,updatedAt:tt}));x(An)},[C,x]),qe=se=>{const je=String(se||"").trim(),Me=se.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!Me||Me==="ai"||je.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${Me.split(" ").map(Fe=>Fe.charAt(0).toUpperCase()+Fe.slice(1)).join(" ")}`},Je=Py(oe,b),at=uu(b),Xe=_c(b,Je),ct=pt.useMemo(()=>new Map(Je.map(se=>[String(se.value),se])),[Je]),vt=ct.get(String(b||"unassigned")),Ot=O?.assigneeActor?.color||vt?.color,Pt=pt.useMemo(()=>{const se=[O?.assigneeActor,O?.createdByActor].filter(Boolean);return new Map(se.map(je=>[String(je.id),je]))},[O?.assigneeActor,O?.createdByActor]),xt=pt.useMemo(()=>Array.isArray(O?.activity)&&O.activity.length>0?O.activity:M.map(se=>({id:`comment:${se.id}`,type:"comment",timestamp:se.timestamp,comment:se})),[M,O?.activity]),Et=(se,je)=>{if(se==="assignee")return _c(String(je||"").trim(),Je)},xn=pt.useCallback((se,je,Me)=>{if(Me&&Me.trim())return Me.trim();const Ee=String(se||"").trim();if(!Ee)return je==="ai"?"AI Agent":Te("taskForm.you");const Fe=Pt.get(Ee);if(Fe?.label)return Fe.label;const tt=ct.get(Ee)||ct.get(Ee.toLowerCase());return tt?.label?tt.label:je==="ai"?qe(Ee):_c(Ee,Je)||Ee},[Pt,ct,qe,Je]),Gt=pt.useMemo(()=>{const se=xt[0];if(!se)return null;if(se.type==="comment"){const Me=se.comment;return xn(Me.author,Me.actor?.kind==="ai"?"ai":Me.actor?.kind==="human"?"human":null,Me.actor?.label||null)}const je=se.event;return xn(je.actor,je.actorType,je.actorProfile?.label||null)},[xn,xt]),Jn=pt.useMemo(()=>{if(!O?.completedAt)return null;for(const je of xt){if(je.type!=="event")continue;const Me=je.event,Ee=Me.details?.changes?.status?.to;if(Ee==="done"||Ee==="cancelled")return xn(Me.actor,Me.actorType,Me.actorProfile?.label||null)}return Gt},[O?.completedAt,Gt,xn,xt]),kn=O?.createdByActor?.label||xn(O?.createdBy||null,O?.createdByActor?.kind==="ai"?"ai":O?.createdByActor?.kind==="human"?"human":null,O?.createdByActor?.label||null),yt=Gt,Gn=xt.length;return t.jsxs("form",{ref:Y,onSubmit:ne,className:`${u.form} ${u.appScrollbar} tf-scrollbar`,children:[s&&t.jsx("div",{className:We.error,children:s}),Nn&&t.jsx("div",{className:`${We.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:Nn,className:We.formFieldsetReset,children:[t.jsxs("div",{className:u.field,children:[t.jsxs("div",{className:u.labelRow,children:[t.jsx("label",{className:u.label,children:"Title"}),b&&t.jsx("span",{title:`Assigned to: ${Xe}`,className:[We.assigneeIndicator,at==="agent"?We.assigneeIndicatorAgent:at==="member"?We.assigneeIndicatorUser:We.assigneeIndicatorUnassigned].join(" "),style:Ot?{color:Ot}:void 0,children:at==="agent"?t.jsx(eu,{size:20}):at==="member"?t.jsx(Eo,{size:20}):t.jsx(Ii,{size:20})})]}),t.jsx("input",{type:"text",value:r,onChange:se=>Ze(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:()=>Ie(!q),title:"Markdown Help",tabIndex:-1,children:t.jsx(Ii,{size:14})})]}),q&&t.jsxs("div",{className:We.markdownHelp,children:[t.jsxs("div",{className:We.helpHeader,children:[t.jsx("span",{children:"Markdown Guide"}),t.jsx("button",{onClick:()=>Ie(!1),className:We.helpClose,children:t.jsx(Di,{size:12})})]}),t.jsxs("div",{className:We.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:We.helpGridItem,children:t.jsx("code",{children:"`inline code`"})}),t.jsxs("div",{className:We.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)"})})]})]}),ce||!o?t.jsx("textarea",{className:`${u.textarea} ${We.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",value:o,onChange:se=>Le(se.target.value),onFocus:()=>I(!0),onBlur:()=>I(!1),rows:9,autoFocus:ce}):t.jsx("div",{className:`${u.textarea} ${We.descriptionSurface} ${We.markdownPreview} ${We.markdownPreviewContainer}`,onClick:()=>I(!0),children:t.jsx(jp,{onTaskIdClick:gt,children:o})})]}),t.jsxs("div",{className:We.compactMetaSection,children:[t.jsxs("div",{className:We.compactMetaGrid,children:[t.jsxs("div",{className:`${u.field} ${We.compactMetaField}`,children:[t.jsx("label",{id:"category-label",className:u.label,children:B?.category||"Category"}),t.jsx(Bl,{value:l,options:At,onChange:se=>Ce(String(se)),required:!0,ariaLabelledBy:"category-label"})]}),t.jsxs("div",{className:`${u.field} ${We.compactMetaField}`,children:[t.jsx("label",{id:"type-label",className:u.label,children:B?.type||"Type"}),t.jsx(Bl,{value:i,options:zt,onChange:se=>Oe(String(se)),ariaLabelledBy:"type-label"})]}),t.jsxs("div",{className:`${u.field} ${We.compactMetaField}`,children:[t.jsx("label",{htmlFor:"task-form-scheduled-date",className:u.label,children:Te("taskForm.scheduledLabel")}),t.jsx("input",{id:"task-form-scheduled-date",type:"date",value:_,onChange:se=>V(se.target.value),className:`${u.input} ${u.taskFormDateInput}`})]}),t.jsx("div",{className:We.compactMetaSpacer,"aria-hidden":"true"}),t.jsxs("div",{className:`${u.field} ${We.compactMetaField}`,children:[t.jsx("label",{id:"assignee-label",className:u.label,children:"Assigned To"}),t.jsx(Bl,{value:b||"unassigned",options:Je,onChange:se=>F(String(se)),ariaLabelledBy:"assignee-label"})]}),t.jsx("div",{className:We.compactMetaField,children:t.jsx(mp,{label:B?.priority||"Priority",options:D,value:p,onChange:R,type:"priority",showSelectedLabel:!1})}),t.jsxs("div",{className:`${u.field} ${We.compactMetaField}`,children:[t.jsx("label",{htmlFor:"task-form-due-date",className:u.label,children:Te("taskForm.dueLabel")}),t.jsx("input",{id:"task-form-due-date",type:"date",value:k,onChange:se=>E(se.target.value),className:`${u.input} ${u.taskFormDateInput}`}),Mn&&t.jsx("span",{className:`${We.taskFormDateWarning} ${We.compactMetaFieldHint}`,children:Te("taskForm.dueBeforeScheduled")}),un&&t.jsx("span",{className:`${We.taskFormDateError} ${We.compactMetaFieldHint}`,children:Te("taskForm.overdue")})]}),w&&t.jsx("div",{className:We.compactMetaField,children:t.jsx(mp,{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:h,onChange:W,type:"general"})})]}),!n&&t.jsxs("div",{className:We.createWorkstreamRow,children:[t.jsx("label",{className:u.label,children:"Attach to workstream"}),t.jsxs("div",{className:u.pathInputGroup,children:[Rt?t.jsx("input",{type:"text",className:u.input,value:g,onChange:se=>y(se.target.value),placeholder:"Type a workstream name or reference","aria-label":"Attach to workstream"}):t.jsx(Bl,{value:g,options:Dt,onChange:se=>y(String(se)),placeholder:"Select workstream...",ariaLabel:"Attach to workstream",className:We.createWorkstreamDropdown}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{if(Rt){we(!1),He||y("");return}we(!0)},"aria-label":Rt?"Use workstream dropdown":"Enter workstream by name",title:Rt?"Use workstream dropdown":"Enter workstream by name",children:t.jsx(sr,{size:14})})]})]})]}),t.jsxs("div",{className:We.sectionBlock,children:[t.jsx("div",{className:We.taxonomyFieldsGrid,children:St.map(se=>{if(se.id==="approach"&&se.isSystem)return null;const je=U[se.id],Me=Array.isArray(je)?je.map(Fe=>String(Fe)):je!=null&&je!==""?[String(je)]:[],Ee=se.options.filter(Fe=>Fe.status!=="retired"||Me.includes(String(Fe.value)));return t.jsxs("div",{className:u.field,children:[t.jsx("label",{className:u.label,children:se.label}),se.description&&t.jsx("div",{className:`${We.settingsHint} tf-text-helper`,children:se.description}),se.widgetType==="level"?t.jsx(mp,{label:se.label,options:Ee.map(Fe=>({...Fe,label:Fe.status==="retired"?`${Fe.label} (Retired)`:Fe.label})),value:U[se.id]||"",onChange:Fe=>X(se.id,Fe),type:"general",hideLabel:!0}):se.multiSelect?t.jsx("div",{className:`${u.dropdownList} ${We.softSectionSurface}`,children:Ee.map(Fe=>{const tt=String(Fe.value),An=Me.includes(tt);return t.jsxs("button",{type:"button",className:`${We.specialistChip} ${An?We.specialistChipActive:""}`,onClick:()=>{const Mt=An?Me.filter(fa=>fa!==tt):[...Me,tt];X(se.id,Mt)},title:An?"Click to remove":"Click to add",children:[An&&t.jsx(ao,{size:12}),Fe.status==="retired"?`${Fe.label} (Retired)`:Fe.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 Fe=se.options.find(Mt=>String(Mt.value)===String(U[se.id])),tt=Fe?.icon&&$s[Fe.icon]?$s[Fe.icon]:Ii,An=Fe?.color||"var(--text-secondary)";return t.jsx("div",{className:u.fieldIcon,style:{color:Aa(An)},children:t.jsx(tt,{size:16})})})(),t.jsxs("select",{value:U[se.id]||"",onChange:Fe=>X(se.id,Fe.target.value),className:`${u.select} ${u.field_dynamic}`,required:se.isRequired,children:[t.jsxs("option",{value:"",children:["Select ",se.label,"..."]}),Ee.map(Fe=>t.jsx("option",{value:Fe.value,children:Fe.status==="retired"?`${Fe.label} (Retired)`:Fe.label},Fe.value))]})]})]},se.id)})}),j&&t.jsxs("div",{className:u.specialistSection,children:[t.jsxs("div",{className:u.toggleHeading,onClick:()=>L(!K),title:K?"Hide checklist":"Show checklist",children:[t.jsxs("label",{className:u.label,children:["Checklist ",C.length>0&&`(${yn}/${C.length})`]}),K?t.jsx(Dc,{size:14}):t.jsx(ji,{size:14})]}),K&&t.jsxs("div",{className:`${u.dropdownList} ${We.stackedList} ${We.stackedListSpaced}`,children:[t.jsxs("div",{className:u.pathInputGroup,children:[t.jsx("input",{type:"text",className:u.input,placeholder:"Add checklist item",value:an,onChange:se=>Tn(se.target.value),onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),_e())}}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:_e,disabled:!an.trim(),children:"Add"})]}),C.length>0?t.jsx(mf,{sensors:Ae,collisionDetection:Tg,onDragEnd:Pe,children:t.jsx(ff,{items:C.map(se=>se.id),strategy:hf,children:C.map((se,je)=>t.jsx(AR,{id:se.id||`checklist-${je}`,item:se,onToggle:()=>{const Me=new Date().toISOString();x(C.map((Ee,Fe)=>Fe===je?{...Ee,isCompleted:!Ee.isCompleted,updatedAt:Me}:Ee))},onRemove:()=>x(C.filter((Me,Ee)=>Ee!==je).map((Me,Ee)=>({...Me,order:Ee})))},se.id||`checklist-${je}`))})}):t.jsx("div",{className:`${We.settingsHint} tf-text-helper`,children:"No checklist items yet."})]})]})]}),t.jsxs("div",{children:[t.jsx(xR,{taskId:n,taskReferenceLabel:wt,workspaceId:Z,apiBaseUrl:$,contextFiles:P,onAddContextFile:G,onRemoveContextFile:ee,onUpdateContextCaption:be}),n&&t.jsxs("div",{className:u.specialistSection,children:[t.jsxs("div",{className:u.toggleHeading,onClick:()=>le(!ye),title:Te(ye?"taskForm.hideComments":"taskForm.showComments"),children:[t.jsxs("label",{className:u.label,children:[Te("taskForm.commentsSectionTitle")," ",Gn>0&&`(${Gn})`]}),ye?t.jsx(Dc,{size:14}):t.jsx(ji,{size:14})]}),ye&&t.jsxs("div",{className:We.commentPanel,children:[t.jsxs("div",{className:We.commentThread,children:[Gn===0&&t.jsx("div",{className:We.emptyComments,children:Te("taskForm.noComments")}),xt.map(se=>{if(se.type==="comment"){const Kt=se.comment,kt=String(Kt.author||"").trim(),$t=kt.toLowerCase(),Yt=Pt.get(kt),Sn=ct.get(kt)||ct.get($t),ft=Kt.actor||Yt||Sn||null,mt=Kt.actor?.kind==="human"?"member":Kt.actor?.kind==="ai"?"agent":Yt?.kind==="human"?"member":Yt?.kind==="ai"?"agent":Sn?.kind||($t===""||$t==="user"||$t==="human"?"member":"agent"),oa=Kt.actor?.label||Yt?.label||Sn?.label||(kt?_c(kt,Je):"")||(mt==="agent"?qe(kt||"ai"):Te("taskForm.you")),en=Kt.actor?.color||Yt?.color||Sn?.color,tn=String(ft?.icon||(mt==="agent"?"Bot":"User")),It=Ri[tn]||(mt==="agent"?eu:Eo);return t.jsxs("div",{className:`${We.comment} ${mt==="agent"?We.commentAi:We.commentUser}`,children:[t.jsxs("div",{className:We.commentHeader,children:[t.jsx("span",{className:We.commentAuthor,style:en?{color:en}:void 0,children:t.jsxs(t.Fragment,{children:[t.jsx(It,{size:12,strokeWidth:1.5})," ",oa]})}),t.jsx("span",{className:We.commentTime,children:Rc(Kt.timestamp,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),t.jsx("div",{className:We.commentText,style:en?{background:`linear-gradient(135deg, ${hp(en,.18)} 0%, ${hp(en,.1)} 100%)`,borderColor:hp(en,.35)}:void 0,children:t.jsx(jp,{onTaskIdClick:gt,children:Kt.text})})]},Kt.id)}const je=se.event,Me=String(je.actor||"").trim(),Ee=Me.toLowerCase(),Fe=Pt.get(Me),tt=ct.get(Me)||ct.get(Ee),An=je.actorProfile||Fe||tt||null,Mt=je.actorType==="ai"?"agent":je.actorType==="human"?"member":"system",fa=je.actorProfile?.label||Fe?.label||tt?.label||(Mt==="system"?"System":Me?_c(Me,Je):Mt==="agent"?qe("ai"):Te("taskForm.you")),Bn=je.actorProfile?.color||Fe?.color||tt?.color,bn=String(An?.icon||(Mt==="agent"?"Bot":Mt==="member"?"User":"ClipboardList")),fn=Ri[bn]||(Mt==="agent"?eu:Mt==="member"?Eo:ng),rn=Object.entries(je.details?.changes||{});return t.jsxs("div",{className:`${We.comment} ${We.activityEvent} ${Mt==="system"?We.activityEventSystem:""}`,children:[t.jsxs("div",{className:`${We.commentHeader} ${We.activityEventHeader}`,children:[t.jsx("span",{className:We.commentAuthor,style:Bn?{color:Bn}:void 0,children:t.jsxs(t.Fragment,{children:[t.jsx(fn,{size:12,strokeWidth:1.5})," ",fa]})}),t.jsx("span",{className:We.commentTime,children:Rc(je.createdAt,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),t.jsxs("div",{className:We.activityEventText,children:[t.jsx("div",{children:ch(je,Et)}),rn.length>1&&t.jsx("div",{className:We.activityEventChanges,children:rn.map(([Kt,kt])=>t.jsx("span",{className:We.activityEventChange,children:ih(Kt,kt,Et)},Kt))})]})]},se.id)}),t.jsx("div",{ref:Ye})]}),t.jsxs("div",{className:We.commentInputArea,children:[t.jsx("textarea",{className:We.commentInput,placeholder:Te("taskForm.commentPlaceholder"),value:S,onChange:se=>H(se.target.value),onKeyDown:se=>{se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),de())},rows:1}),t.jsx("button",{type:"button",className:We.sendCommentBtn,onClick:de,disabled:!S.trim(),children:t.jsx(ag,{size:16})})]})]})]}),t.jsx("div",{className:`${We.taskFormLifecycle} ${We.taskFormMetaDivider}`,children:t.jsx("div",{className:We.taskFormMetaGrid,children:O&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:We.taskFormDateRow,children:[t.jsx("span",{className:We.taskFormDateLabel,children:Te("taskForm.createdLabel")}),t.jsxs("span",{className:We.taskFormMetaStack,children:[t.jsx("span",{className:We.taskFormDateValue,children:sn||Te("taskForm.emptyValue")}),t.jsx("span",{className:We.taskFormMetaActor,children:kn?`by ${kn}`:Te("taskForm.emptyValue")})]})]}),t.jsxs("div",{className:We.taskFormDateRow,children:[t.jsx("span",{className:We.taskFormDateLabel,children:Te("taskForm.updatedLabel")}),t.jsxs("span",{className:We.taskFormMetaStack,children:[t.jsx("span",{className:We.taskFormDateValue,children:Jt||Te("taskForm.emptyValue")}),t.jsx("span",{className:We.taskFormMetaActor,children:yt?`by ${yt}`:Te("taskForm.emptyValue")})]})]}),t.jsxs("div",{className:We.taskFormDateRow,children:[t.jsx("span",{className:We.taskFormDateLabel,children:Te("taskForm.completedLabel")}),t.jsxs("span",{className:We.taskFormMetaStack,children:[t.jsx("span",{className:We.taskFormDateValue,children:Xt||Te("taskForm.emptyValue")}),t.jsx("span",{className:We.taskFormMetaActor,children:Jn?`by ${Jn}`:Te("taskForm.emptyValue")})]})]})]})})})]}),t.jsxs("div",{className:We.keyboardHint,children:["Press ",t.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function yh({editingTaskId:e,loading:n,autoSaveState:s="idle",title:r,handleSubmit:o,resetForm:l,handleCopyId:i,copiedId:p,tasks:h,currentTask:w,currentTaskWorkstream:b,currentTaskInitiative:_,workstreamInput:k="",onWorkstreamInputChange:g,onSetWorkstreamForCurrentTask:C,handleToggleInProgress:M,handleToggleReview:S,handleToggleComplete:P,handleToggleCancel:Z,handleSetStatus:$,handleArchiveTask:ce,handleRestoreDeletedTask:q,handlePermanentlyDeleteDeletedTask:K}){const[j,ye]=pt.useState(!1),U=w??(e&&h.find(ae=>ae.id===e)||null),X=!!U?.isArchived,Ne=!!U?.isDeleted,pe=Af(U),te=pe.label||(pe.isProvisional?"Pending":""),D=pe.isProvisional,B=!!pe.label,oe=b?Vp(b)||b.id:"",xe=_?ar(_)||_.id:"";pt.useEffect(()=>{b&&ye(!1)},[b?.id]);const ie=pt.useCallback(()=>{k.trim()&&C?.()},[C,k]);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(nu,{copied:p===xe,onClick:ae=>i(ae,xe),disabled:n,title:"Copy initiative reference",label:xe}),t.jsx("span",{className:u.taskHierarchyDivider,children:"/"})]}):null,b?t.jsxs(t.Fragment,{children:[t.jsx(nu,{copied:p===oe,onClick:ae=>i(ae,oe),disabled:n,title:"Copy workstream reference",label:oe}),t.jsx("span",{className:u.taskHierarchyDivider,children:"/"})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:`${u.taskIdBadge} ${u.taskHierarchyAddBtn}`,onClick:()=>{g?.(""),ye(ae=>!ae)},disabled:n||X||Ne,title:"Attach to workstream","aria-label":"Attach to workstream",children:t.jsx(sr,{size:13})}),t.jsx("span",{className:u.taskHierarchyDivider,children:"/"})]}),te?t.jsx(nu,{copied:B&&p===pe.label,onClick:ae=>i(ae,pe.label),disabled:n||!B,title:B?Te("actionHeader.copyTaskIdTitle"):"Task reference pending sync",label:te}):null,D?t.jsx("span",{className:u.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),j&&!b?t.jsxs("div",{className:u.taskHierarchyEditor,children:[t.jsx("input",{type:"text",className:`${u.input} ${u.taskHierarchyInput}`,value:k,onChange:ae=>g?.(ae.target.value),placeholder:"WS-123","aria-label":"Attach workstream reference",onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),ie()),ae.key==="Escape"&&(ae.preventDefault(),g?.(""),ye(!1))}}),t.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:ie,disabled:!k.trim()||n,title:"Attach workstream","aria-label":"Attach workstream",children:t.jsx(ao,{size:14})}),t.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>{g?.(""),ye(!1)},disabled:n,title:"Cancel workstream attach","aria-label":"Cancel workstream attach",children:t.jsx(Di,{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(Wa,{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:Ne&&U?.deletedRecordId?t.jsxs(t.Fragment,{children:[q&&t.jsx("button",{type:"button",className:u.actionBtn,onClick:()=>q(U.deletedRecordId||""),disabled:n,title:"Restore deleted task",children:t.jsx(bp,{size:16})}),K&&t.jsx("button",{type:"button",className:`${u.actionBtn} ${u.deleteBtn}`,onClick:()=>K(U.deletedRecordId||""),disabled:n,title:"Permanently delete deleted task",children:t.jsx(Hl,{size:16})})]}):t.jsx(oh,{task:U,disabled:n||X,onSetStatus:(ae,Ze)=>{if($){$(ae,Ze);return}if(Ze==="in-progress"){M(ae);return}if(Ze==="review"){S(ae);return}if(Ze==="done"){P(ae);return}Ze==="cancelled"&&Z(ae)},onArchiveTask:ce})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:l,disabled:n,className:u.secondaryHeaderBtn,title:Te("actionHeader.clearFormTitle"),children:[t.jsx(bp,{size:16}),Te("actionHeader.clear")]}),t.jsxs("button",{type:"button",onClick:ae=>o(ae),disabled:n||!r.trim(),className:u.primaryUpdateBtn,title:Te("actionHeader.addTaskTitle"),children:[n?t.jsx(Wa,{size:16,className:u.spinner}):t.jsx(sr,{size:16}),Te("actionHeader.addTask")]})]})})}const IR="_topNoticeLayer_1m6a1_1",TR="_topNotice_1m6a1_1",NR="_topNoticeMessage_1m6a1_32",jR="_topNoticeSuccess_1m6a1_38",RR="_topNoticeError_1m6a1_44",DR="_topNoticeInfo_1m6a1_50",PR="_topNoticeDismiss_1m6a1_56",bi={topNoticeLayer:IR,topNotice:TR,topNoticeMessage:NR,topNoticeSuccess:jR,topNoticeError:RR,topNoticeInfo:DR,topNoticeDismiss:PR};function kh({notice:e,onDismiss:n}){if(!e)return null;const s=e.tone==="error"?bi.topNoticeError:e.tone==="success"?bi.topNoticeSuccess:bi.topNoticeInfo,r=e.tone==="error"?"alert":"status";return t.jsx("div",{className:bi.topNoticeLayer,children:t.jsxs("div",{className:`${bi.topNotice} ${s}`,role:r,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?t.jsx(Pc,{size:14}):e.tone==="success"?t.jsx(ao,{size:14}):t.jsx(rg,{size:14}),t.jsx("span",{className:bi.topNoticeMessage,children:e.message}),n&&t.jsx("button",{type:"button",className:bi.topNoticeDismiss,onClick:n,"aria-label":"Dismiss notice",title:"Dismiss notice",children:t.jsx(Di,{size:14})})]})})}const ER=pt.lazy(()=>Mo(()=>import("./TaskSettings-BOC5F6Ag.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.TaskSettings})));function LR(e){const{activeTab:n,setActiveTab:s,isOpen:r,setIsOpen:o,currentTheme:l,setCurrentTheme:i,saveSettings:p,pathSaved:h,keyShortcut:w,setKeyShortcut:b,jsonBackupEnabled:_,setJsonBackupEnabled:k,mcpHostRoot:g,setMcpHostRoot:C,settingsSection:M,setSettingsSection:S,projectRoot:P,projectName:Z,mcpScriptPath:$,serverHostRoot:ce,showFolderBrowser:q,setShowFolderBrowser:K,folders:j,files:ye,currentBrowsePath:U,fetchFolders:X,browserTarget:Ne,setBrowserTarget:pe,handleSelectPath:te,handleAddPath:D,handleRemovePath:B,tasks:oe,loadingTasks:xe,archivedTasks:ie,deletedTasks:ae,activeCategories:Ze,activeTypes:Le,priorities:Ce,taxonomyDisplayLabels:Oe,approaches:R,taxonomies:W,searchQuery:F,setSearchQuery:V,filterCategories:E,setFilterCategories:y,filterTypes:x,setFilterTypes:H,filterPriorities:I,setFilterPriorities:Ie,filterStatus:L,setFilterStatus:le,filterAssignees:ne,setFilterAssignees:de,assigneeOptions:G,filterTaxonomies:ee,setFilterTaxonomies:be,sortBy:$e,setSortBy:fe,sortOrder:De,toggleSortOrder:Ke,showArchive:nt,setShowArchive:dt,taskScope:d,setTaskScope:et,clearFilters:gt,filteredTasks:O,filteredArchive:Ye,groupedTasks:wt,collapsedCategories:St,setCollapsedCategories:At,handleEdit:zt,handleDelete:Ht,handleCopyId:sn,handleToggleComplete:Jt,handleToggleCancel:Xt,handleToggleInProgress:gn,handleToggleReview:Mn,handleArchiveTask:un,handleBulkArchive:yn,handleUnarchive:an,handleRestoreDeletedTask:Tn,handlePermanentlyDeleteDeletedTask:Rt,handleEmptyDeletedTasks:we,fetchArchive:Lt,editingTaskId:Qt,loading:Dt,error:He,title:Nn,setTitle:Y,description:Ae,setDescription:_e,checklistItems:Pe,setChecklistItems:qe,category:Je,setCategory:at,type:Xe,setType:ct,priority:vt,setPriority:Ot,complexity:Pt,setComplexity:xt,manualComplexityEnabled:Et,checklistDropdownEnabled:xn,showTaskCardStatusLabel:Gt,approach:Jn,setApproach:kn,assignee:yt,setAssignee:Gn,scheduledDate:se,setScheduledDate:je,dueDate:Me,setDueDate:Ee,workstreamInput:Fe,setWorkstreamInput:tt,formTaxonomies:An,setFormTaxonomies:Mt,comments:fa,newCommentText:Bn,setNewCommentText:bn,attachments:fn,setAttachments:rn,setAttachmentsDirty:Kt,descriptionFocused:kt,setDescriptionFocused:$t,showMarkdownHelp:Yt,setShowMarkdownHelp:Sn,showChecklist:ft,setShowChecklist:mt,showComments:oa,setShowComments:en,handleSubmit:tn,resetForm:It,handleAddComment:Tt,handleSetWorkstreamForCurrentTask:ia,handleOpenTaskById:ya,autoSaveState:Ia,unsavedModalOpen:ha,setUnsavedModalOpen:ka,pendingNavigation:aa,handleNavigation:on,handleClose:jn,scheduleWarningPrompt:Vn,confirmScheduleWarning:_n,cancelScheduleWarning:$n,uiNotice:Wn,clearNotice:vn,taskReturnTrail:cn,clearReturnToParentTask:Rn,returnToPreviousTask:In,copiedId:rt,recentlyChangedTaskIds:wn,tasksScrollRef:nn,setTasksScrollPos:Sa,currentTask:Xn,currentTaskWorkstream:Fa,currentTaskInitiative:Oa,exportEnvironment:vs,setExportEnvironment:ss,exportWorkflowsPath:Ya,setExportWorkflowsPath:ca,exportResult:ln,exportingResource:rr,availableWorkflows:la,onExportWorkflows:va,availableEnvironments:Un,handleUpdateCategory:wa,handleRemoveCategory:Ls,handleSaveCategory:rs,handleUpdateCategoryIcon:sa,handleUpdateCategoryColor:os,handleSaveType:ba,handleRemoveType:is,handleUpdateTaxonomies:cs,handleUpdatePriorities:Da,pathValidation:Q,validatePaths:Ve,getCategoryPaths:Vt,commentsEndRef:bt,currentWorkspaceId:dn,settingsModel:ot,onHeaderMouseDown:da,isDragging:_a}=e,Zn=a.useRef(null),[zn,ga]=pt.useState(0);a.useLayoutEffect(()=>{if(n==="tasks"&&nn.current&&zn>0){const Ge=setTimeout(()=>{nn.current&&(nn.current.scrollTop=zn)},50);return()=>clearTimeout(Ge)}},[n,zn,oe]);const qn=Ge=>{fe(Ge)},Ja=()=>{on(()=>{if(n==="add"||n==="settings"){if(n==="add"&&In())return;n==="add"&&cn.length>0&&Rn(),n==="add"&&It(),s("tasks")}else e.onClose?e.onClose():jn()})},Ms=()=>{ka(!1),aa?(n==="add"&&It(),aa()):s("tasks")},Tr=async()=>{await tn({preventDefault:()=>{}}),ka(!1),aa&&aa()},ls=(Ge,Ut)=>{Mt(Pa=>({...Pa,[Ge]:Ut})),Ge==="approach"&&typeof Ut=="string"&&kn(Ut)},or=a.useCallback(Ge=>{It(),at(Ge),on(()=>{s("add")})},[It,at,s,on]),ua=pt.useMemo(()=>ae.map(Ge=>({...Ge.taskSnapshot,isDeleted:!0,deletedRecordId:Ge.id})),[ae]),Qn=pt.useMemo(()=>new globalThis.Map(ae.map(Ge=>[Ge.taskId,Ge])),[ae]),Bs=pt.useMemo(()=>{const Ge=F.toLowerCase(),Ut=Ze.every(Re=>E.includes(Re.value)),Pa=Le.every(Re=>x.includes(Re.value)),Ca=Array.from(new Set(I.map(Re=>Number(Re)).filter(Re=>Number.isFinite(Re)))),ir=Ce.map(Re=>Number(Re.value)).filter(Re=>Number.isFinite(Re)).every(Re=>Ca.includes(Re)),T=["task","in-progress","review","done","cancelled","on-hold"].every(Re=>L.includes(Re)),ge=G.length>0&&G.every(Re=>ne.includes(Re.value)),Ue=Jl(W,ua);return ua.filter(Re=>{const J=Ar(Re).toLowerCase(),Be=!Ge||Re.title.toLowerCase().includes(Ge)||(Re.description?.toLowerCase()||"").includes(Ge)||Re.id.toLowerCase().includes(Ge)||J.includes(Ge),ht=Ut||E.includes(Re.category),Nt=ir||Ca.includes(cu(Re.priority)),ds=Pa||x.includes(Re.type||Ss),Kn=T||L.includes(Re.status),Dn=ge||ne.includes(Re.assignee||"unassigned"),Ws=Object.entries(ee).every(([Us,zs])=>{const Wo=Ue.find(cr=>cr.id===Us);if(!Wo||Zp(Wo,ua).every(cr=>zs.includes(cr.value)))return!0;const Fo=Re.taxonomies?.[Us];return Fo?Array.isArray(Fo)?Fo.some(cr=>zs.includes(cr)):zs.includes(Fo):zs.includes("")});return Be&&ht&&Nt&&ds&&Kn&&Dn&&Ws}).sort((Re,J)=>mu(Re,J,$e,De,W))},[Ze,Le,ie,G,ua,ne,E,I,L,ee,x,Ce,F,$e,De,W,oe]),oo=pt.useMemo(()=>{const Ge={};return Bs.forEach(Ut=>{const Ca=Ze.find(ws=>ws.value===Ut.category||ws.label===Ut.category)?.label||Ut.category||"General";Ge[Ca]||(Ge[Ca]=[]),Ge[Ca].push(Ut)}),Ge},[Ze,Bs]),Nr=d==="archived"?Ye.length:d==="deleted"?Bs.length:O.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:Zn,className:`${ut.modal} ${u.coreModal} ${n==="settings"?ut.settingsViewModal:""}`,"data-theme":l,children:[t.jsxs("div",{className:"tf-modal-header",onMouseDown:da,style:{cursor:da?_a?"grabbing":"grab":"default"},children:[t.jsxs("div",{className:`tf-modal-title ${hn.headerTitleWidget}`,children:["Taskforce",Z&&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:Z})]}),t.jsx("span",{className:u.taskCountBadge,title:`${d.charAt(0).toUpperCase()+d.slice(1)} tasks`,children:Nr})]}),t.jsxs("div",{className:ut.headerActions,children:[n==="tasks"&&t.jsx(t.Fragment,{children:t.jsx("button",{className:"tf-control-icon",onClick:()=>{on(()=>{It(),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"&&on(()=>{s("settings")})},title:"Settings",children:t.jsx(cf,{size:18})}),t.jsx("button",{className:"tf-control-icon",onClick:Ja,title:n==="tasks"?"Close":"Back to Tasks",children:n==="tasks"?t.jsx(Di,{size:20}):t.jsx(og,{size:20})})]})]}),t.jsx(kh,{notice:Wn,onDismiss:vn}),n==="add"&&t.jsx(yh,{editingTaskId:Qt,loading:Dt,autoSaveState:Ia,title:Nn,currentTask:Xn,currentTaskWorkstream:Fa,currentTaskInitiative:Oa,workstreamInput:Fe,onWorkstreamInputChange:tt,onSetWorkstreamForCurrentTask:ia,handleSubmit:tn,resetForm:It,handleCopyId:sn,copiedId:rt,tasks:oe,handleToggleInProgress:gn,handleToggleReview:Mn,handleToggleComplete:Jt,handleToggleCancel:Xt,handleArchiveTask:un,handleRestoreDeletedTask:Ge=>{Tn(Ge)},handlePermanentlyDeleteDeletedTask:Ge=>{Rt(Ge)}}),n==="tasks"&&t.jsx(mh,{ref:nn,tasks:oe,archivedTasks:ie,categories:Ze,types:Le,priorities:Ce,taxonomyDisplayLabels:Oe,taxonomies:W,searchQuery:F,filterCategories:E,filterTypes:x,filterPriorities:I,filterStatus:L,filterAssignees:ne,assigneeOptions:G,filterTaxonomies:ee,sortBy:$e,sortOrder:De,showArchive:nt,taskScope:d,collapsedCategories:St,loadingTasks:xe,filteredTasks:O,filteredArchive:Ye,groupedTasks:wt,filteredDeletedTasks:Bs,groupedDeletedTasks:oo,copiedId:rt,recentlyChangedTaskIds:wn,showTaskCardStatusLabel:Gt,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:V,onFilterCategoriesChange:Ge=>y(Ge),onFilterTypesChange:Ge=>H(Ge),onFilterPrioritiesChange:Ie,onFilterStatusChange:le,onFilterAssigneesChange:Ge=>de(Ge),onTaxonomyFilterChange:(Ge,Ut)=>be(Pa=>({...Pa,[Ge]:Ut})),onSortByChange:qn,onSortOrderChange:Ke,onShowArchiveChange:dt,onTaskScopeChange:et,onClearFilters:gt,onToggleCategory:Ge=>At(Ut=>({...Ut,[Ge]:!Ut[Ge]})),onEditTask:zt,onOpenTaskById:ya,onCopyId:sn,onToggleInProgress:gn,onToggleReview:Mn,onToggleComplete:Jt,onToggleCancel:Xt,onArchiveTask:un,onBulkArchive:yn,onUnarchive:Ge=>{const Ut=Qn.get(Ge);if(Ut){Tn(Ut.id);return}an(Ge)},onDelete:Ge=>{const Ut=Qn.get(Ge);if(Ut){Rt(Ut.id);return}Ht(Ge)},onDeleteAllDeleted:()=>{we()},onFetchArchive:Lt,onAddTaskToCategory:or,supplementalTasks:ua}),n==="add"&&t.jsx(gh,{editingTaskId:Qt,error:He,title:Nn,description:Ae,checklistItems:Pe,category:Je,type:Xe,priority:vt,complexity:Pt,manualComplexityEnabled:Et,approach:Jn,assignee:yt,scheduledDate:se,dueDate:Me,workstreamInput:Fe,formTaxonomies:An,onTaxonomyChange:ls,taxonomies:W,comments:fa,newCommentText:Bn,contextFiles:fn,currentWorkspaceId:dn,apiBaseUrl:"",descriptionFocused:kt,showMarkdownHelp:Yt,showChecklist:ft,checklistEnabled:xn,showComments:oa,categories:Ze,types:Le,priorities:Ce,taxonomyDisplayLabels:Oe,assigneeOptions:G,workstreams:e.workstreams,copiedId:rt,onTitleChange:Y,onDescriptionChange:_e,onChecklistItemsChange:qe,onCategoryChange:at,onTypeChange:ct,onPriorityChange:Ot,onComplexityChange:xt,onApproachChange:Ge=>{kn(Ge),Mt(Ut=>({...Ut,approach:Ge}))},onAssigneeChange:Gn,onScheduledDateChange:je,onDueDateChange:Ee,onWorkstreamInputChange:tt,onNewCommentTextChange:bn,onDescriptionFocusedChange:$t,onShowMarkdownHelpChange:Sn,onShowChecklistChange:mt,onShowCommentsChange:en,onOpenSettings:Ge=>{on(()=>{S(Ge),s("settings")})},onSubmit:tn,commentsEndRef:bt,onAddComment:()=>Tt(Bn),onOpenTaskById:ya,onAddContextFile:Ge=>{Kt(!0),rn(Ut=>[...Ut,Ge])},onRemoveContextFile:async Ge=>{Kt(!0),rn(Ut=>Ut.filter((Pa,Ca)=>Ca!==Ge))},onUpdateContextCaption:(Ge,Ut)=>{Kt(!0),rn(Pa=>Pa.map((Ca,ws)=>ws!==Ge?Ca:typeof Ca=="string"?{path:Ca,caption:Ut,timestamp:new Date().toISOString()}:{...Ca,caption:Ut}))},onCopyId:sn,onToggleInProgress:gn,onToggleReview:Mn,onToggleComplete:Jt,onToggleCancel:Xt,onArchiveTask:un,onUnarchive:Ge=>{if(Xn?.isDeleted){const Ut=Qn.get(Ge);Ut&&Tn(Ut.id);return}an(Ge)},currentTask:Xn}),n==="settings"&&t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:t.jsx(Wa,{size:20,className:u.spinner})}),children:t.jsx(ER,{settingsModel:ot,onSectionChange:S})})]}),q&&Ai.createPortal(t.jsx("div",{className:On.overlay,children:t.jsxs("div",{className:On.browser,children:[t.jsxs("div",{className:On.header,children:[t.jsxs("div",{className:On.pathInfo,children:[t.jsx(Ti,{size:14}),t.jsx("span",{children:U||"Project Root"})]}),t.jsxs("div",{className:On.actions,children:[U&&t.jsx("button",{className:u.helpLink,onClick:()=>{const Ge=U.split("/").filter(Boolean);Ge.pop(),X(Ge.length?Ge.join("/")+"/":"")},children:"Back"}),t.jsx("button",{className:u.helpLink,onClick:()=>K(!1),children:"Close"})]})]}),t.jsxs("div",{className:On.list,children:[Ne&&typeof Ne=="object"&&t.jsxs("div",{className:`${On.item} ${On.itemCurrent}`,onClick:()=>te(U),children:[t.jsx(ao,{size:14})," Select Current: ./",U||"(root)"]}),j.map(Ge=>t.jsxs("div",{className:On.item,onClick:()=>X(U+Ge+"/"),children:[t.jsx(Ti,{size:14})," ",Ge,"/"]},Ge)),ye.map(Ge=>t.jsxs("div",{className:`${On.item} ${On.itemFile}`,onClick:()=>te(U+Ge),children:[t.jsx(Cp,{size:14})," ",Ge]},Ge)),j.length===0&&ye.length===0&&t.jsx("div",{className:`${On.item} ${On.empty}`,children:"No items found"})]})]})}),document.body),ha&&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(Pc,{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:()=>ka(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),t.jsx("button",{className:u.destructiveBtn,onClick:Ms,title:"Discard unsaved changes and leave",children:"Discard"}),t.jsxs("button",{className:u.submitBtn,onClick:Tr,disabled:Dt,title:"Save changes and leave",children:[Dt?t.jsx(Wa,{size:16,className:u.spinner}):t.jsx(lf,{size:16}),"Save"]})]})]})}),Vn&&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(Pc,{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: ",Vn.dueDate," · Scheduled: ",Vn.scheduledDate]})]}),t.jsxs("div",{className:`${ut.formActions} ${ut.unsavedActions}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:$n,children:"Go Back"}),t.jsx("button",{className:u.submitBtn,onClick:_n,children:"Save Anyway"})]})]})})]})}const MR="_accountMenuWrap_xwxof_1",BR="_avatarBtn_xwxof_5",WR="_avatarBadge_xwxof_9",FR="_avatarImage_xwxof_24",OR="_avatarIcon_xwxof_30",$R="_accountMenu_xwxof_1",UR="_accountMenuItem_xwxof_48",zR="_accountMenuItemActive_xwxof_68",HR="_accountMenuSection_xwxof_73",GR="_accountMenuSectionLabel_xwxof_79",VR="_accountMenuMeta_xwxof_88",ZR="_accountMenuHint_xwxof_93",qR="_accountIdentityEmail_xwxof_99",KR="_accountIdentityBlock_xwxof_104",YR="_accountIdentityMetaLine_xwxof_109",JR="_accountIdentityMetaAction_xwxof_116",XR="_accountIdentityMetaValue_xwxof_125",QR="_accountIdentityMetaLabel_xwxof_130",e1="_accountMenuError_xwxof_159",t1="_accountHubCard_xwxof_165",n1="_profileAvatarEditor_xwxof_172",a1="_profileAvatarPreview_xwxof_178",s1="_profileAvatarImage_xwxof_194",r1="_profileAvatarActions_xwxof_200",o1="_profileAvatarInput_xwxof_206",Qe={accountMenuWrap:MR,avatarBtn:BR,avatarBadge:WR,avatarImage:FR,avatarIcon:OR,accountMenu:$R,accountMenuItem:UR,accountMenuItemActive:zR,accountMenuSection:HR,accountMenuSectionLabel:GR,accountMenuMeta:VR,accountMenuHint:ZR,accountIdentityEmail:qR,accountIdentityBlock:KR,accountIdentityMetaLine:YR,accountIdentityMetaAction:JR,accountIdentityMetaValue:XR,accountIdentityMetaLabel:QR,accountMenuError:e1,accountHubCard:t1,profileAvatarEditor:n1,profileAvatarPreview:a1,profileAvatarImage:s1,profileAvatarActions:r1,profileAvatarInput:o1},i1="_authBlockedBanner_1dg8p_1",c1="_loginView_1dg8p_10",l1="_loginCard_1dg8p_20",d1="_loginCloseBtn_1dg8p_34",u1="_loginLogo_1dg8p_56",p1="_authBrandRow_1dg8p_62",m1="_loginTitle_1dg8p_74",f1="_loginTitleAccent_1dg8p_85",h1="_loginSubtitle_1dg8p_89",g1="_loginError_1dg8p_95",y1="_loginInput_1dg8p_101",k1="_loginPrimaryBtn_1dg8p_117",S1="_registerConsent_1dg8p_122",v1="_registerConsentLink_1dg8p_130",w1="_authModeSwitch_1dg8p_140",b1="_authModeSwitchLink_1dg8p_147",_1="_authModeLinks_1dg8p_162",C1="_authModeLink_1dg8p_162",x1="_optionGrid_1dg8p_191",A1="_optionGroup_1dg8p_197",I1="_optionRow_1dg8p_202",T1="_inlineHint_1dg8p_209",N1="_actionRowEnd_1dg8p_215",ve={authBlockedBanner:i1,loginView:c1,loginCard:l1,loginCloseBtn:d1,loginLogo:u1,authBrandRow:p1,loginTitle:m1,loginTitleAccent:f1,loginSubtitle:h1,loginError:g1,loginInput:y1,loginPrimaryBtn:k1,registerConsent:S1,registerConsentLink:v1,authModeSwitch:w1,authModeSwitchLink:b1,authModeLinks:_1,authModeLink:C1,optionGrid:x1,optionGroup:A1,optionRow:I1,inlineHint:T1,actionRowEnd:N1};function j1(e={x:0,y:0}){const[n,s]=a.useState(e),[r,o]=a.useState(!1),[l,i]=a.useState({x:0,y:0}),[p,h]=a.useState(0),w=a.useRef(null),b=a.useCallback(g=>{const C=g.target;if(!(C.closest("button")||C.closest("input")||C.closest("select")||C.closest("textarea")||C.closest('[role="button"]')||C.closest(".no-drag"))){if(w.current){const M=w.current.getBoundingClientRect();h(M.top-n.y)}o(!0),i({x:g.clientX-n.x,y:g.clientY-n.y})}},[n]),_=a.useCallback(g=>{if(r){let C=g.clientX-l.x,M=g.clientY-l.y;M<-p&&(M=-p),s({x:C,y:M})}},[r,l,p]),k=a.useCallback(()=>{o(!1)},[]);return a.useEffect(()=>(r?(window.addEventListener("mousemove",_),window.addEventListener("mouseup",k)):(window.removeEventListener("mousemove",_),window.removeEventListener("mouseup",k)),()=>{window.removeEventListener("mousemove",_),window.removeEventListener("mouseup",k)}),[r,_,k]),{position:n,isDragging:r,handleMouseDown:b,modalRef:w,setPosition:s}}function ro({isOpen:e,onClose:n,title:s,children:r,footer:o,size:l="md",theme:i=iu,className:p,headerActions:h,draggable:w=!1,isSettings:b=!1,closeOnOverlayClick:_=!0}){const k=a.useRef(null),{position:g,isDragging:C,handleMouseDown:M,modalRef:S}=j1();if(a.useEffect(()=>{const Z=$=>{$.key==="Escape"&&e&&n()};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[e,n]),a.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const P={sm:ut.modalSizeSm,md:ut.modalSizeMd,lg:ut.modalSizeLg,xl:ut.modalSizeXl,full:ut.modalSizeFull};return Ai.createPortal(t.jsx("div",{className:`${ut.overlay} ${p||""} ${ut.overlayHighZ}`,ref:k,onClick:Z=>{_&&Z.target===k.current&&n()},children:t.jsxs("div",{ref:S,className:`tf-surface-modal tf-modal-shell ${ut.modal} tf-scrollbar-scope ${P[l]} ${w?ut.draggableModal:""} ${b?ut.settingsViewModal:""}`,"data-theme":i,style:{transform:w?`translate(${g.x}px, ${g.y}px)`:void 0,transition:C?"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?M:void 0,style:{cursor:w?C?"grabbing":"grab":"default"},children:[t.jsx("div",{className:"tf-modal-title",children:s}),t.jsxs("div",{className:ut.headerActions,children:[h,t.jsx("button",{className:"tf-control-icon",onClick:n,title:"Close",children:t.jsx(Di,{size:20})})]})]}),t.jsx("div",{className:ut.modalContent,children:r}),o&&t.jsx("div",{className:`${ut.formActions} ${ut.modalFooter}`,children:o})]})}),document.body)}const R1="_modalBody_1mute_1",D1="_mutedText_1mute_5",P1="_sectionText_1mute_10",E1="_sectionTextSpaced_1mute_15",L1="_sectionTextTop_1mute_20",M1="_errorText_1mute_25",B1="_inlineFieldLabel_1mute_29",W1="_wrapRow_1mute_35",F1="_actionRowEnd_1mute_42",O1="_modalActionsEnd_1mute_50",$1="_memberRow_1mute_56",U1="_memberTitle_1mute_62",z1="_memberActions_1mute_66",H1="_selectRole_1mute_73",G1="_selectPermission_1mute_77",V1="_inviteRow_1mute_81",Z1="_listHeading_1mute_85",q1="_auditList_1mute_90",K1="_auditPager_1mute_96",Y1="_labelFixed_1mute_103",st={modalBody:R1,mutedText:D1,sectionText:P1,sectionTextSpaced:E1,sectionTextTop:L1,errorText:M1,inlineFieldLabel:B1,wrapRow:W1,actionRowEnd:F1,modalActionsEnd:O1,memberRow:$1,memberTitle:U1,memberActions:z1,selectRole:H1,selectPermission:G1,inviteRow:V1,listHeading:Z1,auditList:q1,auditPager:K1,labelFixed:Y1};function J1({isOpen:e,theme:n,onClose:s,onConfirm:r}){return t.jsx(ro,{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 X1({isOpen:e,theme:n,runtimeMode:s,authRequiredForApi:r,isAuthenticated:o,hasAuthIdentity:l,authIdentityLabel:i,billingLoading:p,billingError:h,billingActionError:w,billingNotice:b,billingActionBusy:_,billingIntervalChoice:k,accountProfileSummary:g,currentWorkspaceId:C,canOpenTeamManagement:M,canManageWorkspaceSync:S,workspaceCloudSyncEnabled:P,syncStatusLabel:Z,workspaceSyncError:$,syncControlBusy:ce,onClose:q,onOpenWorkspaceAudit:K,onBillingIntervalChange:j,onRefreshBilling:ye,onUpdateInterval:U,onManageBilling:X,onStartCheckout:Ne,onToggleWorkspaceSync:pe,onOpenHelp:te}){const D=String(g?.gate||"").trim().toLowerCase(),B=String(g?.billingConflictCode||"").trim().toUpperCase(),oe=String(g?.message||"").trim()||(B==="CHECKOUT_SESSION_EXPIRED"?"Your latest checkout expired. Choose a plan to continue.":B==="CHECKOUT_SESSION_SUPERSEDED"?"A newer checkout is already in progress for this account. Open plans to continue.":""),xe=B==="CHECKOUT_SESSION_EXPIRED"||g?.planSelectionRequired===!0||D==="plan_selection_required"?"Choose Plan":D==="checkout_pending"?"Open Plans":"Start Checkout",ie=String(g?.planName||g?.planId||"n/a").trim()||"n/a";return t.jsx(ro,{isOpen:e,onClose:q,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:Qe.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:Qe.accountIdentityEmail,children:i})]}):"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:Qe.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:Qe.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..."}),h&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:h}),w&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:w}),b&&t.jsx("p",{className:st.errorText,children:b}),oe&&t.jsx("p",{className:st.sectionText,children:oe}),t.jsxs("p",{className:st.sectionTextSpaced,children:["Plan: ",t.jsx("code",{children:ie})," · ","Entitlement: ",t.jsx("code",{children:String(g?.entitlementState||"n/a")})]}),t.jsxs("p",{className:st.sectionText,children:["Stripe status: ",t.jsx("code",{children:String(g?.stripeStatus||"n/a")}),g?.effectiveUntil?` · Effective until ${new Date(g.effectiveUntil).toLocaleString()}`:""]}),t.jsx("div",{className:st.wrapRow,children:t.jsxs("label",{className:`${Qe.accountMenuMeta} ${st.inlineFieldLabel}`,children:["Interval",t.jsxs("select",{className:u.input,value:k,onChange:ae=>j(ae.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:ye,disabled:_||p,children:"Refresh Billing"}),t.jsx("button",{className:u.cancelBtn,onClick:U,disabled:_||!g?.stripeSubscriptionId,children:"Update Interval"}),t.jsx("button",{className:u.cancelBtn,onClick:X,disabled:_||!g?.stripeCustomerId,children:"Manage Billing"}),t.jsx("button",{className:u.submitBtn,onClick:Ne,disabled:_,children:_?"Working...":xe})]})]}):t.jsx("p",{className:st.sectionText,children:"Sign in to manage subscription billing."})]}),t.jsxs("div",{className:Qe.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:C})]}),t.jsx("div",{className:st.actionRowEnd,children:t.jsx("button",{className:u.cancelBtn,onClick:K,disabled:!M,children:"Open Workspace Audit"})})]}),t.jsxs("div",{className:Qe.accountHubCard,children:[t.jsx("strong",{children:"Workspace Cloud Sync"}),t.jsx("p",{className:st.sectionText,children:S?P?`Enabled · ${Z}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),$&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:$}),t.jsx("div",{className:st.actionRowEnd,children:t.jsx("button",{className:u.cancelBtn,disabled:!S||ce,onClick:()=>pe(!P),children:P?"Disable Sync":"Enable Sync"})})]}),t.jsxs("div",{className:`${ut.formActions} ${st.modalActionsEnd}`,children:[t.jsx("button",{className:u.cancelBtn,onClick:te,children:"Help & Tutorial"}),t.jsx("button",{className:u.submitBtn,onClick:q,children:"Close"})]})]})})}function Q1({isOpen:e,theme:n,onClose:s,onSave:r,displayName:o,email:l,avatarDisplayUrl:i,accountBadgeInitial:p,avatarInputRef:h,avatarAccept:w,avatarDraftId:b,saveBusy:_,avatarBusy:k,saveError:g,saveNotice:C,onDisplayNameChange:M,onAvatarInputChange:S,onStartAvatarUpload:P,onDiscardUpload:Z,onRemovePhoto:$}){return t.jsx(ro,{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:_||k,children:"Cancel"}),t.jsx("button",{type:"button",className:u.primaryUpdateBtn,onClick:r,disabled:_||k||!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:Qe.profileAvatarEditor,children:[t.jsx("div",{className:Qe.profileAvatarPreview,"aria-label":"Profile photo preview",children:i?t.jsx("img",{src:i,alt:"",className:Qe.profileAvatarImage}):t.jsx("span",{children:p})}),t.jsxs("div",{className:Qe.profileAvatarActions,children:[t.jsx("input",{ref:h,type:"file","aria-label":"Upload profile photo",accept:w,className:Qe.profileAvatarInput,onChange:ce=>S(ce.target.files?.[0]||null),disabled:_||k}),t.jsx("button",{type:"button",className:u.secondaryButton,onClick:P,disabled:_||k,children:k?"Uploading...":"Upload Photo"}),b&&t.jsx("button",{type:"button",className:u.secondaryButton,onClick:Z,disabled:_||k,children:"Discard Upload"}),i&&t.jsx("button",{type:"button",className:u.secondaryButton,onClick:$,disabled:_||k,children:"Remove Photo"})]})]}),t.jsxs("label",{className:st.inlineFieldLabel,children:["Display name",t.jsx("input",{className:u.input,type:"text",value:o,onChange:ce=>M(ce.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})]}),g&&t.jsx("p",{className:`${ve.loginError} ${st.errorText}`,children:g}),C&&!g&&t.jsx("p",{className:st.errorText,children:C})]})})}function eD({isOpen:e,theme:n,onClose:s,onOpenSettings:r}){return t.jsx(ro,{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 tD({prompt:e,theme:n,onClose:s,onConfirm:r}){return t.jsx(ro,{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 nD="_syncStatusModal_4pd1g_1",aD="_syncStatusTop_4pd1g_6",sD="_syncStatusMetaHeader_4pd1g_15",rD="_syncStatusHeaderInfo_4pd1g_22",oD="_syncToggle_4pd1g_43",iD="_syncStatusBadge_4pd1g_47",cD="_syncToggleControl_4pd1g_75",lD="_syncToggleControlEnabled_4pd1g_91",dD="_syncToggleControlDisabled_4pd1g_98",uD="_syncToggleControlBusy_4pd1g_102",pD="_syncToggleControlBlocked_4pd1g_107",mD="_syncToggleInput_4pd1g_112",fD="_syncToggleState_4pd1g_125",hD="_syncToggleStateOn_4pd1g_136",gD="_syncToggleStateOff_4pd1g_141",yD="_syncToggleThumb_4pd1g_146",kD="_syncStatusSummaryValue_4pd1g_173",SD="_syncStatusSummaryCompact_4pd1g_180",vD="_syncStatusRepairBanner_4pd1g_190",wD="_syncStatusRepairHeader_4pd1g_200",bD="_syncStatusRepairBadge_4pd1g_207",_D="_syncStatusRepairMeta_4pd1g_216",CD="_syncStatusRepairText_4pd1g_223",xD="_syncStatusLabel_4pd1g_257",AD="_syncStatusSectionHeader_4pd1g_265",ID="_syncStatusCompactGrid_4pd1g_278",TD="_syncStatusCompactItem_4pd1g_284",ND="_syncStatusValue_4pd1g_295",jD="_syncStatusValueError_4pd1g_325",RD="_syncStatusActions_4pd1g_329",DD="_syncStatusPanel_4pd1g_336",PD="_syncStatusPanelHeader_4pd1g_346",ED="_syncStatusPanelMeta_4pd1g_353",LD="_syncStatusEventsList_4pd1g_375",MD="_syncStatusEventItem_4pd1g_384",BD="_syncStatusEventItemError_4pd1g_391",WD="_syncStatusEventItemMuted_4pd1g_396",FD="_syncStatusEventLine_4pd1g_401",OD="_syncStatusSecondaryActions_4pd1g_411",$D="_syncStatusPrimaryActions_4pd1g_425",UD="_syncStatusPrimaryActionSlot_4pd1g_432",zD="_syncStatusActionPlaceholder_4pd1g_440",ze={syncStatusModal:nD,syncStatusTop:aD,syncStatusMetaHeader:sD,syncStatusHeaderInfo:rD,syncToggle:oD,syncStatusBadge:iD,syncToggleControl:cD,syncToggleControlEnabled:lD,syncToggleControlDisabled:dD,syncToggleControlBusy:uD,syncToggleControlBlocked:pD,syncToggleInput:mD,syncToggleState:fD,syncToggleStateOn:hD,syncToggleStateOff:gD,syncToggleThumb:yD,syncStatusSummaryValue:kD,syncStatusSummaryCompact:SD,syncStatusRepairBanner:vD,syncStatusRepairHeader:wD,syncStatusRepairBadge:bD,syncStatusRepairMeta:_D,syncStatusRepairText:CD,syncStatusLabel:xD,syncStatusSectionHeader:AD,syncStatusCompactGrid:ID,syncStatusCompactItem:TD,syncStatusValue:ND,syncStatusValueError:jD,syncStatusActions:RD,syncStatusPanel:DD,syncStatusPanelHeader:PD,syncStatusPanelMeta:ED,syncStatusEventsList:LD,syncStatusEventItem:MD,syncStatusEventItemError:BD,syncStatusEventItemMuted:WD,syncStatusEventLine:FD,syncStatusSecondaryActions:OD,syncStatusPrimaryActions:$D,syncStatusPrimaryActionSlot:UD,syncStatusActionPlaceholder:zD};function HD({isOpen:e,theme:n,currentWorkspaceLabel:s,syncStatusMeta:r,workspaceCloudSyncEnabled:o,syncControlBusy:l,canManageWorkspaceSync:i,workspaceSyncSummary:p,workspaceSyncRepairBusy:h,referenceMismatchCount:w,syncStageLabel:b,workspaceSyncPendingChanges:_,formattedLastSyncTime:k,formattedLastPullTime:g,formattedLastPushTime:C,syncLastError:M,workspaceSyncDiagnostics:S,activeReferenceMismatchSummaries:P,syncDiagnosticsSummary:Z,syncEventRows:$,syncEventsListRef:ce,workspaceSyncRepairQueued:q,workspaceSyncBusy:K,workspaceSyncCopied:j,runtimeMode:ye,isAuthenticated:U,onClose:X,onToggleWorkspaceSync:Ne,onRepairSync:pe,onCopyReport:te,onOpenLogin:D,onRetrySync:B}){return t.jsx(ro,{isOpen:e,onClose:X,title:"Sync Manager",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${ut.form} ${ze.syncStatusModal}`,style:{gap:"10px"},children:[t.jsxs("div",{className:ze.syncStatusTop,children:[t.jsx("div",{className:ze.syncStatusHeaderInfo,children:t.jsxs("div",{className:ze.syncStatusMetaHeader,children:[t.jsx("div",{className:ze.syncStatusBadge,style:{borderColor:r.border,background:r.background,color:r.color},children:r.label}),t.jsxs("span",{className:ze.syncStatusLabel,children:["Workspace: ",t.jsx("code",{children:s})]})]})}),t.jsx("label",{className:ze.syncToggle,children:t.jsxs("span",{className:[ze.syncToggleControl,o?ze.syncToggleControlEnabled:ze.syncToggleControlDisabled,l?ze.syncToggleControlBusy:"",i?"":ze.syncToggleControlBlocked].filter(Boolean).join(" "),children:[t.jsx("input",{className:ze.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:o,disabled:!i||l,onChange:oe=>Ne(oe.target.checked)}),t.jsx("span",{className:`${ze.syncToggleState} ${ze.syncToggleStateOn}`,children:"On"}),t.jsx("span",{className:`${ze.syncToggleState} ${ze.syncToggleStateOff}`,children:"Off"}),t.jsx("span",{className:ze.syncToggleThumb})]})})]}),t.jsxs("div",{className:ze.syncStatusSummaryCompact,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Health"}),t.jsx("span",{className:ze.syncStatusSummaryValue,children:p})]}),h&&t.jsxs("div",{className:ze.syncStatusRepairBanner,children:[t.jsxs("div",{className:ze.syncStatusRepairHeader,children:[t.jsxs("div",{className:ze.syncStatusRepairBadge,children:[t.jsx(Wa,{size:13,className:u.spinner}),t.jsx("span",{children:"Repair In Progress"})]}),t.jsx("span",{className:ze.syncStatusRepairMeta,children:"Advanced recovery mode"})]}),t.jsx("span",{className:ze.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:ze.syncStatusSectionHeader,children:t.jsx("span",{className:ze.syncStatusLabel,children:"Current Session"})}),t.jsxs("div",{className:ze.syncStatusCompactGrid,children:[t.jsxs("div",{className:ze.syncStatusCompactItem,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Stage"}),t.jsx("span",{className:ze.syncStatusValue,children:b})]}),t.jsxs("div",{className:ze.syncStatusCompactItem,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Local Changes"}),t.jsx("span",{className:ze.syncStatusValue,children:_})]}),t.jsxs("div",{className:ze.syncStatusCompactItem,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Last Successful"}),t.jsx("span",{className:ze.syncStatusValue,children:k})]})]}),t.jsx("div",{className:ze.syncStatusSectionHeader,children:t.jsx("span",{className:ze.syncStatusLabel,children:"Activity"})}),t.jsxs("div",{className:ze.syncStatusCompactGrid,children:[t.jsxs("div",{className:ze.syncStatusCompactItem,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Last Pull"}),t.jsx("span",{className:ze.syncStatusValue,children:g})]}),t.jsxs("div",{className:ze.syncStatusCompactItem,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Last Push"}),t.jsx("span",{className:ze.syncStatusValue,children:C})]})]}),M!=="None"&&t.jsxs("div",{className:ze.syncStatusPanel,style:{background:"rgba(239, 68, 68, 0.05)",borderColor:"rgba(239, 68, 68, 0.2)"},children:[t.jsxs("div",{className:ze.syncStatusSectionHeader,style:{marginTop:0},children:[t.jsx(Pc,{size:12,color:"#fda4af"}),t.jsxs("span",{className:ze.syncStatusLabel,style:{color:"#fda4af"},children:["Last Error (",S.lastErrorAt?new Date(S.lastErrorAt).toLocaleTimeString():"Recent",")"]})]}),t.jsx("span",{className:`${ze.syncStatusValue} ${ze.syncStatusValueError}`,children:M})]}),w>0&&t.jsxs("div",{className:ze.syncStatusPanel,style:{background:"rgba(250, 204, 21, 0.08)",borderColor:"rgba(250, 204, 21, 0.22)"},children:[t.jsxs("div",{className:ze.syncStatusPanelHeader,children:[t.jsx("span",{className:ze.syncStatusLabel,style:{color:"#fde68a"},children:"Identifier Integrity"}),t.jsxs("span",{className:ze.syncStatusPanelMeta,children:[w," mismatch",w===1?"":"es"," detected"]})]}),t.jsx("span",{className:ze.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."}),P.length>0&&t.jsx("div",{style:{marginTop:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:P.map(oe=>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:ze.syncStatusValue,style:{fontSize:"12px",wordBreak:"break-all"},children:oe.pathLabel}),oe.refsLabel?t.jsx("span",{className:ze.syncStatusPanelMeta,children:oe.refsLabel}):null]},oe.key))})]}),t.jsxs("div",{className:ze.syncStatusPanel,children:[t.jsxs("div",{className:ze.syncStatusPanelHeader,children:[t.jsx("span",{className:ze.syncStatusLabel,children:"Local Sync Diagnostics"}),t.jsx("span",{className:ze.syncStatusPanelMeta,style:{fontSize:"10px"},children:"AI profiles & metadata"})]}),t.jsx("div",{className:ze.syncStatusCompactGrid,style:{gridTemplateColumns:"repeat(2, 1fr)"},children:Z.map(oe=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"8px"},children:[t.jsx("span",{className:ze.syncStatusLabel,style:{fontSize:"9px",textTransform:"capitalize"},children:oe.label}),t.jsx("span",{className:ze.syncStatusValue,style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:oe.value})]},oe.label))})]}),t.jsxs("div",{className:ze.syncStatusPanel,children:[t.jsx("div",{className:ze.syncStatusPanelHeader,children:t.jsx("span",{className:ze.syncStatusLabel,children:"Recent Events"})}),t.jsx("div",{ref:ce,className:ze.syncStatusEventsList,style:{height:"120px"},children:$.map(oe=>t.jsx("div",{className:[ze.syncStatusEventItem,oe.tone==="error"?ze.syncStatusEventItemError:"",oe.tone==="muted"?ze.syncStatusEventItemMuted:""].filter(Boolean).join(" "),style:{padding:"6px 8px",borderRadius:"6px"},children:t.jsx("span",{className:ze.syncStatusEventLine,style:{fontSize:"11px"},children:oe.text})},oe.key))})]}),t.jsxs("div",{className:`${ut.formActions} ${ze.syncStatusActions}`,children:[t.jsxs("div",{className:ze.syncStatusSecondaryActions,children:[t.jsx("button",{className:u.cancelBtn,onClick:pe,disabled:h,title:h?"Repair is running now.":q?"Repair is queued and will start when the current sync finishes.":K?"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:h?t.jsxs(t.Fragment,{children:[t.jsx(Wa,{size:14,className:u.spinner}),t.jsx("span",{style:{marginLeft:"6px"},children:"Repairing..."})]}):q?"Repair Queued":"Repair"}),t.jsxs("button",{className:u.cancelBtn,onClick:te,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[t.jsx(Ol,{size:14}),t.jsx("span",{style:{marginLeft:"6px"},children:j?"Copied":"Copy Report"})]})]}),t.jsxs("div",{className:ze.syncStatusPrimaryActions,children:[t.jsx("div",{className:ze.syncStatusPrimaryActionSlot,children:ye==="local"&&!U?t.jsx("button",{className:u.submitBtn,onClick:D,children:"Sign In / Register"}):t.jsx("div",{className:ze.syncStatusActionPlaceholder,"aria-hidden":"true"})}),t.jsx("div",{className:ze.syncStatusPrimaryActionSlot,children:t.jsx("button",{className:u.submitBtn,onClick:B,disabled:K,children:K?t.jsxs(t.Fragment,{children:[t.jsx(Wa,{size:14,className:u.spinner}),"Syncing..."]}):t.jsxs(t.Fragment,{children:[t.jsx(ig,{size:14}),"Sync"]})})})]})]})]})})}function GD({isOpen:e,theme:n,teamPlanMode:s,teamMgmtError:r,teamManagementTab:o,teamUsersLoading:l,teamUsers:i,teamActionBusyUserId:p,teamInviteFeedback:h,teamInviteEmail:w,teamInviteRole:b,teamInvitePermissionMode:_,teamInviteBusy:k,pendingInvites:g,teamAuditLoading:C,teamAuditEvents:M,teamAuditPage:S,teamAuditPages:P,teamAuditHasMore:Z,onClose:$,onOpenMembersTab:ce,onOpenInvitesTab:q,onOpenAuditTab:K,onMemberRoleChange:j,onMemberPermissionChange:ye,onToggleMemberDisabled:U,onRevokeInvite:X,onRemoveMember:Ne,onInviteEmailChange:pe,onInviteRoleChange:te,onInvitePermissionModeChange:D,onSubmitInvite:B,onLoadAuditPrevious:oe,onLoadAuditNext:xe}){return t.jsx(ro,{isOpen:e,onClose:$,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:ce,children:"Members"}),t.jsx("button",{className:`${u.settingsTabBtn} ${o==="invites"?u.settingsTabBtnActive:""}`,onClick:q,children:"Invites"}),t.jsx("button",{className:`${u.settingsTabBtn} ${o==="audit"?u.settingsTabBtnActive:""}`,onClick:K,children:"Audit Log"})]}),o==="members"&&t.jsxs("div",{className:Qe.accountHubCard,children:[l&&t.jsx("p",{className:st.mutedText,children:"Loading members..."}),!l&&i.length===0&&t.jsx("p",{className:st.mutedText,children:"No users found."}),!l&&i.map(ie=>t.jsxs("div",{className:st.memberRow,children:[t.jsx("div",{className:st.memberTitle,children:ie.displayName||ie.email}),t.jsxs("div",{className:Qe.accountMenuMeta,children:[ie.email," · ",ie.status,ie.disabled?" · deactivated":""]}),t.jsxs("div",{className:st.memberActions,children:[t.jsxs("select",{className:`${u.input} ${st.selectRole}`,value:ie.role,onChange:ae=>j(ie.userId,ae.target.value),disabled:p===ie.userId,children:[t.jsx("option",{value:"owner",children:"Owner"}),t.jsx("option",{value:"admin",children:"Admin"}),t.jsx("option",{value:"member",children:"Member"})]}),ie.role==="member"&&t.jsxs("select",{className:`${u.input} ${st.selectPermission}`,value:ie.permissionMode,onChange:ae=>ye(ie.userId,ae.target.value),disabled:p===ie.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===ie.userId,onClick:()=>U(ie.userId,!ie.disabled),children:ie.disabled?"Reactivate":"Deactivate"}),ie.status==="invited"&&t.jsx("button",{className:u.cancelBtn,disabled:p===ie.userId,onClick:()=>X(ie.userId),children:"Revoke Invite"}),t.jsx("button",{className:u.cancelBtn,disabled:p===ie.userId,onClick:()=>Ne(ie.userId),children:"Remove"})]})]},ie.userId))]}),o==="invites"&&t.jsxs("div",{className:Qe.accountHubCard,children:[h&&t.jsx("p",{className:st.sectionText,children:h}),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:ie=>pe(ie.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:b,onChange:ie=>te(ie.target.value==="admin"?"admin":"member"),children:[t.jsx("option",{value:"member",children:"Member"}),t.jsx("option",{value:"admin",children:"Admin"})]}),b==="member"&&t.jsxs("select",{className:`${u.input} ${st.selectPermission}`,value:_,onChange:ie=>D(ie.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:k||!w.trim()||s!=="team",onClick:B,children:k?"Sending...":"Send Invite"})]}),t.jsxs("div",{className:st.inviteRow,children:[t.jsx("div",{className:st.listHeading,children:"Pending Invites"}),g.length===0&&t.jsx("p",{className:st.mutedText,children:"No pending invites."}),g.map(ie=>t.jsxs("div",{className:st.memberRow,children:[t.jsx("div",{className:st.memberTitle,children:ie.displayName||ie.email}),t.jsxs("div",{className:Qe.accountMenuMeta,children:[ie.email," · ",ie.role]})]},ie.userId))]})]}),o==="audit"&&t.jsxs("div",{className:Qe.accountHubCard,children:[C&&t.jsx("p",{className:st.mutedText,children:"Loading audit entries..."}),!C&&M.length===0&&t.jsx("p",{className:st.mutedText,children:"No audit events for this workspace."}),!C&&t.jsx("div",{className:st.auditList,children:M.map(ie=>t.jsxs("div",{className:st.memberRow,children:[t.jsx("div",{className:Qe.accountMenuMeta,children:new Date(ie.createdAt).toLocaleString()}),t.jsx("div",{className:st.memberTitle,children:ie.action}),t.jsxs("div",{className:Qe.accountMenuMeta,children:[ie.actorUserId," (",ie.actorRole,")"]})]},ie.id))}),t.jsxs("div",{className:st.auditPager,children:[t.jsx("button",{className:u.cancelBtn,disabled:C||S===0,onClick:oe,children:"Previous"}),t.jsxs("span",{className:Qe.accountMenuMeta,children:["Page ",S+1," of ",P]}),t.jsx("button",{className:u.cancelBtn,disabled:C||!Z||S+1>=P,onClick:xe,children:"Next"})]})]}),t.jsx("div",{className:`${ut.formActions} ${st.modalActionsEnd}`,children:t.jsx("button",{className:u.cancelBtn,onClick:$,children:"Close"})})]})})}const au="expired::";function VD({tasks:e,columns:n,groupBy:s,searchQuery:r,copiedId:o,taxonomies:l,types:i,priorities:p,approaches:h,assigneeOptions:w=[],onUpdateTask:b,onTaskClick:_,onOpenTaskById:k,onCopyId:g,onToggleInProgress:C,onToggleReview:M,onToggleComplete:S,onToggleCancel:P,onSetStatus:Z,onArchiveTask:$,onUnarchive:ce,onDelete:q,allTasks:K=[],onAddTaskToColumn:j,emptyColumnMode:ye="show",filterCategories:U=[],filterTypes:X=[],filterPriorities:Ne=[],filterStatus:pe=[],filterAssignees:te=[],scheduleFilteredTaskIds:D,categories:B=[],compressed:oe=!1,readOnlyMode:xe=null,recentlyChangedTaskIds:ie=[],scheduleDates:ae,onScheduleDaySelected:Ze,persistedScrollLeft:Le,onScrollLeftChange:Ce,sortBy:Oe="created",sortOrder:R="desc",planningDropTargets:W=null,onAssignTaskToWorkstream:F,onAssignWorkstreamToInitiative:V,showTaskCardStatusLabel:E=!0,workstreams:y=[],initiatives:x=[]}){const[H,I]=a.useState(null),[Ie,L]=a.useState(!1),[le,ne]=a.useState(!1),de=a.useMemo(()=>new Set(ie),[ie]),G=a.useMemo(()=>new Map(y.map(Y=>[Y.id,Y])),[y]),ee=a.useMemo(()=>new Map(x.map(Y=>[Y.id,Y])),[x]),be=a.useCallback(Y=>{const Ae=Y.workstreamId&&G.get(Y.workstreamId)||null,_e=Ae?.initiativeId&&ee.get(Ae.initiativeId)||null;return{taskWorkstream:Ae,taskInitiative:_e}},[ee,G]),$e=a.useMemo(()=>new Set(e.map(Y=>Y.id)),[e]),fe=a.useCallback(Y=>Y.startsWith(au)?Y.slice(au.length):Y,[]),De=a.useCallback(Y=>$e.has(fe(Y)),[$e,fe]),Ke=a.useMemo(()=>new Set(D||[]),[D]),nt=a.useRef(null),dt=a.useCallback(Y=>{const Ae=Y?.data?.current||{},_e=String(Y?.id||"");let Pe=String(Ae.taskId||""),qe=String(Ae.workstreamId||"");!Pe&&_e&&De(_e)&&(Pe=fe(_e)),!qe&&_e.startsWith("planning-workstream:")&&(qe=_e.slice(20));let Je=String(Ae.type||"");return Je||(Pe?Je="task-card":qe&&(Je="planning-workstream")),{activeId:_e,type:Je,taskId:Pe,workstreamId:qe}},[fe,De]),d=pf(xp(gf,{activationConstraint:{distance:5}}),xp(Dg,{coordinateGetter:Rg})),et=Y=>{const Ae=Y.status||"task";return Ae==="done"||Ae==="cancelled"?"completed":Ae},gt=a.useMemo(()=>{const Y=new Date,Ae=Y.getFullYear(),_e=String(Y.getMonth()+1).padStart(2,"0"),Pe=String(Y.getDate()).padStart(2,"0");return`${Ae}-${_e}-${Pe}`},[]),O=a.useMemo(()=>{const Y=Pe=>{const qe=Pe.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!qe)return null;const Je=new Date(Date.UTC(Number(qe[1]),Number(qe[2])-1,Number(qe[3]))),at=Je.getUTCDay()||7;Je.setUTCDate(Je.getUTCDate()+4-at);const Xe=new Date(Date.UTC(Je.getUTCFullYear(),0,1)),ct=Math.ceil(((Je.getTime()-Xe.getTime())/864e5+1)/7);return`${Je.getUTCFullYear()}-W${String(ct).padStart(2,"0")}`};return{dates:{...(()=>{const Pe=new Date,qe=Pe.getDay(),Je=qe===0?-6:1-qe,at=new Date(Pe);at.setDate(Pe.getDate()+Je);const Xe=Ot=>{const Pt=Ot.getFullYear(),xt=String(Ot.getMonth()+1).padStart(2,"0"),Et=String(Ot.getDate()).padStart(2,"0");return`${Pt}-${xt}-${Et}`},ct={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((Ot,Pt)=>{const xt=new Date(at);xt.setDate(at.getDate()+Pt),ct[Ot]=Xe(xt)}),ct})(),...ae||{}},parseToIsoWeekKey:Y}},[ae]),Ye=Y=>{const Ae=Y.scheduledDate||null;return Ae?new Map([[O.dates.mon,"mon"],[O.dates.tue,"tue"],[O.dates.wed,"wed"],[O.dates.thu,"thu"],[O.dates.fri,"fri"],[O.dates.sat,"sat"],[O.dates.sun,"sun"]]).get(Ae)||"__offweek":"backlog"},wt=a.useMemo(()=>{const Y=new Map;for(const Ae of n)Y.set(String(Ae.value),Ae),Y.has(Ae.label)||Y.set(Ae.label,Ae);return Y},[n]),St=a.useMemo(()=>{const Y={};return n.forEach(_e=>{Y[String(_e.value)]=0}),(K.length>0?K:e).forEach(_e=>{let Pe="";if(s==="status")Pe=et(_e);else if(s==="schedule")Pe=Ye(_e);else{const Je=_e[s];Pe=String(Je??"")}const qe=wt.get(Pe);if(qe&&Y[String(qe.value)]++,s==="schedule"){const Je=_e.status==="done"||_e.status==="cancelled";_e.scheduledDate&&!Je&&_e.scheduledDate<gt&&wt.has("expired")&&(Y.expired=(Y.expired||0)+1)}}),Y},[K,e,n,s,wt,gt]),At=a.useMemo(()=>{const Y={};if(n.forEach(Ae=>{Y[String(Ae.value)]=[]}),e.forEach(Ae=>{let _e="";if(s==="status")_e=et(Ae);else if(s==="schedule")_e=Ye(Ae);else{const qe=Ae[s];_e=String(qe??"")}const Pe=wt.get(_e);if(Pe){if(s==="schedule"&&String(Pe.value)==="backlog"&&!Ke.has(Ae.id))return;Y[String(Pe.value)].push(Ae)}if(s==="schedule"){const qe=Ae.status==="done"||Ae.status==="cancelled";Ae.scheduledDate&&!qe&&Ae.scheduledDate<gt&&Y.expired&&Y.expired.push(Ae)}}),s==="schedule"){const Ae=(Pe,qe)=>{const Je=typeof Pe.orderInDay=="number"?Pe.orderInDay:Number.MAX_SAFE_INTEGER,at=typeof qe.orderInDay=="number"?qe.orderInDay:Number.MAX_SAFE_INTEGER;return Je!==at?Je-at:String(Pe.createdAt||"").localeCompare(String(qe.createdAt||""))},_e=(Pe,qe)=>mu(Pe,qe,Oe,R,l);Object.keys(Y).forEach(Pe=>{if(Pe==="backlog"||Pe==="expired"){Y[Pe].sort(_e);return}Y[Pe].sort(Ae)})}return Y},[e,K,n,s,wt,Ke,gt,Oe,R]),zt=H?fe(H):null,Ht=zt?e.find(Y=>Y.id===zt):null,sn=a.useRef(null),Jt=a.useRef(null),Xt=a.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),gn=a.useRef(-1),Mn=(Y,Ae)=>s==="category"?!U.includes(String(Y)):s==="type"?!X.includes(String(Y)):s==="priority"?!Ne.some(_e=>Number(_e)===Number(Y)):s==="status"?String(Y)==="completed"?!pe.includes("done")&&!pe.includes("cancelled"):!pe.includes(String(Y)):s==="assignee"?!te.includes(String(Y)):!1,un=a.useMemo(()=>{let Pe=0;return n.forEach((qe,Je)=>{const at=At[String(qe.value)]||[],Xe=Mn(qe.value,qe.label),ct=s!=="schedule"&&ye==="hide"&&at.length===0;if(Xe||ct)return;const vt=ye==="collapse"&&at.length===0;Pe+=vt?72:320,Pe+=4}),Pe},[n,At,ye,s,U,X,Ne,pe]),yn=a.useCallback(Y=>{if(!Ce)return;const Ae=Math.max(0,Math.round(Y));Ae!==gn.current&&(gn.current=Ae,Ce(Ae))},[Ce]);a.useEffect(()=>{const Y=sn.current,Ae=Jt.current;if(!Y||!Ae)return;let _e=!1,Pe=!1;const qe=()=>{!Y||Pe||(_e=!0,Y.scrollLeft=Ae.scrollLeft,yn(Ae.scrollLeft),setTimeout(()=>_e=!1,0))},Je=()=>{!Ae||_e||(Pe=!0,Ae.scrollLeft=Y.scrollLeft,yn(Y.scrollLeft),setTimeout(()=>Pe=!1,0))};return Ae.addEventListener("scroll",qe),Y.addEventListener("scroll",Je),()=>{Ae.removeEventListener("scroll",qe),Y.removeEventListener("scroll",Je)}},[yn]);const an=a.useRef(!1);a.useEffect(()=>{if(an.current)return;if(typeof Le!="number"||!Number.isFinite(Le)){an.current=!0;return}const Y=sn.current,Ae=Jt.current;if(!Y||!Ae)return;const _e=Math.max(0,Y.scrollWidth-Y.clientWidth),Pe=Math.min(Math.max(0,Le),_e);Y.scrollLeft=Pe,Ae.scrollLeft=Pe,an.current=!0},[Le,un]),a.useEffect(()=>{const Y=()=>{const Ae=sn.current;if(!Ae){ne(!1);return}ne(Ae.scrollWidth>Ae.clientWidth+4)};return Y(),window.addEventListener("resize",Y),()=>{window.removeEventListener("resize",Y)}},[un,n.length,At]),a.useEffect(()=>{const Y=_e=>{const Pe=Xt.current;if(Pe.pointerId===null||Pe.pointerId!==_e.pointerId)return;const qe=_e.clientX-Pe.startX,Je=_e.clientY-Pe.startY;if(!Pe.didPan){if(Math.abs(qe)<7||Math.abs(qe)<Math.abs(Je))return;Pe.didPan=!0,L(!0),document.body.style.userSelect="none"}const at=Pe.startScrollLeft-qe;sn.current&&(sn.current.scrollLeft=at),Jt.current&&(Jt.current.scrollLeft=at),_e.preventDefault()},Ae=()=>{const _e=Xt.current;_e.pointerId!==null&&(_e.pointerId=null,_e.didPan=!1,Ie&&(L(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",Y),window.addEventListener("pointerup",Ae),window.addEventListener("pointercancel",Ae),()=>{window.removeEventListener("pointermove",Y),window.removeEventListener("pointerup",Ae),window.removeEventListener("pointercancel",Ae),document.body.style.userSelect=""}},[Ie]);const Tn=Y=>{!le||Y.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(Xt.current.pointerId=Y.pointerId,Xt.current.startX=Y.clientX,Xt.current.startY=Y.clientY,Xt.current.startScrollLeft=sn.current?.scrollLeft||0,Xt.current.didPan=!1)},Rt=Y=>{I(Y.active.id)},we=Y=>{const Ae=dt(Y.active),_e=String(Y.over?.data?.current?.type||"");Ae.type==="task-card"&&_e.startsWith("planning-")?nt.current=`${String(Y.over?.id||"")}:${_e}`:nt.current&&(nt.current=null)},Lt=Y=>{const{active:Ae,over:_e}=Y;nt.current=null,I(null);const Pe=dt(Ae),qe=Pe.type,Je=String(_e?.data?.current?.type||""),at=Pe.taskId,Xe=Pe.workstreamId,ct=String(_e?.data?.current?.workstreamId||""),vt=String(_e?.data?.current?.initiativeId||"");if(qe==="task-card"){if(Je==="planning-workstream-target"&&at&&ct){F?.(at,ct);return}if(Je==="planning-task-unlink"&&at){F?.(at,null);return}}if(qe==="planning-workstream"){if(Je==="planning-initiative-target"&&Xe&&vt){V?.(Xe,vt);return}if(Je==="planning-workstream-unlink"&&Xe){V?.(Xe,null);return}return}const Ot=String(Ae.id),Pt=_e?String(_e.id):null,xt=fe(Ot);Pt&&fe(Pt);const Et=e.find(se=>se.id===xt);if(!Et||!Pt)return;const xn=Qt(Ot),Jn=String(Ae?.data?.current?.sortable?.containerId||"")||xn,yt=String(_e?.data?.current?.sortable?.containerId||"")||Qt(Pt);if(!yt)return;const Gn=wt.get(yt)||n.find(se=>String(se.value)===yt||se.label===yt);if(Gn){if(s==="schedule"){const Me=String(Gn.value),Ee=["mon","tue","wed","thu","fri","sat","sun"],Fe=Me==="backlog"||Me==="expired"||Ee.includes(Me),tt=kt=>{let $t=kt.length;const Yt=Pt&&De(Pt)?fe(Pt):null;if(!Yt||!$e.has(Yt))return $t;const Sn=Yt,ft=kt.findIndex(It=>It.id===Sn);if(ft<0)return $t;const mt=_e?.rect,en=Ae.rect.current.translated||Ae.rect.current.initial,tn=!!(mt&&en&&en.top+en.height/2>mt.top+mt.height/2);return ft+(tn?1:0)},An=(kt,$t,Yt)=>{if(!kt||kt===$t)return;(At[String(kt)]||[]).filter(ft=>ft.id!==xt).forEach((ft,mt)=>{Yt.set(ft.id,{...Yt.get(ft.id)||{},orderInDay:mt})})};if(Me==="expired"){if(Jn!=="expired")return;const kt=new Map,$t=(At.expired||[]).filter(ft=>ft.id!==xt),Yt=tt($t),Sn=[...$t];Sn.splice(Yt,0,Et),Sn.forEach((ft,mt)=>{kt.set(ft.id,{...kt.get(ft.id)||{},orderInDay:mt})}),kt.forEach((ft,mt)=>b(mt,ft));return}if(Me==="backlog"){const kt=new Map,$t=(At.backlog||[]).filter(ft=>ft.id!==xt),Yt=tt($t),Sn=[...$t];Sn.splice(Yt,0,Et),Sn.forEach((ft,mt)=>{ft.id===xt?Et.scheduledDate?kt.set(ft.id,{...kt.get(ft.id)||{},scheduledDate:null,scheduledWeekKey:null,orderInDay:mt}):kt.set(ft.id,{...kt.get(ft.id)||{},orderInDay:mt}):kt.set(ft.id,{...kt.get(ft.id)||{},orderInDay:mt})}),An(Jn,Me,kt),kt.forEach((ft,mt)=>b(mt,ft));return}if(!Fe||!Ee.includes(Me))return;const Mt=O.dates[Me];if(!Mt)return;if(!(Et.status==="done"||Et.status==="cancelled")&&Mt<gt){window.alert("Only completed work can be scheduled in the past.");return}const Bn=O.parseToIsoWeekKey(Mt),bn=new Map,fn=(At[Me]||[]).filter(kt=>kt.id!==xt),rn=tt(fn),Kt=[...fn];Kt.splice(rn,0,Et),Kt.forEach((kt,$t)=>{kt.id===xt?bn.set(kt.id,{...bn.get(kt.id)||{},scheduledDate:Mt,scheduledWeekKey:Bn,orderInDay:$t}):bn.set(kt.id,{...bn.get(kt.id)||{},orderInDay:$t})}),An(Jn,Me,bn),bn.forEach((kt,$t)=>b($t,kt)),Ze?.(Mt);return}let se=Gn.value;if(s==="status"){const Me=et(Et),Ee=String(se);if(Me!==Ee){const Fe={status:Ee};Ee==="task"||Ee==="on-hold"?(Fe.inProgress=!1,Fe.readyForReview=!1,Fe.completed=!1,Fe.cancelled=!1):Ee==="in-progress"?(Fe.inProgress=!0,Fe.readyForReview=!1,Fe.completed=!1,Fe.cancelled=!1):Ee==="review"?(Fe.inProgress=!1,Fe.readyForReview=!0,Fe.completed=!1,Fe.cancelled=!1):Ee==="done"||Ee==="completed"?(Fe.status="done",Fe.inProgress=!1,Fe.readyForReview=!1,Fe.completed=!0,Fe.cancelled=!1,Fe.completedAt=new Date().toISOString()):Ee==="cancelled"&&(Fe.status="cancelled"),b(Et.id,Fe)}return}(s==="priority"||s==="complexity")&&(se=Number(se));const je=Et[s];if(String(je??"")!==String(se??"")){const Me={[s]:se};b(Et.id,Me)}}},Qt=Y=>{if(wt.has(Y)){const Pe=wt.get(Y);return Pe?String(Pe.value):Y}if(s==="schedule"&&Y.startsWith(au))return"expired";const Ae=fe(Y),_e=e.find(Pe=>Pe.id===Ae);if(_e){let Pe="";s==="status"?Pe=et(_e):s==="schedule"?Pe=Ye(_e):Pe=String(_e[s]??"");const qe=wt.get(Pe);return qe?String(qe.value):null}return null},Dt={sideEffects:Pg({styles:{active:{opacity:"0"}}})},He=Y=>{try{const Ae=jg(Y);if(Ae.length>0){const _e=Ae.find(ct=>String(ct.id).startsWith("planning-"));if(_e)return[_e];const Pe=Y.pointerCoordinates;if(!Pe)return[Ae[0]];const qe=Ae.filter(ct=>{const vt=String(ct.id);return De(vt)&&vt!==H});if(qe.length===0){const vt=Ae.filter(xt=>{const Et=String(xt.id);return!De(Et)}).find(xt=>!!Qt(String(xt.id)))||null,Ot=vt?Qt(String(vt.id)):null,Pt=(Y.droppableContainers||[]).filter(xt=>{const Et=String(xt.id);return!De(Et)||Et===H?!1:Ot?Qt(Et)===Ot:!0});if(Pt.length>0){const xt=hm({...Y,droppableContainers:Pt});if(xt.length>0)return[xt[0]]}return vt?[vt]:[Ae[0]]}const Je=qe;let at=Je[0],Xe=Number.POSITIVE_INFINITY;for(const ct of Je){const vt=Y.droppableRects?.get(ct.id);if(!vt)continue;const Ot=vt.left+vt.width/2,Pt=vt.top+vt.height/2,xt=Pe.x-Ot,Et=Pe.y-Pt,xn=xt*xt+Et*Et;xn<Xe&&(Xe=xn,at=ct)}return[at]}return hm(Y)}catch(Ae){return console.error("[TaskKanban] collision detection error",Ae),[]}},Nn={searchQuery:r,copiedId:o,taxonomies:l,types:i,priorities:p,approaches:h,assigneeOptions:w,onCopyId:g,onToggleInProgress:C,onToggleReview:M,onToggleComplete:S,onToggleCancel:P,onSetStatus:Z,onArchiveTask:$,onUnarchive:ce,onDelete:q,onOpenTaskById:k,categories:B,readOnlyMode:xe,changedTaskIdSet:de,resolveTaskHierarchy:be,groupBy:s,showStatusLabel:E};return t.jsxs(mf,{sensors:d,collisionDetection:He,onDragStart:Rt,onDragOver:we,onDragEnd:Lt,onDragCancel:Y=>{nt.current=null,I(null)},children:[W,t.jsxs("div",{className:u.kanbanWrapper,children:[t.jsx("div",{ref:Jt,className:`${u.kanbanTopScroll} tf-scrollbar`,children:t.jsx("div",{className:u.kanbanTopScrollSpacer,style:{width:`${un}px`}})}),t.jsx("div",{className:u.kanbanContainer,ref:sn,children:n.map(Y=>{const Ae=At[String(Y.value)]||[],_e=Mn(Y.value,Y.label),Pe=s!=="schedule"&&ye==="hide"&&Ae.length===0,qe=s==="schedule",Je=qe&&n.some(Et=>String(Et.value)==="backlog"),at=qe&&String(Y.value)==="backlog",Xe=qe&&String(Y.value)==="expired",ct=At.backlog||[],Ot=ye==="collapse"&&ct.length===0?72:320,Pt=at?0:Xe?Je?Ot+4:0:void 0,xt=at?6:Xe?5:void 0;return _e||Pe?null:t.jsx(ZD,{id:String(Y.value),title:Y.label,color:Y.color,icon:Y.icon,tasks:Ae,activeId:H,activeTaskId:zt,totalCount:St[String(Y.value)],onAddTask:()=>j?.(s,Y.value),onTaskClick:_,commonCardProps:Nn,collapseEmpty:ye==="collapse",compressed:oe,onHeaderPointerDown:Tn,isHeaderPanning:Ie,headerPanEnabled:le,stickyLeft:Pt,stickyZIndex:xt,isPast:!!Y.isPast,isSelected:!!Y.isSelected,isWeekend:!!Y.isWeekend,disableSorting:!1,scheduleDate:s==="schedule"?O.dates[String(Y.value)]:void 0,onScheduleDaySelected:Ze},String(Y.value))})})]}),Ai.createPortal(t.jsx(Ng,{dropAnimation:Dt,children:Ht?(()=>{const{taskWorkstream:Y,taskInitiative:Ae}=be(Ht);return t.jsx(ql,{task:Ht,taskWorkstream:Y,taskInitiative:Ae,isOverlay:!0,...Nn,isArchived:Ht.isArchived,categories:B,compressed:oe,isRecentlyChanged:de.has(Ht.id)})})():null}),document.body)]})}function ZD({id:e,title:n,color:s,icon:r,tasks:o,activeId:l=null,activeTaskId:i=null,totalCount:p,onAddTask:h,onTaskClick:w,commonCardProps:b,collapseEmpty:_,compressed:k,onHeaderPointerDown:g,isHeaderPanning:C=!1,headerPanEnabled:M=!1,stickyLeft:S,stickyZIndex:P,isPast:Z=!1,isSelected:$=!1,isWeekend:ce=!1,disableSorting:q=!1,scheduleDate:K,onScheduleDaySelected:j}){const{setNodeRef:ye}=Kl({id:e,data:{type:"Column"}}),U=_&&o.length===0,X=i?o.filter(B=>B.id!==i):o,Ne=typeof S=="number",pe=a.useRef(null),te=B=>e==="expired"?`${au}${B}`:B,D=B=>{if(!K||!j)return;const oe=B.target;oe&&(oe.closest('[data-task-card="true"]')||oe.closest(`.${u.kanbanCardWrapper}`)||j(K))};return t.jsxs("div",{ref:ye,className:`${u.kanbanColumn} ${U?u.kanbanColumnCollapsed:""} ${Ne?u.kanbanColumnSticky:""} ${Z?u.kanbanColumnPast:""} ${$?u.kanbanColumnSelectedDay:""} ${ce?u.kanbanColumnWeekend:""}`,style:Ne?{left:`${S}px`,zIndex:P??4}:void 0,onClick:D,children:[t.jsxs("div",{className:`${u.kanbanHeader} ${M?u.kanbanHeaderDraggable:""} ${C?u.kanbanHeaderPanning:""}`,style:{borderTopColor:Aa(s)||"var(--color-purple)"},onPointerDown:g,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const B=r&&Ri[r]?Ri[r]:Ti,oe=Aa(s)||"var(--color-purple)";return t.jsx(B,{size:16,style:{color:oe}})})(),!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}`}),!b.readOnlyMode&&t.jsx("button",{className:"tf-control-icon tf-control-icon-compact",onClick:B=>{B.stopPropagation(),h()},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:pe,children:q?X.map(B=>t.jsx("div",{className:u.kanbanCardWrapper,children:(()=>{const{taskWorkstream:oe,taskInitiative:xe}=b.resolveTaskHierarchy?.(B)||{};return t.jsx(ql,{task:B,taskWorkstream:oe,taskInitiative:xe,onClick:w,...b,isArchived:B.isArchived,readOnlyMode:b.readOnlyMode||null,compressed:k,isRecentlyChanged:!1})})()},B.id)):t.jsx(ff,{id:e,items:X.map(B=>te(B.id)),strategy:hf,children:X.map(B=>t.jsx(qD,{sortableId:te(B.id),task:B,onClick:w,commonCardProps:b,compressed:k,isRecentlyChanged:b.changedTaskIdSet?.has(B.id)},te(B.id)))})})})]})}function qD({sortableId:e,task:n,onClick:s,commonCardProps:r,compressed:o,isRecentlyChanged:l=!1}){const i=!!r?.readOnlyMode,{attributes:p,listeners:h,setNodeRef:w,transform:b,transition:_,isDragging:k}=yf({id:e,disabled:i,data:{type:"task-card",taskId:n.id}}),g={transform:Mp.Transform.toString(b),transition:_,opacity:k?0:1,pointerEvents:k?"none":"auto"},C=r?.groupBy==="schedule",M=!C&&l;return t.jsx("div",{ref:w,style:g,...i?{}:p,...i?{}:h,className:`${u.kanbanCardWrapper} ${M?u.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:S,taskInitiative:P}=r.resolveTaskHierarchy?.(n)||{};return t.jsx(ql,{task:n,taskWorkstream:S,taskInitiative:P,onClick:s,...r,isArchived:n.isArchived,readOnlyMode:r?.readOnlyMode||null,compressed:o,isRecentlyChanged:C?!1:l})})()})}function KD(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 YD(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 Gm="/api/taskforce/account/profile-summary",JD=9e4,Cc=new Map;function Qd(){return typeof performance<"u"?performance.now():Date.now()}function Sh(e,n){const s=String(e||"").trim();if(!s)return"";const r=String(n||"").trim();return r?`${s}::${r}`:s}function Vm(e,n){Cc.delete(Sh(e,n?.identityKey))}async function XD(e,n){const s=String(e||"").trim(),r=Sh(e,n?.identityKey);if(!r||!s)return null;const o=n?.force===!0,l=Date.now(),i=Cc.get(r);if(!o&&i?.payload!==void 0&&l-i.fetchedAt<JD)return Hn("account_profile_summary_cache_hit",{url:s,cacheKey:r,ageMs:l-i.fetchedAt}),i.payload;if(!o&&i?.promise)return Hn("account_profile_summary_request_reused",{url:s,cacheKey:r}),i.promise;const p=Qd(),h=(async()=>{const w=await fetch(s,{method:"GET",credentials:"include"});if(!w.ok)throw new Error(String((await w.json().catch(()=>({})))?.error||"Failed to load account summary."));const _=await w.json().catch(()=>({}))||null;return Cc.set(r,{payload:_,fetchedAt:Date.now(),promise:null}),Hn("account_profile_summary_loaded",{url:s,cacheKey:r,durationMs:Math.round(Qd()-p),fromCache:!1}),_})().catch(w=>{const b=i?.payload??null;if(b)return Cc.set(r,{payload:b,fetchedAt:i?.fetchedAt??Date.now(),promise:null}),Hn("account_profile_summary_failed",{url:s,cacheKey:r,durationMs:Math.round(Qd()-p),error:w instanceof Error?w.message:String(w||"Unknown error"),returnedStale:!0}),b;throw Cc.delete(r),Hn("account_profile_summary_failed",{url:s,cacheKey:r,durationMs:Math.round(Qd()-p),error:w instanceof Error?w.message:String(w||"Unknown error"),returnedStale:!1}),w});return Cc.set(r,{payload:i?.payload??null,fetchedAt:i?.fetchedAt??0,promise:h}),h}const Pp="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",vh="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Zm="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function QD({projectName:e,currentWorkspaceId:n,brandLabel:s="TaskForce",runtimeMode:r="local",theme:o=iu,meta:l,actions:i}){const p=_f(o)?vh:Pp;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:h=>{const w=h.currentTarget;w.src!==Zm?w.src=Zm: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:i})]})}function eP({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(cg,{size:16,className:u.searchIcon}),t.jsx("input",{type:"text",className:`${u.searchInput} ${s?u.searchActive:""}`,placeholder:n,value:e,onChange:i=>r(i.target.value)}),e&&o&&t.jsx("button",{className:u.clearSearchBtn,onClick:o,title:l,children:t.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function qm({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:i=>r(i.target.value),children:s.map(i=>t.jsx("option",{value:i.value,children:i.label},String(i.value)))}),o]})}function gp({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 Km(){return t.jsx("div",{className:u.headerDivider})}function tP({icon:e,label:n,onClick:s,disabled:r=!1}){return t.jsxs("button",{className:u.primaryUpdateBtn,onClick:s,disabled:r,children:[e," ",n]})}function Kp({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 nP(){return t.jsx(Kp,{children:t.jsx("div",{"aria-hidden":"true",style:{minHeight:"32px",flex:1}})})}function aP({categoryFilterOptions:e,typeFilterOptions:n,priorities:s,taxonomyDisplayLabels:r,filterCategories:o,setFilterCategories:l,filterTypes:i,setFilterTypes:p,filterPriorities:h,setFilterPriorities:w,filterStatus:b,setFilterStatus:_,filterAssignees:k,setFilterAssignees:g,assigneeOptions:C,initiativeFilterOptions:M=[],selectedInitiativeId:S="",setSelectedInitiativeId:P=()=>{},workstreamFilterOptions:Z=[],selectedWorkstreamId:$="",setSelectedWorkstreamId:ce=()=>{},taskScope:q,setTaskScope:K,showArchive:j,setShowArchive:ye,fetchArchive:U,onDeleteAllDeleted:X,clearFilters:Ne}){return t.jsxs(t.Fragment,{children:[t.jsx(lh,{}),t.jsx(xi,{label:r?.category||Te("standalone.categoryLabel"),options:e,selected:o,onChange:pe=>l(pe),variant:"value"}),t.jsx(xi,{label:r?.type||Te("standalone.typeLabel"),options:n,selected:i,onChange:pe=>p(pe),variant:"value"}),t.jsx(xi,{label:r?.priority||Te("standalone.priorityLabel"),options:s,selected:h,onChange:pe=>w(pe),variant:"value"}),t.jsx(xi,{label:Te("standalone.statusLabel"),options:to,selected:b,onChange:pe=>_(pe),variant:"value"}),t.jsx(xi,{label:Te("standalone.assigneeLabel"),options:C,selected:k,onChange:pe=>g(pe),variant:"value"}),t.jsx("div",{className:u.headerDivider,style:{height:"16px",margin:"0 8px"}}),t.jsx(Om,{label:"Initiative",options:M,selected:S,onChange:P,allLabel:"All Initiatives",title:"Filter by initiative"}),t.jsx(Om,{label:"Workstream",options:Z,selected:$,onChange:ce,allLabel:"All Workstreams",title:"Filter by workstream"}),t.jsx(uh,{scope:q,onScopeChange:pe=>{K(pe),pe==="archived"?(ye(!0),U()):j&&ye(!1)},className:u.groupByContainer,labelClassName:u.groupByLabel}),t.jsx("div",{style:{flex:1}}),q==="deleted"&&X&&t.jsx(ph,{onClick:X,className:`${u.bulkArchiveBtn} ${u.taskToolbarAction} ${u.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),t.jsx(dh,{onClick:Ne})]})}function sP(e){return t.jsx(Kp,{children:t.jsx(aP,{...e})})}const su=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],ru=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function rP({typeFilters:e,setTypeFilters:n,attachmentFilters:s,setAttachmentFilters:r,clearFilters:o}){return t.jsxs(Kp,{children:[t.jsx(lh,{}),t.jsx(xi,{label:"Attachment",options:ru,selected:s,onChange:l=>r(l),variant:"value"}),t.jsx(xi,{label:"Type",options:su,selected:e,onChange:l=>n(l),variant:"value"}),t.jsx("div",{style:{flex:1}}),t.jsx(dh,{onClick:o})]})}const oP="_drawerBody_126ut_1",iP="_paneShell_126ut_9",cP="_collapsedPaneShell_126ut_18",lP="_collapsedPaneHeader_126ut_27",dP="_collapsedPaneLabel_126ut_39",uP="_treePane_126ut_49",pP="_treePaneSplit_126ut_59",mP="_detailPane_126ut_63",fP="_paneHeader_126ut_73",hP="_paneHeaderLabel_126ut_87",gP="_paneContent_126ut_96",yP="_sectionTitle_126ut_105",kP="_sectionHeaderRow_126ut_113",SP="_sectionGroup_126ut_120",vP="_treeList_126ut_145",wP="_treeChildren_126ut_151",bP="_treeRow_126ut_159",_P="_treeRowDetailOpen_126ut_171",CP="_treeRowDropReady_126ut_177",xP="_treeRowDropActive_126ut_181",AP="_treeRowDropMode_126ut_187",IP="_treeChevron_126ut_187",TP="_rowButton_126ut_188",NP="_detailsButton_126ut_189",jP="_treeRowDragging_126ut_193",RP="_rowContent_126ut_234",DP="_rowTopRow_126ut_244",PP="_referenceBadgeButton_126ut_253",EP="_referenceBadgeStatic_126ut_259",LP="_rowTitle_126ut_280",MP="_rowMeta_126ut_294",BP="_detailsButtonActive_126ut_322",WP="_unlinkZone_126ut_329",FP="_unlinkZoneActive_126ut_340",OP="_emptyPanel_126ut_346",$P="_emptyPanelTitle_126ut_355",UP="_emptyPanelText_126ut_361",zP="_sectionNote_126ut_367",HP="_detailHero_126ut_374",GP="_detailReferenceRow_126ut_381",VP="_detailTitle_126ut_386",ZP="_detailDescription_126ut_393",qP="_detailActionRow_126ut_404",KP="_metricGrid_126ut_411",YP="_metricCard_126ut_418",JP="_editorCard_126ut_423",XP="_editorField_126ut_430",QP="_editorLabel_126ut_436",eE="_editorHint_126ut_442",tE="_editorSubActions_126ut_447",nE="_editorActions_126ut_452",aE="_metricValue_126ut_458",sE="_metricLabel_126ut_465",rE="_progressTrack_126ut_472",oE="_progressFill_126ut_480",iE="_listCard_126ut_486",cE="_sectionDropReady_126ut_495",lE="_sectionDropActive_126ut_500",dE="_sectionDropMode_126ut_506",uE="_attachReferenceRow_126ut_510",pE="_listItem_126ut_521",mE="_listItemButton_126ut_530",fE="_detailCardButton_126ut_539",hE="_listItemText_126ut_547",gE="_listItemTitle_126ut_554",yE="_listItemMeta_126ut_568",kE="_detailChildCard_126ut_573",SE="_detailChildCardTopRow_126ut_585",vE="_taskStatusIcon_126ut_594",he={drawerBody:oP,paneShell:iP,collapsedPaneShell:cP,collapsedPaneHeader:lP,collapsedPaneLabel:dP,treePane:uP,treePaneSplit:pP,detailPane:mP,paneHeader:fP,paneHeaderLabel:hP,paneContent:gP,sectionTitle:yP,sectionHeaderRow:kP,sectionGroup:SP,treeList:vP,treeChildren:wP,treeRow:bP,treeRowDetailOpen:_P,treeRowDropReady:CP,treeRowDropActive:xP,treeRowDropMode:AP,treeChevron:IP,rowButton:TP,detailsButton:NP,treeRowDragging:jP,rowContent:RP,rowTopRow:DP,referenceBadgeButton:PP,referenceBadgeStatic:EP,rowTitle:LP,rowMeta:MP,detailsButtonActive:BP,unlinkZone:WP,unlinkZoneActive:FP,emptyPanel:OP,emptyPanelTitle:$P,emptyPanelText:UP,sectionNote:zP,detailHero:HP,detailReferenceRow:GP,detailTitle:VP,detailDescription:ZP,detailActionRow:qP,metricGrid:KP,metricCard:YP,editorCard:JP,editorField:XP,editorLabel:QP,editorHint:eE,editorSubActions:tE,editorActions:nE,metricValue:aE,metricLabel:sE,progressTrack:rE,progressFill:oE,listCard:iE,sectionDropReady:cE,sectionDropActive:lE,sectionDropMode:dE,attachReferenceRow:uE,listItem:pE,listItemButton:mE,detailCardButton:fE,listItemText:hE,listItemTitle:gE,listItemMeta:yE,detailChildCard:kE,detailChildCardTopRow:SE,taskStatusIcon:vE},Wl=332,xr=392,yp=56;function wh(e,n,s,r,o){return(e?yp:Wl)+(n?s?yp:xr:0)+(r?o?yp:xr:0)}function kp(e){return e?e.split(/[-_\s]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"No status"}function ou({label:e,entityType:n,interactive:s=!0}){const[r,o]=pt.useState(!1),l=pt.useCallback(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),window.setTimeout(()=>o(!1),1200)}catch{o(!1)}},[e]);return s?t.jsx(Xf,{copied:r,label:e,onClick:l,title:`Copy ${n} reference`,ariaLabel:r?`Copied ${n} reference`:`Copy ${n} reference`,className:he.referenceBadgeButton,children:e}):t.jsx("span",{className:`${u.taskIdBadge} ${he.referenceBadgeStatic}`.trim(),children:t.jsx("span",{children:e})})}function Sp({rowId:e,rowType:n,referenceLabel:s,title:r,meta:o,active:l,detailOpen:i=!1,canExpand:p=!1,expanded:h=!1,onToggleExpand:w,onToggleScope:b,onToggleDetails:_}){const{active:k}=ku(),g=String(k?.data?.current?.type||""),C=n==="workstream"&&g==="task-card",M=n==="initiative"&&g==="planning-workstream",S=n==="workstream"?"planning-workstream-target":"planning-initiative-target",{setNodeRef:P,isOver:Z}=Kl({id:`${S}:${e}`,data:n==="workstream"?{type:S,workstreamId:e}:{type:S,initiativeId:e}}),$=n==="workstream",{attributes:ce,listeners:q,setNodeRef:K,transform:j,isDragging:ye}=Eg({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!$}),U=$&&j?{transform:Mp.Translate.toString(j)}:void 0,X=C||M;return t.jsxs("div",{ref:P,style:U,className:`${he.treeRow} ${i?he.treeRowDetailOpen:""} ${X?he.treeRowDropReady:""} ${Z?he.treeRowDropActive:""} ${ye?he.treeRowDragging:""} ${X?he.treeRowDropMode:""}`,children:[p?t.jsx("button",{type:"button",className:he.treeChevron,onClick:w,title:h?"Collapse workstreams":"Expand workstreams",children:h?t.jsx(df,{size:15}):t.jsx(lg,{size:15})}):t.jsx("span",{className:he.treeChevron,"aria-hidden":"true",children:t.jsx(ji,{size:14})}),t.jsxs("div",{className:he.rowContent,children:[t.jsxs("div",{className:he.rowTopRow,children:[s?t.jsx(ou,{label:s,entityType:n}):t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:`${he.detailsButton} ${l?he.detailsButtonActive:""}`,onClick:b,title:l?"Clear board scope":"Scope board to this item",children:t.jsx(uf,{size:14})})]}),t.jsxs("button",{type:"button",ref:$?K:void 0,className:he.rowButton,onClick:_,...$?ce:{},...$?q:{},children:[t.jsx("span",{className:he.rowTitle,children:r}),t.jsx("span",{className:he.rowMeta,children:o})]})]})]})}function vp({label:e,onExpand:n}){return t.jsx("div",{className:`${he.paneShell} ${he.collapsedPaneShell}`.trim(),children:t.jsxs("div",{className:he.collapsedPaneHeader,children:[t.jsx("button",{type:"button",className:"tf-control-icon",onClick:n,title:`Expand ${e}`,children:t.jsx(ji,{size:16})}),t.jsx("span",{className:he.collapsedPaneLabel,children:e})]})})}function wE({targetType:e,label:n}){const{active:s}=ku(),r=String(s?.data?.current?.type||""),o=e==="task"&&r==="task-card"||e==="workstream"&&r==="planning-workstream",{setNodeRef:l,isOver:i}=Kl({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:`${he.unlinkZone} ${i?he.unlinkZoneActive:""}`,children:n}):null}function bE({initiatives:e,standaloneWorkstreams:n,activeInitiativeId:s,activeWorkstreamId:r,expandedInitiativeIds:o,detail:l,secondaryPane:i,onCreateInitiative:p,onCreateWorkstream:h,onToggleInitiative:w,onSelectInitiative:b,onSelectWorkstream:_,onOpenInitiativeDetails:k,onOpenWorkstreamDetails:g}){const{active:C}=ku(),S=String(C?.data?.current?.type||"")==="planning-workstream",{setNodeRef:P,isOver:Z}=Kl({id:"planning-workstream-unlink",data:{type:"planning-workstream-unlink"}});return t.jsxs(t.Fragment,{children:[t.jsx(wE,{targetType:"task",label:"Drop here to make task standalone"}),t.jsxs("div",{className:he.sectionGroup,children:[t.jsxs("div",{className:he.sectionHeaderRow,children:[t.jsx("div",{className:he.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:he.treeList,children:e.length===0?t.jsxs("div",{className:he.emptyPanel,children:[t.jsx("div",{className:he.emptyPanelTitle,children:"No initiatives yet"}),t.jsxs("div",{className:he.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($=>{const ce=o.has($.id),q=`${$.workstreamCount||0} workstreams • ${$.taskCount} tasks${$.isArchived?" • archived":""}`;return t.jsxs("div",{children:[t.jsx(Sp,{rowId:$.id,rowType:"initiative",referenceLabel:ar($),title:$.title,meta:q,active:s===$.id&&!r,detailOpen:l?.type==="initiative"&&l.item.id===$.id,canExpand:$.workstreams.length>0,expanded:ce,onToggleExpand:()=>w($.id),onToggleScope:()=>b($.id),onToggleDetails:()=>{if(l?.type==="initiative"&&l.item.id===$.id){k("");return}k($.id)}}),ce&&$.workstreams.length>0&&t.jsx("div",{className:he.treeChildren,children:$.workstreams.map(K=>t.jsx(Sp,{rowId:K.id,rowType:"workstream",referenceLabel:eo(K),title:K.title,meta:`${K.taskCount} tasks • ${K.progressPercent}% complete${K.isArchived?" • archived":""}`,active:r===K.id,detailOpen:l?.type==="workstream"&&l.item.id===K.id||i?.kind==="detail"&&i.detail.item.id===K.id,onToggleScope:()=>_(K.id,$.id),onToggleDetails:()=>{if(i?.kind==="detail"&&i.detail.item.id===K.id){g("");return}if(l?.type==="workstream"&&l.item.id===K.id){g("");return}g(K.id)}},K.id))})]},$.id)})})]}),t.jsxs("div",{ref:P,className:`${he.sectionGroup} ${S?he.sectionDropReady:""} ${Z?he.sectionDropActive:""}`.trim(),children:[t.jsxs("div",{className:he.sectionHeaderRow,children:[t.jsx("div",{className:he.sectionTitle,children:"Workstreams"}),t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:h,children:t.jsx(sr,{size:15})})]}),t.jsx("div",{className:he.treeList,children:n.length===0?t.jsxs("div",{className:he.emptyPanel,children:[t.jsx("div",{className:he.emptyPanelTitle,children:"No standalone workstreams yet"}),t.jsxs("div",{className:he.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($=>t.jsx(Sp,{rowId:$.id,rowType:"workstream",referenceLabel:eo($),title:$.title,meta:`${$.taskCount} tasks • ${$.progressPercent}% complete${$.isArchived?" • archived":""}`,active:r===$.id,detailOpen:l?.type==="workstream"&&l.item.id===$.id||i?.kind==="detail"&&i.detail.item.id===$.id,onToggleScope:()=>_($.id,null),onToggleDetails:()=>{if(l?.type==="workstream"&&l.item.id===$.id){g("");return}g($.id)}},$.id))})]})]})}function Ym({detail:e,onOpenNestedWorkstreamDetails:n,onEdit:s,onArchive:r,onUnarchive:o,onCreateTaskInWorkstream:l,onCreateWorkstreamInInitiative:i,onOpenTaskById:p,onAttachTaskToWorkstreamByReference:h,onAttachWorkstreamToInitiativeByReference:w}){const[b,_]=pt.useState(""),{active:k}=ku(),g=String(k?.data?.current?.type||""),C=e.type==="workstream"&&g==="task-card",M=e.type==="initiative"&&g==="planning-workstream",S=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:P,isOver:Z}=Kl({id:`${S}:detail:${e.item.id}`,data:e.type==="initiative"?{type:S,initiativeId:e.item.id}:{type:S,workstreamId:e.item.id}}),$=e.type==="initiative"?"Workstreams":"Tasks",ce=e.type==="initiative"?e.item.workstreams:[],q=e.type==="initiative"?"Initiative":"Workstream",K=e.type==="initiative"?ar(e.item):eo(e.item);return pt.useEffect(()=>{_("")},[e.item.id,e.type]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:he.detailHero,children:[K?t.jsx("div",{className:he.detailReferenceRow,children:t.jsx(ou,{label:K,entityType:e.type})}):null,t.jsx("h3",{className:he.detailTitle,children:e.item.title}),t.jsx("p",{className:he.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:he.progressTrack,"aria-label":`${e.item.progressPercent}% complete`,children:t.jsx("div",{className:he.progressFill,style:{width:`${e.item.progressPercent}%`}})}),t.jsxs("div",{className:he.detailActionRow,children:[t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:s,children:t.jsxs("span",{children:["Edit ",q]})}),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:he.metricGrid,children:[t.jsxs("div",{className:he.metricCard,children:[t.jsx("span",{className:he.metricValue,children:e.item.taskCount}),t.jsx("span",{className:he.metricLabel,children:"Tasks in scope"})]}),t.jsxs("div",{className:he.metricCard,children:[t.jsx("span",{className:he.metricValue,children:e.item.completedTaskCount}),t.jsx("span",{className:he.metricLabel,children:"Done / terminal"})]}),t.jsxs("div",{className:he.metricCard,children:[t.jsx("span",{className:he.metricValue,children:e.item.ownerLabel||"Unassigned"}),t.jsx("span",{className:he.metricLabel,children:"Owner"})]}),t.jsxs("div",{className:he.metricCard,children:[t.jsx("span",{className:he.metricValue,children:(e.item.commentCount||0)+(e.item.attachmentCount||0)}),t.jsx("span",{className:he.metricLabel,children:"Context items"})]})]}),t.jsxs("div",{ref:P,className:`${he.listCard} ${C||M?he.sectionDropReady:""} ${Z?he.sectionDropActive:""} ${C||M?he.sectionDropMode:""}`.trim(),children:[t.jsxs("div",{className:he.sectionHeaderRow,children:[t.jsx("div",{className:he.sectionTitle,children:$}),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:()=>i?.(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:he.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:b,onChange:j=>_(j.target.value)}),t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>{const j=b.trim();j&&(e.type==="initiative"?w?.(e.item.id,j):h?.(e.item.id,j),_(""))},children:"Attach"})]}),e.type==="initiative"?ce.length>0?ce.map(j=>t.jsx("button",{type:"button",className:`${he.listItemButton} ${he.detailCardButton}`.trim(),onClick:()=>n?.(j.id),children:t.jsxs("div",{className:`${he.listItem} ${he.detailChildCard}`.trim(),children:[t.jsx("div",{className:he.detailChildCardTopRow,children:j.referenceNumber?t.jsx(ou,{label:eo(j),entityType:"workstream"}):t.jsx("span",{"aria-hidden":"true"})}),t.jsxs("div",{className:he.listItemText,children:[t.jsx("span",{className:he.listItemTitle,children:j.title}),t.jsxs("span",{className:he.listItemMeta,children:[j.taskCount," tasks • ",j.progressPercent,"% complete"]})]})]})},j.id)):t.jsxs("div",{className:he.emptyPanel,children:[t.jsx("div",{className:he.emptyPanelTitle,children:"No workstreams yet"}),t.jsx("div",{className:he.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((j,ye)=>{const U=$l(j.status).value==="done",X=$l(ye.status).value==="done";return U===X?0:U?1:-1}).map(j=>{const ye=j.referenceNumber?`T-${j.referenceNumber}`:"",U=$l(j.status),X=Ri[U.icon||"Square"],Ne=Aa(U.color)||"var(--text-secondary)";return t.jsx("button",{type:"button",className:`${he.listItemButton} ${he.detailCardButton}`.trim(),onClick:()=>p?.(j.id),children:t.jsxs("div",{className:`${he.listItem} ${he.detailChildCard}`.trim(),children:[t.jsxs("div",{className:he.detailChildCardTopRow,children:[ye?t.jsx(ou,{label:ye,entityType:"task"}):t.jsx("span",{"aria-hidden":"true"}),t.jsx("span",{className:he.taskStatusIcon,style:{color:Ne},"aria-label":U.shortLabel||kp(j.status),title:U.shortLabel||kp(j.status),children:X?t.jsx(X,{size:18,strokeWidth:2.4}):null})]}),t.jsxs("div",{className:he.listItemText,children:[t.jsx("span",{className:he.listItemTitle,children:j.title}),t.jsx("span",{className:he.listItemMeta,children:kp(j.status)})]})]})},j.id)}):t.jsxs("div",{className:he.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:he.listCard,children:[t.jsx("div",{className:he.sectionTitle,children:"Context"}),t.jsx("div",{className:he.sectionNote,children:"Comments, attachments, and planning notes can live here without pushing that context down into task cards."})]})]})}function Jm({editor:e,draftTitle:n,draftDescription:s,draftOwner:r,draftInitiativeId:o,assigneeOptions:l,draftInitiativeSummary:i,onChangeDraftTitle:p,onChangeDraftDescription:h,onChangeDraftOwner:w,onChangeDraftInitiativeId:b,onCancel:_,onSubmit:k,onAssignInitiativeToWorkstream:g}){const C=e.entityType==="initiative"?"Initiative":"Workstream",M=e.mode==="create"?`Create ${C}`:`Save ${C}`;return t.jsx(t.Fragment,{children:t.jsxs("div",{className:he.editorCard,children:[t.jsxs("div",{className:he.editorField,children:[t.jsx("label",{className:he.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:he.editorField,children:[t.jsx("label",{className:he.editorLabel,children:"Description"}),t.jsx("textarea",{className:u.textarea,value:s,onChange:S=>h(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:he.editorField,children:[t.jsx("label",{className:he.editorLabel,children:"Initiative"}),i&&t.jsxs("div",{className:he.editorHint,children:["Current: ",i.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=>b(S.target.value)}),e.mode==="edit"&&t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>g?.(e.targetId),children:"Set Initiative"})]}),e.mode==="edit"&&t.jsx("div",{className:he.editorSubActions,children:t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:()=>g?.(e.targetId,null),children:"Clear Initiative"})})]}),t.jsxs("div",{className:he.editorField,children:[t.jsx("label",{className:he.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:he.editorActions,children:[t.jsx("button",{type:"button",className:u.secondaryHeaderBtn,onClick:_,children:"Cancel"}),t.jsx("button",{type:"button",className:u.primaryUpdateBtn,onClick:k,children:M})]})]})})}function _E({open:e,leftOffset:n=0,initiatives:s,standaloneWorkstreams:r,activeInitiativeId:o,activeWorkstreamId:l,expandedInitiativeIds:i,detail:p,editor:h,secondaryPane:w,assigneeOptions:b,draftInitiativeSummary:_,draftTitle:k,draftDescription:g,draftOwner:C,draftInitiativeId:M,onChangeDraftTitle:S,onChangeDraftDescription:P,onChangeDraftOwner:Z,onChangeDraftInitiativeId:$,onCollapseTreePane:ce,onExpandTreePane:q,onCollapsePrimaryPane:K,onExpandPrimaryPane:j,onCollapseSecondaryPane:ye,onExpandSecondaryPane:U,onBackFromSecondary:X,treeCollapsed:Ne,primaryCollapsed:pe,secondaryCollapsed:te,onCancelEditor:D,onSubmitEditor:B,onCreateInitiative:oe,onCreateWorkstream:xe,onToggleInitiative:ie,onSelectInitiative:ae,onSelectWorkstream:Ze,onOpenInitiativeDetails:Le,onOpenWorkstreamDetails:Ce,onOpenNestedWorkstreamDetails:Oe,onEditInitiative:R,onEditWorkstream:W,onArchiveInitiative:F,onUnarchiveInitiative:V,onArchiveWorkstream:E,onUnarchiveWorkstream:y,onCreateTaskInWorkstream:x,onCreateWorkstreamInInitiative:H,onAssignInitiativeToWorkstream:I,onOpenTaskById:Ie,onAttachTaskToWorkstreamByReference:L,onAttachWorkstreamToInitiativeByReference:le}){const ne=!!(p||h),de=!!w,G=wh(Ne,ne,pe,de,te),ee=h?h.entityType==="initiative"?h.mode==="create"?"New Initiative":"Edit Initiative":h.mode==="create"?"New Workstream":"Edit Workstream":p?.type==="initiative"?"Initiative":"Workstream",be=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:he.drawerBody,children:[Ne?t.jsx(vp,{label:"Planning",onExpand:q}):t.jsxs("div",{className:`${he.paneShell} ${u.appScrollbar} tf-scrollbar ${he.treePane} ${ne&&!pe?he.treePaneSplit:""}`.trim(),style:{flex:`0 0 ${Wl}px`,width:`${Wl}px`,minWidth:`${Wl}px`,maxWidth:`${Wl}px`},children:[t.jsxs("div",{className:he.paneHeader,children:[t.jsx("span",{className:he.paneHeaderLabel,children:"Planning"}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:ce,children:t.jsx(Nc,{size:16})})]}),t.jsx("div",{className:he.paneContent,children:t.jsx(bE,{initiatives:s,standaloneWorkstreams:r,activeInitiativeId:o,activeWorkstreamId:l,expandedInitiativeIds:i,detail:p,secondaryPane:w,onCreateInitiative:oe,onCreateWorkstream:xe,onToggleInitiative:ie,onSelectInitiative:ae,onSelectWorkstream:Ze,onOpenInitiativeDetails:Le,onOpenWorkstreamDetails:Ce})})]}),ne&&(pe?t.jsx(vp,{label:ee,onExpand:j}):t.jsxs("div",{className:`${he.paneShell} ${u.appScrollbar} tf-scrollbar ${he.detailPane}`.trim(),style:{flex:`0 0 ${xr}px`,width:`${xr}px`,minWidth:`${xr}px`,maxWidth:`${xr}px`},children:[t.jsxs("div",{className:he.paneHeader,children:[t.jsx("span",{className:he.paneHeaderLabel,children:ee}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:K,children:t.jsx(Nc,{size:16})})]}),t.jsx("div",{className:he.paneContent,children:h?t.jsx(Jm,{editor:h,draftTitle:k,draftDescription:g,draftOwner:C,draftInitiativeId:M,assigneeOptions:b,draftInitiativeSummary:_,onChangeDraftTitle:S,onChangeDraftDescription:P,onChangeDraftOwner:Z,onChangeDraftInitiativeId:$,onCancel:D,onSubmit:B,onAssignInitiativeToWorkstream:I}):p?t.jsx(Ym,{detail:p,onOpenNestedWorkstreamDetails:p.type==="initiative"?Oe:void 0,onCreateTaskInWorkstream:p.type==="workstream"?x:void 0,onCreateWorkstreamInInitiative:p.type==="initiative"?H:void 0,onOpenTaskById:p.type==="workstream"?Ie:void 0,onAttachTaskToWorkstreamByReference:p.type==="workstream"?L:void 0,onAttachWorkstreamToInitiativeByReference:p.type==="initiative"?le:void 0,onEdit:()=>p.type==="initiative"?R(p.item.id):W(p.item.id),onArchive:()=>p.type==="initiative"?F(p.item.id):E(p.item.id),onUnarchive:()=>p.type==="initiative"?V(p.item.id):y(p.item.id)}):null})]})),de&&(te?t.jsx(vp,{label:be,onExpand:U}):t.jsxs("div",{className:`${he.paneShell} ${u.appScrollbar} tf-scrollbar ${he.detailPane}`.trim(),style:{flex:`0 0 ${xr}px`,width:`${xr}px`,minWidth:`${xr}px`,maxWidth:`${xr}px`},children:[t.jsxs("div",{className:he.paneHeader,children:[t.jsx("span",{className:he.paneHeaderLabel,children:be}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:ye,children:t.jsx(Nc,{size:16})})]}),t.jsx("div",{className:he.paneContent,children:w?.kind==="editor"?t.jsx(Jm,{editor:w.editor,draftTitle:k,draftDescription:g,draftOwner:C,draftInitiativeId:M,assigneeOptions:b,draftInitiativeSummary:_,onChangeDraftTitle:S,onChangeDraftDescription:P,onChangeDraftOwner:Z,onChangeDraftInitiativeId:$,onCancel:X,onSubmit:B,onAssignInitiativeToWorkstream:I}):w?t.jsx(Ym,{detail:w.detail,onCreateTaskInWorkstream:x,onOpenTaskById:Ie,onAttachTaskToWorkstreamByReference:L,onEdit:()=>W(w.detail.item.id),onArchive:()=>E(w.detail.item.id),onUnarchive:()=>y(w.detail.item.id)}):null})]}))]})})}const CE={"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"}},Ul="annotated_attachments.workspace_access",zl="documents.workspace_access",gu="workflows.workspace_access",yu="agents.workspace_access",Xm="initiatives.workspace_access",xE=Object.entries(CE).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 AE(e){const n=String(e||"").trim();return n&&xE[n]||null}function IE(e){const n=AE(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 Ll(e){return IE(e.featureKey)}const TE=["tasks","docs","annotate","workflows","agents"];function NE(e){const n=e?.featureAccess||{},s={tasks:{id:"tasks",label:"Tasks",featureKey:null,enabled:!0,fallbackModuleId:"tasks"},docs:{id:"docs",label:"Documents",featureKey:zl,enabled:n[zl]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:"Image Notes",featureKey:Ul,enabled:n[Ul]?.allowed??!1,fallbackModuleId:"tasks"},workflows:{id:"workflows",label:"Workflows",featureKey:gu,enabled:n[gu]?.allowed??!1,fallbackModuleId:"tasks"},agents:{id:"agents",label:"Agents",featureKey:yu,enabled:n[yu]?.allowed??!1,fallbackModuleId:"tasks"}};return TE.map(r=>s[r])}function jE(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 Qm(e,n){const s=n.find(r=>r.id===e);return s?s.enabled?s.id:s.fallbackModuleId:"tasks"}const RE="_weekLabel_vet2o_1",DE="_sectionTitle_vet2o_6",PE="_calendarHeader_vet2o_11",EE="_monthLabel_vet2o_18",LE="_weekdayGrid_vet2o_23",ME="_weekdayLabel_vet2o_30",BE="_calendarGrid_vet2o_36",WE="_calendarDay_vet2o_42",FE="_calendarDayDot_vet2o_55",OE="_jumpRow_vet2o_67",$E="_displaySection_vet2o_73",UE="_toggleLabel_vet2o_79",zE="_expiredSummary_vet2o_87",HE="_actionButton_vet2o_95",Ra={weekLabel:RE,sectionTitle:DE,calendarHeader:PE,monthLabel:EE,weekdayGrid:LE,weekdayLabel:ME,calendarGrid:BE,calendarDay:WE,calendarDayDot:FE,jumpRow:OE,displaySection:$E,toggleLabel:UE,expiredSummary:zE,actionButton:HE},ef=["mon","tue","wed","thu","fri","sat","sun"],GE={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function Tc(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 Fl(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 Ep(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 VE(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 bh(e,n){const s=new Date(e);return s.setDate(e.getDate()+n),s}function ZE(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 Lp=320;function qE({open:e,onClose:n,scheduleSelectedDate:s,setScheduleSelectedDate:r,scheduleCalendarMonth:o,setScheduleCalendarMonth:l,scheduleShowWeekends:i,setScheduleShowWeekends:p,scheduleShowBacklog:h,setScheduleShowBacklog:w,scheduleOnlyExpired:b,setScheduleOnlyExpired:_,expiredScheduledCount:k,overdueDueCount:g,expiredLeafCandidates:C,expiredRecoveryCandidates:M,onMoveExpiredToSelectedWeek:S,onMoveExpiredToBacklog:P,scheduleBulkBusy:Z,globalWeekStartsOn:$,resolvedLocale:ce,todayDateOnly:q,scheduleBaseTasks:K,scheduleWeekStart:j,scheduleWeekLabel:ye}){const U=pt.useMemo(()=>{const[D,B]=o.split("-"),oe=Number(D),xe=Number(B);if(!Number.isInteger(oe)||!Number.isInteger(xe)||xe<1||xe>12){const ie=Fl(s)||new Date;return new Date(ie.getFullYear(),ie.getMonth(),1)}return new Date(oe,xe-1,1)},[o,s]),X=pt.useMemo(()=>Rc(U,{month:"long",year:"numeric"},ce),[U,ce]),Ne=pt.useMemo(()=>{const D=Ep(U,$);return Array.from({length:42},(B,oe)=>bh(D,oe))},[U,$]),pe=pt.useMemo(()=>{const D=new Map;for(const B of K){const oe=B.scheduledDate||"";if(!oe)continue;const ie=!(B.status==="done"||B.status==="cancelled")&&oe<q,ae=D.get(oe);ae?(ae.count+=1,ie&&(ae.hasExpired=!0)):D.set(oe,{count:1,hasExpired:ie})}return D},[K,q]),te=pt.useMemo(()=>$==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[$]);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:`${Lp}px`,minWidth:`${Lp}px`},children:[t.jsxs("div",{className:"tf-sidebar-header",children:[t.jsxs("div",{className:"tf-sidebar-title",children:[t.jsx(dg,{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(ji,{size:16})})]}),t.jsxs("div",{className:Ra.weekLabel,children:["Week of ",ye]}),t.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[t.jsxs("div",{className:Ra.calendarHeader,children:[t.jsx("button",{className:"tf-control-icon",onClick:()=>{const D=new Date(U);D.setMonth(U.getMonth()-1),l(`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:t.jsx(Nc,{size:14})}),t.jsx("div",{className:Ra.monthLabel,children:X}),t.jsx("button",{className:"tf-control-icon",onClick:()=>{const D=new Date(U);D.setMonth(U.getMonth()+1),l(`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:t.jsx(ji,{size:14})})]}),t.jsx("div",{className:Ra.weekdayGrid,children:te.map(D=>t.jsx("div",{className:Ra.weekdayLabel,children:D},D))}),t.jsx("div",{className:Ra.calendarGrid,children:Ne.map(D=>{const B=Tc(D),oe=D.getMonth()!==U.getMonth(),xe=Ep(D,$),ie=Tc(xe)===Tc(j),ae=B===s,Ze=B===q,Le=B<q,Ce=pe.get(B),Oe=!!Ce,R=!!Ce?.hasExpired;return t.jsxs("button",{onClick:()=>{r(B),l(`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}`)},className:Ra.calendarDay,style:{"--calendar-day-border":ae?"1px solid #2563eb":Ze?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":ae?"rgba(59,130,246,0.22)":Ze?"rgba(245,158,11,0.16)":ie?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":oe?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":ae||Ze?700:500,"--calendar-day-opacity":Le?.42:1},title:`${Ze?`${B} (Today)`:B}`+(Oe?` • ${Ce?.count} scheduled`:"")+(R?" • includes expired":""),children:[D.getDate(),Oe&&t.jsx("span",{className:Ra.calendarDayDot,style:{"--calendar-dot-background":R?"#ef4444":"#3b82f6","--calendar-dot-opacity":oe?.6:.95}})]},B)})}),t.jsx("div",{className:Ra.jumpRow,children:t.jsx("button",{className:"tf-control-icon",onClick:()=>{const D=new Date;r(Tc(D)),l(`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),t.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${Ra.displaySection}`,children:[t.jsx("div",{className:Ra.sectionTitle,children:"Display"}),t.jsxs("label",{className:Ra.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:i,onChange:D=>p(D.target.checked)}),"Show weekends"]}),t.jsxs("label",{className:Ra.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:h,onChange:D=>w(D.target.checked)}),"Show backlog"]}),t.jsxs("label",{className:Ra.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:b,onChange:D=>_(D.target.checked)}),"Only expired/overdue"]})]}),k>0&&t.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[t.jsx("div",{className:Ra.sectionTitle,children:"Expired Tasks"}),t.jsxs("div",{className:Ra.expiredSummary,children:[t.jsxs("span",{children:[k," expired"]}),t.jsxs("span",{children:[g," overdue"]})]}),t.jsx("button",{className:`tf-control-icon ${Ra.actionButton}`,onClick:S,disabled:Z||C.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",children:Z?"Working...":"Schedule to selected week"}),t.jsx("button",{className:`tf-control-icon ${Ra.actionButton}`,onClick:P,disabled:Z||M.length===0,title:"Unschedule expired/overdue tasks back to backlog",children:Z?"Working...":"Unschedule to backlog"})]})]})}function _h(e,n){return e&&(n==="owner"||n==="admin")}function KE(e,n,s){return _h(e,n)&&s==="team"}const YE=pt.lazy(()=>Mo(()=>import("./TaskSettings-BOC5F6Ag.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.TaskSettings}))),JE=pt.lazy(()=>Mo(()=>import("./AnnotatedAttachmentWorkspace-C_TmXZwA.js"),__vite__mapDeps([7,1,2,3,4,5,8])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),XE=pt.lazy(()=>Mo(()=>import("./DocumentWorkspace-C3GyzrWm.js"),__vite__mapDeps([9,1,2,3,4,5,10])).then(e=>({default:e.DocumentWorkspaceShell}))),QE=pt.lazy(()=>Mo(()=>import("./WorkflowsModule-CGk9s3NJ.js"),__vite__mapDeps([11,1,2,3,4,5])).then(e=>({default:e.WorkflowsModule}))),eL=pt.lazy(()=>Mo(()=>import("./AgentsModule-CpsTmrIW.js"),__vite__mapDeps([12,1,2,3,4,5])).then(e=>({default:e.AgentsModule})));pt.lazy(()=>Mo(()=>import("./InitiativesModule-4-Rh2K2n.js"),__vite__mapDeps([13,1,2,3,4,5])).then(e=>({default:e.InitiativesModule})));const tL=pt.lazy(()=>Mo(()=>import("./PlansPage-BP7AYOqr.js"),__vite__mapDeps([14,1,2,5,3,4,15])).then(e=>({default:e.PlansPage}))),nL="image/png,image/jpeg,image/webp,image/gif",aL=5*1024*1024,sL=e=>e;function Lc(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 rL(e,n,s=15){const r=new Map;for(const[o,l]of e.entries())r.set(Lc(l,o),l);for(const[o,l]of n.entries())r.set(Lc(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 oL(e,n){if(e.length!==n.length)return!1;for(let s=0;s<e.length;s+=1)if(Lc(e[s],s)!==Lc(n[s],s))return!1;return!0}function iL(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 cL(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 lL(e,n){const s=vu(e);if(s)return Sm(s).label.toUpperCase();for(const r of n){const o=String(r||"").trim();if(!o)continue;const l=$p(o);if(l)return Sm(l).label.toUpperCase();let i=o.toLowerCase();try{i=new URL(o.includes("://")?o:`https://${o}`).hostname.toLowerCase()}catch{i=o.toLowerCase()}if(!(i.includes("localhost")||i.includes("127.0.0.1")||i.includes("::1")))return i.toUpperCase()}return"UNKNOWN"}function Ml(){return typeof performance<"u"?performance.now():Date.now()}function dL(e){const r=kf(),o=Sf(),l=a.useMemo(()=>new URLSearchParams(o.search),[o.search]),i=String(l.get("screen")||"").trim().toLowerCase()==="plans",p=a.useCallback(c=>{const f=new URLSearchParams(o.search);f.set("screen","plans");for(const[v,ue]of Object.entries(c||{}))ue==null||String(ue).trim()===""?f.delete(v):f.set(v,String(ue));r(`/?${f.toString()}${o.hash||""}`)},[o.hash,o.search,r]),h=a.useCallback(()=>{const c=new URLSearchParams(o.search);c.delete("screen"),c.delete("gate"),c.delete("checkout"),c.delete("planId"),c.delete("planVersionId"),c.delete("interval");const f=c.toString();r(`${o.pathname==="/"?"/":o.pathname}${f?`?${f}`:""}${o.hash||""}`)},[o.hash,o.pathname,o.search,r]),w=a.useCallback(()=>{h()},[h]),{activeTab:b,setActiveTab:_,activeCategories:k,groupBy:g,setGroupBy:C,activeWorkspaceModule:M,setActiveWorkspaceModule:S,emptyColumnMode:P,setEmptyColumnMode:Z,zenMode:$,setZenMode:ce,filterStatus:q,setFilterStatus:K,tasks:j,handleEdit:ye,handleSubmit:U,resetForm:X,handleUpdateTask:Ne,editingTaskId:pe,loading:te,error:D,title:B,setTitle:oe,description:xe,setDescription:ie,checklistItems:ae,setChecklistItems:Ze,category:Le,setCategory:Ce,type:Oe,setType:R,priority:W,setPriority:F,complexity:V,setComplexity:E,setStatus:y,approach:x,setApproach:H,assignee:I,setAssignee:Ie,scheduledDate:L,setScheduledDate:le,dueDate:ne,setDueDate:de,workstreamInput:G,setWorkstreamInput:ee,manualComplexityEnabled:be,checklistDropdownEnabled:$e,showTaskCardStatusLabel:fe,formTaxonomies:De,setFormTaxonomies:Ke,comments:nt,newCommentText:dt,setNewCommentText:d,attachments:et,setAttachments:gt,setAttachmentsDirty:O,descriptionFocused:Ye,setDescriptionFocused:wt,showMarkdownHelp:St,setShowMarkdownHelp:At,showChecklist:zt,setShowChecklist:Ht,showComments:sn,setShowComments:Jt,handleAddComment:Xt,handleSetWorkstreamForCurrentTask:gn,handleOpenTaskById:Mn,taxonomies:un,activeTypes:yn,priorities:an,taxonomyDisplayLabels:Tn,approaches:Rt,copiedId:we,handleCopyId:Lt,handleToggleInProgress:Qt,handleToggleComplete:Dt,handleToggleReview:He,handleToggleCancel:Nn,handleArchiveTask:Y,handleDelete:Ae,handleUnarchive:_e,handleRestoreDeletedTask:Pe,handlePermanentlyDeleteDeletedTask:qe,handleEmptyDeletedTasks:Je,fetchTasks:at,searchQuery:Xe,setSearchQuery:ct,filterCategories:vt,setFilterCategories:Ot,filterTypes:Pt,setFilterTypes:xt,filterPriorities:Et,setFilterPriorities:xn,filterAssignees:Gt,setFilterAssignees:Jn,assigneeOptions:kn,taskScope:yt,setTaskScope:Gn,sortBy:se,setSortBy:je,clearFilters:Me,settingsModel:Ee,configLoaded:Fe,currentTheme:tt,setCurrentTheme:An,pathSaved:Mt,saveSettings:fa,keyShortcut:Bn,setKeyShortcut:bn,globalWeekStartsOn:fn,locale:rn,jsonBackupEnabled:Kt,setJsonBackupEnabled:kt,mcpHostRoot:$t,setMcpHostRoot:Yt,settingsSection:Sn,setSettingsSection:ft,runtimeMode:mt,workspaceSwitchingEnabled:oa,cloudAuthConfigured:en,authRequiredForApi:tn,authBlocked:It,isAuthenticated:Tt,authUserId:ia,authWorkspaceId:ya,authUserEmail:Ia,authUserDisplayName:ha,authUserAvatarUrl:ka,authSessionResolved:aa,realtimeSyncEnabled:on,realtimeSyncFlagSource:jn,workspaceCloudSyncEnabled:Vn,workspaceSyncPhase:_n,workspaceSyncStatus:$n,workspaceSyncSummary:Wn,workspaceSyncRecommendedAction:vn,workspaceSyncBusy:cn,workspaceSyncPendingChanges:Rn,saveWorkspaceCloudSyncSettings:In,pushNotice:rt,userGlobalSyncStatus:wn,workspaceLastSuccessfulSyncAt:nn,workspaceLastPullAt:Sa,workspaceLastPushAt:Xn,workspaceLastErrorAt:Fa,userGlobalSyncError:Oa,workspaceLastErrorMessage:vs,retryWorkspaceCloudSync:ss,resetWorkspaceSyncCursorAndPull:Ya,getWorkspaceSyncDiagnostics:ca,currentWorkspaceId:ln,currentWorkspaceRole:rr,availableWorkspaces:la,switchWorkspace:va,updateCurrentUserProfile:Un,resolveCloudAuthUrl:wa=sL,logout:Ls,projectRoot:rs,projectName:sa,mcpScriptPath:os,serverHostRoot:ba,showFolderBrowser:is,setShowFolderBrowser:cs,folders:Da,files:Q,currentBrowsePath:Ve,fetchFolders:Vt,browserTarget:bt,setBrowserTarget:dn,handleSelectPath:ot,handleAddPath:da,handleRemovePath:_a,handleUpdateCategory:Zn,handleRemoveCategory:zn,handleSaveCategory:ga,handleUpdateCategoryIcon:qn,handleUpdateCategoryColor:Ja,handleSaveType:Ms,handleRemoveType:Tr,handleUpdateTaxonomies:ls,handleUpdatePriorities:or,pathValidation:ua,exportEnvironment:Qn,setExportEnvironment:Bs,exportWorkflowsPath:oo,setExportWorkflowsPath:Nr,exportResult:Ge,exportingResource:Ut,availableWorkflows:Pa,onExportWorkflows:Ca,fetchWorkflows:ws,availableEnvironments:ir,initiativeTemplates:Bo,fetchInitiativeTemplates:T,createInitiativeFromTemplate:ge,uiNotice:Ue,clearNotice:Re,taskReturnTrail:J,clearReturnToParentTask:Be,returnToPreviousTask:ht,tasksScrollRef:Nt,setTasksScrollPos:ds,commentsEndRef:Kn,autoSaveState:Dn,unsavedModalOpen:Ws,setUnsavedModalOpen:Us,pendingNavigation:zs,handleNavigation:Wo,currentTask:jr,currentTaskWorkstream:Pi,currentTaskInitiative:Fo,scheduleWarningPrompt:cr,confirmScheduleWarning:bu,cancelScheduleWarning:xa}=e,bs=rn||jf();a.useEffect(()=>{const c=String(sa||"").trim();document.title=c?`Taskforce - ${c}`:"Taskforce"},[sa]);const us=()=>{Us(!1),zs?(b==="add"&&X(),zs()):(b==="add"&&X(),_("tasks"))},io=async()=>{await U({preventDefault:()=>{}}),Us(!1),zs&&zs()},[lr,Ei]=a.useState(!1),[_s,Oo]=a.useState(!1),[Rr,co]=a.useState(!0),[$o,lo]=a.useState(!1),[ps,Li]=a.useState(!0),[Dr,Bc]=a.useState(Tc(new Date)),[Pr,Uo]=a.useState(()=>{const c=new Date;return`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}`}),[$a,Mi]=a.useState(0),[dr,Wc]=a.useState(!1),[uo,Ua]=a.useState(!1),[ea,ms]=a.useState(!1),[Hs,po]=a.useState(!1),[zo,Cs]=a.useState(!1),[Er,Ea]=a.useState(!1),[ta,Cn]=a.useState(""),[xs,za]=a.useState(""),[Xa,Xl]=a.useState(new Set),[ur,Fs]=a.useState(null),[Ha,pa]=a.useState(null),[Ho,Gs]=a.useState(null),[pr,fs]=a.useState(null),[As,Lr]=a.useState(""),[mo,mr]=a.useState(""),[Bi,fr]=a.useState(""),[Is,Ta]=a.useState(""),[pn,Pn]=a.useState(()=>su.map(c=>c.value)),[La,hr]=a.useState(()=>ru.map(c=>c.value)),[Go,Yn]=a.useState(null),[_u,Vo]=a.useState(null),[Ma,Vs]=a.useState(null),[Mr,Zo]=a.useState(null),[Cu,Ql]=a.useState(0),[fo,Wi]=a.useState({}),[ed,td]=a.useState(!1),nd=a.useRef(""),Fc=a.useRef(null),ad=a.useRef(null),Oc=a.useRef(new Set),ho=a.useMemo(()=>{const c={},f=String(ln||"").trim();return mt==="cloud"&&f&&f!=="default"&&(c["x-taskforce-workspace-id"]=f),c},[mt,ln]),qo=a.useMemo(()=>`${mt}:${String(ln||"default").trim()||"default"}`,[mt,ln]),Br=a.useMemo(()=>`taskforce:annotate-layout:${qo}`,[qo]),$c=a.useMemo(()=>mt==="cloud"?aa:Fe,[aa,Fe,mt]);a.useEffect(()=>{Fc.current=Ma},[Ma]),a.useEffect(()=>{ad.current=Mr},[Mr]);const Zs=a.useMemo(()=>({[zl]:Ll({featureKey:zl}),[Ul]:Ll({featureKey:Ul}),[gu]:Ll({featureKey:gu}),[yu]:Ll({featureKey:yu}),[Xm]:Ll({featureKey:Xm})}),[mt]),Wr=a.useMemo(()=>NE({featureAccess:Zs}),[Zs]),ma=a.useMemo(()=>Qm(M,Wr),[M,Wr]),Ko=Zs[zl]?.allowed??!1,Uc=Zs[Ul]?.allowed??!1,Fi="Documents is not available in this build yet.",Oi="Annotate is not available in this build yet.";a.useEffect(()=>{const c=f=>{const v=f,ue=v.detail?.fsPath,re=String(v.detail?.assetId||"").trim()||null;if(!(!ue&&!re)){if(v.preventDefault(),!Ko){rt(Fi,"error");return}Yn(ue||null),Vo(re),S("docs")}};return window.addEventListener("taskforce:open-markdown-document",c),()=>{window.removeEventListener("taskforce:open-markdown-document",c)}},[Ko,Fi,rt,S]),a.useEffect(()=>{ma!==M&&S(ma)},[M,ma,S]),a.useEffect(()=>{ma==="docs"&&Ko||(Yn(null),Vo(null))},[Ko,ma]),a.useEffect(()=>{if(!(typeof window>"u"))try{const c=window.sessionStorage.getItem(Br);if(!c)return;const f=JSON.parse(c);f?.annotatedTarget&&typeof f.annotatedTarget=="object"&&Vs(f.annotatedTarget),typeof f?.annotatedSessionId=="string"&&Zo(f.annotatedSessionId.trim()||null)}catch{}},[Br]),a.useEffect(()=>{if(nd.current===qo)return;nd.current=qo,td(!1);let c=!1;return(async()=>{try{const v=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:ho});if(!v.ok)return;const ue=await v.json().catch(()=>({})),re=ue?.state&&typeof ue.state=="object"?ue.state:null;if(!re||c)return;if(typeof re.scheduleShowWeekends=="boolean"&&Oo(re.scheduleShowWeekends),typeof re.scheduleShowBacklog=="boolean"&&co(re.scheduleShowBacklog),typeof re.scheduleOnlyExpired=="boolean"&&lo(re.scheduleOnlyExpired),typeof re.scheduleSidebarOpen=="boolean"&&Li(re.scheduleSidebarOpen),typeof re.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(re.scheduleSelectedDate)&&Bc(re.scheduleSelectedDate),typeof re.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(re.scheduleCalendarMonth)&&Uo(re.scheduleCalendarMonth),typeof re.scheduleScrollLeft=="number"&&Number.isFinite(re.scheduleScrollLeft)&&re.scheduleScrollLeft>=0&&Mi(re.scheduleScrollLeft),typeof re.showFilters=="boolean"&&Wc(re.showFilters),Array.isArray(re.documentTypeFilters)&&Pn(re.documentTypeFilters),Array.isArray(re.documentAttachmentFilters)&&hr(re.documentAttachmentFilters),typeof re.planningDrawerOpen=="boolean"&&ms(re.planningDrawerOpen),typeof re.planningTreeCollapsed=="boolean"&&po(re.planningTreeCollapsed),typeof re.planningPrimaryCollapsed=="boolean"&&Cs(re.planningPrimaryCollapsed),typeof re.planningSecondaryCollapsed=="boolean"&&Ea(re.planningSecondaryCollapsed),Array.isArray(re.planningExpandedInitiativeIds)&&Xl(new Set(re.planningExpandedInitiativeIds.map(Ct=>String(Ct||"").trim()).filter(Boolean))),re.planningDrawerDetail&&typeof re.planningDrawerDetail=="object"&&(re.planningDrawerDetail.type==="initiative"||re.planningDrawerDetail.type==="workstream")&&typeof re.planningDrawerDetail.id=="string"){const Ct=re.planningDrawerDetail.id.trim();Fs(Ct?{type:re.planningDrawerDetail.type,id:Ct}:null)}else re.planningDrawerDetail===null&&Fs(null);typeof re.planningNestedWorkstreamDetailId=="string"?pa(re.planningNestedWorkstreamDetailId.trim()||null):re.planningNestedWorkstreamDetailId===null&&pa(null);const it=re.annotatedTarget;it&&typeof it=="object"&&(Fc.current||Vs(it)),typeof re.annotatedSessionId=="string"&&(ad.current||Zo(re.annotatedSessionId.trim()||null))}catch{}finally{c||td(!0)}})(),()=>{c=!0}},[qo,ho]),a.useEffect(()=>{if(!ed)return;const c=window.setTimeout(async()=>{try{await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json",...ho},credentials:"include",body:JSON.stringify({stateKey:"layout",patch:{scheduleShowWeekends:_s,scheduleShowBacklog:Rr,scheduleOnlyExpired:$o,scheduleSidebarOpen:ps,scheduleSelectedDate:Dr,scheduleCalendarMonth:Pr,scheduleScrollLeft:$a,showFilters:dr,documentTypeFilters:pn,documentAttachmentFilters:La,planningDrawerOpen:ea,planningTreeCollapsed:Hs,planningPrimaryCollapsed:zo,planningSecondaryCollapsed:Er,planningExpandedInitiativeIds:Array.from(Xa),planningDrawerDetail:ur,planningNestedWorkstreamDetailId:Ha,annotatedTarget:Ma,annotatedSessionId:Mr}})})}catch{}},250);return()=>window.clearTimeout(c)},[ed,_s,Rr,$o,ps,Dr,Pr,$a,dr,pn,La,ea,Hs,zo,Er,Xa,ur,Ha,Ma,Mr,ho]),a.useEffect(()=>{if(!(typeof window>"u"))try{window.sessionStorage.setItem(Br,JSON.stringify({annotatedTarget:Ma,annotatedSessionId:Mr}))}catch{}},[Br,Mr,Ma]),a.useEffect(()=>{g==="schedule"&&Li(!0)},[g]);const{showArchive:gr,setShowArchive:$i,fetchArchive:go,filteredArchive:Fr}=e,Or=a.useMemo(()=>Fr.map(c=>({...c,isArchived:!0})),[Fr]),Na=a.useMemo(()=>e.archivedTasks.map(c=>({...c,isArchived:!0})),[e.archivedTasks]),qs=a.useMemo(()=>[...e.searchAgnosticTasks,...Na],[Na,e.searchAgnosticTasks]),sd=a.useCallback(c=>{const f=String(c||"").trim();if(!f)return"";const v=qs.find(ue=>ue.id===f);return Ar(v)||""},[qs]),rd=a.useCallback(c=>{const f=String(c||"").trim();if(!f)return"";const v=String(fo[f]||"").trim();if(v)return v;for(const ue of qs)for(const re of ue.attachments||[]){if(!re||typeof re!="object"||String(re.assetId||"").trim()!==f)continue;const it=nh({referenceNumber:typeof re.referenceNumber=="number"?re.referenceNumber:null,referenceLabel:String(re.referenceLabel||"").trim()||null});if(it)return it}return""},[qs,fo]);a.useEffect(()=>{const c=f=>{const v=f,ue=Mm(v.detail,qs);if(ue){if(v.preventDefault(),!Uc){rt(Oi,"error");return}Vs(ue),Zo(null),Ql(re=>re+1),S("annotate")}};return window.addEventListener("taskforce:open-annotated-attachment",c),()=>{window.removeEventListener("taskforce:open-annotated-attachment",c)}},[qs,Uc,Oi,rt,S]),a.useEffect(()=>{if(!Ma)return;const c=Mm(Ma,qs);c&&(c.taskReferenceLabel===Ma.taskReferenceLabel&&c.imageReferenceLabel===Ma.imageReferenceLabel||Vs(c))},[qs,Ma]),a.useEffect(()=>{const c=Fc.current,f=String(c?.assetId||"").trim();if(!f)return;const v=String(fo[f]||"").trim();v&&v!==String(c?.imageReferenceLabel||"").trim()&&Vs(ue=>!ue||String(ue.assetId||"").trim()!==f?ue:{...ue,imageReferenceLabel:v})},[fo,Ma]),a.useEffect(()=>{if(!$c)return;const f=String(Ma?.assetId||"").trim();if(!f||Oc.current.has(f)||String(fo[f]||"").trim())return;let v=!1;Oc.current.add(f);const ue=String(ln||"default").trim()||"default",re=new URLSearchParams({workspaceId:ue});return(async()=>{try{const Ct=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(f)}?${re.toString()}`,{method:"GET",credentials:"include",headers:ho});if(!Ct.ok)return;const Ln=await Ct.json().catch(()=>({})),mn=String(Ln?.target?.imageReferenceLabel||"").trim();if(!mn||v)return;Wi(nr=>nr[f]===mn?nr:{...nr,[f]:mn})}catch{}finally{Oc.current.delete(f)}})(),()=>{v=!0}},[$c,fo,ln,Ma,ho]);const Ga=a.useMemo(()=>e.deletedTasks.map(c=>({...c.taskSnapshot,isDeleted:!0,deletedRecordId:c.id})),[e.deletedTasks]),Ui=a.useMemo(()=>{const c=new Map;return e.deletedTasks.forEach(f=>{c.set(f.taskSnapshot.id,f)}),c},[e.deletedTasks]),zi=a.useMemo(()=>{const c=Ga,f=Xe.trim().toLowerCase(),v=k.every(mn=>vt.includes(mn.value)),ue=yn.every(mn=>Pt.includes(mn.value)),re=new Set(Et.map(mn=>String(mn))),it=an.every(mn=>re.has(String(mn.value))),Ct=new Set(q.map(mn=>String(mn))),Ln=to.every(mn=>Ct.has(String(mn.value)));return c.filter(mn=>{const nr=(Ar(mn)||mn.id).toLowerCase(),Rl=!f||mn.title.toLowerCase().includes(f)||String(mn.description||"").toLowerCase().includes(f)||mn.id.toLowerCase().includes(f)||nr.includes(f),np=v||vt.includes(mn.category),jt=ue||Pt.includes(mn.type||Ss),Ds=it||re.has(String(mn.priority)),Jr=Ln||Ct.has(String(mn.status)),Ps=Gt.length===0||Gt.includes(mn.assignee||"unassigned");return Rl&&np&&jt&&Ds&&Jr&&Ps})},[k,yn,Ga,Gt,vt,Et,q,Pt,an,Xe]),Yo=a.useMemo(()=>[...e.tasks,...Na,...Ga],[Na,Ga,e.tasks]),zc=a.useMemo(()=>{const c=k.filter(v=>!v.disabled).map(v=>({value:v.value,label:v.label})),f=k.filter(v=>v.disabled&&Yo.some(ue=>ue.category===v.value)).map(v=>({value:v.value,label:`${v.label} (Legacy)`}));return[...c,...f]},[k,Yo]),Hc=a.useMemo(()=>{const c=yn.filter(v=>v.status!=="retired").map(v=>({value:v.value,label:v.label})),f=yn.filter(v=>v.status==="retired"&&Yo.some(ue=>(ue.type||Ss)===v.value)).map(v=>({value:v.value,label:`${v.label} (Retired)`}));return[...c,...f]},[yn,Yo]),$r=a.useMemo(()=>yt==="archived"?Or:yt==="deleted"?zi:gr?[...e.filteredTasks,...Or]:e.filteredTasks,[Or,zi,e.filteredTasks,gr,yt]),Hi=a.useMemo(()=>yt==="open"?e.tasks.filter(c=>!c.isArchived):$r,[$r,e.tasks,yt]),od=a.useMemo(()=>new Set($r.map(c=>c.id)),[$r]),Gi=a.useMemo(()=>yt==="archived"?Na:yt==="deleted"?Ga:gr?[...e.tasks,...Na]:e.tasks,[Na,Ga,e.tasks,gr,yt]),Jo=a.useMemo(()=>{const c=new Map;for(const f of Na)c.set(f.id,f);for(const f of Ga)c.set(f.id,f);for(const f of e.tasks)c.set(f.id,f);return Array.from(c.values())},[Na,Ga,e.tasks]),yo=a.useMemo(()=>{const c=new Map;return Jo.forEach(f=>c.set(f.id,f)),c},[Jo]),Vi=a.useMemo(()=>{const c=new Map;return kn.forEach(f=>{c.set(String(f.value),f.label)}),c},[kn]),lt=a.useMemo(()=>{const c=yt==="archived"?Na:yt==="deleted"?Ga:e.tasks.filter(jt=>!jt.isArchived),f=jt=>{const Ds=jt.length,Jr=jt.filter(Ps=>Ps.isArchived||Ps.status==="done"||Ps.status==="cancelled").length;return{progressPercent:Ds>0?Math.round(Jr/Ds*100):0,taskCount:Ds,completedTaskCount:Jr}},v=new Map,ue=new Map,re=new Map,it=new Map,Ct=new Map,Ln=jt=>{const Ds=c.filter(ja=>(ja.workstreamId||null)===jt.id),Jr=Ds.map(ja=>({id:ja.id,referenceNumber:ja.referenceNumber??null,title:ja.title,status:ja.status||null})),Ps={id:jt.id,referenceNumber:jt.referenceNumber??null,title:jt.title,description:String(jt.description||"").trim()||void 0,ownerLabel:jt.ownerId?Vi.get(String(jt.ownerId))||String(jt.ownerId):null,...f(Ds),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,Ds.map(ja=>ja.id)),jt.initiativeId&&ue.set(jt.id,jt.initiativeId),it.set(Ps.id,Ps),Ps},mn=e.workstreams.map(Ln),nr=e.initiatives.map(jt=>{const Ds=mn.filter(ja=>(ja.initiativeId||null)===jt.id),Jr=Ds.flatMap(ja=>v.get(ja.id)||[]).map(ja=>yo.get(ja)).filter(ja=>!!ja),Ps={id:jt.id,referenceNumber:jt.referenceNumber??null,title:jt.title,description:String(jt.description||"").trim()||void 0,ownerLabel:jt.ownerId?Vi.get(String(jt.ownerId))||String(jt.ownerId):null,...f(Jr),workstreamCount:Ds.length,workstreams:Ds,commentCount:Array.isArray(jt.comments)?jt.comments.length:0,attachmentCount:Array.isArray(jt.attachments)?jt.attachments.length:0,isArchived:!!jt.isArchived};return re.set(jt.id,Jr.map(ja=>ja.id)),Ct.set(Ps.id,Ps),Ps}),Rl=yt==="deleted"?[]:nr.filter(jt=>yt==="archived"?!!jt.isArchived:!jt.isArchived),np=mn.filter(jt=>!jt.initiativeId).filter(jt=>yt==="deleted"?!1:yt==="archived"?!!jt.isArchived:!jt.isArchived);return{initiatives:Rl,standaloneWorkstreams:np,workstreamTaskIds:v,workstreamInitiativeIds:ue,initiativeTaskIds:re,workstreamById:it,initiativeById:Ct}},[Na,Vi,Ga,yo,e.initiatives,e.tasks,e.workstreams,yt]),Gc=a.useMemo(()=>lt.initiatives.map(c=>{const f=ar(c);return{value:c.id,label:f?`${f} - ${c.title}`:c.title,selectedLabel:f||c.title}}),[lt.initiatives]),Zi=a.useMemo(()=>[...lt.initiatives.flatMap(c=>c.workstreams.map(f=>{const v=eo(f);return{value:f.id,label:v?`${v} - ${f.title}`:f.title,selectedLabel:v||f.title}})),...lt.standaloneWorkstreams.map(c=>{const f=eo(c);return{value:c.id,label:f?`${f} - ${c.title}`:c.title,selectedLabel:f||c.title}})],[lt.initiatives,lt.standaloneWorkstreams]),Ks=a.useMemo(()=>xs?new Set(lt.workstreamTaskIds.get(xs)||[]):ta?new Set(lt.initiativeTaskIds.get(ta)||[]):null,[lt.initiativeTaskIds,lt.workstreamTaskIds,ta,xs]),qi=a.useMemo(()=>{if(!ur)return null;if(ur.type==="initiative"){const f=lt.initiativeById.get(ur.id);return f?{type:"initiative",item:f}:null}const c=lt.workstreamById.get(ur.id)||lt.standaloneWorkstreams.find(f=>f.id===ur.id);return c?{type:"workstream",item:c}:null},[ur,lt.initiativeById,lt.standaloneWorkstreams,lt.workstreamById]),Ki=a.useMemo(()=>{if(!Ha)return null;const c=lt.workstreamById.get(Ha)||lt.standaloneWorkstreams.find(f=>f.id===Ha);return c?{type:"workstream",item:c}:null},[Ha,lt.standaloneWorkstreams,lt.workstreamById]),Yi=a.useMemo(()=>pr?{kind:"editor",editor:pr}:Ki?{kind:"detail",detail:Ki}:null,[Ki,pr]),Vc=wh(Hs,!!(qi||Ho),zo,!!Yi,Er),id=a.useMemo(()=>{if(!Is.trim())return null;const c=lt.initiativeById.get(Is);return c||dp(lt.initiatives,Is)},[Is,lt.initiativeById,lt.initiatives]);a.useEffect(()=>{ta&&!lt.initiativeById.has(ta)&&Cn(""),xs&&!lt.workstreamById.has(xs)&&za("")},[lt.initiativeById,lt.workstreamById,ta,xs]);const Qa=a.useMemo(()=>g==="schedule"?Hi:$r,[g,$r,Hi]),ra=a.useMemo(()=>{const c=new Date,f=c.getFullYear(),v=String(c.getMonth()+1).padStart(2,"0"),ue=String(c.getDate()).padStart(2,"0");return`${f}-${v}-${ue}`},[]),Xo=a.useMemo(()=>g!=="schedule"||!$o?Qa:Qa.filter(c=>{if(c.status==="done"||c.status==="cancelled")return!1;const v=!!c.scheduledDate&&c.scheduledDate<ra,ue=!!c.dueDate&&c.dueDate<ra;return v||ue}),[g,$o,Qa,ra]),xu=a.useMemo(()=>!Ks||Ks.size===0?Xo:Xo.filter(c=>Ks.has(c.id)),[Xo,Ks]),Zc=a.useMemo(()=>!Ks||Ks.size===0?Gi:Gi.filter(c=>Ks.has(c.id)),[Gi,Ks]),Ur=a.useMemo(()=>g!=="schedule"?[]:Qa.filter(c=>{if(c.status==="done"||c.status==="cancelled")return!1;const v=!!c.scheduledDate&&c.scheduledDate<ra,ue=!!c.dueDate&&c.dueDate<ra;return v||ue}),[g,Qa,ra]),Qo=a.useMemo(()=>g!=="schedule"?0:Qa.filter(c=>c.status==="done"||c.status==="cancelled"?!1:!!c.scheduledDate&&c.scheduledDate<ra).length,[g,Qa,ra]),cd=a.useMemo(()=>g!=="schedule"?0:Qa.filter(c=>c.status==="done"||c.status==="cancelled"?!1:!!c.dueDate&&c.dueDate<ra).length,[g,Qa,ra]),hs=String(ia||"").trim(),ld=a.useMemo(()=>!hs||hs==="anonymous"?0:j.filter(c=>c.status==="done"||c.status==="cancelled"?!1:String(c.assignee||"").trim()===hs).length,[hs,j]),ei=a.useMemo(()=>!hs||hs==="anonymous"?0:j.filter(c=>c.status==="done"||c.status==="cancelled"||String(c.assignee||"").trim()!==hs?!1:!!c.dueDate&&c.dueDate<ra).length,[hs,j,ra]),Ji=a.useMemo(()=>g!=="schedule"?[]:Qa.filter(c=>c.status==="done"||c.status==="cancelled"?!1:!!c.scheduledDate&&c.scheduledDate<ra),[g,Qa,ra]),ko=Ur,[So,vo]=a.useState(!1),qc=()=>{Wo(()=>{ht()||(b==="add"&&J.length>0&&Be(),Ua(!1),b==="add"&&X(),_("tasks"))})};a.useEffect(()=>{b!=="add"&&Ua(!1)},[b]);const ti=a.useCallback((c,f)=>{if(c.status!==f){if(f==="in-progress"){Qt(c);return}if(f==="review"){He(c);return}if(f==="done"){Dt(c);return}if(f==="cancelled"){Nn(c);return}Ne(c.id,{status:f,completedAt:null})}},[Qt,He,Dt,Nn,Ne]),dd=a.useCallback((c,f)=>{X();const v=KD(c,f,{categories:k,approaches:Rt});v.category&&Ce(v.category),v.type&&R(v.type),typeof v.priority=="number"&&F(v.priority),typeof v.complexity=="number"&&E(v.complexity),v.approach&&H(v.approach);const ue=v.taxonomyApproach;typeof ue=="string"&&ue.length>0&&Ke(re=>({...re,approach:ue})),v.assignee&&Ie(v.assignee),v.status&&y(v.status),v.scheduledDate&&le(v.scheduledDate),_("add")},[X,k,Rt,Ce,R,F,E,y,H,Ie,le,Ke,_]);pt.useEffect(()=>{q&&!q.includes("done")&&K(c=>[...c,"done"])},[]);const[Kc,ni]=a.useState(!1),[Ys,es]=a.useState(!1),[zr,wo]=a.useState(!1),[Xi,Qi]=a.useState(!1),[ai,ec]=a.useState(!1),[Yc,Jc]=a.useState(!1),[ud,tc]=a.useState(null),[yr,nc]=a.useState(!1),[ac,pd]=a.useState(!1),[Au,Xc]=a.useState(!1),[Va,md]=a.useState([]),[fd,hd]=a.useState(!1),[si,sc]=a.useState(null),Qc=a.useRef(null),el=a.useRef(null),[rc,gd]=a.useState(!1),[yd,tl]=a.useState(""),[nl,oc]=a.useState(!1),[kd,ic]=a.useState(!1),[cc,Za]=a.useState("members"),[ts,lc]=a.useState(null),[al,dc]=a.useState("unknown"),[Sd,Hr]=a.useState(!1),[uc,kr]=a.useState(null),[pc,Ba]=a.useState(null),[ri,oi]=a.useState(!1),[ii,Gr]=a.useState([]),[Sr,sl]=a.useState(null),[ci,rl]=a.useState(""),[mc,Iu]=a.useState("member"),[ol,Tu]=a.useState("read-write"),[Nu,il]=a.useState(!1),[ju,cl]=a.useState(null),[bo,Ru]=a.useState(0),[ll,_o]=a.useState(!1),[vd,wd]=a.useState([]),[Vr,li]=a.useState(!1),[na,di]=a.useState(1),[Fn,Co]=a.useState(null),[bd,vr]=a.useState(!1),[Ts,dl]=a.useState(null),[Du,ui]=a.useState(!1),[Pu,Js]=a.useState(null),[Eu,ul]=a.useState(null),[pi,Lu]=a.useState("month"),[pl,_d]=a.useState(""),[ml,xo]=a.useState(""),[ns,Ao]=a.useState(null),[Mu,fl]=a.useState(!1),[Bu,hl]=a.useState(!1),[Wu,Ns]=a.useState(null),[Fu,js]=a.useState(null),Cd=25,xd=a.useRef(null),mi=a.useRef(null),wr=a.useRef(null),fc=a.useRef({billing:!1,teamManagement:!1}),hc=a.useRef(null);a.useEffect(()=>{hc.current=Fn},[Fn]),a.useEffect(()=>{if(!Ys)return;const c=f=>{xd.current?.contains(f.target)||es(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[Ys]);const gl=mt==="cloud"&&oa&&Tt,br=Tt&&(mt==="cloud"||en),fi=mt==="local"&&Tt,Ad=a.useCallback(async c=>{if(!fi)return;tc(null),Jc(!0);const f=await In({enabled:c});f.success||tc(f.error||(c?"Failed to enable sync.":"Failed to disable sync.")),Jc(!1)},[fi,In]),Id=Yc,gc=a.useMemo(()=>{const c=la.find(ue=>ue.id===ln),f=String(c?.name||"").trim();if(f)return f;if(mt==="local"){const ue=String(sa||"").trim();if(ue)return ue}return String(ln||"").trim()||"Workspace"},[la,ln,sa,mt]),yc=_h(br,ts),Zr=KE(br,ts,al),hi=String(ha||"").trim(),gs=String(ka||"").trim(),Io=String(Ia||"").trim(),gi=hi||Io,yl=gi.length>0,Td=Io.length>0,kl=(gi||Io||"").trim(),Sl=Tt&&aa&&kl.length>0?kl.charAt(0).toUpperCase():"",vl=gs,Nd=Tt&&aa&&vl.length>0,jd=String(ml||gs).trim(),kc=String(Fn?.planName||Fn?.planId||"").trim(),Rd=kc.length>0,Xs=String(Fn?.workspaceId||ya||ln||"").trim(),$u=mt==="cloud"?"CLOUD":"LOCAL",Dd=e.config?.apiBaseUrl||"",Pd=a.useMemo(()=>lL(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]),To=en&&!aa;a.useEffect(()=>{Xi&&(_d(hi),xo(gs),Ao(null),Ns(null),js(null))},[gs,hi,Xi]);const Qs=a.useCallback(async c=>{const f=String(c||"").trim();if(!(!f||!en))try{const v=mt==="local"?e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"":e.config?.apiBaseUrl||e.config?.cloudAuthBaseUrl||"";await cp("/api/taskforce/auth/profile/avatar/discard",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:f})},v)}catch{}},[en,e.config?.apiBaseUrl,e.config?.cloudAuthBaseUrl,mt]),Uu=a.useCallback(()=>{const c=ns;Qi(!1),Ns(null),js(null),Ao(null),xo(gs),c&&Qs(c)},[gs,Qs,ns]),zu=a.useCallback(async c=>{if(!(!c||!en)){if(!c.type.startsWith("image/")){Ns("Profile photo must be an image file."),js(null);return}if(c.size>aL){Ns("Profile photo must be 5 MB or smaller."),js(null);return}fl(!0),Ns(null),js(null);try{const f=mt==="local"?e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"":e.config?.apiBaseUrl||e.config?.cloudAuthBaseUrl||"",v=await cp("/api/taskforce/auth/profile/avatar/init",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:c.name,mimeType:c.type,size:c.size})},f),ue=await v.json().catch(()=>({}));if(!v.ok||!ue?.success||typeof ue?.uploadUrl!="string"||typeof ue?.relativePath!="string")throw new Error(ue?.error||"Failed to start avatar upload.");if(!(await fetch(ue.uploadUrl,{method:String(ue.method||"PUT"),headers:ue.headers||{"Content-Type":c.type||"application/octet-stream"},body:c})).ok)throw new Error("Failed to upload avatar.");const it=await cp("/api/taskforce/auth/profile/avatar/finalize",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:ue.draftId,relativePath:ue.relativePath})},f),Ct=await it.json().catch(()=>({}));if(!it.ok||!Ct?.success||typeof Ct?.draftId!="string")throw new Error(Ct?.error||"Failed to finalize avatar upload.");const Ln=ns;Ao(Ct.draftId),xo(typeof Ct?.avatarUrl=="string"?Ct.avatarUrl:""),js("Profile photo ready to save."),Ln&&Ln!==Ct.draftId&&Qs(Ln)}catch(f){Ns(f instanceof Error?f.message:"Failed to upload profile photo.")}finally{fl(!1),mi.current&&(mi.current.value="")}}},[en,Qs,ns,e.config?.apiBaseUrl,e.config?.cloudAuthBaseUrl,mt]),wl=a.useCallback(()=>{if(!ns)return;const c=ns;Ao(null),xo(gs),js(null),Ns(null),Qs(c)},[gs,Qs,ns]),Ed=a.useCallback(()=>{const c=ns;Ao(null),xo(""),js(gs?"Profile photo will be removed when you save.":null),Ns(null),c&&Qs(c)},[gs,Qs,ns]),Ld=a.useCallback(async()=>{const c=pl.trim();if(!c){Ns("Display name is required."),js(null);return}hl(!0),Ns(null),js(null);const f=await Un({displayName:c,avatarDraftId:ns,clearAvatar:!ns&&!ml&&!!gs});if(!f.success){Ns(f.error||"Failed to update profile."),hl(!1);return}js("Profile updated."),Ao(null),xo(""),hl(!1),Qi(!1)},[gs,ns,ml,pl,Un]),Rs=a.useCallback(()=>{const c={},f=String(Xs||"").trim();f&&(c["x-taskforce-workspace-id"]=f);const v=ts||rr;return(v==="owner"||v==="admin"||v==="member"||v==="read-only")&&(c["x-taskforce-workspace-role"]=v),c},[rr,Xs,ts]),Md=a.useCallback(c=>{const f=Tt,v=br;wr.current=Ml(),fc.current={billing:f,teamManagement:v},Hn("account_surface_opened",{surface:c,expectsBilling:f,expectsTeamManagement:v}),!f&&!v&&(Hn("account_surface_ready",{surface:c,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),wr.current=null)},[br,Tt]),yi=a.useCallback(c=>{const f=fc.current;if(f[c]=!1,f.billing||f.teamManagement)return;const v=wr.current;v!==null&&(Hn("account_surface_ready",{surface:zr?"account_hub":Ys?"account_menu":"closed",durationMs:Math.round(Ml()-v),teamManagementVisible:Zr,billingPlanId:String(Fn?.planId||"").trim()||null}),wr.current=null)},[Fn?.planId,Zr,zr,Ys]),er=a.useCallback(async()=>{const c=wa(Gm);if(!Tt)return Co(null),dl(null),lc(null),dc("unknown"),Hr(!1),kr(null),Vm(c,{identityKey:ia}),yi("billing"),yi("teamManagement"),null;const f=Ml();vr(!0),dl(null),Hr(br),kr(null);try{const v=await XD(c,{identityKey:ia}),ue=v?.workspaceRole==="owner"||v?.workspaceRole==="admin"||v?.workspaceRole==="member"||v?.workspaceRole==="read-only"?v.workspaceRole:null,re=v?.teamPlanMode==="team"||v?.teamPlanMode==="personal"?v.teamPlanMode:"unknown";return Co(v),lc(ue),dc(re),kr(null),Hn("account_profile_summary_resolved",{durationMs:Math.round(Ml()-f),planId:String(v?.planId||"").trim()||null,gate:String(v?.gate||"").trim()||null,teamManagementAllowed:v?.teamManagementAllowed===!0}),v}catch(v){const ue=v instanceof Error?v.message:"Failed to load account summary.",re=!!hc.current;return dl(ue),re?kr(null):(lc(null),dc("unknown"),kr(ue)),Hn("account_profile_summary_failed",{durationMs:Math.round(Ml()-f),error:ue,preservedSummary:re}),hc.current}finally{vr(!1),Hr(!1),yi("billing"),yi("teamManagement")}},[ia,br,Tt,yi,wa]),bl=a.useCallback(async()=>{const c=new URLSearchParams;c.set("screen","plans"),c.set("interval",pi);const f=String(Fn?.planId||"").trim(),v=String(Fn?.planVersionId||"").trim();f&&c.set("planId",f),v&&c.set("planVersionId",v),r(`/?${c.toString()}`)},[Fn?.planId,Fn?.planVersionId,pi,r]),_l=a.useCallback(async()=>{Js(null),ul(null),ui(!0);try{const c=await fetch(wa("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),f=await c.json().catch(()=>({}));if(!c.ok){Js(String(f?.error||"Failed to create portal session."));return}const v=String(f?.url||"").trim();if(!v){Js("Portal session did not return a redirect URL.");return}window.location.assign(v)}catch{Js("Failed to open billing portal.")}finally{ui(!1)}},[wa]),Cl=a.useCallback(async()=>{Js(null),ul(null),ui(!0);try{const c=String(Fn?.planVersionId||"").trim();if(!c){Js("No active plan version is linked to this account.");return}const f=await fetch(wa("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:c,interval:pi})}),v=await f.json().catch(()=>({}));if(!f.ok){Js(String(v?.error||"Failed to update subscription interval."));return}ul("Subscription updated."),Vm(wa(Gm),{identityKey:ia}),await er()}catch{Js("Failed to update subscription interval.")}finally{ui(!1)}},[Fn?.planVersionId,ia,pi,er,wa]);a.useEffect(()=>{!Tt||!aa||er()},[aa,Tt,er]),a.useEffect(()=>{!zr&&!Ys||er()},[er,zr,Ys]);const qr=a.useCallback(async()=>{if(yc){oi(!0),Ba(null);try{const c=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:Rs()}),f=await c.json().catch(()=>({}));if(!c.ok){Ba(f?.error||"Failed to load workspace users.");return}const v=Array.isArray(f?.users)?f.users:[],ue={owner:0,admin:1,member:2,"read-only":3},re=v.map(it=>({userId:String(it?.userId||""),email:String(it?.email||""),displayName:typeof it?.displayName=="string"?it.displayName:null,role:it?.role==="owner"||it?.role==="admin"||it?.role==="member"||it?.role==="read-only"?it.role:"member",permissionMode:it?.permissionMode==="read-only"?"read-only":"read-write",status:String(it?.status||"active"),disabled:it?.disabled===!0}));re.sort((it,Ct)=>{const Ln=(ue[it.role]??99)-(ue[Ct.role]??99);return Ln!==0?Ln:(it.displayName||it.email).localeCompare(Ct.displayName||Ct.email,void 0,{sensitivity:"base"})}),Gr(re)}catch{Ba("Failed to load workspace users.")}finally{oi(!1)}}},[yc,Rs]),tr=a.useCallback(async c=>{if(!yc)return;const f=Math.max(0,Math.floor(c));_o(!0),Ba(null);try{const v=f*Cd,ue=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${Cd}&offset=${v}`,{method:"GET",credentials:"include",headers:Rs()}),re=await ue.json().catch(()=>({}));if(!ue.ok){Ba(re?.error||"Failed to load workspace audit log.");return}const it=Array.isArray(re?.events)?re.events:[];wd(it.map(Ln=>({id:String(Ln?.id||""),action:String(Ln?.action||""),actorUserId:String(Ln?.actorUserId||""),actorRole:String(Ln?.actorRole||""),createdAt:String(Ln?.createdAt||Ln?.ts||"")}))),Ru(f);const Ct=Math.max(1,Number(re?.pages||1));di(Ct),li(f+1<Ct)}catch{Ba("Failed to load workspace audit log.")}finally{_o(!1)}},[yc,Rs]),No=a.useCallback(async()=>{await Promise.all([qr(),tr(bo)])},[qr,tr,bo]),Sc=a.useCallback((c="login")=>{const f=`${o.pathname}${o.search}${o.hash}`,v=!f||f==="/login"||!f.startsWith("/")?"/":f;es(!1),wo(!1),ec(!1),r(`/login?mode=${c}&next=${encodeURIComponent(v)}`)},[o.hash,o.pathname,o.search,r]),xl=a.useCallback(c=>{es(!1),oc(!1);const f=new URLSearchParams({step:"workspace"});c?.intent==="create-workspace"&&f.set("intent","create-workspace"),r(`/setup?${f.toString()}`,{replace:!0})},[r]),Hu=a.useCallback(async c=>{if(!(!c||rc)){tl(""),gd(!0);try{const f=await va(c);if(!f.success){if(f.code==="WORKSPACE_NOT_FOUND"||f.code==="WORKSPACE_ID_REQUIRED"){xl();return}tl(f.error||"Failed to switch workspace.");return}await at(!0),es(!1)}finally{gd(!1)}}},[va,rc,at,xl]),Bd=a.useCallback(async()=>{es(!1),ic(!0),Za("members"),((await er())?.teamManagementAllowed??Zr)&&(await qr(),await tr(0))},[Zr,er,tr,qr]),ki=a.useCallback(async(c,f)=>{Ba(null),sl(c);try{const v=await f(),ue=await v.json().catch(()=>({}));if(!v.ok){Ba(ue?.error||"Team management action failed.");return}await No()}catch{Ba("Team management action failed.")}finally{sl(null)}},[No]),Gu=a.useCallback(async()=>{const c=ci.trim();if(c){il(!0),Ba(null),cl(null);try{const f=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...Rs()},credentials:"include",body:JSON.stringify({workspaceId:Xs,email:c,role:mc,permissionMode:mc==="member"?ol:"read-write"})}),v=await f.json().catch(()=>({}));if(!f.ok){Ba(v?.error||"Failed to send invite.");return}rl(""),v?.inviteEmailSent===!1?cl(`Invite created, but email delivery failed${v?.inviteEmailError?`: ${String(v.inviteEmailError)}`:"."}`):cl("Invite sent."),await No()}catch{Ba("Failed to send invite.")}finally{il(!1)}}},[ln,No,Rs,ci,ol,mc]),Al=a.useMemo(()=>Xe.trim().length>0,[Xe]),Wd=a.useMemo(()=>ii.filter(c=>c.status==="invited"),[ii]),Il=a.useMemo(()=>{const c=vt.length!==k.length,f=Pt.length!==yn.length,v=Et.length!==an.length,ue=q.length!==to.length,re=Gt.length!==kn.length,it=ta.length>0,Ct=xs.length>0;return c||f||v||ue||re||it||Ct},[k.length,yn.length,kn.length,Gt.length,vt.length,Et.length,q.length,Pt.length,an.length,ta,xs]),Tl=a.useMemo(()=>pn.length!==su.length||La.length!==ru.length,[La.length,pn.length]),Fd=ma,Os=a.useMemo(()=>jE(Fd),[Fd]),Od=a.useMemo(()=>{switch(Os.filterBar.kind){case"task-filters":return Il;case"document-filters":return Tl;default:return!1}},[Tl,Il,Os.filterBar.kind]),$d=Al||Il,Ud=yt==="archived"?Na.length:yt==="deleted"?Ga.length:j.length,Vu=yt==="archived"?Or.length:yt==="deleted"?zi.length:e.filteredTasks.length,Zu=$d?`${Vu}/${Ud}`:`${Ud}`,qu=$d?`${yt.charAt(0).toUpperCase()+yt.slice(1)} tasks matching current filters`:`${yt.charAt(0).toUpperCase()+yt.slice(1)} tasks`,Ku=mt==="local"&&Tt,jo=a.useCallback(c=>{if(!c)return"Never";const f=new Date(c);return Number.isNaN(f.getTime())?"Never":f.toLocaleString()},[]),vc=a.useMemo(()=>jo(nn),[jo,nn]),Nl=a.useMemo(()=>jo(Sa),[jo,Sa]),zd=a.useMemo(()=>jo(Xn),[jo,Xn]),m=ud||vs||Oa||"None",A=a.useMemo(()=>YD({runtimeMode:mt,isAuthenticated:Tt,workspaceSyncStatus:$n,workspaceCloudSyncEnabled:Vn,workspaceSyncSummary:Wn,workspaceSyncRecommendedAction:vn,workspaceSyncError:m}),[mt,Tt,$n,Vn,Wn,vn,m]),N=A.lastError,[z,ke]=a.useState(A.status),me=a.useMemo(()=>{if(yr)return"Repairing";if(cn&&_n==="error")return"Recovering";switch(_n){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"}},[_n,yr]),Se=ca(),_t=a.useMemo(()=>[{label:"AI profile snapshot",value:`${Se.aiProfileSnapshotCount} local profile${Se.aiProfileSnapshotCount===1?"":"s"}`},{label:"AI profile raw response",value:`${Se.aiProfileSnapshotRawCount} from route`},{label:"Last pushed AI profiles",value:`${Se.lastPushedAiProfileCount} tracked`},{label:"AI watermark map",value:`${Se.lastPushedAiProfileWatermarkCount} tracked`},{label:"Document snapshot",value:`${Se.documentSnapshotCount} local doc${Se.documentSnapshotCount===1?"":"s"}`},{label:"Asset snapshot",value:`${Se.assetSnapshotCount} local asset${Se.assetSnapshotCount===1?"":"s"}`},{label:"Queued full AI sync",value:Se.forceFullAiProfilePushQueued?"Yes":"No"},{label:"AI snapshot last fetch",value:Se.aiProfileSnapshotLastFetchAt?new Date(Se.aiProfileSnapshotLastFetchAt).toLocaleString():"Never"},{label:"AI snapshot fetch error",value:Se.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:Se.aiProfileSnapshotLastSkipReason||"None"}],[Se]),Ft=A.actionable&&$n==="syncing"&&_n==="active"&&Rn===0;a.useEffect(()=>{if(!Ft){ke(A.status);return}const c=window.setTimeout(()=>{ke(A.status)},1200);return()=>window.clearTimeout(c)},[A.status,Ft]);const Wt=a.useCallback(c=>{const f=typeof c.occurredAt=="string"&&c.occurredAt.trim().length>0?c.occurredAt:"unknown-time",v=typeof c.eventType=="string"&&c.eventType.trim().length>0?c.eventType.trim():"sync",ue=c.status==="error"?"failed":"succeeded",re=Number(c.changeCount),it=Number.isFinite(re)?` (${Math.max(0,Math.floor(re))} change${Math.floor(re)===1?"":"s"})`:"",Ct=Number(c.requestMs),Ln=Number.isFinite(Ct)?` in ${Math.max(0,Math.floor(Ct))}ms`:"",mn=Number(c.statusCode),nr=Number.isFinite(mn)?` [${Math.floor(mn)}]`:"",Rl=typeof c.errorMessage=="string"&&c.errorMessage.trim().length>0?`: ${c.errorMessage.trim()}`:"";return`${f} ${v} ${ue}${it}${Ln}${nr}${Rl}`},[]),Bt=a.useMemo(()=>fd&&Va.length===0?[{key:"loading",text:"Loading recent sync events...",tone:"muted"}]:si?[{key:"error",text:si,tone:"error"}]:Va.length===0?[{key:"empty",text:"No recent sync events recorded.",tone:"muted"}]:Va.map((c,f)=>({key:Lc(c,f),text:Wt(c),tone:c.status==="error"?"error":"default"})),[Wt,Va,si,fd]),Zt=a.useMemo(()=>iL(Va),[Va]),ys=a.useMemo(()=>cL(Va),[Va]),Kr=a.useMemo(()=>ys.map((c,f)=>{const v=c.details&&typeof c.details=="object"?c.details:null,ue=String(v?.path||"").trim(),re=String(v?.referenceLabel||"").trim(),it=String(v?.taskTitle||v?.existingTaskTitle||"").trim(),Ct=Number(v?.existingReferenceNumber),Ln=Number(v?.incomingReferenceNumber),mn=ue||it||re||`Mismatch ${f+1}`,nr=Number.isFinite(Ct)||Number.isFinite(Ln)?`Existing ${Number.isFinite(Ct)?Ct:"?"} vs incoming ${Number.isFinite(Ln)?Ln:"?"}`:re?`Both claimed ${re}`:null;return{key:Lc(c,f),pathLabel:mn,refsLabel:nr}}),[ys]);a.useLayoutEffect(()=>{const c=el.current,f=Qc.current;if(!c||!f)return;const v=f.scrollHeight-c.scrollHeight;f.scrollTop=c.scrollTop+Math.max(0,v),el.current=null},[Va]);const qa=a.useCallback(async()=>{const c=await fetch(`/api/taskforce/sync/events?workspace_id=${encodeURIComponent(ln)}&limit=15`,{method:"GET",credentials:"include"});if(!c.ok)throw new Error(`Failed to load sync events (${c.status})`);const f=await c.json().catch(()=>({}));return Array.isArray(f?.events)?f.events.filter(v=>v&&typeof v=="object"):[]},[ln]);a.useEffect(()=>{if(!ai)return;let c=!1;const f=Va.length===0;return f&&hd(!0),qa().then(v=>{if(c)return;const ue=Qc.current;el.current=ue&&ue.scrollTop>8?{scrollTop:ue.scrollTop,scrollHeight:ue.scrollHeight}:null,md(re=>{const it=re.length===0?v:rL(re,v,15);return oL(re,it)?re:it}),sc(null)}).catch(v=>{if(c)return;const ue=v instanceof Error&&v.message.trim().length>0?v.message.trim():"Unable to load recent sync events.";sc(ue),f&&md([])}).finally(()=>{c||f&&hd(!1)}),()=>{c=!0}},[ai,qa,Va.length,Xn,Sa,Fa,$n]);const as=a.useMemo(()=>{switch(z){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)"}}},[z]),En=a.useCallback(async()=>{const c=["Taskforce Sync Manager",`Workspace ID: ${ln}`,`Status: ${as.label}`,`Summary: ${A.summary}`,`Last successful sync: ${vc}`,`Last pull from cloud: ${Nl}`,`Last push to cloud: ${zd}`,`Last error at: ${Se.lastErrorAt?new Date(Se.lastErrorAt).toLocaleString():"Never"}`,`Pending local changes: ${Rn}`,`Last error: ${N}`,`Sync stage: ${me}`,`AI profile snapshot: ${Se.aiProfileSnapshotCount}`,`AI profile raw response: ${Se.aiProfileSnapshotRawCount}`,`Last pushed AI profiles tracked: ${Se.lastPushedAiProfileCount}`,`AI profile watermarks tracked: ${Se.lastPushedAiProfileWatermarkCount}`,`AI snapshot last fetch: ${Se.aiProfileSnapshotLastFetchAt?new Date(Se.aiProfileSnapshotLastFetchAt).toLocaleString():"Never"}`,`AI snapshot fetch error: ${Se.aiProfileSnapshotLastFetchError||"None"}`,`AI snapshot skip reason: ${Se.aiProfileSnapshotLastSkipReason||"None"}`,`Document snapshot: ${Se.documentSnapshotCount}`,`Asset snapshot: ${Se.assetSnapshotCount}`,`Reference mismatches detected: ${Zt}`,`Queued full AI sync: ${Se.forceFullAiProfilePushQueued?"Yes":"No"}`];try{const v=(Va.length>0?Va:await qa()).map(re=>Wt(re)),ue=[...c,"","Recent sync events",...v.length>0?v:["No recent sync events recorded."]].join(`
|
|
6
|
+
`);await navigator.clipboard.writeText(ue),Xc(!0),window.setTimeout(()=>{Xc(!1)},1800),rt("Sync details copied to clipboard.","success")}catch{Xc(!1),rt("Failed to copy sync details.","error")}},[ln,as.label,A.summary,vc,Nl,zd,Se,Rn,N,me,Zt,rt,Va,qa,Wt]),Ro=a.useCallback(async()=>{pd(!1),nc(!0);try{await Ya()}finally{nc(!1)}},[Ya]),wc=a.useCallback(()=>{if(!yr){if(cn){pd(!0);return}Ro()}},[Ro,cn,yr]);a.useEffect(()=>{ac&&(cn||yr||Ro())},[Ro,cn,yr,ac]);const Hd=a.useMemo(()=>Fl(Dr)||new Date,[Dr]),_r=a.useMemo(()=>Ep(Hd,fn),[Hd,fn]),Yr=a.useMemo(()=>{const c={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return ef.forEach(f=>{const v=VE(f,fn);c[f]=Tc(bh(_r,v))}),c},[_r,fn]),Yp=a.useCallback(c=>{const f=Fl(c);if(!f)return Yr.mon;const v=f.getDay();return Yr[v===1?"mon":v===2?"tue":v===3?"wed":v===4?"thu":v===5?"fri":v===6?_s?"sat":"fri":_s?"sun":"fri"]||Yr.mon},[Yr,_s]),xh=a.useCallback(async()=>{if(!(So||ko.length===0)){vo(!0);try{for(const c of ko){const f=c.scheduledDate||c.dueDate||ra,v=Yp(f);await Ne(c.id,{scheduledDate:v,scheduledWeekKey:ZE(v),orderInDay:null})}await at(!0)}finally{vo(!1)}}},[So,ko,ra,Yp,Ne,at]),Ah=a.useCallback(async()=>{if(!(So||Ur.length===0)){vo(!0);try{for(const c of Ur)await Ne(c.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await at(!0)}finally{vo(!1)}}},[So,Ur,Ne,at]),Ih=a.useMemo(()=>Rc(_r,{month:"short",day:"numeric",year:"numeric"},bs),[_r,bs]),Jp=a.useMemo(()=>{const v=(_s?fn==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:ef:["mon","tue","wed","thu","fri"]).map(re=>{const it=Fl(Yr[re])||_r,Ct=Yr[re],Ln=re==="sat"||re==="sun";return{value:re,label:`${GE[re]} ${Rc(it,{month:"short",day:"numeric"},bs)}`,color:Ln?"#1e3a8a":"#3b82f6",icon:"Calendar",date:Ct,isPast:Ct<ra,isSelected:Ct===Dr,isWeekend:Ln}}),ue=Ji.length>0;return[...Rr?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...ue?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...v]},[_s,Rr,Yr,_r,Ji.length,ra,Dr,fn,bs]),Xp=a.useMemo(()=>{switch(g){case"category":return k;case"type":return(yn||[]).map(c=>({...c,icon:c.icon||pu[c.value]?.icon,color:c.color||pu[c.value]?.color}));case"priority":return an;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 Rt;case"assignee":return kn.map(c=>({value:c.value,label:c.label,icon:c.icon==="HelpCircle"?"Circle":c.icon,color:c.color}));case"status":return[...to.filter(c=>c.value!=="done"&&c.value!=="cancelled"),{value:"completed",label:"Completed",icon:$l("done").icon,color:$l("done").color}];case"schedule":return Jp;default:return k}},[g,k,yn,an,Rt,kn,Jp]),Th=t.jsxs("div",{className:Qe.accountMenuWrap,ref:xd,children:[t.jsx("button",{className:`tf-control-icon ${Qe.avatarBtn}`,onClick:()=>{es(c=>{const f=!c;return f?Md("account_menu"):(wr.current=null,fc.current={billing:!1,teamManagement:!1}),f})},title:Tt?"Account":"Account (Not signed in)","aria-label":Tt?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":Ys,children:t.jsx("span",{className:Qe.avatarBadge,"aria-hidden":"true",children:Nd?t.jsx("img",{src:vl,alt:"",className:Qe.avatarImage}):Sl||t.jsx(Eo,{size:14,className:Qe.avatarIcon})})}),Ys&&t.jsxs("div",{className:Qe.accountMenu,role:"menu","aria-label":"Account menu",children:[t.jsxs("div",{className:Qe.accountMenuSection,children:[t.jsx("div",{className:Qe.accountMenuSectionLabel,children:"Account"}),t.jsx("div",{className:Qe.accountMenuHint,children:To?"Checking sign-in status...":Tt?t.jsx(t.Fragment,{children:yl?t.jsx(t.Fragment,{children:t.jsxs("span",{className:Qe.accountIdentityBlock,children:[t.jsx("span",{className:Qe.accountIdentityEmail,children:gi}),Td&&hi&&t.jsxs("span",{className:Qe.accountIdentityMetaLine,children:[t.jsx("span",{className:Qe.accountIdentityMetaLabel,children:"Email"}),t.jsx("span",{className:Qe.accountIdentityMetaValue,children:Io})]}),bd?t.jsxs("span",{className:Qe.accountIdentityMetaLine,children:[t.jsx("span",{className:Qe.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:Qe.accountIdentityMetaValue,children:"Loading…"})]}):Rd?t.jsxs("button",{"aria-label":`Subscription ${kc}`,className:`${Qe.accountIdentityMetaLine} ${Qe.accountIdentityMetaAction}`,onClick:()=>{es(!1),p()},type:"button",children:[t.jsx("span",{className:Qe.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:Qe.accountIdentityMetaValue,children:kc})]}):Ts?t.jsxs("span",{className:Qe.accountIdentityMetaLine,children:[t.jsx("span",{className:Qe.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:Qe.accountIdentityMetaValue,children:"Unavailable"})]}):null,t.jsxs("span",{className:Qe.accountIdentityMetaLine,children:[t.jsx("span",{className:Qe.accountIdentityMetaLabel,children:"Runtime"}),t.jsx("span",{className:Qe.accountIdentityMetaValue,children:$u})]}),t.jsxs("span",{className:Qe.accountIdentityMetaLine,children:[t.jsx("span",{className:Qe.accountIdentityMetaLabel,children:"Environment"}),t.jsx("span",{className:Qe.accountIdentityMetaValue,children:Pd})]})]})}):"Signed in"}):"Not signed in"})]}),gl&&t.jsxs("div",{className:Qe.accountMenuSection,children:[t.jsx("div",{className:Qe.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),la.length===0&&t.jsx("div",{className:Qe.accountMenuHint,children:"No workspaces found for this account yet."}),la.map(c=>t.jsxs("button",{className:`${Qe.accountMenuItem} ${c.id===ln?Qe.accountMenuItemActive:""}`,onClick:()=>Hu(c.id),role:"menuitem",disabled:rc||c.id===ln,title:c.description||c.name,children:[t.jsx(Ti,{size:15}),t.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[t.jsx("span",{children:c.name}),t.jsx("span",{className:Qe.accountMenuMeta,children:c.role})]})]},c.id)),t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{tl(""),oc(!0),es(!1)},role:"menuitem",disabled:rc,children:[t.jsx(sr,{size:15}),"Create Workspace"]}),yd&&t.jsx("div",{className:Qe.accountMenuError,children:yd})]}),Sd?t.jsx("div",{className:Qe.accountMenuHint,children:"Resolving team management access..."}):Zr?t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{Bd()},role:"menuitem",children:[t.jsx(ug,{size:15}),"Team Management"]}):uc?t.jsx("div",{className:Qe.accountMenuHint,children:"Team Management unavailable right now."}):null,Tt&&t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{es(!1),Qi(!0)},role:"menuitem",children:[t.jsx(Eo,{size:15}),"Edit Profile"]}),t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{es(!1),p()},role:"menuitem",children:[t.jsx(_p,{size:15}),"Plans"]}),t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{es(!1),Md("account_hub"),wo(!0)},role:"menuitem",children:[t.jsx(Eo,{size:15}),"Account Hub"]}),t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{es(!1),ni(!0)},role:"menuitem",children:[t.jsx(Ii,{size:15}),"Help & Tutorial"]}),mt==="local"&&!Tt&&!To&&t.jsxs("button",{className:Qe.accountMenuItem,onClick:()=>{Sc("login")},role:"menuitem",children:[t.jsx(Eo,{size:15}),"Sign In / Register"]}),Tt&&t.jsxs("button",{className:Qe.accountMenuItem,onClick:async()=>{es(!1),await Ls()},role:"menuitem",children:[t.jsx(pg,{size:15}),"Sign Out"]})]})]}),Qp=a.useCallback(()=>{Z(c=>c==="show"?"collapse":c==="collapse"?"hide":"show")},[Z]),em=a.useCallback(()=>{X(),S("tasks"),_("add")},[X,_,S]),Nh=a.useCallback(c=>{const f=e.workstreams.find(v=>v.id===c);X(),ee(eo(f)||c),S("tasks"),_("add")},[e.workstreams,X,_,S,ee]),tm=a.useCallback(c=>{Gs(c),Cs(!1),fs(null),Ea(!1),Lr(""),mr(""),fr("");const f=c.entityType==="workstream"&&ta&<.initiativeById.get(ta)||null;Ta(f?ar(f):""),pa(null)},[lt.initiativeById,ta]),nm=a.useCallback((c,f)=>{fs(c),Ea(!1),Lr(""),mr(""),fr("");const v=c.entityType==="workstream"&&((f?lt.initiativeById.get(f):null)||ta&<.initiativeById.get(ta))||null;Ta(v?ar(v):""),pa(null)},[lt.initiativeById,ta]),Yu=a.useCallback(()=>{Gs(null),Lr(""),mr(""),fr(""),Ta("")},[]),am=a.useCallback(()=>{fs(null),Lr(""),mr(""),fr(""),Ta("")},[]),jh=a.useCallback(async()=>{const c=pr||Ho;if(!c)return;const f=!!pr,v=Bi.trim()||null;try{if(c.entityType==="initiative")if(c.mode==="edit")await e.updateInitiative(c.targetId,{title:As.trim()||"Untitled Initiative",description:mo.trim()||null,ownerId:v}),Fs({type:"initiative",id:c.targetId}),pa(null),rt("Initiative updated","success");else{const ue=await e.createInitiative({title:As.trim()||"Untitled Initiative",description:mo.trim()||null,ownerId:v});Fs({type:"initiative",id:ue.id}),pa(null),rt("Initiative created","success")}else{const ue=Is.trim(),re=ue.length===0?null:dp(lt.initiatives,ue);if(ue.length>0&&!re){rt("Initiative not found by that reference.","error");return}const it={title:As.trim()||"Untitled Workstream",description:mo.trim()||null,ownerId:v,initiativeId:re?.id||null};if(c.mode==="edit")await e.updateWorkstream(c.targetId,it),f?pa(c.targetId):(Fs({type:"workstream",id:c.targetId}),pa(null)),rt("Workstream updated","success");else{const Ct=await e.createWorkstream(it);f?pa(Ct.id):(Fs({type:"workstream",id:Ct.id}),pa(null)),rt("Workstream created","success")}}f?am():Yu()}catch(ue){rt(ue instanceof Error?ue.message:"Failed to save planning item.","error")}},[Yu,am,mo,Is,Bi,As,Ho,pr,lt.initiatives,e,rt]),Rh=a.useCallback(c=>{Xl(f=>{const v=new Set(f);return v.has(c)?v.delete(c):v.add(c),v})},[]),Dh=a.useCallback(c=>{Cn(f=>f===c?"":c),za("")},[]),Ph=a.useCallback((c,f)=>{za(v=>{const ue=v===c?"":c;return Cn(ue&&f||""),ue})},[]),Eh=a.useCallback(c=>{Gs(null),fs(null),Cs(!1),Ea(!1),Fs(c?{type:"initiative",id:c}:null),pa(null)},[]),Lh=a.useCallback(c=>{Gs(null),fs(null),Cs(!1),Ea(!1),Fs(c?{type:"workstream",id:c}:null),pa(null)},[]),Mh=a.useCallback(c=>{fs(null),Ea(!1),pa(c)},[]),Ju=a.useMemo(()=>{const c=new Map;return kn.forEach(f=>{c.set(f.label,String(f.value))}),c},[kn]),Xu=a.useCallback((c,f)=>{if(c==="workstream"&&f){nm({mode:"create",entityType:"workstream"},f);return}if(tm({mode:"create",entityType:c}),c==="workstream"){const v=(f?lt.initiativeById.get(f):null)||(ta?lt.initiativeById.get(ta):null)||null;Ta(v?ar(v):"")}},[tm,nm,lt.initiativeById,ta]),sm=a.useCallback((c,f)=>{if(c==="initiative"){const v=lt.initiativeById.get(f);if(!v)return;Gs({mode:"edit",entityType:"initiative",targetId:f}),Lr(v.title),mr(v.description||""),fr(v.ownerLabel&&Ju.get(v.ownerLabel)||""),Ta("")}else{const v=lt.workstreamById.get(f)||lt.standaloneWorkstreams.find(re=>re.id===f);if(!v)return;Gs({mode:"edit",entityType:"workstream",targetId:f}),Lr(v.title),mr(v.description||""),fr(v.ownerLabel&&Ju.get(v.ownerLabel)||"");const ue=v.initiativeId&<.initiativeById.get(v.initiativeId)||null;Ta(ue?ar(ue):"")}pa(null)},[Ju,lt.initiativeById,lt.standaloneWorkstreams,lt.workstreamById]),Gd=a.useCallback(async(c,f)=>{const v=e.workstreams.find(Ct=>Ct.id===c);if(!v){rt("Workstream not found.","error");return}const ue=typeof f=="string"?f.trim():f===null?"":Is.trim(),re=ue.length===0?null:dp(lt.initiatives,ue);if(ue.length>0&&!re){rt("Initiative not found by that reference.","error");return}const it=re?.id||null;if((v.initiativeId||null)===it){rt(it?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info");return}try{await e.updateWorkstream(c,{initiativeId:it}),Ta(re?ar(re):""),rt(it?"Initiative set":"Initiative removed","success")}catch{rt("Failed to set initiative.","error")}},[Is,lt.initiatives,e,rt]),Qu=a.useCallback(async(c,f)=>{const v=yo.get(c);if(!v){rt("Task not found.","error");return}const ue=f||null;if(lt.initiativeById.has(c)||lt.workstreamById.has(c)){rt("Only execution tasks can be moved into workstreams.","error");return}if(ue&&!lt.workstreamById.has(ue)){rt("Workstream not found.","error");return}if((v.workstreamId||null)===ue){rt(ue?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const re=await fetch(`/api/taskforce/task/${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:ue})});if(!re.ok){const it=await re.json().catch(()=>({}));rt(it?.error||"Failed to set workstream.","error");return}await re.json().catch(()=>null),await at(!0),rt(ue?"Workstream set":"Workstream removed","success")}catch{rt("Failed to set workstream.","error")}},[at,yo,lt.initiativeById,lt.workstreamById,rt]),Bh=a.useCallback(async(c,f)=>{const v=f.trim();if(!v){rt("Enter a task reference.","error");return}const ue=xf(v),re=Jo.find(it=>it.id===v||Ar(it)===v||ue!==null&&it.referenceNumber===ue);if(!re){rt("Task not found by that reference.","error");return}await Qu(re.id,c)},[Qu,Jo,rt]),Wh=a.useCallback(async(c,f)=>{const v=f.trim();if(!v){rt("Enter a workstream reference.","error");return}const ue=lt.initiativeById.get(c);if(!ue){rt("Initiative not found.","error");return}const re=qf(v),it=e.workstreams.find(Ct=>Ct.id===v||eo(Ct)===v||re!==null&&Ct.referenceNumber===re);if(!it){rt("Workstream not found by that reference.","error");return}await Gd(it.id,ar(ue))},[Gd,lt.initiativeById,e.workstreams,rt]),rm=a.useCallback(c=>{Cn(c),za("")},[]),om=a.useCallback(c=>{za(c),Cn(c&<.workstreamInitiativeIds.get(c)||"")},[lt.workstreamInitiativeIds]),ep=a.useCallback(c=>{const f=Qm(c,Wr);if(f!==c){const v=Wr.find(ue=>ue.id===c)?.label||"That module";rt(`${v} is not available in this build yet.`,"error");return}S(f)},[rt,S,Wr]),im=a.useCallback(()=>{if(ma==="tasks"&&ea){ms(!1),Fs(null),pa(null),Gs(null);return}if(ma!=="tasks"){S("tasks"),ms(!0);return}ms(c=>!c)},[ea,ma,S]),Fh=a.useCallback(c=>{S("tasks"),Mn(c)},[Mn,S]),Oh=a.useCallback((c,f)=>{Vs(c),Zo(f?.sessionId??null),Ql(v=>v+1),S("annotate")},[S]),$h=a.useCallback(({target:c,sessionId:f})=>{Vs(v=>!v&&!c||v&&c&&v.taskId===c.taskId&&v.taskReferenceLabel===c.taskReferenceLabel&&v.assetId===c.assetId&&v.imageReferenceLabel===c.imageReferenceLabel&&v.path===c.path&&v.displayName===c.displayName?v:c),Zo(v=>v===f?v:f)},[]),cm=a.useMemo(()=>[{value:"created",label:Te("standalone.sortCreated")},{value:"updated",label:Te("standalone.sortUpdated")},{value:"priority",label:Te("standalone.sortPriority")},{value:"complexity",label:Te("standalone.sortComplexity")},...Jf(un,[...e.searchAgnosticTasks,...Na])],[Na,e.searchAgnosticTasks,un]),lm=a.useMemo(()=>[{value:"category",label:Te("standalone.groupCategory")},{value:"type",label:Te("standalone.groupType")},{value:"priority",label:Te("standalone.groupPriority")},{value:"complexity",label:Te("standalone.groupComplexity")},{value:"assignee",label:Te("standalone.groupAssignee")},{value:"status",label:Te("standalone.groupStatus")},{value:"schedule",label:Te("standalone.groupSchedule")}],[]),dm=a.useMemo(()=>Wr.filter(c=>c.enabled),[Wr]),um=a.useMemo(()=>[{key:"empty-columns",icon:P==="show"?t.jsx(mm,{size:16}):P==="collapse"?t.jsx(fm,{size:16}):t.jsx(mg,{size:16}),title:Te(P==="show"?"standalone.showEmptyColumns":P==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:Qp,active:P!=="show"},{key:"compressed-cards",icon:lr?t.jsx(df,{size:16}):t.jsx(fg,{size:16}),title:Te(lr?"standalone.expandCards":"standalone.compressCards"),onClick:()=>Ei(!lr),active:lr}],[lr,Qp,P]),Uh=a.useMemo(()=>[{key:"filter-toggle",icon:t.jsx(uf,{size:16}),title:Te("standalone.toggleFilters"),onClick:()=>Wc(!dr),active:dr,className:Od?u.filterGlow:""}],[Od,Wc,dr]),zh=a.useMemo(()=>{switch(Os.filterBar.kind){case"task-filters":return t.jsx(sP,{categoryFilterOptions:zc,typeFilterOptions:Hc,priorities:an,taxonomyDisplayLabels:Tn,filterCategories:vt,setFilterCategories:Ot,filterTypes:Pt,setFilterTypes:xt,filterPriorities:Et,setFilterPriorities:xn,filterStatus:q,setFilterStatus:K,filterAssignees:Gt,setFilterAssignees:Jn,assigneeOptions:kn,initiativeFilterOptions:Gc,selectedInitiativeId:ta,setSelectedInitiativeId:rm,workstreamFilterOptions:Zi,selectedWorkstreamId:xs,setSelectedWorkstreamId:om,taskScope:yt,setTaskScope:Gn,showArchive:gr,setShowArchive:$i,fetchArchive:go,onDeleteAllDeleted:()=>{const c=Ga.length;c===0||!window.confirm(`Permanently delete ${c} deleted task${c===1?"":"s"}? This cannot be undone.`)||Je()},clearFilters:()=>{Me(),Cn(""),za("")}});case"document-filters":return t.jsx(rP,{typeFilters:pn,setTypeFilters:Pn,attachmentFilters:La,setAttachmentFilters:hr,clearFilters:()=>{Pn(su.map(c=>c.value)),hr(ru.map(c=>c.value))}});default:return t.jsx(nP,{})}},[kn,zc,Me,Ga.length,La,pn,Gt,vt,Et,q,Pt,rm,om,Gc,an,ta,xs,hr,Pn,Jn,Ot,xn,K,xt,Cn,za,$i,Gn,gr,yt,Tn,Hc,Zi,Os.filterBar.kind,go,Je]),Hh=a.useMemo(()=>[{key:"zen-toggle",icon:t.jsx(hg,{size:16,fill:$?"currentColor":"none"}),title:Te($?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>ce(),active:$}],[$,ce]),Gh=a.useMemo(()=>({search:t.jsx(eP,{value:Xe,placeholder:Te("standalone.searchPlaceholder"),active:Al,onChange:ct,onClear:()=>ct(""),clearTitle:Te("standalone.clearSearchTitle")}),sort:t.jsx(qm,{label:t.jsxs(t.Fragment,{children:[t.jsx(gg,{size:12})," ",Te("standalone.sortLabel")]}),value:se,options:cm,onChange:c=>je(c),trailingAction:t.jsx("button",{className:`tf-control-icon ${u.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?Te("standalone.sortDirectionDescTitle"):Te("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?t.jsx(rf,{size:14}):t.jsx(of,{size:14})})}),"divider-primary":t.jsx(Km,{}),grouping:t.jsx(qm,{label:t.jsxs(t.Fragment,{children:[t.jsx(_p,{size:12})," ",Te("standalone.groupLabel")]}),value:g,options:lm,onChange:c=>C(c)}),"divider-secondary":t.jsx(Km,{}),"task-display-actions":t.jsx(gp,{actions:um})}),[g,lm,ep,Al,e,Xe,C,ct,je,se,cm,um,Os.moduleId]),Vh=a.useMemo(()=>({"add-task":t.jsx(tP,{icon:t.jsx(sr,{size:16}),label:Te("standalone.addTask"),onClick:em}),"add-document":null}),[em]),jl=a.useMemo(()=>{const c={tasks:t.jsx(_g,{size:18}),docs:t.jsx(Cp,{size:18}),annotate:t.jsx(bg,{size:18}),workflows:t.jsx(wg,{size:18}),agents:t.jsx(eu,{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"&&ea?hn.workspaceToolButtonActive:""}`.trim(),onClick:im,title:ma==="tasks"&&ea?"Collapse planning trays":"Planning","aria-label":ma==="tasks"&&ea?"Collapse planning trays":"Planning",children:ma==="tasks"&&ea?t.jsx(Nc,{size:18}):t.jsx(yg,{size:18})}),t.jsx("div",{className:hn.workspaceToolRailDivider}),dm.map(f=>t.jsx("button",{type:"button",className:`${hn.workspaceToolButton} ${ma===f.id?hn.workspaceToolButtonActive:""}`.trim(),onClick:()=>ep(f.id),title:f.label,"aria-label":f.label,children:c[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} ${b==="settings"?hn.workspaceToolButtonActive:""}`.trim(),onClick:()=>{ft("general"),_("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:t.jsx(cf,{size:18})})]})]})},[b,ep,im,ea,ma,ft,_,dm]),tp=a.useRef(null),Zh=t.jsx(_E,{open:ea,leftOffset:56,initiatives:lt.initiatives,standaloneWorkstreams:lt.standaloneWorkstreams,activeInitiativeId:ta,activeWorkstreamId:xs,expandedInitiativeIds:Xa,detail:qi,editor:Ho,secondaryPane:Yi,assigneeOptions:kn.map(c=>({value:String(c.value),label:c.label})),draftInitiativeSummary:id,draftTitle:As,draftDescription:mo,draftOwner:Bi,draftInitiativeId:Is,onChangeDraftTitle:Lr,onChangeDraftDescription:mr,onChangeDraftOwner:fr,onChangeDraftInitiativeId:Ta,onCollapseTreePane:()=>po(!0),onExpandTreePane:()=>po(!1),onCollapsePrimaryPane:()=>Cs(!0),onExpandPrimaryPane:()=>Cs(!1),onCollapseSecondaryPane:()=>Ea(!0),onExpandSecondaryPane:()=>Ea(!1),onBackFromSecondary:()=>{fs(null),pa(null)},treeCollapsed:Hs,primaryCollapsed:zo,secondaryCollapsed:Er,onCancelEditor:Yu,onSubmitEditor:jh,onCreateInitiative:()=>Xu("initiative"),onCreateWorkstream:()=>Xu("workstream"),onCreateTaskInWorkstream:Nh,onCreateWorkstreamInInitiative:c=>Xu("workstream",c),onAssignInitiativeToWorkstream:Gd,onOpenTaskById:Mn,onAttachTaskToWorkstreamByReference:Bh,onAttachWorkstreamToInitiativeByReference:Wh,onToggleInitiative:Rh,onSelectInitiative:Dh,onSelectWorkstream:Ph,onOpenInitiativeDetails:Eh,onOpenWorkstreamDetails:Lh,onOpenNestedWorkstreamDetails:Mh,onEditInitiative:c=>sm("initiative",c),onEditWorkstream:c=>sm("workstream",c),onArchiveInitiative:c=>{e.archiveInitiative(c).then(()=>{rt("Initiative archived","success")}).catch(f=>{rt(f instanceof Error?f.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:c=>{e.unarchiveInitiative(c).then(()=>{rt("Initiative unarchived","success")}).catch(f=>{rt(f instanceof Error?f.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:c=>{e.archiveWorkstream(c).then(()=>{rt("Workstream archived","success")}).catch(f=>{rt(f instanceof Error?f.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:c=>{e.unarchiveWorkstream(c).then(()=>{rt("Workstream unarchived","success")}).catch(f=>{rt(f instanceof Error?f.message:"Failed to unarchive workstream.","error")})}}),qh=Os.headerSections.map(c=>{const f=Gh[c];return f?t.jsx(pt.Fragment,{children:f},c):null}).filter(Boolean),Kh=Os.primaryAction?Vh[Os.primaryAction]:null;return t.jsxs("div",{className:`${hn.standaloneWrapper} ${$?u.zenModeEnabled:""}`,"data-theme":tt,children:[t.jsx(QD,{projectName:sa,currentWorkspaceId:ln,runtimeMode:mt,theme:tt,meta:i?null:t.jsxs(t.Fragment,{children:[t.jsx("span",{className:u.taskCountBadge,title:qu,children:Zu}),hs&&hs!=="anonymous"&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:u.taskCountBadge,title:"Tasks assigned to me",children:[t.jsx(Eo,{size:13,className:u.taskCountBadgeIcon,"aria-hidden":"true"}),ld]}),t.jsxs("span",{className:`${u.taskCountBadge} ${ei>0?u.taskCountBadgeAlert:""}`.trim(),title:"Tasks overdue",children:[t.jsx(kg,{size:13,className:u.taskCountBadgeIcon,"aria-hidden":"true"}),ei]})]}),Ku&&t.jsx("button",{className:"tf-control-icon",onClick:()=>ec(!0),title:`Sync manager: ${as.label} | Last success: ${vc}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${as.border}`,background:as.background,color:as.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:as.icon==="off"?t.jsx(Sg,{size:16}):t.jsx(vg,{size:16})})]}),actions:t.jsxs(t.Fragment,{children:[i&&t.jsx("button",{className:"tf-control-icon",onClick:w,title:"Back",children:"Back"}),!i&&t.jsxs(t.Fragment,{children:[qh,Kh]}),!i&&t.jsx(gp,{actions:Hh}),!i&&t.jsx(gp,{actions:Uh}),Th]})}),t.jsx(kh,{notice:Ue,onDismiss:Re}),It&&t.jsx("div",{className:ve.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),!i&&dr&&zh,i?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(Wa,{size:20,className:u.spinner})}),children:t.jsx(tL,{...e,currentTheme:tt,projectName:sa,currentWorkspaceId:ln,authUserId:ia,apiBaseUrl:Dd,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",resolveCloudAuthUrl:wa,embedded:!0,shellOwnsScroll:!0})})}):ma==="docs"&&Ko?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[jl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Wa,{size:20,className:u.spinner})}),children:t.jsx(XE,{tasks:j,runtimeMode:mt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:pn,attachmentFilters:La,onTypeFiltersChange:Pn,onAttachmentFiltersChange:hr,requestedDocPath:Go,requestedDocAssetId:_u,onRequestedDocHandled:()=>{Yn(null),Vo(null)},enableTaskGeneration:!0})})]}):ma==="annotate"&&Uc?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[jl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Wa,{size:20,className:u.spinner})}),children:t.jsx(JE,{runtimeMode:mt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:ln,sessionLoadReady:$c,requestedTarget:Ma,requestedSessionId:Mr,requestedOpenVersion:Cu,resolveTaskReferenceLabel:sd,resolveImageReferenceLabel:rd,onOpenTarget:Oh,onContextChange:$h,onBackToTask:Fh})})]}):ma==="workflows"?t.jsxs("div",{className:`${hn.standalonePage} ${hn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[jl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Wa,{size:20,className:u.spinner})}),children:t.jsx(QE,{availableWorkflows:Pa,availableEnvironments:ir,exportEnvironment:Qn,exportWorkflowsPath:e.exportWorkflowsPath,exportingResource:Ut,exportResult:Ge,onExportEnvironmentChange:e.setExportEnvironment,onExportWorkflows:Ca,onRefreshWorkflows:ws,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:[jl,t.jsx(a.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Wa,{size:20,className:u.spinner})}),children:t.jsx(eL,{workspaceId:ln})})]}):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:ea?`${56+Vc+6}px`:"62px",paddingRight:g==="schedule"&&ps?`${Lp}px`:0},children:[jl,t.jsx("div",{ref:tp,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&&Xo.length>0&&t.jsx("div",{className:u.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:t.jsx(Wa,{size:14,className:u.spinner})}),t.jsx(VD,{tasks:xu,allTasks:Zc,columns:Xp,groupBy:g,scheduleDates:Yr,searchQuery:Xe,filterCategories:vt,filterTypes:Pt,filterPriorities:Et,filterStatus:q,filterAssignees:Gt,assigneeOptions:kn,scheduleFilteredTaskIds:Array.from(od),copiedId:we,taxonomies:un,types:yn,priorities:an,onUpdateTask:Ne,onTaskClick:c=>ye(c),onOpenTaskById:Mn,onCopyId:Lt,onToggleInProgress:Qt,onToggleReview:He,onToggleComplete:Dt,onToggleCancel:Nn,onSetStatus:ti,onArchiveTask:Y,onAddTaskToColumn:dd,showTaskCardStatusLabel:fe,onScheduleDaySelected:c=>{Bc(c);const f=Fl(c);f&&Uo(`${f.getFullYear()}-${String(f.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:g==="schedule"?$a:void 0,onScrollLeftChange:c=>{g==="schedule"&&Mi(c)},emptyColumnMode:P,categories:k,compressed:lr,readOnlyMode:yt==="deleted"?"deleted":yt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:se,sortOrder:e.sortOrder,planningDropTargets:tp.current?Ai.createPortal(Zh,tp.current):null,onAssignTaskToWorkstream:Qu,onAssignWorkstreamToInitiative:Gd,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:c=>{if(yt==="deleted"){const f=Ui.get(c);if(!f)return;Pe(f.id);return}_e(c)},onDelete:c=>{if(yt==="deleted"){const f=Ui.get(c);if(!f||!window.confirm("Permanently delete this task? This cannot be undone."))return;qe(f.id);return}Ae(c)}},`${g}-${Xp.map(c=>String(c.value)).join("|")}-${Yr.mon}`),g==="schedule"&&!ps&&t.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{Fs(null),Li(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:t.jsx(Nc,{size:16})})]}),g==="schedule"&&t.jsx(qE,{open:ps,onClose:()=>Li(!1),scheduleSelectedDate:Dr,setScheduleSelectedDate:Bc,scheduleCalendarMonth:Pr,setScheduleCalendarMonth:Uo,scheduleShowWeekends:_s,setScheduleShowWeekends:Oo,scheduleShowBacklog:Rr,setScheduleShowBacklog:co,scheduleOnlyExpired:$o,setScheduleOnlyExpired:lo,expiredScheduledCount:Qo,overdueDueCount:cd,expiredLeafCandidates:ko,expiredRecoveryCandidates:Ur,onMoveExpiredToSelectedWeek:xh,onMoveExpiredToBacklog:Ah,scheduleBulkBusy:So,globalWeekStartsOn:fn,resolvedLocale:bs,todayDateOnly:ra,scheduleBaseTasks:Hi,scheduleWeekStart:_r,scheduleWeekLabel:Ih})]}),t.jsxs(ro,{isOpen:b==="add",onClose:qc,title:pe?jr?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:uo?"full":"xl",theme:tt,headerActions:t.jsx("button",{className:"tf-control-icon",onClick:()=>Ua(c=>!c),title:uo?"Exit full screen":"Enter full screen","aria-label":uo?"Exit full screen":"Enter full screen",children:uo?t.jsx(fm,{size:18}):t.jsx(mm,{size:18})}),draggable:!uo,closeOnOverlayClick:!1,children:[t.jsx(yh,{editingTaskId:pe,loading:te,autoSaveState:Dn,title:B,currentTask:jr,currentTaskWorkstream:Pi,currentTaskInitiative:Fo,workstreamInput:G,onWorkstreamInputChange:ee,onSetWorkstreamForCurrentTask:gn,handleSubmit:U,resetForm:X,handleCopyId:Lt,copiedId:we,tasks:j,handleToggleInProgress:Qt,handleToggleReview:He,handleToggleComplete:Dt,handleToggleCancel:Nn,handleSetStatus:ti,handleArchiveTask:Y,handleRestoreDeletedTask:jr?.deletedRecordId?c=>{Pe(c)}:void 0,handlePermanentlyDeleteDeletedTask:jr?.deletedRecordId?c=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(qe(c),X(),_("tasks"))}:void 0}),t.jsx(gh,{editingTaskId:pe,error:D,title:B,description:xe,checklistItems:ae,category:Le,type:Oe,priority:W,complexity:V,manualComplexityEnabled:be,approach:x,assignee:I,scheduledDate:L,dueDate:ne,workstreamInput:G,formTaxonomies:De,onTaxonomyChange:(c,f)=>Ke(v=>({...v,[c]:f})),taxonomies:un,comments:nt,newCommentText:dt,contextFiles:et,currentWorkspaceId:ln,apiBaseUrl:Dd,descriptionFocused:Ye,showMarkdownHelp:St,showChecklist:zt,checklistEnabled:$e,showComments:sn,categories:k,types:yn,priorities:an,taxonomyDisplayLabels:Tn,assigneeOptions:kn,workstreams:e.workstreams,copiedId:we,onTitleChange:oe,onDescriptionChange:ie,onChecklistItemsChange:Ze,onCategoryChange:Ce,onTypeChange:R,onPriorityChange:F,onComplexityChange:E,onApproachChange:c=>{H(c),Ke(f=>({...f,approach:c}))},onAssigneeChange:Ie,onScheduledDateChange:le,onDueDateChange:de,onWorkstreamInputChange:ee,onNewCommentTextChange:d,onDescriptionFocusedChange:wt,onShowMarkdownHelpChange:At,onShowChecklistChange:Ht,onShowCommentsChange:Jt,onOpenSettings:c=>{ft(c),_("settings")},onSubmit:U,commentsEndRef:Kn,onAddComment:()=>Xt(dt),onOpenTaskById:Mn,onAddContextFile:c=>{let f=et;gt(v=>(f=[...v,c],f)),O(!0),pe&&Ne(pe,{attachments:f})},onRemoveContextFile:async c=>{let f=et;gt(v=>(f=v.filter((ue,re)=>re!==c),f)),O(!0),pe&&Ne(pe,{attachments:f})},onUpdateContextCaption:(c,f)=>{let v=et;gt(ue=>(v=ue.map((re,it)=>it!==c?re:typeof re=="string"?{path:re,caption:f,timestamp:new Date().toISOString()}:{...re,caption:f}),v)),O(!0),pe&&Ne(pe,{attachments:v})},onCopyId:Lt,onToggleInProgress:Qt,onToggleReview:He,onToggleComplete:Dt,onToggleCancel:Nn,onSetStatus:ti,onArchiveTask:Y,onUnarchive:c=>{if(jr?.isDeleted){const f=Ui.get(c);if(!f)return;Pe(f.id);return}_e(c)},currentTask:jr})]}),t.jsx(ro,{isOpen:b==="settings",onClose:qc,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(Wa,{size:20,className:u.spinner})}),children:t.jsx(YE,{settingsModel:Ee,onSectionChange:ft})})}),t.jsx(tD,{prompt:cr,theme:tt,onClose:xa,onConfirm:bu}),t.jsx(eD,{isOpen:Kc,theme:tt,onClose:()=>ni(!1),onOpenSettings:()=>{ni(!1),_("settings"),ft("general")}}),t.jsx(Q1,{isOpen:Xi,theme:tt,onClose:Uu,onSave:()=>{Ld()},displayName:pl,email:Io,avatarDisplayUrl:jd,accountBadgeInitial:Sl,avatarInputRef:mi,avatarAccept:nL,avatarDraftId:ns,saveBusy:Bu,avatarBusy:Mu,saveError:Wu,saveNotice:Fu,onDisplayNameChange:_d,onAvatarInputChange:c=>{zu(c)},onStartAvatarUpload:()=>mi.current?.click(),onDiscardUpload:wl,onRemovePhoto:Ed}),t.jsx(X1,{isOpen:zr,theme:tt,runtimeMode:mt,authRequiredForApi:tn,isAuthenticated:Tt,hasAuthIdentity:yl,authIdentityLabel:gi,billingLoading:bd,billingError:Ts,billingActionError:Pu,billingNotice:Eu,billingActionBusy:Du,billingIntervalChoice:pi,accountProfileSummary:Fn,currentWorkspaceId:ln,canOpenTeamManagement:Zr,canManageWorkspaceSync:fi,workspaceCloudSyncEnabled:Vn,syncStatusLabel:as.label,workspaceSyncError:ud,syncControlBusy:Id,onClose:()=>wo(!1),onOpenWorkspaceAudit:()=>{wo(!1),Bd(),Za("audit")},onBillingIntervalChange:Lu,onRefreshBilling:()=>{er()},onUpdateInterval:()=>{Cl()},onManageBilling:()=>{_l()},onStartCheckout:()=>{bl()},onToggleWorkspaceSync:c=>{Ad(c)},onOpenHelp:()=>{wo(!1),ni(!0)}}),t.jsx(GD,{isOpen:kd,theme:tt,teamPlanMode:al,teamMgmtError:pc,teamManagementTab:cc,teamUsersLoading:ri,teamUsers:ii,teamActionBusyUserId:Sr,teamInviteFeedback:ju,teamInviteEmail:ci,teamInviteRole:mc,teamInvitePermissionMode:ol,teamInviteBusy:Nu,pendingInvites:Wd,teamAuditLoading:ll,teamAuditEvents:vd,teamAuditPage:bo,teamAuditPages:na,teamAuditHasMore:Vr,onClose:()=>ic(!1),onOpenMembersTab:()=>{Za("members"),qr()},onOpenInvitesTab:()=>Za("invites"),onOpenAuditTab:()=>{Za("audit"),tr(bo)},onMemberRoleChange:(c,f)=>{ki(c,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...Rs()},credentials:"include",body:JSON.stringify({workspaceId:Xs,role:f})}))},onMemberPermissionChange:(c,f)=>{ki(c,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...Rs()},credentials:"include",body:JSON.stringify({workspaceId:Xs,mode:f})}))},onToggleMemberDisabled:(c,f)=>{ki(c,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...Rs()},credentials:"include",body:JSON.stringify({workspaceId:Xs,disabled:f})}))},onRevokeInvite:c=>{ki(c,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...Rs()},credentials:"include",body:JSON.stringify({workspaceId:Xs})}))},onRemoveMember:c=>{ki(c,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c)}?workspaceId=${encodeURIComponent(Xs)}`,{method:"DELETE",headers:Rs(),credentials:"include"}))},onInviteEmailChange:rl,onInviteRoleChange:Iu,onInvitePermissionModeChange:Tu,onSubmitInvite:()=>{Gu()},onLoadAuditPrevious:()=>{tr(bo-1)},onLoadAuditNext:()=>{tr(bo+1)}}),t.jsx(J1,{isOpen:nl,theme:tt,onClose:()=>oc(!1),onConfirm:()=>xl({intent:"create-workspace"})}),t.jsx(HD,{isOpen:ai,theme:tt,currentWorkspaceLabel:gc,syncStatusMeta:as,workspaceCloudSyncEnabled:Vn,syncControlBusy:Id,canManageWorkspaceSync:fi,workspaceSyncSummary:Wn,workspaceSyncRepairBusy:yr,referenceMismatchCount:Zt,syncStageLabel:me,workspaceSyncPendingChanges:Rn,formattedLastSyncTime:vc,formattedLastPullTime:Nl,formattedLastPushTime:zd,syncLastError:N,workspaceSyncDiagnostics:Se,activeReferenceMismatchSummaries:Kr,syncDiagnosticsSummary:_t,syncEventRows:Bt,syncEventsListRef:Qc,workspaceSyncRepairQueued:ac,workspaceSyncBusy:cn,workspaceSyncCopied:Au,runtimeMode:mt,isAuthenticated:Tt,onClose:()=>ec(!1),onToggleWorkspaceSync:c=>{Ad(c)},onRepairSync:wc,onCopyReport:()=>{En()},onOpenLogin:()=>{Sc("login")},onRetrySync:()=>{ss()}}),Ws&&Ai.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(Pc,{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:()=>Us(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),t.jsx("button",{className:u.destructiveBtn,onClick:us,title:"Discard unsaved changes and leave",children:"Discard"}),t.jsxs("button",{className:u.submitBtn,onClick:io,disabled:te,title:"Save changes and leave",children:[te?t.jsx(Wa,{size:16,className:u.spinner}):t.jsx(lf,{size:16}),"Save"]})]})]})}),document.body),is&&Ai.createPortal(t.jsx("div",{className:On.overlay,children:t.jsxs("div",{className:On.browser,children:[t.jsxs("div",{className:On.header,children:[t.jsxs("div",{className:On.pathInfo,children:[t.jsx(Ti,{size:14}),t.jsx("span",{children:Ve||"Project Root"})]}),t.jsxs("div",{className:On.actions,children:[Ve&&t.jsx("button",{className:u.helpLink,onClick:()=>{const c=Ve.split("/").filter(Boolean);c.pop(),Vt(c.length?c.join("/")+"/":"")},children:"Back"}),t.jsx("button",{className:u.helpLink,onClick:()=>cs(!1),children:"Close"})]})]}),t.jsxs("div",{className:On.list,children:[bt&&typeof bt=="object"&&t.jsxs("div",{className:`${On.item} ${On.itemFile} ${On.itemCurrent}`,onClick:()=>ot(Ve),children:[t.jsx(ao,{size:14})," Select Current: ./",Ve||"(root)"]}),Da.map(c=>t.jsxs("div",{className:On.item,onClick:()=>Vt(Ve+c+"/"),children:[t.jsx(Ti,{size:14})," ",c,"/"]},c)),Q.map(c=>t.jsxs("div",{className:`${On.item} ${On.itemFile}`,onClick:()=>ot(Ve+c),children:[t.jsx(Cp,{size:14})," ",c]},c)),Da.length===0&&Q.length===0&&t.jsx("div",{className:`${On.item} ${On.empty}`,children:"No items found"})]})]})}),document.body)]})}function uL(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"),i=!!(n&&s==="cloud"&&r&&n.workspaceSetupState==="missing"),p=!!(n&&s==="local"&&n.workspaceSetupState==="missing"),h=!!(n&&(n.forceSetup||n.forceGlobalSetup||n.forceWorkspaceSetup||o||i||l||p));if(!h)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const w=!!(n&&(n.forceSetup||n.forceGlobalSetup||o||l)),b=!!(n&&(n.forceSetup||n.forceWorkspaceSetup||i||p)),_=!!(w&&n?.globalSetupState==="missing"),k=!!(b&&n?.workspaceSetupState==="missing"),g=!!(w&&n?.globalSetupState==="unreadable"),C=!!(b&&n?.workspaceSetupState==="unreadable"),M=g||C;return{setupGateActive:h,needsGlobalSetup:_,needsWorkspaceSetup:k,hasSetupReadError:M,phase:M?"setup-read-error":_?"needs-global-setup":k?"needs-workspace-setup":"ready"}}const wp="/taskforce/assets/taskforce-BxLPokNB.png";function tf(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function nf(e={}){const n=new URLSearchParams;n.set("screen","plans");for(const[s,r]of Object.entries(e)){const o=String(r||"").trim();o&&n.set(s,o)}return`/?${n.toString()}`}function af({config:e={},initialTaskId:n,onTaskCountChange:s,onHeaderMouseDown:r,isDragging:o,onClose:l,mode:i="standalone"}){const p=Sf(),h=a.useMemo(()=>new URLSearchParams(p.search),[p.search]),w=String(h.get("planId")||"").trim(),b=String(h.get("planVersionId")||"").trim(),_=String(h.get("interval")||"").trim(),k=p.pathname==="/pricing",g=p.pathname==="/plans",C=p.pathname==="/"&&String(h.get("screen")||"").trim().toLowerCase()==="plans",M=nf({gate:"plan_selection_required"}),S=kf(),[P,Z]=a.useState(""),[$,ce]=a.useState(""),[q,K]=a.useState(""),[j,ye]=a.useState("login"),[U,X]=a.useState(""),[Ne,pe]=a.useState(!1),[te,D]=a.useState(null),[B,oe]=a.useState(""),[xe,ie]=a.useState(""),[ae,Ze]=a.useState(null),[Le,Ce]=a.useState(null),[Oe,R]=a.useState("unknown"),[W,F]=a.useState(!1),[V,E]=a.useState(null),[y,x]=a.useState(null),[H,I]=a.useState(null),[Ie,L]=a.useState(!1),[le,ne]=a.useState(0),[de,G]=a.useState(0),[ee,be]=a.useState(()=>Date.now()),[$e,fe]=a.useState("core"),[De,Ke]=a.useState(!1),[nt,dt]=a.useState(null),[d,et]=a.useState(null),[gt,O]=a.useState(""),[Ye,wt]=a.useState(""),[St,At]=a.useState("local"),[zt,Ht]=a.useState([]),[sn,Jt]=a.useState(""),[Xt,gn]=a.useState(!1),[Mn,un]=a.useState(null),[yn,an]=a.useState(!1),Tn=a.useMemo(()=>Kf(),[]),[Rt,we]=a.useState(Tn),[Lt,Qt]=a.useState(()=>Tn.find(Q=>Q.isDefaultStarter)?.id||Tn[0]?.id||""),[Dt,He]=a.useState(()=>tf(Tn.find(Q=>Q.isDefaultStarter)||Tn[0]||null)),[Nn,Y]=a.useState(!1),[Ae,_e]=a.useState(null),[Pe,qe]=a.useState(!1),[Je,at]=a.useState(null),Xe=CS({config:e,initialTaskId:n,onTaskCountChange:s,onClose:l}),{runtimeMode:ct,workspaceSwitchingEnabled:vt,currentWorkspaceId:Ot,configLoaded:Pt,cloudAuthConfigured:xt,authRequiredForApi:Et,authBlocked:xn,isAuthenticated:Gt,hasBetaAccess:Jn,authSessionResolved:kn,workspaceBootstrapPending:yt,bootstrapPhase:Gn,bootstrapError:se,setupState:je,runtimeCapabilities:Me,refreshSetupContext:Ee,retryBootstrapChecks:Fe,createWorkspace:tt,saveWorkspaceProfile:An,fetchWorkspaces:Mt,applyWorkspaceSyncStateSnapshot:fa,settingsModel:Bn,fetchTasks:bn,loginWithCredentials:fn,registerWithCredentials:rn,requestEmailVerification:Kt,confirmEmailVerification:kt,requestPasswordReset:$t,confirmPasswordReset:Yt,inspectInviteAcceptance:Sn,acceptInviteWithToken:ft,joinInviteWithToken:mt,authUserEmail:oa,currentTheme:en,logout:tn}=Xe,It=a.useMemo(()=>Rt.find(Q=>Q.id===Lt)||Rt.find(Q=>Q.isDefaultStarter)||Rt[0]||null,[Lt,Rt]);_f(en);const Tt=Pp,ia=a.useMemo(()=>{const Q=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return Q?Q.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),ya=ct==="cloud"||Me?.runtimeMode==="cloud",Ia=!ya&&xt&&!!ia,ha=typeof window<"u"&&/^app\./i.test(window.location.hostname),ka=ct==="cloud"&&Et,aa=ct==="cloud"&&xn,on=p.pathname==="/login",jn=p.pathname==="/setup",Vn=p.pathname==="/coming-soon",_n=ha?(!Gt||xn)&&!k&&!g&&!C:(ka&&!Gt||aa)&&!k&&!g&&!C,$n=ct==="cloud"&&Gt&&!Jn&&!k&&!g&&!C,Wn=ct==="cloud"&&Gt&&kn&&Je?.canAccessApp===!1&&Je?.canAccessPlans!==!1&&!k&&!g&&!C,vn=xt,cn=a.useMemo(()=>String(new URLSearchParams(p.search).get("step")||"").trim().toLowerCase(),[p.search]),Rn=a.useMemo(()=>String(new URLSearchParams(p.search).get("intent")||"").trim().toLowerCase(),[p.search]),In=jn&&cn==="workspace"&&Rn==="create-workspace",rt=i!=="widget"&&!kn&&!on&&!jn&&!k&&!g&&!C&&(ct==="cloud"||ha),wn=a.useMemo(()=>uL({setupState:je?{globalSetupState:je.globalSetupState,workspaceSetupState:je.workspaceSetupState,runtimeMode:je.runtimeMode,workspaceId:je.workspaceId,mode:je.mode,forceSetup:je.forceSetup,forceGlobalSetup:je.forceGlobalSetup,forceWorkspaceSetup:je.forceWorkspaceSetup}:null,runtimeMode:ct,isAuthenticated:Gt}),[je,ct,Gt]),nn=wn.setupGateActive,Sa=wn.needsGlobalSetup,Xn=wn.needsWorkspaceSetup,Fa=wn.hasSetupReadError,Oa=i!=="widget"&&kn&&!_n&&!$n&&!k&&!g&&!C&&(!Pt||yt||Gn==="stalled")&&(jn||ct==="cloud"||ha),vs=a.useMemo(()=>Gn==="auth"?"Verifying session...":Gn==="workspace"?"Resolving workspace access...":Gn==="config"?"Loading configuration...":"Checking account, workspace access, and setup status...",[Gn]),ss=a.useCallback((Q,Ve,Vt)=>{const bt=String(Q||"").trim().toLowerCase(),dn=String(Ve||"").trim().toLowerCase();return!!(!bt||bt==="system default workspace"||dn&&bt===dn)},[]);a.useEffect(()=>{const Q=je?.mode==="operations"?"operations":"core";fe(Q)},[je?.mode]),a.useEffect(()=>{if(ct!=="cloud"||!Gt||!kn){at(null);return}at(null);let Q=!1;return(async()=>{try{const Ve=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),Vt=await Ve.json().catch(()=>({}));if(Q||!Ve.ok)return;const bt=String(Vt?.gate||"").trim().toLowerCase();if(bt!=="ok"&&bt!=="plan_selection_required"&&bt!=="checkout_pending"&&bt!=="misconfigured"&&bt!=="missing_entitlement"){at(null);return}at({gate:bt,canAccessApp:Vt?.canAccessApp===!0,canAccessPlans:Vt?.canAccessPlans!==!1,message:typeof Vt?.message=="string"?Vt.message:null})}catch{Q||at(null)}})(),()=>{Q=!0}},[kn,Gt,ct,p.pathname,p.search]),a.useEffect(()=>{if(In){O(""),wt("");return}if(!je)return;const Q=String(je.workspace?.name||"").trim(),Ve=String(je.suggestedWorkspaceName||"").trim(),Vt=ss(Q,je.workspaceId,je.workspace?.description)?Ve:Q;O(Vt||Ve||Q),wt(String(je.workspace?.description||""))},[je?.workspace?.name,je?.workspace?.description,je?.suggestedWorkspaceName,je?.workspaceId,In,ss]),a.useEffect(()=>{if(!jn||cn!=="workspace")return;if(String(new URLSearchParams(p.search).get("source")||"").trim().toLowerCase()==="cloud"&&Ia){At("cloud"),an(!1);return}At("local")},[Ia,jn,p.search,cn]);const Ya=a.useCallback(async()=>{if(!Ia||!Gt){Ht([]),Jt("");return}gn(!0),un(null);try{const Q=await fetch(`${ia}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),Ve=await Q.json().catch(()=>({}));if(!Q.ok||Ve?.success===!1){Ht([]),Jt(""),un(Ve?.error||`Failed to load cloud projects (${Q.status})`);return}const Vt=Array.isArray(Ve?.workspaces)?Ve.workspaces.map(bt=>({id:String(bt?.id||"").trim(),name:String(bt?.name||bt?.id||"").trim(),description:typeof bt?.description=="string"?bt.description:null})).filter(bt=>bt.id.length>0):[];Ht(Vt),Jt(bt=>bt&&Vt.some(dn=>dn.id===bt)?bt:Vt[0]?.id||"")}catch{Ht([]),Jt(""),un("Failed to load cloud projects.")}finally{gn(!1)}},[Ia,Gt,ia]);a.useEffect(()=>{St==="cloud"&&Ya()},[Ya,St]),a.useEffect(()=>{if(!jn||cn!=="workspace"||St==="cloud")return;let Q=!1;return Y(!0),_e(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async Ve=>{if(!Ve.ok)throw new Error(`Failed to load starter libraries (${Ve.status})`);const Vt=await Ve.json().catch(()=>({})),bt=Array.isArray(Vt?.packs)?Vt.packs:[];Q||bt.length===0||(we(bt),Qt(dn=>bt.some(ot=>ot.id===dn)?dn:bt.find(ot=>ot.isDefaultStarter)?.id||bt[0]?.id||""))}).catch(Ve=>{Q||(we(Tn),_e(Ve instanceof Error?Ve.message:"Failed to load starter libraries."))}).finally(()=>{Q||Y(!1)}),()=>{Q=!0}},[Tn,jn,cn,St]),a.useEffect(()=>{He(tf(It))},[Lt,It]);const ca=a.useMemo(()=>{const Q=new URLSearchParams(p.search).get("next")||"/";return!Q.startsWith("/")||Q==="/login"?"/":Q},[p.search]),ln=_==="year"?"year":"month",rr=a.useCallback(Q=>Q?.planSelectionRequired||Q?.commercialState==="pending_plan_selection"?M:Q?.checkoutPending||Q?.commercialState==="checkout_pending"?nf({gate:"checkout_pending",checkout:b?"start":null,planId:w||null,planVersionId:b||null,interval:b?ln:null}):ca,[ca,M,ln,w,b]),la=a.useMemo(()=>{const Q=String(new URLSearchParams(p.search).get("mode")||"").trim().toLowerCase();return Q==="register"?vn?"register":"login":Q==="verify"||Q==="forgot"||Q==="reset"||Q==="invite"?Q:"login"},[vn,p.search]),va=a.useMemo(()=>String(new URLSearchParams(p.search).get("token")||"").trim(),[p.search]),Un=a.useCallback(Q=>{const Ve=new URLSearchParams(p.search),Vt=Q==="register"&&!vn?"login":Q;Vt==="login"?Ve.delete("mode"):Ve.set("mode",Vt);const bt=Ve.toString();S(`/login${bt?`?${bt}`:""}`,{replace:!0})},[vn,p.search,S]),wa=a.useCallback(async Q=>{if(!vt)return!1;const Ve=await Mt();return Ve.success?(Array.isArray(Ve.workspaces)?Ve.workspaces.length:0)===0?(S("/setup?step=workspace",{replace:!0}),!0):!1:Q?(S("/setup?step=workspace",{replace:!0}),!0):!1},[Mt,S,vt]);a.useEffect(()=>{on&&(ye(la),la==="verify"&&va&&X(va),la==="reset"&&va&&oe(va),la==="invite"&&va&&ie(va))},[on,la,va]),a.useEffect(()=>{j!=="verify"&&(on&&la==="verify"||(pe(!1),D(null)))},[j,on,la]),a.useEffect(()=>{if(!on||j!=="invite"||!xe.trim())return;let Q=!0;return(async()=>{const Ve=await Sn(xe);if(Q)if(Ve.success){Ze(Ve.email||null),Ce(Ve.workspaceId||null),F(Ve.passwordRequired===!0);const Vt=!!(Gt&&oa&&Ve.email&&oa.trim().toLowerCase()===Ve.email.trim().toLowerCase()),bt=Ve.passwordRequired===!0?"new_user":Vt?"existing_user_ready":"existing_user_signed_out";R(bt),E(bt==="new_user"?"Create your account password to join this workspace.":bt==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),x(null),I(null)}else Ze(null),Ce(null),R("invalid"),F(!1),x(ba(Ve)),I(Ve.code||Ve.state||null)})(),()=>{Q=!1}},[on,j,xe,Sn,Gt,oa]),a.useEffect(()=>{j==="invite"&&Oe==="existing_user_signed_out"&&ae&&Z(Q=>Q.trim()?Q:ae)},[j,Oe,ae]),a.useEffect(()=>{if(!(le>Date.now()||de>Date.now()))return;const Ve=window.setInterval(()=>be(Date.now()),1e3);return()=>window.clearInterval(Ve)},[le,de]);const Ls=Math.max(0,Math.ceil((le-ee)/1e3)),rs=Math.max(0,Math.ceil((de-ee)/1e3)),sa=Ls>0,os=rs>0,ba=Q=>{const Ve=Q.error||"Request failed.",Vt=Q.code||Q.state;return Vt?`[${Vt}] ${Ve}`:Ve};a.useEffect(()=>{if(i!=="widget"&&!yt){if($n){Vn||S("/coming-soon",{replace:!0});return}if(Vn&&!$n){S("/",{replace:!0});return}if(_n){if(!on){const Q=`${p.pathname}${p.search}${p.hash}`;S(`/login?next=${encodeURIComponent(Q||"/")}`,{replace:!0});return}return}else{const Q=on&&j==="invite"&&xe.trim().length>0;on&&Gt&&!Q&&S(ca,{replace:!0})}if(Wn){if(!C){const Q=encodeURIComponent(String(Je?.gate||"plan_selection_required"));S(`/?screen=plans&gate=${Q}`,{replace:!0})}return}if(nn){if(Fa){(!jn||cn!=="error")&&S("/setup?step=error",{replace:!0});return}if(Sa){(!jn||cn!=="global")&&S("/setup?step=global",{replace:!0});return}if(Xn){(!jn||cn!=="workspace")&&S("/setup?step=workspace",{replace:!0});return}jn&&S("/",{replace:!0});return}jn&&je&&!In&&S("/",{replace:!0})}},[i,_n,$n,Wn,on,jn,Vn,g,C,Je?.gate,nn,je,Fa,In,Sa,Xn,cn,yt,p.pathname,p.search,p.hash,S,ca]),a.useEffect(()=>{if(i==="widget"||ct!=="local"||!Pt||on||jn)return;const Q=String(Ot||"").trim().toLowerCase();(!Q||Q==="default")&&S("/setup?step=workspace",{replace:!0})},[i,ct,Pt,on,jn,Ot,S]);const is=a.useCallback(async()=>{qe(!0);try{await Fe()}finally{qe(!1)}},[Fe]),cs=a.useCallback(async()=>{await tn(),S("/login",{replace:!0})},[tn,S]);if(i==="widget")return t.jsx(LR,{...Xe,onHeaderMouseDown:r,isDragging:o,onClose:l});if(k){const Q=new URLSearchParams(p.search);return Q.set("screen","plans"),t.jsx(gm,{to:`/?${Q.toString()}${p.hash||""}`,replace:!0})}if(g){const Q=new URLSearchParams(p.search);return Q.set("screen","plans"),t.jsx(gm,{to:`/?${Q.toString()}${p.hash||""}`,replace:!0})}if(rt)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":en,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:Tt,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(Oa)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":en,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:Tt,alt:"Taskforce",className:ve.loginLogo}),t.jsx("h1",{className:ve.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:ve.loginSubtitle,children:vs}),Gn==="stalled"&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:ve.loginError,children:se||"Startup checks timed out."}),t.jsx("button",{className:u.submitBtn,disabled:Pe,onClick:is,children:Pe?"Retrying...":"Retry checks"}),ya&&t.jsx("button",{className:u.cancelBtn,disabled:Pe,onClick:cs,children:"Go to sign-in"})]})]})})});if(on)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":en,children:t.jsx("div",{className:ve.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${wp})`},children:t.jsxs("div",{className:ve.loginCard,children:[!ya&&!_n&&t.jsx("button",{className:ve.loginCloseBtn,"aria-label":"Close sign in",onClick:()=>S(ca,{replace:!0}),children:"×"}),t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Tt,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:[j==="login"&&"Sign in with your account credentials.",j==="register"&&"Create your Taskforce account.",j==="verify"&&"Enter your verification token.",j==="forgot"&&"Request a password reset link.",j==="reset"&&"Set a new password using your reset token.",j==="invite"&&(Oe==="existing_user_ready"?`You've been invited to join ${Le||"this workspace"}.`:Oe==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(j==="login"||j==="register"||j==="forgot"||j==="invite"&&Oe==="existing_user_signed_out")&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"email",value:P,placeholder:"Email",onChange:Q=>Z(Q.target.value)}),j==="register"&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:$,placeholder:"Display name",onChange:Q=>ce(Q.target.value)}),(j==="login"||j==="register"||j==="reset"||j==="invite"&&(W||Oe==="existing_user_signed_out"))&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"password",value:q,placeholder:j==="reset"?"New password":j==="invite"&&W?"Create password":"Password",onChange:Q=>K(Q.target.value)}),j==="verify"&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:U,placeholder:"Verification token",onChange:Q=>X(Q.target.value)}),j==="reset"&&t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:B,placeholder:"Reset token",onChange:Q=>oe(Q.target.value)}),j==="invite"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{className:`${u.input} ${ve.loginInput}`,type:"text",value:xe,placeholder:"Invite token",onChange:Q=>ie(Q.target.value)}),ae&&t.jsxs("p",{className:ve.loginSubtitle,children:["Invite for: ",t.jsx("strong",{children:ae}),Le?` · Workspace: ${Le}`:""]})]}),V&&t.jsx("p",{className:ve.loginSubtitle,children:V}),y&&t.jsx("p",{className:ve.loginError,children:y}),j==="login"&&H==="EMAIL_NOT_VERIFIED"&&P.trim()&&t.jsx("button",{className:ve.authModeLink,disabled:Ie||sa,onClick:async()=>{L(!0),E(null);const Q=await Kt(P);Q.success?(ne(Date.now()+3e4),Un("verify"),Q.verificationToken&&X(Q.verificationToken),E("Verification email resent."),x(null),I(null)):x(ba(Q)),L(!1)},children:sa?`Resend in ${Ls}s`:"Resend Verification Email"}),t.jsx("button",{className:`${u.submitBtn} ${ve.loginPrimaryBtn}`,disabled:Ie||j==="verify"&&sa||j==="forgot"&&os,onClick:async()=>{if(L(!0),E(null),x(null),I(null),j==="register"&&!$.trim()){x("Display name is required."),L(!1);return}let Q={success:!1};if(j==="login"?Q=await fn(P,q):j==="register"?Q=await rn(P,q,{displayName:$,planId:w||void 0,planVersionId:b||void 0,interval:_||void 0}):j==="verify"?Q=await kt(U):j==="forgot"?Q=await $t(P):j==="reset"?Q=await Yt(B,q):j==="invite"&&(Oe==="existing_user_signed_out"?Q=await fn(P,q):Q=W?await ft(xe,q):await mt(xe)),Q.success)if(j==="register"){const Ve=rr(Q);if(Q.verificationRequired)pe(!!Q.workspaceSetupRequired),D(Ve),Q.verificationToken&&X(Q.verificationToken),ne(Date.now()+3e4),Un("verify"),E(Q.emailSent===!1?`Account created, but verification email failed to send. ${Q.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.");else{if(await Fe(),await wa(Q.workspaceSetupRequired)){L(!1);return}Z(""),ce(""),K(""),S(Ve,{replace:!0})}}else if(j==="verify"){if(await Fe(),await wa(Ne)){L(!1);return}Z(""),K(""),S(te||ca,{replace:!0})}else if(j==="forgot")Q.resetToken&&oe(Q.resetToken),G(Date.now()+3e4),Un("reset"),E(Q.emailSent===!1?`Password reset email failed to send. ${Q.emailError||"Try again in a minute."}`:"Password reset instructions sent.");else if(j==="reset")Un("login"),E("Password updated. Sign in with your new password.");else if(j==="invite"){if(Oe==="existing_user_signed_out"){ye("invite"),K(""),E("Signed in. Review the invite details to continue."),L(!1);return}if(Q.workspaceSetupRequired){S("/setup?step=workspace",{replace:!0}),L(!1);return}S(ca,{replace:!0})}else if(j==="login"){if(xe.trim()){ye("invite"),K(""),E("Signed in. Review the invite details to continue."),L(!1);return}if(Q.workspaceSetupRequired){S("/setup?step=workspace",{replace:!0}),L(!1);return}Z(""),ce(""),K(""),S(ca,{replace:!0})}else Z(""),ce(""),K(""),S(ca,{replace:!0});else{if(j==="register"&&(Q.code==="SIGNUP_PLAN_NOT_ENABLED"||Q.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||Q.code==="SIGNUP_PLAN_VERSION_REQUIRED")){S(M,{replace:!0}),L(!1);return}if(x(ba(Q)),I(Q.code||null),j==="login"&&(Q.code==="WORKSPACE_NOT_FOUND"||Q.code==="WORKSPACE_ID_REQUIRED")){S("/setup?step=workspace",{replace:!0}),L(!1);return}if(j==="login"&&Q.code==="EMAIL_NOT_VERIFIED"&&P.trim()){const Ve=await Kt(P);Ve.success&&(ne(Date.now()+3e4),Un("verify"),Ve.verificationToken&&X(Ve.verificationToken),E("Email not verified. A verification token was sent."),x(null),I(null))}}L(!1)},children:Ie?"Working...":j==="login"?"Sign In":j==="register"?"Create Account":j==="verify"?sa?`Resend in ${Ls}s`:"Resend Verification":j==="forgot"?os?`Retry in ${rs}s`:"Send Reset Link":j==="reset"?"Reset Password":Oe==="existing_user_signed_out"?"Sign In to Continue":W?"Create Account and Join":"Join Workspace"}),j==="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"}),"."]}),vn&&(j==="login"||j==="register")&&t.jsxs("p",{className:ve.authModeSwitch,children:[j==="login"?"Need an account?":"Already have an account?"," ",t.jsx("button",{className:ve.authModeSwitchLink,disabled:Ie,onClick:()=>{x(null),I(null),E(null),Un(j==="login"?"register":"login")},children:j==="login"?"Register":"Sign In"})]}),t.jsxs("div",{className:ve.authModeLinks,children:[(j==="login"||j==="register")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:ve.authModeLink,disabled:Ie||os,onClick:()=>{x(null),I(null),E(null),Un("forgot")},children:os?`Forgot Password (${rs}s)`:"Forgot Password"}),t.jsx("button",{className:ve.authModeLink,disabled:Ie||sa,onClick:()=>{x(null),I(null),E(null),Un("verify")},children:sa?`Resend Verification (${Ls}s)`:"Resend Verification"}),t.jsx("button",{className:ve.authModeLink,disabled:Ie,onClick:()=>{x(null),I(null),E(null),Un("invite")},children:"Accept Invite"})]}),j!=="login"&&j!=="register"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:ve.authModeLink,disabled:Ie,onClick:()=>{x(null),I(null),E(null),Un("login")},children:"Sign In"}),vn&&t.jsx("button",{className:ve.authModeLink,disabled:Ie,onClick:()=>{x(null),I(null),E(null),Un("register")},children:"Register"}),j==="reset"&&t.jsx("button",{className:ve.authModeLink,disabled:Ie||os,onClick:()=>{x(null),I(null),E(null),Un("forgot")},children:os?`Forgot Password (${rs}s)`:"Forgot Password"})]})]})]})})});if(_n&&!on)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":en,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:Tt,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(Vn&&$n)return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":en,children:t.jsx("div",{className:ve.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${wp})`},children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Tt,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 Xe.logout(),S("/login",{replace:!0})},children:"Sign Out"})]})})});if(In||jn&&nn&&(Fa||Sa||Xn)){const Q=!In&&(Fa||cn==="error"),Ve=!In&&!Q&&(Sa||cn==="global"),Vt=Q?Te("setup.headingCheckFailed"):Ve?Te("setup.headingGlobalRequired"):In?"Create Workspace":Te("setup.headingWorkspaceRequired"),bt=Q?Te("setup.subtitleUnreadable"):Ve?Te("setup.subtitleGlobalRequired"):In?"Set up the new workspace before it is created.":Te("setup.subtitleWorkspaceRequired"),dn=Te($e==="operations"?"setup.workspaceTermMission":"setup.workspaceTermProject");return t.jsx("div",{className:hn.standaloneWrapper,"data-theme":en,children:t.jsx("div",{className:ve.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${wp})`},children:t.jsxs("div",{className:ve.loginCard,children:[t.jsxs("div",{className:ve.authBrandRow,children:[t.jsx("img",{src:Tt,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:Vt})}),t.jsx("p",{className:ve.loginSubtitle,children:bt}),Me&&t.jsxs("p",{className:ve.loginSubtitle,children:[Te("setup.runtimeLabel"),": ",t.jsx("strong",{children:Me.runtimeMode})]}),d&&t.jsx("p",{className:ve.loginSubtitle,children:d}),nt&&t.jsx("p",{className:ve.loginError,children:nt}),Ve&&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:$e==="core",onChange:()=>fe("core"),disabled:De}),t.jsx("span",{children:Te("setup.coreModeOption",{workspaceLabel:dn})})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:$e==="operations",onChange:()=>fe("operations"),disabled:De}),t.jsx("span",{children:Te("setup.operationsModeOption")})]})]}),!Q&&!Ve&&t.jsxs("div",{className:ve.optionGrid,children:[!ya&&Ia&&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:St==="local",onChange:()=>At("local"),disabled:De}),t.jsxs("span",{children:["Create new local ",dn.toLowerCase()]})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:St==="cloud",onChange:()=>At("cloud"),disabled:De}),t.jsxs("span",{children:["Sync existing cloud ",dn.toLowerCase()]})]})]}),!ya&&St==="cloud"&&Ia?t.jsxs("div",{className:ve.optionGroup,children:[!Gt&&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:De,onClick:()=>{S(`/login?mode=login&next=${encodeURIComponent("/setup?step=workspace&source=cloud")}`,{replace:!0})},children:"Sign In"})]}),Gt&&t.jsxs(t.Fragment,{children:[t.jsxs("select",{className:u.input,value:sn,onChange:ot=>Jt(ot.target.value),disabled:De||Xt||zt.length===0,children:[zt.length===0&&t.jsx("option",{value:"",children:Xt?"Loading cloud projects...":"No cloud projects found"}),zt.map(ot=>t.jsxs("option",{value:ot.id,children:[ot.name," (",ot.id,")"]},ot.id))]}),t.jsx("div",{className:ve.actionRowEnd,children:t.jsx("button",{className:u.cancelBtn,disabled:De||Xt,onClick:()=>{Ya()},children:"Refresh Cloud Projects"})}),Mn&&t.jsx("p",{className:ve.loginError,children:Mn})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("input",{className:u.input,type:"text",value:gt,placeholder:Te("setup.workspaceNamePlaceholder",{workspaceLabel:dn}),onChange:ot=>O(ot.target.value),disabled:De}),t.jsx("textarea",{className:u.textarea,value:Ye,placeholder:Te("setup.workspaceDescriptionPlaceholder",{workspaceLabel:dn}),onChange:ot=>wt(ot.target.value),disabled:De,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."}),Rt.map(ot=>{const da=It?.id===ot.id;return t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-taxonomy-library",checked:da,onChange:()=>Qt(ot.id),disabled:De||Nn}),t.jsx("span",{children:ot.label})]},ot.id)}),It?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:ve.inlineHint,children:It.description}),t.jsxs("p",{className:ve.inlineHint,children:["Includes ",It.categories.length," categories, ",It.types.length," task types, and ",It.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:Dt.categories,onChange:()=>He(ot=>({...ot,categories:!ot.categories})),disabled:De||!It?.categories.length}),t.jsx("span",{children:"Categories"})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:Dt.types,onChange:()=>He(ot=>({...ot,types:!ot.types})),disabled:De||!It?.types.length}),t.jsx("span",{children:"Task Types"})]}),t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:Dt.priorities,onChange:()=>He(ot=>({...ot,priorities:!ot.priorities})),disabled:De||!It?.priorities.length}),t.jsx("span",{children:"Priorities"})]})]}),Nn?t.jsx("p",{className:ve.inlineHint,children:"Loading starter libraries…"}):null,Ae?t.jsx("p",{className:ve.loginError,children:Ae}):null]}),!ya&&Ia&&Gt&&t.jsxs("div",{className:ve.optionGroup,children:[t.jsxs("label",{className:`${ve.authModeLink} ${ve.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:yn,onChange:ot=>an(ot.target.checked),disabled:De}),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:[Ve?t.jsx("button",{className:u.submitBtn,disabled:De,onClick:async()=>{Ke(!0),et(null),dt(null);try{const ot=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:$e}})}),da=await ot.json().catch(()=>({}));!ot.ok||da?.success===!1?dt(da?.error||Te("setup.saveFailedWithStatus",{status:ot.status})):(et(Te("setup.globalSetupSaved")),await Ee())}catch{dt(Te("setup.saveFailed"))}finally{Ke(!1)}},children:Te(De?"setup.saving":"setup.saveGlobalSetup")}):Q?t.jsx("button",{className:u.submitBtn,disabled:De,onClick:Ee,children:Te("setup.retrySetupCheck")}):t.jsx("button",{className:u.submitBtn,disabled:De,onClick:async()=>{if(Ke(!0),et(null),dt(null),!ya&&St==="cloud"&&Ia){if(!Gt){dt("Sign in is required before syncing a cloud project."),Ke(!1);return}const ot=zt.find(ga=>ga.id===sn);if(!ot){dt("Select a cloud project to sync."),Ke(!1);return}const da=await An({workspaceId:ot.id,name:ot.name||ot.id,description:ot.description||void 0});if(!da.success){dt(da.error||Te("setup.saveWorkspaceFailed")),Ke(!1);return}const _a=String(da.workspaceId||ot.id||"").trim();if(!_a){dt("Failed to resolve workspace id for sync setup."),Ke(!1);return}const Zn=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:_a,stateKey:"workspace-sync",patch:{version:2,enabled:!0,phase:"attach-cloud",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),zn=await Zn.json().catch(()=>({}));if(!Zn.ok||zn?.success===!1){dt(zn?.error||`Failed to configure workspace sync (${Zn.status})`),Ke(!1);return}fa({enabled:!0,phase:"attach-cloud",pullCursor:null}),await Ee(),et(`Cloud project synced setup ready: ${ot.name}`)}else{const ot=In||je?.workspaceSetupState==="missing",da=In?await tt(gt,Ye||void 0):null,_a=In?null:await An({workspaceId:ot?void 0:je?.workspaceId,name:gt,description:Ye}),Zn=da||_a;if(!Zn?.success)dt(Zn?.error||Te("setup.saveWorkspaceFailed"));else{const zn=String(da?.workspace?.id||_a?.workspaceId||je?.workspaceId||"").trim();if(!zn){dt("Failed to resolve workspace id for setup."),Ke(!1);return}if(St==="local"&&!!It&&(Dt.categories||Dt.types||Dt.priorities)&&It){const ls=await Bn.onApplySystemTaxonomyPack({pack:It,sections:Dt,remapExistingValuesToDefault:!0,workspaceIdOverride:zn});if(!ls?.success){dt(ls?.error||"Failed to apply starter taxonomy library."),Ke(!1);return}}const qn=!!(!ya&&yn&&Ia&&Gt),Ms=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:zn,stateKey:"workspace-sync",patch:{version:2,enabled:qn,phase:qn?"provision-local":"idle",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),Tr=await Ms.json().catch(()=>({}));if(!Ms.ok||Tr?.success===!1){dt(Tr?.error||`Failed to configure workspace sync (${Ms.status})`),Ke(!1);return}fa({enabled:qn,phase:qn?"provision-local":"idle",pullCursor:null}),et(qn?`${dn} setup saved. Cloud sync enabled.`:Te("setup.workspaceSetupSaved",{workspaceLabel:dn})),In&&(await Ee(),await bn(!0),S("/",{replace:!0}))}}Ke(!1)},children:De?Te("setup.saving"):Te("setup.saveWorkspaceSetup",{workspaceLabel:dn})}),In?t.jsx("button",{className:u.cancelBtn,onClick:()=>{dt(null),et(null),S("/",{replace:!0})},children:"Cancel"}):ct==="cloud"?t.jsx("button",{className:u.cancelBtn,onClick:async()=>{await Xe.logout(),S("/login",{replace:!0})},children:Te("setup.signOut")}):null]})]})})})}return t.jsx(dL,{...Xe,onHeaderMouseDown:r,isDragging:o,onClose:l})}function pL(e){return Lg()?t.jsx(af,{...e}):t.jsx(Mg,{children:t.jsx(af,{...e})})}const Ch={},sf="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=sf,console.info(`[Taskforce] Build marker: ${sf}`));function mL(){return Up(Ch).apiBaseUrl||void 0}function fL(e){const n=Up(Ch),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 i=new URL(s,window.location.origin);if(i.origin!==window.location.origin)console.warn(`[Taskforce] Ignoring cross-origin cloud auth base in hosted runtime: ${i.origin}`);else return s}catch{}else return s}else return s;if(n.baseUrl)return n.baseUrl;if(e)return e}function hL(){const e=mL(),n=fL(e);return t.jsx(Bg,{children:t.jsx(pL,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:n}})})}Yh.createRoot(document.getElementById("root")).render(t.jsx(pt.StrictMode,{children:t.jsx(hL,{})}));export{AL as A,Vm as B,XD as C,jc as D,QD as E,Ri as I,ro as M,IL as P,Xf as R,Bl as T,Su as a,Ss as b,Cy as c,qg as d,Hn as e,cp as f,nu as g,gN as h,cS as i,TL as j,yN as k,Kf as l,gR as m,We as n,zy as o,Hf as p,su as q,Aa as r,ru as s,u as t,CL as u,bL as v,xL as w,_L as x,$p as y,Gm as z};
|