@taskforcehq/taskforce 0.3.323 → 0.3.326
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 +56 -0
- package/dist/components/features/TaskSettings.js +26 -9
- package/dist/components/task/TaskKanban.d.ts +2 -2
- package/dist/components/views/AppShellHeader.js +47 -2
- package/dist/components/views/StandaloneLayout.js +22 -22
- package/dist/components/views/panels/PlanningDrawer.d.ts +2 -2
- package/dist/components/views/panels/PlanningDrawer.js +26 -12
- package/dist/components/views/planningScope.d.ts +4 -0
- package/dist/components/views/planningScope.js +5 -0
- package/dist/core/AiProfileService.js +6 -1
- package/dist/core/Taskforce.d.ts +3 -0
- package/dist/core/Taskforce.js +21 -0
- package/dist/hooks/useTaskforce.js +74 -17
- package/dist/hooks/workspace/workspaceLocalState.d.ts +25 -0
- package/dist/hooks/workspace/workspaceLocalState.js +38 -0
- package/dist/mcp/adminWorkspaceRegistrar.js +0 -10
- package/dist/mcp/clientIntegrations.d.ts +1 -1
- package/dist/mcp/clientIntegrations.js +50 -0
- package/dist/mcp/clientProfileDefaults.js +4 -0
- package/dist/mcp/collaborationRegistrar.js +3 -3
- package/dist/mcp/documentAssetRegistrar.js +24 -72
- package/dist/mcp/documentHelpers.d.ts +11 -4
- package/dist/mcp/documentHelpers.js +21 -17
- package/dist/mcp/runtime.d.ts +4 -0
- package/dist/mcp/runtime.js +466 -534
- package/dist/mcp/taskPlanningRegistrar.js +45 -81
- package/dist/mcp/toolProfiles.d.ts +7 -0
- package/dist/mcp/toolProfiles.js +36 -0
- package/dist/mcp/toolRegistry.d.ts +87 -609
- package/dist/mcp/toolRegistry.js +93 -88
- package/dist/resources/templates/workflow-sources/workflowDocs.mjs +10 -10
- package/dist/resources/templates/workflows/collaborate.yaml +2 -3
- package/dist/resources/templates/workflows/do.yaml +2 -3
- package/dist/resources/templates/workflows/evaluate.yaml +2 -3
- package/dist/resources/templates/workflows/execute.yaml +12 -15
- package/dist/resources/templates/workflows/plan.yaml +3 -4
- package/dist/resources/templates/workflows/review.yaml +2 -3
- package/dist/server/routes/admin.d.ts +1 -0
- package/dist/server/routes/admin.js +29 -1
- package/dist/shared/taxonomyLibrary.js +1 -1
- package/dist/sync/cloudSyncApi.js +22 -3
- package/dist/types.js +1 -1
- package/dist/ui/.well-known/openai-apps-challenge +1 -1
- package/dist/ui/assets/{AgentsModule-7jpDeuVR.js → AgentsModule-C4LcqhcZ.js} +1 -1
- package/dist/ui/assets/{AnnotatedAttachmentWorkspace-BJLe8DFj.js → AnnotatedAttachmentWorkspace-B-Dq22d2.js} +1 -1
- package/dist/ui/assets/{ContextAttachmentManager-AmEny3eI.js → ContextAttachmentManager-DsXPTvi-.js} +1 -1
- package/dist/ui/assets/{DocumentWorkspace-Cqdq31Ha.js → DocumentWorkspace-CxA1wO3U.js} +1 -1
- package/dist/ui/assets/{EntityActivityTimeline-BlS7DhA4.js → EntityActivityTimeline-B8nSe8l3.js} +1 -1
- package/dist/ui/assets/{InitiativesModule-C1qfO1uZ.js → InitiativesModule-VY95v38E.js} +1 -1
- package/dist/ui/assets/{PlansPage-DFt5w-0Y.js → PlansPage-CQbKDv1a.js} +1 -1
- package/dist/ui/assets/{TaskContextUpload-zuro5gDT.js → TaskContextUpload-DvDlNpHC.js} +1 -1
- package/dist/ui/assets/TaskSettings-CUWbYYtP.js +12 -0
- package/dist/ui/assets/{WorkflowsModule-CEEGuxsf.js → WorkflowsModule-CgM3Jako.js} +1 -1
- package/dist/ui/assets/documentReferences-Do9YjrS3.js +1 -0
- package/dist/ui/assets/index--mh3pktj.js +5 -0
- package/dist/ui/assets/index-BawaaEXS.css +1 -0
- package/dist/ui/index.html +2 -2
- package/dist/utils/theme.js +1 -1
- package/package.json +1 -1
- package/src/resources/templates/workflow-sources/workflowDocs.mjs +10 -10
- package/src/resources/templates/workflows/collaborate.yaml +2 -3
- package/src/resources/templates/workflows/do.yaml +2 -3
- package/src/resources/templates/workflows/evaluate.yaml +2 -3
- package/src/resources/templates/workflows/execute.yaml +12 -15
- package/src/resources/templates/workflows/plan.yaml +3 -4
- package/src/resources/templates/workflows/review.yaml +2 -3
- package/dist/ui/assets/TaskSettings-CJPC2Bft.js +0 -9
- package/dist/ui/assets/documentReferences-Ca2P--i5.js +0 -1
- package/dist/ui/assets/index-CGDQY0nN.js +0 -5
- package/dist/ui/assets/index-DcK_8tuE.css +0 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EntityActivityTimeline-B8nSe8l3.js","assets/vendor-react-CKJs5o3c.js","assets/vendor-icons-CLnehDTw.js","assets/vendor-markdown-BUxTU7dS.js","assets/vendor-dnd-DRzYolkg.js","assets/vendor-router-BbWMxlnO.js","assets/EntityActivityTimeline-DyqvvhuF.css","assets/TaskContextUpload-DvDlNpHC.js","assets/ContextAttachmentManager-DsXPTvi-.js","assets/documentReferences-Do9YjrS3.js","assets/TaskSettings-CUWbYYtP.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-B-Dq22d2.js","assets/AnnotatedAttachmentWorkspace-BVKew-mH.css","assets/DocumentWorkspace-CxA1wO3U.js","assets/DocumentWorkspace-D4rJKXzd.css","assets/WorkflowsModule-CgM3Jako.js","assets/AgentsModule-C4LcqhcZ.js","assets/InitiativesModule-VY95v38E.js","assets/PlansPage-CQbKDv1a.js","assets/PlansPage-DeAzWYTb.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r,j as n,R as ze,a as Xi,b as jk}from"./vendor-react-CKJs5o3c.js";import{I as hs,C as ec,a as sl,b as eo,c as of,F as Pk,A as Mk,R as Sd,T as xm,L as Fp,d as Io,e as Ek,X as oc,f as fg,g as hg,h as br,B as sm,U as fi,i as gg,S as Dk,P as to,j as tl,G as Lk,k as Qu,l as om,m as wd,n as Bk,o as cf,p as Wk,q as Op,r as yg,s as Fk,t as Ok,M as kg,W as $k,u as Uk,v as zk,w as Hk,x as To,E as lf,y as vg,z as Sg,D as Gk,H as Vk,J as qk,K as eh,N as th,O as Kk,Q as Zk,Z as Yk,V as Jk,Y as Qk,_ as Xk,$ as wg,a0 as ev,a1 as nh,a2 as tv,a3 as nv,a4 as av,a5 as rv}from"./vendor-icons-CLnehDTw.js";import{M as sv,r as ov,a as iv}from"./vendor-markdown-BUxTU7dS.js";import{u as bg,a as $p,b as cv,D as _g,c as lv,S as Cg,v as Ag,P as xg,d as Ig,C as df,e as dv,p as uv,f as ah,s as mv,K as pv,g as uf,h as fv,i as Tg,j as hv}from"./vendor-dnd-DRzYolkg.js";import{u as Rg,a as Ng,b as gv,M as yv,N as rh,B as kv}from"./vendor-router-BbWMxlnO.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const i of c.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function a(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(o){if(o.ep)return;o.ep=!0;const c=a(o);fetch(o.href,c)}})();const el="default",Im="General",Gr="task",vv=2,Sv=[{value:el,label:Im,icon:"Inbox"}],jg=[{value:Gr,label:"Task",icon:"CheckSquare",color:"blue-500"}],wv=[{value:vv,label:"Medium",color:"blue-500",icon:"Minus"}];function bv(){return Sv.map(e=>({...e}))}function _v(){return jg.map(e=>({...e}))}function Cv(e){const t=String(e||"").trim().toLowerCase();return jg.find(a=>a.value===t)}function Pg(){return wv.map(e=>({...e}))}const Av="default",xv=[{value:Av,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 Mg(){return xv.map(e=>({...e}))}const Iv={categories:bv(),types:_v(),priorities:Pg(),approaches:Mg(),taxonomies:[],apiEndpoint:"/api/taskforce/task",apiBaseUrl:void 0,cloudAuthBaseUrl:void 0,cloudMcpBaseUrl:void 0,wsBaseUrl:void 0,position:"bottom-right",offsetY:70,theme:"dawn",shortcut:"Alt+T",manualComplexityEnabled:!1,checklistDropdownEnabled:!0,showTaskCardStatusLabel:!0},Tv=["light","dawn","dark","midnight"],im="dawn",Rv=[{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"}],Nv=new Set(Tv),jv=new Set(Rv.filter(e=>e.family==="light").map(e=>e.id));function Pv(e){return typeof e=="string"&&Nv.has(e)}function Yc(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return Pv(t)?t:null}function Eg(e){const t=Yc(e);return t!==null&&jv.has(t)}function Up(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return null;const a=Math.floor(t);return a>0?a:null}function nl(e,t){const a=Up(typeof t=="object"&&t!==null?t.referenceNumber:t);return a?`${e}${a}`:""}function mf(e,t){const a=String(e||"").trim(),s=String(t||"").trim();if(!a||!s)return null;const o=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=s.match(new RegExp(`^${o}(\\d+)$`,"i"));return c?Up(c[1]):null}function Tm(e,t){return t?typeof t.referenceLabel=="string"&&t.referenceLabel.trim().length>0?t.referenceLabel.trim():nl(e,t.referenceNumber):""}const pf="T-",sh="LT-";function Mv(e){return nl(pf,e)}function Dg(e){return typeof e=="number"||e===null||e===void 0?nl(sh,e):nl(sh,{referenceNumber:e.localReferenceNumber??null})}function Lg(e){return mf(pf,e)}function nc(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const t=Tm(pf,e);return t||Dg(e.localReferenceNumber)}function Ev(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function Bg(e){return{label:nc(e),isProvisional:Ev(e)}}Pg();const Dv={low:1,medium:2,high:3,critical:4,"on-hold":1},Lv={1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function Bv(e){const t=String(e||"").trim().toLowerCase();return t==="blocked"||t==="on hold"||t==="on-hold"?"on-hold":t==="task"||t==="on-hold"||t==="in-progress"||t==="review"||t==="done"||t==="cancelled"?t:"task"}function cm(e){if(typeof e=="number"&&Number.isFinite(e))return Math.max(1,Math.round(e));const t=Number(e);return Number.isFinite(t)?Math.max(1,Math.round(t)):Dv[String(e||"").trim().toLowerCase()]??2}function Wv(e,t){return Lv[String(e)]||t}function No(e){const t=typeof e.referenceNumber=="number"?e.referenceNumber:Number.isFinite(Number(e.referenceNumber))?Number(e.referenceNumber):null,a=typeof e.localReferenceNumber=="number"?e.localReferenceNumber:Number.isFinite(Number(e.localReferenceNumber))?Number(e.localReferenceNumber):null;return{...e,referenceNumber:t&&t>0?Math.floor(t):null,localReferenceNumber:a&&a>0?Math.floor(a):null,referenceLabel:typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0?e.referenceLabel.trim():t?Mv(t):Dg(a),assignee:(()=>{const s=String(e.assignee||"").trim(),o=s.toLowerCase();return o==="agent"||o==="ai"?"agent":!s||o==="user"||o==="human"||o==="unassigned"||o==="none"||o==="null"?"unassigned":s})(),category:typeof e.category=="string"?e.category:e.category?.value||"default",type:(typeof e.type=="string"?e.type:e.type?.label||"task").toLowerCase(),priority:cm(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:Bv(e.status)}}function Fv(e,t,a){if(!e||typeof e!="object")return{tasks:t,archivedTasks:a};const s=No(e),o=String(s.id||"").trim();if(!o)return{tasks:t,archivedTasks:a};const c=!!s.isArchived,i=c?{...s,isArchived:!0}:{...s,isArchived:!1},d=k=>[...k].sort((S,h)=>{const g=Date.parse(String(S.updatedAt||S.createdAt||"")),v=Date.parse(String(h.updatedAt||h.createdAt||""));if(Number.isFinite(g)&&Number.isFinite(v)&&g!==v)return v-g;if(Number.isFinite(g)!==Number.isFinite(v))return Number.isFinite(v)?1:-1;const _=Date.parse(String(h.createdAt||""))-Date.parse(String(S.createdAt||""));return Number.isFinite(_)&&_!==0?_:String(S.id).localeCompare(String(h.id))}),m=t.filter(k=>k.id!==o),y=a.filter(k=>k.id!==o);return c?y.push(i):m.push(i),{tasks:d(m),archivedTasks:d(y)}}function Ov(e,t){if(!t.length||!e.length)return[];const a=new Set(t.map(o=>Number(o.value))),s=Array.from(new Set(e.map(o=>Number(o)).filter(o=>Number.isFinite(o)&&a.has(o))));return s.length>0?s:t.map(o=>Number(o.value))}function gp(e,t){return t.some(a=>String(a)===String(e))}function $v(e,t){if(!e.length||!t.length)return e;const a=new Set(t.map(o=>o.value)),s=Array.from(new Set(e.filter(o=>a.has(o))));return s.length>0?s:t.map(o=>o.value)}const Uv={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:"—",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 & Support",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:"Configure your new workspace.",subtitleUnreadable:"Taskforce could not read setup state. Retry to continue.",subtitleGlobalRequired:"Choose your default operating mode to continue.",subtitleWorkspaceRequired:"",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"}},zv={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:"—",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 y soporte",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"}},Hv={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:"—",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 e suporte",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"}},Wg=["en-US","es-419","pt-BR"],lm="en-US",yp={"en-US":Uv,"es-419":zv,"pt-BR":Hv},Fg={en:"en-US",es:"es-419",pt:"pt-BR"};let tc=lm;function Gv(e){return e.split(".").filter(Boolean)}function kp(e,t){let a=e;for(const s of t){if(!a||typeof a!="object")return;a=a[s]}return typeof a=="string"?a:void 0}function Og(e){if(!e)return lm;const t=Wg.find(s=>s.toLowerCase()===e.toLowerCase());if(t)return t;const a=e.split("-")[0]?.toLowerCase()||"";return Fg[a]||lm}function vp(e,t){return t?e.replace(/\{([^}]+)\}/g,(a,s)=>{const o=t[s];return o==null?"":String(o)}):e}function $g(){return tc}function Vv(){return[...Wg]}function Ug(e){const t=Og(e);return tc=t,t}function qv(e){const t=typeof navigator<"u"?navigator.language:null;return tc=Og(t),tc}function qe(e,t){const a=Gv(e),s=kp(yp[tc],a);if(s)return vp(s,t);const o=tc.split("-")[0]?.toLowerCase()||"",c=Fg[o];if(c&&c!==tc){const d=kp(yp[c],a);if(d)return vp(d,t)}const i=kp(yp[lm],a);return i?vp(i,t):e}const Kv="default",ac="bootstrap";function Zv(e){let t=2166136261;for(let a=0;a<e.length;a+=1)t^=e.charCodeAt(a),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function ff(e){const t=String(e||"").trim().toLowerCase();return t?`${(t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${Zv(t)}`:ac}function zg(e){const t=String(e||"").trim().toLowerCase();if(!t)return ac;const a=t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return a?a.slice(0,96):ac}function Hg(e){const t=String(e||"").trim();return t?ff(t):ac}function Yv(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?ac:Hg(e.projectRoot)}function Jv(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const a=String(e.workspaceId||"").trim();return a&&!hf(a)?ff(`cloud-workspace:${a}`):ac}return Hg(e.projectRoot)}function hf(e){return String(e||"").trim().toLowerCase()===Kv}const Qv={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function Xv(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function eS(e){return Qv[Xv(e)]}const bd={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 Rm(e){const t=String(e||"").trim().toLowerCase();return t==="production"||t==="staging"||t==="performance"?t:null}function tS(e){return Rm(e)||"production"}function oh(e){return bd[tS(String(e||""))]}function nS(e){const t=String(e||"").trim().toLowerCase();if(!t)return null;for(const[a,s]of Object.entries(bd))if(new URL(s.appBaseUrl).hostname.toLowerCase()===t||new URL(s.mcpBaseUrl).hostname.toLowerCase()===t)return a;return null}function gf(e){const t=String(e||"").trim();if(!t)return null;try{return nS(new URL(t).hostname)}catch{return null}}function aS(e){const t=gf(e);return t?bd[t].mcpBaseUrl:null}function Vi(e,t){return String(e[t]||"").trim()}function ih(e,t,a){e.push(t),a?.(t)}function rS(e,t){const a=[],s=Vi(e,"ENV"),o=Rm(s);if(o)return ih(a,`[Taskforce compat] ENV=${s} is deprecated; set TASKFORCE_CLOUD_ENVIRONMENT=${o} instead.`,t),{cloudEnvironment:o,warnings:a};const c=[{key:"TASKFORCE_CLOUD_PROXY_BASE_URL",value:Vi(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:Vi(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:Vi(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:Vi(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:Vi(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:Vi(e,"TASKFORCE_BASE_URL")}];for(const i of c){if(!i.value)continue;const d=gf(i.value);if(d)return ih(a,`[Taskforce compat] ${i.key} is being used to infer TASKFORCE_CLOUD_ENVIRONMENT=${d}. Set TASKFORCE_CLOUD_ENVIRONMENT explicitly.`,t),{cloudEnvironment:d,warnings:a}}return{cloudEnvironment:null,warnings:a}}function Ys(e,t){return String(e[t]||"").trim()}function sS(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function qc(e){return String(e||"").trim().replace(/\/+$/,"")}function oS(e){return String(e||"").trim().replace(/\/+$/,"")}function Ao(...e){for(const t of e)if(String(t||"").trim())return String(t||"").trim();return""}function iS(e,t={}){const a=[],s=ie=>{a.push(ie),t.onWarning?.(ie)},o=sS(Ys(e,"TASKFORCE_RUNTIME_MODE")),c=Rm(Ys(e,"TASKFORCE_CLOUD_ENVIRONMENT")),i=c?{cloudEnvironment:c}:rS(e,s),d=c||i.cloudEnvironment,m=qc(String(t.requestBaseUrl||"")),y=qc(Ao(Ys(e,"VITE_TASKFORCE_BASE_URL"),Ys(e,"TASKFORCE_BASE_URL"))),k=qc(Ys(e,"VITE_TASKFORCE_API_BASE_URL")),S=qc(Ys(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),h=qc(Ao(Ys(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),Ys(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),g=qc(Ys(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),v=oS(Ys(e,"VITE_TASKFORCE_WS_BASE_URL")),_=d?bd[d].appBaseUrl:"",I=d?bd[d].mcpBaseUrl:"",A=Ao(g,S,k,y,_),D=Ao(h,I,A),U=Ao(m,y,k,S,A),W=Ao(m,k,y,A),Q=Ao(S,y,k,A),le=o==="local"?Ao(v,m,k,y,g,S,_,A):Ao(m,v,W,U,A);return{runtimeMode:o,cloudEnvironment:d,cloudBaseUrl:A,cloudMcpBaseUrl:D,baseUrl:U,apiBaseUrl:W,cloudAuthBaseUrl:Q,wsBaseUrl:le,cloudAuthViaLocalProxy:o==="local"||!!g,warnings:a}}function yf(e){return iS({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})}function ch(e){const t=String(e.workspaceId||"default").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"default",a=Number.isFinite(Number(e.epoch))?Math.max(0,Math.floor(Number(e.epoch))):0,s=String(e.seed||"session").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"session",o=String(e.phase||"bootstrap").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"bootstrap";return`tfb-${s}-${t}-e${a}-${o}`}function Sp(e,t){const a=String(t||"").trim();if(!a)return e;const s=new Headers(e?.headers||void 0);return s.has("x-taskforce-bootstrap-trace-id")||s.set("x-taskforce-bootstrap-trace-id",a),{...e||{},headers:s}}const dm="unassigned",Gg="agent",cS="user",lS=/^[0-9a-f]{8,}$/i;function Vg(e){const t=String(e||"").trim().toLowerCase();return t===Gg||t==="ai"||t.startsWith("ai-profile-")}function qg(e){const t=String(e||"").trim().toLowerCase();return!t||t===dm||t==="none"||t==="null"||t===cS}function um(e){return Vg(e)?"agent":qg(e)?"unassigned":"member"}function dS(e){const t=String(e.displayName||"").trim(),a=String(e.email||"").trim().toLowerCase();return t||a||String(e.userId||"").trim()||"Workspace member"}function gi(){return[{value:dm,label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)",kind:"unassigned"}]}function uS(e){const t=new Map;for(const a of e){const s=String(a.userId||"").trim();s&&t.set(s,{value:s,label:dS(a),icon:"User",color:"#22c55e",kind:"member",avatarUrl:typeof a.avatarUrl=="string"&&a.avatarUrl.trim().length>0?a.avatarUrl.trim():null})}return _d(Array.from(t.values()))}function _d(e){const t=new Map;for(const s of gi())t.set(s.value,s);for(const s of Array.isArray(e)?e:[]){const o=String(s?.value||"").trim(),c=typeof s?.archivedAt=="string"?s.archivedAt.trim():"";!o||c||o===dm||o===Gg||t.set(o,{value:o,label:String(s.label||o).trim()||o,icon:String(s.icon||(s.kind==="agent"?"Bot":"User")),color:String(s.color||(s.kind==="agent"?"#8b5cf6":"#22c55e")),kind:s.kind==="agent"?"agent":"member",avatarUrl:typeof s.avatarUrl=="string"&&s.avatarUrl.trim().length>0?s.avatarUrl.trim():null,avatarRevision:Number.isFinite(Number(s.avatarRevision))?Math.max(0,Math.floor(Number(s.avatarRevision))):null,avatarUpdatedAt:typeof s.avatarUpdatedAt=="string"&&s.avatarUpdatedAt.trim().length>0?s.avatarUpdatedAt.trim():null,username:typeof s.username=="string"&&s.username.trim().length>0?s.username.trim():null,archivedAt:null,createdAt:typeof s.createdAt=="string"&&s.createdAt.trim().length>0?s.createdAt.trim():null,updatedAt:typeof s.updatedAt=="string"&&s.updatedAt.trim().length>0?s.updatedAt.trim():null})}const a=[dm];return Array.from(t.values()).sort((s,o)=>{const c=a.indexOf(s.value),i=a.indexOf(o.value);return c>=0||i>=0?c<0?1:i<0?-1:c-i:s.label.localeCompare(o.label,void 0,{sensitivity:"base"})})}function mS(e,t){const a=String(t||"").trim();if(!a||e.some(c=>c.value===a))return e;const s=a.replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),o=s?s.split(" ").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" "):a;if(um(a)==="agent"){const c=String(a).toLowerCase().startsWith("ai-profile-")&&s.split(" ").every(i=>lS.test(i));return _d([...e,{value:a,label:c?"AI":o||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return um(a)==="member"?_d([...e,{value:a,label:o||a,icon:"User",color:"#22c55e",kind:"member"}]):e}function Kg(e){const t=Array.isArray(e)?e.filter(Boolean):[];return _d(t)}function hd(e,t){const a=String(e||"").trim(),o=Kg(t).find(c=>c.value===a);return o?o.label:Vg(a)?"AI":qg(a)?"Unassigned":a||"Unassigned"}const Zg="taskforce.workspaceContext.v2",pS="taskforce.uiState.app.v1",fS="taskforce.bootstrapDebug.v1",lh=5e3,Du=new Map;function Lu(e){return Array.from(new Set(e.map(t=>String(t??"").trim()).filter(t=>t.length>0))).sort()}function hS(e){const t=Lu(e.categories.map(c=>c.value)),a=Lu(e.types.map(c=>c.value)),s=Lu(e.priorities.map(c=>c.value));if(t.length===0||a.length===0||s.length===0)return null;const o={};return(e.taxonomies||[]).forEach(c=>{const i=String(c.id??"").trim();i&&(o[i]=Lu((c.options||[]).map(d=>d.value)))}),{categories:t,types:a,priorities:s,taxonomies:o}}function ad(e,t){return e.length===t.length&&e.every((a,s)=>a===t[s])}function gS(e,t){if(!e||!t||!ad(e.categories||[],t.categories||[])||!ad(e.types||[],t.types||[])||!ad(e.priorities||[],t.priorities||[]))return!1;const a=Object.keys(e.taxonomies||{}).sort(),s=Object.keys(t.taxonomies||{}).sort();return ad(a,s)?a.every(o=>ad(e.taxonomies[o]||[],t.taxonomies[o]||[])):!1}function yS(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(fS)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Ut(e,t){if(!yS())return;console.info("[Taskforce Bootstrap]",e,t&&typeof t=="object"?t:{})}function kS(e,t){const a=String(e).trim()||"default";return`${String(t).trim()||"default"}::${a}`}async function kf(e){const t=String(e.stateKey||"default").trim()||"default",a=String(e.workspaceId||"").trim(),s=e.patch&&typeof e.patch=="object"?e.patch:{},o=JSON.stringify(s),c=kS(t,a||"default"),i=Date.now(),d=Du.get(c);if(d&&d.serializedPatch===o){if(d.status==="success"&&e.skipIfUnchanged!==!1)return Ut("ui_state_persist_skipped",{stateKey:t,workspaceId:a||"default",reason:"unchanged"}),{skipped:!0,reason:"unchanged"};if(e.respectFailureCooldown!==!1&&d.retryAfter>i)return Ut("ui_state_persist_skipped",{stateKey:t,workspaceId:a||"default",reason:"cooldown",retryAfterMs:d.retryAfter-i}),{skipped:!0,reason:"cooldown"}}try{const m=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json",...e.headers||{}},credentials:"include",body:JSON.stringify({stateKey:t,...a?{workspaceId:a}:{},patch:s})}),y=await m.json().catch(()=>({}));if(m.ok&&y?.success!==!1)return Du.set(c,{serializedPatch:o,status:"success",retryAfter:0}),{skipped:!1,response:m,payload:y};if(Du.set(c,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??lh)}),Ut("ui_state_persist_failed",{stateKey:t,workspaceId:a||"default",status:m.status,error:String(y?.error||"")}),e.throwOnError)throw new Error(String(y?.error||`Failed to persist UI state (${m.status})`));return{skipped:!1,response:m,payload:y}}catch(m){if(Du.set(c,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??lh)}),Ut("ui_state_persist_failed",{stateKey:t,workspaceId:a||"default",error:m instanceof Error?m.message:String(m)}),e.throwOnError)throw m;return{skipped:!1,payload:null}}}function vf(e){const t=ff(e);return`${Zg}.${t}`}function Yg(e){const t=zg(e);return`${Zg}.${t}`}function zp(e){if(typeof window>"u")return"";try{const t=vf(e),a=String(window.localStorage.getItem(t)||"").trim();if(a&&a.length<=120&&!/\s/.test(a))return a;const s=Yg(e),o=String(window.localStorage.getItem(s)||"").trim();return o&&o.length<=120&&!/\s/.test(o)?(window.localStorage.setItem(t,o),o):""}catch{return""}}function vS(e,t){if(typeof window>"u")return;const a=String(e||"").trim();try{if(!a||hf(a))return;const s=vf(t),o=String(window.localStorage.getItem(s)||"").trim();if(!a&&o&&o.toLowerCase()!=="default")return;window.localStorage.setItem(s,a)}catch{}}function dh(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(vf(e)),window.localStorage.removeItem(Yg(e))}catch{}}function Jg(e){const t=zg(e);return`${pS}.${t}`}function uh(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Jg(e));if(!t)return null;const a=JSON.parse(t);return a&&typeof a=="object"?a:null}catch{return null}}function SS(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Jg(t),JSON.stringify(e))}catch{}}const Hp="taskforce.localMutationActorUserId.v1";function Qg(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function wS(e){const t=String(e||"").trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function cd(e){if(!(typeof window>"u"))try{const t=String(e||"").trim();if(!t||t==="anonymous"){window.sessionStorage.removeItem(Hp);return}window.sessionStorage.setItem(Hp,t)}catch{}}function Sf(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Hp)||"").trim()}catch{return""}}function bS(e,t){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!wS(window.location.hostname))return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function _S(e,t,a){if(!bS(e,t))return a;const s=Sf();if(!s)return a;const o=new Headers(a?.headers||void 0);return o.has("x-taskforce-user-id")||o.set("x-taskforce-user-id",s),{...a,headers:o}}function CS(e,t){if(!e.startsWith("/"))return e;const a=Qg(t);return a?`${a}${e}`:e}async function YO(e,t,a){const s=CS(e,a),o=Qg(a).length>0,c=_S(e,s,t),i=typeof performance<"u"?performance.now():Date.now();try{const d=await fetch(s,c);if(!(o&&s!==e&&e.startsWith("/api/taskforce/")&&(d.status===401||d.status===403)))return d;Ut("taskforce_api_auth_fallback_retry",{path:e,primaryUrl:s,fallbackUrl:e,status:d.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)});try{const y=await fetch(e,c);return Ut("taskforce_api_auth_fallback_completed",{path:e,primaryUrl:s,fallbackUrl:e,primaryStatus:d.status,fallbackStatus:y.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),y}catch{return Ut("taskforce_api_auth_fallback_failed",{path:e,primaryUrl:s,fallbackUrl:e,status:d.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),d}}catch(d){if(!o||!e.startsWith("/"))throw d;Ut("taskforce_api_network_fallback_retry",{path:e,primaryUrl:s,fallbackUrl:e,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i),error:d instanceof Error?d.message:String(d)});const m=await fetch(e,c);return Ut("taskforce_api_network_fallback_completed",{path:e,primaryUrl:s,fallbackUrl:e,fallbackStatus:m.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),m}}const AS=45e3;function xS(e){const t=Number(e?.status);return Number.isFinite(t)&&t>0?Math.floor(t):0}async function ol(e){try{const t=await e,a=await t.text().catch(()=>"");let s={};if(a)try{s=JSON.parse(a)}catch{s={error:!t.ok&&t.statusText?`${t.status} ${t.statusText}`:a.slice(0,400)}}else!t.ok&&t.statusText&&(s={error:`${t.status} ${t.statusText}`});const o=t.headers.get("retry-after");let c;if(o){const i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>0)c=i*1e3;else{const d=Date.parse(o);if(Number.isFinite(d)){const m=d-Date.now();m>0&&(c=m)}}}return{ok:t.ok,status:t.status,data:s,retryAfterMs:c}}catch(t){const s=String(t?.name||"").trim()==="AbortError"?{error:"Workspace sync pull request timed out."}:{};return{ok:!1,status:xS(t),data:s}}}function IS(e,t,a){const s=typeof AbortController=="function"?new AbortController:null,o=s?globalThis.setTimeout(()=>s.abort(),Math.max(1,Math.floor(a))):null;return fetch(e,{...t,...s?{signal:s.signal}:{}}).finally(()=>{o!==null&&globalThis.clearTimeout(o)})}async function TS(e){return ol(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function RS(e,t){return ol(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function wp(e,t){return ol(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t})}))}async function mh(e,t){return ol(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function NS(e,t){const a=new URLSearchParams({limit:String(t.limit),workspaceId:t.workspaceId});t.cursor&&a.set("cursor",t.cursor),t.repairMode===!0&&a.set("repair","1");const s=e("/api/taskforce/sync/workspace/pull"),o=s.includes("?")?"&":"?";return ol(IS(`${s}${o}${a.toString()}`,{method:"GET",credentials:"include"},AS))}async function jS(e,t){return ol(fetch(e("/api/taskforce/sync/workspace/push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({...t,...t.repairMode===!0?{repair:!0}:{}})}))}async function Gp(e,t,a){const s=JSON.stringify({workspaceId:e,changes:t,workspaceMembers:Array.isArray(a?.workspaceMembers)?a.workspaceMembers:void 0,...a?.repairMode===!0?{repair:!0}:{},bootstrapSnapshot:a?.bootstrapSnapshot?{currentAnnotatedAttachmentSessionIds:Array.isArray(a.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds)?a.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds:[]}:void 0}),o="/api/taskforce/sync/workspace/apply-local",c=[];try{const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:s});if(i.ok){const y=await i.json().catch(()=>({}));return{ok:!0,status:i.status,data:y,failures:c}}const d=await i.text().catch(()=>"");let m={};if(d)try{m=JSON.parse(d)}catch{m={error:d.slice(0,400)}}else i.statusText&&(m={error:`${i.status} ${i.statusText}`});return c.push(`${o}:${i.status}`),{ok:!1,status:i.status,data:m,failures:c}}catch{c.push(`${o}:network`)}return{ok:!1,status:0,data:{},failures:c}}const Vp="V1:AESGCM:",wf="AES-GCM",PS=12;async function Xg(e){const t=Buffer.from(e,"base64");if(t.length!==32)throw new Error("Encryption key must be exactly 32 bytes (256-bit).");return crypto.subtle.importKey("raw",t,{name:wf},!1,["encrypt","decrypt"])}async function ph(e,t){if(!e)return e;const a=crypto.getRandomValues(new Uint8Array(PS)),s=await Xg(t),c=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:wf,iv:a},s,c),d=Buffer.from(i).toString("base64"),m=Buffer.from(a).toString("base64");return`${Vp}${m}:${d}`}async function fh(e,t){if(!e||!e.startsWith(Vp))return e;const a=e.slice(Vp.length),[s,o]=a.split(":");if(!s||!o)throw new Error("Malformed encrypted document payload.");const c=Buffer.from(s,"base64"),i=Buffer.from(o,"base64"),d=await Xg(t);try{const m=await crypto.subtle.decrypt({name:wf,iv:c},d,i);return new TextDecoder("utf-8").decode(m)}catch(m){throw new Error(`Failed to decrypt document: ${m.message}`)}}var Jc={};function ss(e){return e&&typeof e=="object"?e:{}}function Ms(e){const t=Number(e||0);return t===0||t===429||t>=500}function hh(e,t){const a=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim();return a==="WORKSPACE_ID_ALREADY_EXISTS"||s.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.":s||`Workspace provisioning failed (${t})`}function MS(e,t){if(t!==400)return!1;const a=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim().toLowerCase();return a==="WORKSPACE_ID_REQUIRED"&&s.includes("no cloud workspace is selected")}async function ES(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 t=await wp(e.resolveCloudAuthUrl,e.workspaceId);if(t.ok)return{success:!0,provisioned:!1};const a=ss(t.data);if(t.status===401)return{success:!1,statusCode:401,transient:!1,error:String(a.error||"Authentication required for workspace sync.")};if(t.status===429)return{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(a.error||"Workspace sync rate limited. Please retry later.")};if(MS(a,t.status)){const s=await mh(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=ss(s.data);return{success:!1,statusCode:s.status,transient:Ms(s.status),retryAfterMs:s.retryAfterMs,error:hh(o,s.status)}}if(t=await wp(e.resolveCloudAuthUrl,e.workspaceId),!t.ok){const o=ss(t.data);return t.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:t.status===429?{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:t.status,transient:Ms(t.status),error:String(o.error||`Workspace sync handshake failed (${t.status})`)}}return{success:!0,provisioned:!0}}if(t.status===409&&a.code==="WORKSPACE_ID_MISMATCH"){if(e.allowProvisionOnMismatch===!1)return{success:!1,statusCode:409,transient:!1,error:String(a.error||"Selected cloud workspace could not be attached to this local workspace.")};const s=await mh(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=ss(s.data);return{success:!1,statusCode:s.status,error:hh(o,s.status)}}if(t=await wp(e.resolveCloudAuthUrl,e.workspaceId),!t.ok){const o=ss(t.data);return t.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:t.status===429?{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:t.status,transient:Ms(t.status),error:String(o.error||`Workspace sync handshake failed (${t.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:t.status,transient:Ms(t.status),error:String(a.error||`Workspace sync handshake failed (${t.status})`)}}catch{return{success:!1,statusCode:0,transient:!0,error:"Failed to validate workspace sync access."}}}async function DS(e,t){const a=JSON.stringify([e,t]);try{const s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a));return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{let s=2166136261;for(let c=0;c<a.length;c+=1)s^=a.charCodeAt(c),s=Math.imul(s,16777619);const o=(s>>>0).toString(16).padStart(8,"0");return`${e}:fallback:${o}`}}async function LS(e){const t=e.payload.changes.length,a=e.payload.deleteTaskIds.size,s=await DS(e.workspaceId,e.payload.changes);let o=0,c=e.payload.changes;if(typeof process<"u"&&Jc?.TASKFORCE_SYNC_KEY){const S=Jc.TASKFORCE_SYNC_KEY,h=[];for(const g of c)g.op==="document-upsert"&&typeof g.content=="string"?h.push({...g,content:await ph(g.content,S)}):g.op==="asset-upsert"&&typeof g.contentBase64=="string"&&g.contentBase64.length>0?h.push({...g,contentBase64:await ph(g.contentBase64,S)}):h.push(g);c=h}const i=async()=>{const S=Date.now(),h=await jS(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,idempotencyKey:s,changes:c,repairMode:e.repairMode===!0});return o+=Date.now()-S,h};let d=await i();if(!d.ok&&(d.status===403||d.status===409)&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(d=await i()),!d.ok){const S=ss(d.data);return{success:!1,status:d.status,error:typeof S.error=="string"?S.error:void 0,code:typeof S.code=="string"?S.code:void 0,retryAfterMs:d.retryAfterMs,transient:Ms(d.status),requestMs:o,changeCount:t,deleteCount:a,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,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,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,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,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]}}const m=ss(d.data),y=Array.isArray(m.emittedEventIds)?Array.from(new Set(m.emittedEventIds.map(S=>String(S||"").trim()).filter(Boolean))):[],k=Array.isArray(m.appliedTaskUpserts)?m.appliedTaskUpserts.map(S=>{const h=S&&typeof S=="object"?S:{},g=h.task&&typeof h.task=="object"?h.task:null,v=String(g?.id||"").trim();return!g||!v?null:{archived:h.archived===!0,task:g}}).filter(S=>!!S):[];return{success:!0,syncedAt:new Date().toISOString(),requestMs:o,changeCount:t,deleteCount:a,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,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,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,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,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:e.payload.pushedWatermarks,pushedTaskChangeKeys:e.payload.pushedTaskChangeKeys??new Map,emittedEventIds:y,appliedTaskUpserts:k}}async function BS(e){let t=e.cursor,a=!0,s=0,o=0,c=0,i=0;const d=new Set;let m=!1,y=!1,k=!1,S=!1;const h=new Set,g=new Set,v=new Set;let _=null;const I=Number.isFinite(Number(e.maxPages))?Math.max(1,Math.floor(Number(e.maxPages))):20;try{for(;a&&s<I;){const A=async()=>{const se=Date.now(),$=await NS(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:t,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0});return c+=Date.now()-se,$};let D=await A();if(!D.ok&&D.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(D=await A()),!D.ok){const se=ss(D.data);return{success:!1,kind:"pull_http",status:D.status,errorCode:typeof se.code=="string"?se.code:void 0,error:typeof se.error=="string"?se.error:void 0,retryAfterMs:D.retryAfterMs,transient:Ms(D.status),cursor:t,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),serverDiagnostics:null}}const U=D.data||{},W=Array.isArray(U?.changes)?U.changes:[],Q=U?.diagnostics&&typeof U.diagnostics=="object"?U.diagnostics:null;_=Q;const le=Array.isArray(U?.workspaceMembers),ie=le?U.workspaceMembers:void 0;for(const se of W){if(se.op==="upsert"){se?.archived===!0||se?.task?.isArchived===!0?y=!0:m=!0;continue}if(se.op==="annotated-attachment-session-upsert"){const C=String(se?.session?.id||"").trim();C&&v.add(C);continue}if(se.op==="task-event-upsert"||se.op==="entity-event-upsert"){k=!0;continue}if(se.op==="initiative-upsert"||se.op==="workstream-upsert"){S=!0;continue}if(se.op==="document-upsert"){if(typeof se.content=="string"&&typeof process<"u"&&Jc?.TASKFORCE_SYNC_KEY)try{se.content=await fh(se.content,Jc.TASKFORCE_SYNC_KEY)}catch{const C=String(se.path||"").trim();C&&h.add(C)}continue}if(se.op==="asset-upsert"){if(typeof se.contentBase64=="string"&&typeof process<"u"&&Jc?.TASKFORCE_SYNC_KEY)try{se.contentBase64=await fh(se.contentBase64,Jc.TASKFORCE_SYNC_KEY)}catch{const C=String(se.path||"").trim();C&&h.add(C)}continue}if(se.op!=="delete")continue;const $=String(se.taskId||"").trim();$&&d.add($)}if(e.onPagePulled&&e.onPagePulled(),W.length>0||le){const se=Date.now(),$=await Gp(e.workspaceId,W,{...le?{workspaceMembers:ie}:{},repairMode:e.repairMode===!0}),C=$.failures;if(!$.ok){i+=Date.now()-se;const ke=ss($.data);if(C.some(H=>H.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:C,cursor:t,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,documentDecryptFailures:Array.from(h),serverDiagnostics:Q};const j=C.some(H=>{if(H.endsWith(":network"))return!0;const ue=H.split(":").pop()||"",ye=Number.parseInt(ue,10);return Number.isFinite(ye)&&(ye===429||ye>=500)});return{success:!1,kind:"apply_all_candidates",status:$.status||void 0,transient:j,error:String(ke.error||"").trim()||void 0,failures:C,hasTransientApplyFailure:j,cursor:t,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_}}const de=ss($.data);if(de.success===!1)return i+=Date.now()-se,{success:!1,kind:"apply_payload",transient:!1,error:String(de.error||"Workspace sync apply failed."),cursor:t,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_};if(i+=Date.now()-se,o+=W.length,Array.isArray(de.emittedEventIds))for(const ke of de.emittedEventIds)g.add(String(ke));e.onChangesApplied&&e.onChangesApplied(W.length)}U&&"nextCursor"in U&&(U.nextCursor===null||typeof U.nextCursor=="string")&&(t=U.nextCursor),a=!!U?.hasMore,s+=1}if(e.bootstrap){const A=Date.now(),D=await Gp(e.workspaceId,[],{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(v)}}),U=D.failures;if(!D.ok){i+=Date.now()-A;const W=ss(D.data);if(U.some(ie=>ie.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:U,cursor:t,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_};const le=U.some(ie=>{if(ie.endsWith(":network"))return!0;const se=ie.split(":").pop()||"",$=Number.parseInt(se,10);return Number.isFinite($)&&($===429||$>=500)});return{success:!1,kind:"apply_all_candidates",status:D.status||void 0,transient:le,error:String(W.error||"").trim()||void 0,failures:U,hasTransientApplyFailure:le,cursor:t,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_}}i+=Date.now()-A}return{success:!0,syncedAt:new Date().toISOString(),cursor:t||null,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_}}catch(A){return{success:!1,kind:"exception",status:0,transient:!0,error:String(A?.message||A||"Workspace sync pull failed unexpectedly."),cursor:t||null,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:null}}}async function WS(e){const t=await TS(e.resolveCloudAuthUrl);if(!t.ok){const h=Number(t.status||0);return{success:!1,error:`Sync pull failed (${t.status})`,statusCode:t.status,retryAfterMs:t.retryAfterMs,transient:Ms(h)}}const a=ss(t.data),s=a.settings&&typeof a.settings=="object"?a.settings:{},o=typeof a.updatedAt=="string"&&a.updatedAt.trim().length>0?a.updatedAt.trim():null,c=e.getLocalUpdatedAt(e.userId),i=c?Date.parse(c):NaN,d=o?Date.parse(o):NaN;if(!c&&e.preferCloudOnFirstSync&&Number.isFinite(d))return await e.applyRemoteSettings(s),{success:!0,mode:"pulled",updatedAt:o};if(Number.isFinite(d)&&(!Number.isFinite(i)||d>i))return await e.applyRemoteSettings(s),{success:!0,mode:"pulled",updatedAt:o};const m=c||new Date().toISOString(),y=await RS(e.resolveCloudAuthUrl,{settings:e.buildLocalSettings(),updatedAt:m});if(!y.ok){const h=Number(y.status||0);return{success:!1,error:`Sync push failed (${y.status})`,statusCode:y.status,retryAfterMs:y.retryAfterMs,transient:Ms(h)}}const k=ss(y.data);return{success:!0,mode:"pushed",updatedAt:typeof k.updatedAt=="string"&&k.updatedAt.trim().length>0?k.updatedAt.trim():m}}function FS(e){const t=Math.max(1,Math.floor(Number(e)||1)),a=Math.min(12e4,1500*2**Math.max(0,t-1)),s=Math.floor(a*(.15*Math.random()));return a+s}const OS=["chat_app","ide","cli","coding_tool","agent"],JO=["chat_app","ide","cli","coding_tool","agent","unclassified"],$S={chat_app:"Chat App",ide:"IDE",cli:"CLI",coding_tool:"Coding Tool",agent:"Agent"},US={chat_app:"Chat Apps",ide:"IDEs",cli:"CLI",coding_tool:"Coding Tools",agent:"Agents",unclassified:"Unclassified"};function zS(e){return typeof e=="string"&&OS.includes(e)}function ey(e){if(typeof e!="string")return null;const t=e.trim();return t==="other"?"agent":zS(t)?t:null}function QO(e){return $S[e]}function XO(e){return e??"unclassified"}function e$(e){return US[e]}const HS=["cloud_metered","local_unmetered"],GS={cloud_metered:"Cloud MCP",local_unmetered:"Local MCP"};function VS(e){return typeof e=="string"&&HS.includes(e)}function ty(e){if(typeof e!="string")return null;const t=e.trim();return VS(t)?t:null}function t$(e){return GS[e]}function hi(e){if(e==null)return;const t=String(e).trim();return t.length>0?t:void 0}function ha(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Cd(e){return hi(e)}function mm(e){return ha(e)}function Hr(e){return ha(e)}function al(e){const t=ha(e);return t&&t.startsWith("/api/taskforce/context/")?t:null}function Bu(e){return hi(e)}function Wu(e){if(e!==void 0)return ha(e)}function qS(e){return typeof e=="boolean"?e:void 0}function Fu(e,t){if(e===void 0)return;if(e===null||e==="")return t?.nullable?null:void 0;const a=typeof e=="number"?e:Number(e);if(!Number.isFinite(a))return t?.nullable?null:void 0;const s=Math.floor(a);return Number.isFinite(t?.min)&&s<Number(t?.min)?t?.nullable?null:void 0:s}function KS(e){if(!e||typeof e!="object"||Array.isArray(e))return;const a=Object.entries(e).reduce((s,[o,c])=>Array.isArray(c)?(s[o]=c.map(i=>String(i??"")),s):(c==null||(s[o]=String(c)),s),{});return Object.keys(a).length>0?a:{}}function ZS(e){return Array.isArray(e)?e:void 0}function YS(e){return Array.isArray(e)?e:void 0}function JS(e){return Array.isArray(e)?e:void 0}function ny(e){const t=e&&typeof e=="object"?e:{};return{id:String(t.id||"").trim(),title:String(t.title||"").trim(),description:t.description===void 0?void 0:t.description||null,status:String(t.status||"task").trim()||"task",priority:Fu(t.priority,{min:1})??void 0,complexity:Fu(t.complexity,{min:1,nullable:!0}),type:String(t.type||"").trim(),category:String(t.category||"").trim(),approach:Bu(t.approach),canceledReason:t.canceledReason===void 0?void 0:t.canceledReason||null,createdAt:String(t.createdAt||"").trim(),updatedAt:Bu(t.updatedAt),completedAt:t.completedAt===void 0?void 0:t.completedAt||null,isArchived:qS(t.isArchived),taxonomies:KS(t.taxonomies),createdBy:Bu(t.createdBy),assignee:Bu(t.assignee),scheduledDate:Wu(t.scheduledDate),dueDate:Wu(t.dueDate),scheduledWeekKey:Wu(t.scheduledWeekKey),orderInDay:Fu(t.orderInDay,{min:0,nullable:!0}),workstreamId:Wu(t.workstreamId),referenceNumber:Fu(t.referenceNumber,{min:1,nullable:!0}),comments:ZS(t.comments),attachments:YS(t.attachments),checklistItems:JS(t.checklistItems)}}function QS(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=Object.entries(e).filter(([s])=>String(s||"").trim().length>0).sort(([s],[o])=>s.localeCompare(o)),a={};for(const[s,o]of t){if(Array.isArray(o)){a[s]=o.map(c=>String(c??"")).sort((c,i)=>c.localeCompare(i));continue}o!=null&&(a[s]=String(o))}return a}function XS(e){return Array.isArray(e)?e.map(t=>{const a=t&&typeof t=="object"?t:{};return{id:String(a.id||"").trim(),title:String(a.title||"").trim(),isCompleted:!!a.isCompleted,order:a.order===void 0||a.order===null?"":String(a.order)}}).sort((t,a)=>{const s=Number.parseInt(t.order,10),o=Number.parseInt(a.order,10);return Number.isFinite(s)&&Number.isFinite(o)&&s!==o?s-o:t.title!==a.title?t.title.localeCompare(a.title):t.id.localeCompare(a.id)}):[]}function ew(e){return Array.isArray(e)?e.map(t=>{const a=t&&typeof t=="object"?t:null;return{id:String(a?.id||"").trim(),author:String(a?.author||"").trim(),submittedAuthor:hi(a?.submittedAuthor)||"",text:String(a?.text||""),timestamp:Hr(a?.timestamp)||"",actor:a?.actor??null}}).sort((t,a)=>t.timestamp!==a.timestamp?t.timestamp.localeCompare(a.timestamp):t.id!==a.id?t.id.localeCompare(a.id):t.author!==a.author?t.author.localeCompare(a.author):t.text.localeCompare(a.text)):[]}function tw(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t.trim(),fsPath:"",caption:"",displayName:"",originalFilename:"",assetId:"",referenceNumber:"",taskId:"",timestamp:""};const a=t&&typeof t=="object"?t:null;return{path:String(a?.path||"").trim(),fsPath:hi(a?.fsPath)||"",caption:hi(a?.caption)||"",displayName:hi(a?.displayName)||"",originalFilename:hi(a?.originalFilename)||"",assetId:Cd(a?.assetId)||"",referenceNumber:a?.referenceNumber===void 0||a.referenceNumber===null?"":String(a.referenceNumber),taskId:mm(a?.taskId)||"",timestamp:Hr(a?.timestamp)||""}}).sort((t,a)=>t.path!==a.path?t.path.localeCompare(a.path):t.assetId!==a.assetId?t.assetId.localeCompare(a.assetId):t.timestamp!==a.timestamp?t.timestamp.localeCompare(a.timestamp):JSON.stringify(t).localeCompare(JSON.stringify(a))):[]}function nw(e,t){const a=ny(e);return JSON.stringify({id:a.id,title:a.title,description:ha(a.description)||"",category:a.category,type:a.type,priority:a.priority===void 0||a.priority===null?"":String(a.priority),complexity:a.complexity===void 0||a.complexity===null?"":String(a.complexity),status:a.status,approach:hi(a.approach)||"",canceledReason:ha(a.canceledReason)||"",createdAt:a.createdAt,completedAt:Hr(a.completedAt)||"",taxonomies:QS(a.taxonomies),createdBy:Cd(a.createdBy)||"",assignee:Cd(a.assignee)||"",scheduledDate:ha(a.scheduledDate)||"",dueDate:ha(a.dueDate)||"",scheduledWeekKey:ha(a.scheduledWeekKey)||"",orderInDay:a.orderInDay===void 0||a.orderInDay===null?"":String(a.orderInDay),workstreamId:mm(a.workstreamId)||"",referenceNumber:a.referenceNumber===void 0||a.referenceNumber===null?"":String(a.referenceNumber),comments:ew(a.comments),attachments:tw(a.attachments),checklistItems:XS(a.checklistItems),isArchived:t?"1":"0"})}function aw(...e){return e.reduce((t,a)=>{const s=Hr(a)||"";return t?s&&s>t?s:t:s},"")}function rw(e){const t=e||{};return aw(t.createdAt,t.updatedAt,t.lastActiveAt,t.archivedAt,t.rosterStateUpdatedAt)}function sw(e){const t=e||{};return JSON.stringify({id:String(t.id||"").trim(),workspaceId:String(t.workspaceId||"").trim(),profileToken:String(t.profileToken||"").trim(),name:String(t.name||"").trim(),username:String(t.username||"").trim(),icon:String(t.icon||"Bot").trim()||"Bot",color:String(t.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:al(t.avatarUrl)||"",avatarSourceUrl:al(t.avatarSourceUrl)||"",avatarRevision:Number.isFinite(Number(t.avatarRevision))?Math.max(0,Math.floor(Number(t.avatarRevision))):0,avatarUpdatedAt:Hr(t.avatarUpdatedAt)||"",description:ha(t.description)||"",role:ha(t.role)||"",provider:ha(t.provider)||"",model:ha(t.model)||"",surfaceType:ha(t.surfaceType)||"",seatScope:ha(t.seatScope)||"",providerMetadata:t.providerMetadata&&typeof t.providerMetadata=="object"&&!Array.isArray(t.providerMetadata)?t.providerMetadata:null,archivedAt:Hr(t.archivedAt)||"",archivedBy:Cd(t.archivedBy)||"",archivedReason:ha(t.archivedReason)||"",mergedIntoProfileId:Cd(t.mergedIntoProfileId)||"",rosterStateUpdatedAt:Hr(t.rosterStateUpdatedAt)||"",createdAt:Hr(t.createdAt)||"",updatedAt:Hr(t.updatedAt)||"",lastActiveAt:Hr(t.lastActiveAt)||""})}const fs={kind:"task",getId:e=>String(e?.id||"").trim(),getWatermark:e=>String(e?.updatedAt||e?.createdAt||"").trim(),getChangeKey:e=>nw(e,!!e?.isArchived)},gd={kind:"ai-profile",getId:e=>String(e?.id||"").trim(),getWatermark:e=>rw(e),getChangeKey:e=>sw(e)};function gh(e,t,a){const s=e.getId(t);if(!s)return!1;const o=e.getChangeKey(t),c=a?.watermarks;if(!c||c.size===0||!c.has(s))return!0;const d=a?.changeKeys?.get(s);return typeof d=="string"?d!==o:(c.get(s)||"")!==o}function yh(e){return ny(e)}function kh(e,t){const a=e??t;return new Set(Array.from(a).map(s=>String(s||"").trim()).filter(s=>s.length>0))}function ow(e){return[...e].sort((t,a)=>{const s=String(t?.createdAt||"").trim(),o=String(a?.createdAt||"").trim(),c=s.localeCompare(o);return c!==0?c:String(t?.id||"").trim().localeCompare(String(a?.id||"").trim())})}function vh(e){return[...e].sort((t,a)=>{const s=String(t?.id||"").trim(),o=String(a?.id||"").trim();return s.localeCompare(o)})}function pm(e){return Array.isArray(e)?e:void 0}function iw(e){const t=new Date().toISOString(),a=new Set(Array.from(e.pendingDeletedTaskIds).map(l=>String(l||"").trim()).filter(l=>l.length>0)),s=new Map(Array.from(e.pendingDeletedTaskWatermarks||new Map).map(([l,J])=>[String(l||"").trim(),String(J||"").trim()]).filter(([l,J])=>l.length>0&&Number.isFinite(Date.parse(J)))),o=e.lastPushedWatermarks,c=e.lastPushedTaskChangeKeys,i=(l,J)=>(l?.referenceNumber===void 0||l?.referenceNumber===null)&&Number.isFinite(Number(l?.localReferenceNumber))?!0:gh(fs,{...l,isArchived:J},{watermarks:o,changeKeys:c}),d=vh(e.tasks||[]),m=vh(e.archivedTasks||[]),y=new Map,k=new Map,S=new Map,h=new Map,g=d.filter(l=>!a.has(String(l?.id||"").trim())&&i(l,!1)).map(l=>{const J=String(l?.id||"").trim(),Se=fs.getWatermark(l),Ie=fs.getChangeKey({...l,isArchived:!1});return J&&(S.set(J,Se),h.set(J,Ie)),{op:"upsert",archived:!1,task:yh(l)}}),v=m.filter(l=>!a.has(String(l?.id||"").trim())&&i(l,!0)).map(l=>{const J=String(l?.id||"").trim(),Se=fs.getWatermark(l),Ie=fs.getChangeKey({...l,isArchived:!0});return J&&(S.set(J,Se),h.set(J,Ie)),{op:"upsert",archived:!0,task:yh(l)}}),_=new Set;for(const l of e.tasks||[]){const J=String(l?.id||"").trim();J&&(_.add(J),y.set(J,fs.getWatermark(l)),k.set(J,fs.getChangeKey({...l,isArchived:!1})))}for(const l of e.archivedTasks||[]){const J=String(l?.id||"").trim();J&&(_.add(J),y.set(J,fs.getWatermark(l)),k.set(J,fs.getChangeKey({...l,isArchived:!0})))}const I=Array.from(e.lastPushedTaskIds).filter(l=>!_.has(l)).map(l=>({op:"delete",taskId:l,deletedAt:s.get(l)||t})),A=Array.from(a).map(l=>({op:"delete",taskId:l,deletedAt:s.get(l)||t})),D=new Set([...I.map(l=>String(l.taskId)),...A.map(l=>String(l.taskId))]),U=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),W=new Map((Array.isArray(e.initiatives)?e.initiatives:[]).map(l=>[String(l?.id||"").trim(),String(l?.updatedAt||l?.createdAt||"").trim()]).filter(([l])=>l.length>0)),Q=e.lastPushedInitiativeWatermarks,le=!Q||Q.size===0,ie=(Array.isArray(e.initiatives)?e.initiatives:[]).map(l=>({op:"initiative-upsert",initiative:{id:String(l?.id||"").trim(),referenceNumber:Number.isFinite(Number(l?.referenceNumber))?Math.max(1,Math.floor(Number(l.referenceNumber))):null,referenceLabel:typeof l?.referenceLabel=="string"&&l.referenceLabel.trim().length>0?l.referenceLabel.trim():void 0,title:String(l?.title||"").trim(),description:typeof l?.description=="string"?l.description:null,ownerId:typeof l?.ownerId=="string"&&l.ownerId.trim().length>0?l.ownerId.trim():null,createdAt:String(l?.createdAt||"").trim(),updatedAt:String(l?.updatedAt||l?.createdAt||"").trim(),order:Number.isFinite(Number(l?.order))?Math.floor(Number(l.order)):null,attachments:pm(l?.attachments),isArchived:!!l?.isArchived}})).filter(l=>l.initiative.id.length>0).filter(l=>le?!0:Q.get(l.initiative.id)!==l.initiative.updatedAt),se=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),$=new Map((Array.isArray(e.workstreams)?e.workstreams:[]).map(l=>[String(l?.id||"").trim(),String(l?.updatedAt||l?.createdAt||"").trim()]).filter(([l])=>l.length>0)),C=e.lastPushedWorkstreamWatermarks,de=!C||C.size===0,ke=(Array.isArray(e.workstreams)?e.workstreams:[]).map(l=>({op:"workstream-upsert",workstream:{id:String(l?.id||"").trim(),referenceNumber:Number.isFinite(Number(l?.referenceNumber))?Math.max(1,Math.floor(Number(l.referenceNumber))):null,referenceLabel:typeof l?.referenceLabel=="string"&&l.referenceLabel.trim().length>0?l.referenceLabel.trim():void 0,initiativeId:typeof l?.initiativeId=="string"&&l.initiativeId.trim().length>0?l.initiativeId.trim():null,title:String(l?.title||"").trim(),description:typeof l?.description=="string"?l.description:null,ownerId:typeof l?.ownerId=="string"&&l.ownerId.trim().length>0?l.ownerId.trim():null,createdAt:String(l?.createdAt||"").trim(),updatedAt:String(l?.updatedAt||l?.createdAt||"").trim(),order:Number.isFinite(Number(l?.order))?Math.floor(Number(l.order)):null,attachments:pm(l?.attachments),isArchived:!!l?.isArchived}})).filter(l=>l.workstream.id.length>0).filter(l=>de?!0:C.get(l.workstream.id)!==l.workstream.updatedAt),K=new Set((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),j=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(l=>[String(l?.id||"").trim(),gd.getWatermark(l)]).filter(([l])=>l.length>0)),H=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(l=>[String(l?.id||"").trim(),gd.getChangeKey(l)]).filter(([l])=>l.length>0)),ue=e.lastPushedAiProfileWatermarks,ye=e.lastPushedAiProfileChangeKeys,G=!ue||ue.size===0,je=(Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(l=>({op:"ai-profile-upsert",profile:{id:String(l.id||"").trim(),workspaceId:String(l.workspaceId||"").trim(),profileToken:String(l.profileToken||"").trim(),name:String(l.name||"").trim(),username:String(l.username||"").trim(),icon:String(l.icon||"Bot").trim()||"Bot",color:String(l.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:al(l.avatarUrl),avatarSourceUrl:al(l.avatarSourceUrl),avatarRevision:Number.isFinite(Number(l.avatarRevision))?Math.max(0,Math.floor(Number(l.avatarRevision))):0,avatarUpdatedAt:typeof l.avatarUpdatedAt=="string"&&l.avatarUpdatedAt.trim().length>0?l.avatarUpdatedAt.trim():null,description:typeof l.description=="string"&&l.description.trim()||null,role:typeof l.role=="string"&&l.role.trim()||null,provider:typeof l.provider=="string"&&l.provider.trim()||null,model:typeof l.model=="string"&&l.model.trim()||null,surfaceType:ey(l.surfaceType),seatScope:ty(l.seatScope),providerMetadata:l.providerMetadata&&typeof l.providerMetadata=="object"&&!Array.isArray(l.providerMetadata)?l.providerMetadata:null,archivedAt:typeof l.archivedAt=="string"&&l.archivedAt.trim().length>0?l.archivedAt.trim():null,archivedBy:typeof l.archivedBy=="string"&&l.archivedBy.trim().length>0?l.archivedBy.trim():null,archivedReason:typeof l.archivedReason=="string"&&l.archivedReason.trim()||null,mergedIntoProfileId:typeof l.mergedIntoProfileId=="string"&&l.mergedIntoProfileId.trim().length>0?l.mergedIntoProfileId.trim():null,rosterStateUpdatedAt:typeof l.rosterStateUpdatedAt=="string"&&l.rosterStateUpdatedAt.trim().length>0?l.rosterStateUpdatedAt.trim():null,createdAt:String(l.createdAt||"").trim(),updatedAt:String(l.updatedAt||l.createdAt||"").trim(),lastActiveAt:typeof l.lastActiveAt=="string"&&l.lastActiveAt.trim().length>0?l.lastActiveAt.trim():null}})).filter(l=>l.profile.id.length>0&&l.profile.workspaceId.length>0).filter(l=>G?!0:gh(gd,l.profile,{watermarks:ue,changeKeys:ye})),be=kh(e.currentDocumentPaths,(Array.isArray(e.documents)?e.documents:[]).map(l=>String(l?.path||"").trim())),ce=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(l=>String(l||"").trim()).filter(l=>l.length>0&&!be.has(l))),me=new Map((Array.isArray(e.documents)?e.documents:[]).map(l=>[String(l?.path||"").trim(),String(l?.updatedAt||"").trim()]).filter(([l])=>l.length>0)),Te=e.lastPushedDocumentWatermarks,Me=!Te||Te.size===0,Pe=(Array.isArray(e.documents)?e.documents:[]).map(l=>({op:"document-upsert",path:String(l.path||"").trim(),updatedAt:String(l.updatedAt||"").trim(),content:typeof l.content=="string"?l.content:"",assetId:typeof l.assetId=="string"&&l.assetId.trim().length>0?l.assetId.trim():void 0,documentId:typeof l.documentId=="string"&&l.documentId.trim().length>0?l.documentId.trim():null,referenceNumber:Number.isFinite(Number(l.referenceNumber))?Math.max(1,Math.floor(Number(l.referenceNumber))):null,version:Number.isFinite(Number(l.version))?Math.max(1,Math.floor(Number(l.version))):null,taskId:typeof l.taskId=="string"&&l.taskId.trim().length>0?l.taskId.trim():null,linkTargetType:l.linkTargetType==="initiative"||l.linkTargetType==="workstream"||l.linkTargetType==="task"?l.linkTargetType:null,linkTargetId:typeof l.linkTargetId=="string"&&l.linkTargetId.trim().length>0?l.linkTargetId.trim():null,logicalName:typeof l.logicalName=="string"&&l.logicalName.trim().length>0?l.logicalName.trim():null,caption:typeof l.caption=="string"&&l.caption.trim().length>0?l.caption.trim():null,originalFilename:typeof l.originalFilename=="string"&&l.originalFilename.trim().length>0?l.originalFilename.trim():null,linkRole:l.linkRole==="reference"?"reference":"attachment"})).filter(l=>l.path.length>0).filter(l=>Me?!0:Te.get(l.path)!==l.updatedAt),Ee=kh(e.currentAssetPaths,(Array.isArray(e.assets)?e.assets:[]).map(l=>String(l?.path||"").trim())),Z=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(l=>String(l||"").trim()).filter(l=>l.length>0&&!Ee.has(l))),x=new Map((Array.isArray(e.assets)?e.assets:[]).map(l=>[String(l?.path||"").trim(),String(l?.updatedAt||"").trim()]).filter(([l])=>l.length>0)),b=e.lastPushedAssetWatermarks,R=!b||b.size===0,B=(Array.isArray(e.assets)?e.assets:[]).map(l=>({op:"asset-upsert",path:String(l.path||"").trim(),updatedAt:String(l.updatedAt||"").trim(),contentBase64:typeof l.contentBase64=="string"?l.contentBase64:"",assetId:typeof l.assetId=="string"&&l.assetId.trim().length>0?l.assetId.trim():void 0,kind:l.kind==="image"?"image":"file",mimeType:typeof l.mimeType=="string"&&l.mimeType.trim().length>0?l.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(l.referenceNumber))?Math.max(1,Math.floor(Number(l.referenceNumber))):null,taskId:typeof l.taskId=="string"&&l.taskId.trim().length>0?l.taskId.trim():null,linkTargetType:l.linkTargetType==="initiative"||l.linkTargetType==="workstream"||l.linkTargetType==="task"?l.linkTargetType:null,linkTargetId:typeof l.linkTargetId=="string"&&l.linkTargetId.trim().length>0?l.linkTargetId.trim():null,logicalName:typeof l.logicalName=="string"&&l.logicalName.trim().length>0?l.logicalName.trim():null,caption:typeof l.caption=="string"&&l.caption.trim().length>0?l.caption.trim():null,originalFilename:typeof l.originalFilename=="string"&&l.originalFilename.trim().length>0?l.originalFilename.trim():null,linkRole:l.linkRole==="reference"?"reference":l.linkRole==="image"?"image":"attachment"})).filter(l=>l.path.length>0&&l.contentBase64.length>0).filter(l=>R?!0:b.get(l.path)!==l.updatedAt),Y=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],fe=new Set(Y.map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),te=new Set(Y.filter(l=>String(l?.deletedAt||"").trim().length===0).map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),Le=e.lastPushedDocumentReviewSessionIds||new Set,oe=new Map(Y.map(l=>[String(l?.id||"").trim(),String(l?.deletedAt||l?.updatedAt||l?.createdAt||"").trim()]).filter(([l])=>l.length>0)),L=e.lastPushedDocumentReviewSessionWatermarks,X=!L||L.size===0,M=Y.map(l=>({op:"document-review-session-upsert",session:{id:String(l.id||"").trim(),assetId:String(l.assetId||"").trim(),documentId:typeof l.documentId=="string"&&l.documentId.trim().length>0?l.documentId.trim():null,documentVersion:Number.isFinite(Number(l.documentVersion))?Math.max(1,Math.floor(Number(l.documentVersion))):null,title:typeof l.title=="string"&&l.title.trim().length>0?l.title.trim():null,status:l.status==="resolved"?"resolved":"open",comments:[],createdByActorId:typeof l.createdByActorId=="string"&&l.createdByActorId.trim().length>0?l.createdByActorId.trim():null,updatedByActorId:typeof l.updatedByActorId=="string"&&l.updatedByActorId.trim().length>0?l.updatedByActorId.trim():null,createdAt:String(l.createdAt||"").trim(),updatedAt:String(l.updatedAt||l.createdAt||"").trim(),deletedAt:typeof l.deletedAt=="string"&&l.deletedAt.trim().length>0?l.deletedAt.trim():null}})).filter(l=>l.session.id.length>0&&l.session.assetId.length>0&&!l.session.deletedAt).filter(l=>X?!0:L.get(l.session.id)!==l.session.updatedAt),V=Y.filter(l=>String(l?.deletedAt||"").trim().length>0).map(l=>({sessionId:String(l?.id||"").trim(),deletedAt:String(l?.deletedAt||l?.updatedAt||l?.createdAt||t).trim()||t})).filter(l=>l.sessionId.length>0).filter(l=>X?!0:L.get(l.sessionId)!==l.deletedAt),ne=Array.from(Le).map(l=>String(l||"").trim()).filter(l=>l.length>0&&!fe.has(l)),Ce=[...ne.map(l=>({sessionId:l,deletedAt:t})),...V],Ae=new Set([...ne,...V.map(l=>l.sessionId)]),Re=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],$e=new Set(Re.map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),vt=new Set(Re.filter(l=>String(l?.deletedAt||"").trim().length===0).map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),st=e.lastPushedDocumentReviewCommentIds||new Set,kt=new Map(Re.map(l=>[String(l?.id||"").trim(),String(l?.deletedAt||l?.updatedAt||l?.createdAt||"").trim()]).filter(([l])=>l.length>0)),Ye=e.lastPushedDocumentReviewCommentWatermarks,Ct=!Ye||Ye.size===0,dt=Re.map(l=>({op:"document-review-comment-upsert",comment:{id:String(l.id||"").trim(),sessionId:String(l.sessionId||"").trim(),body:String(l.body||"").trim(),anchor:l.anchor??null,order:Number.isFinite(Number(l.order))?Math.max(0,Math.floor(Number(l.order))):0,authorActorId:typeof l.authorActorId=="string"&&l.authorActorId.trim().length>0?l.authorActorId.trim():null,createdAt:String(l.createdAt||"").trim(),updatedAt:String(l.updatedAt||l.createdAt||"").trim(),deletedAt:typeof l.deletedAt=="string"&&l.deletedAt.trim().length>0?l.deletedAt.trim():null}})).filter(l=>l.comment.id.length>0&&l.comment.sessionId.length>0&&!l.comment.deletedAt).filter(l=>Ct?!0:Ye.get(l.comment.id)!==l.comment.updatedAt),Qe=Re.filter(l=>String(l?.deletedAt||"").trim().length>0).map(l=>({commentId:String(l?.id||"").trim(),deletedAt:String(l?.deletedAt||l?.updatedAt||l?.createdAt||t).trim()||t})).filter(l=>l.commentId.length>0).filter(l=>Ct?!0:Ye.get(l.commentId)!==l.deletedAt),Tt=Array.from(st).map(l=>String(l||"").trim()).filter(l=>l.length>0&&!$e.has(l)),ae=[...Tt.map(l=>({commentId:l,deletedAt:t})),...Qe],Ge=new Set([...Tt,...Qe.map(l=>l.commentId)]),ft=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],it=new Set(ft.map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),Mt=new Set(ft.filter(l=>String(l?.deletedAt||"").trim().length===0).map(l=>String(l?.id||"").trim()).filter(l=>l.length>0)),ht=e.lastPushedAnnotatedAttachmentSessionIds||new Set,Ft=new Map(ft.map(l=>[String(l?.id||"").trim(),String(l?.deletedAt||l?.updatedAt||l?.createdAt||"").trim()]).filter(([l])=>l.length>0)),Et=e.lastPushedAnnotatedAttachmentSessionWatermarks,We=!Et||Et.size===0,tt=ft.map(l=>({op:"annotated-attachment-session-upsert",session:{id:String(l.id||"").trim(),workspaceId:String(l.workspaceId||"").trim(),taskId:String(l.taskId||"").trim(),baseImageAssetId:String(l.baseImageAssetId||"").trim(),title:typeof l.title=="string"&&l.title.trim().length>0?l.title.trim():null,globalInstruction:typeof l.globalInstruction=="string"&&l.globalInstruction.trim().length>0?l.globalInstruction.trim():null,annotations:Array.isArray(l.annotations)?l.annotations:[],createdByActorId:typeof l.createdByActorId=="string"&&l.createdByActorId.trim().length>0?l.createdByActorId.trim():null,updatedByActorId:typeof l.updatedByActorId=="string"&&l.updatedByActorId.trim().length>0?l.updatedByActorId.trim():null,createdAt:String(l.createdAt||"").trim(),updatedAt:String(l.updatedAt||l.createdAt||"").trim(),deletedAt:typeof l.deletedAt=="string"&&l.deletedAt.trim().length>0?l.deletedAt.trim():null}})).filter(l=>l.session.id.length>0&&l.session.workspaceId.length>0&&l.session.baseImageAssetId.length>0&&!l.session.deletedAt).filter(l=>We?!0:Et.get(l.session.id)!==l.session.updatedAt),Oe=ft.filter(l=>String(l?.deletedAt||"").trim().length>0).map(l=>({sessionId:String(l?.id||"").trim(),deletedAt:String(l?.deletedAt||l?.updatedAt||l?.createdAt||t).trim()||t})).filter(l=>l.sessionId.length>0).filter(l=>We?!0:Et.get(l.sessionId)!==l.deletedAt),Ze=Array.from(ht).map(l=>String(l||"").trim()).filter(l=>l.length>0&&!it.has(l)),St=[...Ze.map(l=>({sessionId:l,deletedAt:t})),...Oe],ot=new Set([...Ze,...Oe.map(l=>l.sessionId)]),re=ow(Array.isArray(e.taskEvents)?e.taskEvents:[]),Be=new Map(re.map(l=>[String(l?.id||"").trim(),String(l?.createdAt||"").trim()]).filter(([l])=>l.length>0)),At=e.lastPushedTaskEventWatermarks,Rt=!At||At.size===0,Bt=re.map(l=>{const J=l.entityType==="initiative"||l.entityType==="workstream"?l.entityType:"task",Se=String(l.entityId||l.taskId||"").trim(),Ie={id:String(l.id||"").trim(),workspaceId:String(l.workspaceId||"").trim(),entityType:J,entityId:Se,taskId:J==="task"?String(l.taskId||Se).trim():void 0,action:String(l.action||"").trim(),actor:String(l.actor||"system").trim()||"system",actorType:l.actorType==="ai"||l.actorType==="human"||l.actorType==="system"?l.actorType:"system",details:l.details&&typeof l.details=="object"&&!Array.isArray(l.details)?l.details:{},createdAt:String(l.createdAt||"").trim()};return J==="task"?{op:"task-event-upsert",event:{...Ie,entityType:"task",taskId:String(Ie.taskId||Se).trim()}}:{op:"entity-event-upsert",event:{...Ie,entityType:J,taskId:void 0}}}).filter(l=>l.event.id.length>0&&l.event.entityId.length>0&&l.event.workspaceId.length>0&&l.event.action.length>0&&Number.isFinite(Date.parse(l.event.createdAt))).filter(l=>Rt?!0:At.get(l.event.id)!==l.event.createdAt),Ve=[...ie,...ke,...e.taxonomyState&&typeof e.taxonomyState=="object"?[{op:"taxonomy-upsert",taxonomyState:e.taxonomyState,updatedAt:t}]:Array.isArray(e.taxonomies)?[{op:"taxonomy-upsert",taxonomies:e.taxonomies,updatedAt:t}]:[],...je,...Pe,...Array.from(ce).map(l=>({op:"document-delete",path:l,deletedAt:t})),...B,...Array.from(Z).map(l=>({op:"asset-delete",path:l,deletedAt:t})),...M,...Ce.map(l=>({op:"document-review-session-delete",sessionId:l.sessionId,deletedAt:l.deletedAt})),...dt,...ae.map(l=>({op:"document-review-comment-delete",commentId:l.commentId,deletedAt:l.deletedAt})),...tt,...St.map(l=>({op:"annotated-attachment-session-delete",sessionId:l.sessionId,deletedAt:l.deletedAt})),...Bt,...g,...v,...Array.from(D).map(l=>({op:"delete",taskId:l,deletedAt:s.get(l)||t}))],Ot=e.baselineResetReason??null,yt=l=>{const J=l.upsertCount+(l.deleteCount||0);if(l.currentCount===0&&J===0)return{mode:"none",reason:null,currentCount:0,baselineCount:l.baselineCount,changeCount:J};if(l.alwaysFull)return{mode:J>0?"send-all":"none",reason:J>0?"full-state-domain":null,currentCount:l.currentCount,baselineCount:l.baselineCount,changeCount:J};const Se=l.baselineCount===0&&l.currentCount>0&&l.upsertCount>=l.currentCount;return{mode:Se?"send-all":"delta",reason:Se?Ot||"missing-baseline":null,currentCount:l.currentCount,baselineCount:l.baselineCount,changeCount:J}},E=Ve.reduce((l,J)=>{const Se=String(J.op||"").trim();return l[Se]=(l[Se]||0)+1,l},{});return{changes:Ve,currentTaskIds:new Set(Array.from(_).filter(l=>!a.has(l))),currentTaskWatermarks:new Map(Array.from(y.entries()).filter(([l])=>!a.has(l))),currentTaskChangeKeys:new Map(Array.from(k.entries()).filter(([l])=>!a.has(l))),deleteTaskIds:D,currentInitiativeIds:U,currentInitiativeWatermarks:W,currentWorkstreamIds:se,currentWorkstreamWatermarks:$,currentAiProfileIds:K,currentAiProfileWatermarks:j,currentAiProfileChangeKeys:H,currentDocumentPaths:be,deleteDocumentPaths:ce,currentDocumentWatermarks:me,currentAssetPaths:Ee,deleteAssetPaths:Z,currentAssetWatermarks:x,currentDocumentReviewSessionIds:te,deleteDocumentReviewSessionIds:Ae,currentDocumentReviewSessionWatermarks:oe,currentDocumentReviewCommentIds:vt,deleteDocumentReviewCommentIds:Ge,currentDocumentReviewCommentWatermarks:kt,currentAnnotatedAttachmentSessionIds:Mt,deleteAnnotatedAttachmentSessionIds:ot,currentAnnotatedAttachmentSessionWatermarks:Ft,currentTaskEventWatermarks:Be,pushedWatermarks:S,pushedTaskChangeKeys:h,deltaDiagnostics:{totalChanges:Ve.length,byOp:E,baselineResetReason:Ot,domains:{tasks:yt({currentCount:_.size,baselineCount:o?.size||0,upsertCount:g.length+v.length,deleteCount:D.size}),initiatives:yt({currentCount:U.size,baselineCount:Q?.size||0,upsertCount:ie.length}),workstreams:yt({currentCount:se.size,baselineCount:C?.size||0,upsertCount:ke.length}),aiProfiles:yt({currentCount:K.size,baselineCount:ue?.size||0,upsertCount:je.length}),documents:yt({currentCount:be.size,baselineCount:Te?.size||0,upsertCount:Pe.length,deleteCount:ce.size}),assets:yt({currentCount:Ee.size,baselineCount:b?.size||0,upsertCount:B.length,deleteCount:Z.size}),documentReviewSessions:yt({currentCount:te.size,baselineCount:L?.size||0,upsertCount:M.length,deleteCount:Ae.size}),documentReviewComments:yt({currentCount:vt.size,baselineCount:Ye?.size||0,upsertCount:dt.length,deleteCount:Ge.size}),annotatedAttachmentSessions:yt({currentCount:Mt.size,baselineCount:Et?.size||0,upsertCount:tt.length,deleteCount:ot.size}),taskEvents:yt({currentCount:Be.size,baselineCount:At?.size||0,upsertCount:Bt.length}),taxonomy:yt({currentCount:e.taxonomyState&&typeof e.taxonomyState=="object"||Array.isArray(e.taxonomies)?1:0,baselineCount:0,upsertCount:E["taxonomy-upsert"]||0,alwaysFull:!0})}}}}function cw(e){const t=(e.tasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),a=(e.archivedTasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),s=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():"",attachments:pm(i.attachments)||[],isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)),c=(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():"",attachments:pm(i.attachments)||[],isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id));return JSON.stringify({workspaceId:e.workspaceId,initiatives:o,workstreams:c,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(),archivedAt:String(i.archivedAt||"").trim(),archivedReason:String(i.archivedReason||"").trim(),mergedIntoProfileId:String(i.mergedIntoProfileId||"").trim(),rosterStateUpdatedAt:String(i.rosterStateUpdatedAt||"").trim()})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)):[],taskEvents:Array.isArray(e.taskEvents)?e.taskEvents.map(i=>({id:String(i.id||"").trim(),taskId:String(i.taskId||"").trim(),action:String(i.action||"").trim(),actor:String(i.actor||"").trim(),actorType:i.actorType==="ai"||i.actorType==="human"||i.actorType==="system"?i.actorType:"system",createdAt:String(i.createdAt||"").trim()})).filter(i=>i.id.length>0&&i.taskId.length>0).sort((i,d)=>i.id.localeCompare(d.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,d)=>i.path.localeCompare(d.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,d)=>i.path.localeCompare(d.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,d)=>i.id.localeCompare(d.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,d)=>i.id.localeCompare(d.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,d)=>i.id.localeCompare(d.id)):[],active:t,archived:a,pendingDeletes:s})}function Xu(){return{version:2,enabled:!1,phase:"idle",setupIntent:null,startupFullReconcileCompletedAt:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null,pushBaseline:null}}function Js(e){const t=String(e||"").trim();return t.length>0?t:null}function Sh(e){return String(e||"").trim().toLowerCase()==="attach-cloud-import"?"attach-cloud-import":null}function lw(e){if(!Array.isArray(e)||e.length<2)return null;const t=String(e[0]||"").trim(),a=String(e[1]||"").trim();return!t||!a?null:[t,a]}function dw(e){return Array.isArray(e)?e.map(t=>String(t||"").trim()).filter(t=>t.length>0):[]}function wh(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,a=s=>Array.isArray(t[s])?t[s].map(o=>lw(o)).filter(o=>Array.isArray(o)):[];return{taskIds:dw(t.taskIds),taskWatermarks:a("taskWatermarks"),taskChangeKeys:a("taskChangeKeys"),initiativeWatermarks:a("initiativeWatermarks"),workstreamWatermarks:a("workstreamWatermarks"),aiProfileWatermarks:a("aiProfileWatermarks"),aiProfileChangeKeys:a("aiProfileChangeKeys"),documentWatermarks:a("documentWatermarks"),assetWatermarks:a("assetWatermarks"),documentReviewSessionWatermarks:a("documentReviewSessionWatermarks"),documentReviewCommentWatermarks:a("documentReviewCommentWatermarks"),annotatedAttachmentSessionWatermarks:a("annotatedAttachmentSessionWatermarks"),taskEventWatermarks:a("taskEventWatermarks"),taxonomyStateFingerprint:String(t.taxonomyStateFingerprint||"").trim()}}function uw(e,t){if(!!!(e.enabled??e.cloudSyncEnabled))return"idle";const s=String(e.phase||"").trim().toLowerCase();if(s==="idle"||s==="provision-local"||s==="attach-cloud"||s==="active"||s==="error")return s;const o=String(e.bootstrapMode||"").trim().toLowerCase();if(o==="provision-local"||o==="attach-cloud")return o;const c=String(e.sourceOfTruth||"").trim().toLowerCase();return e.onboardingCompleted?"active":c==="cloud"?t.lastPullAt?"active":"attach-cloud":c==="local"?t.lastPullAt||t.lastPushAt?"active":"provision-local":(t.lastPullAt||t.lastPushAt,"active")}function mw(e){const t=Xu();if(!e||typeof e!="object")return{state:t,changed:!1};const a=e,s=a.lastErrorMessage,o=typeof s=="string"&&s.trim().length>0?s:null,c={version:2,enabled:!!(a.enabled??a.cloudSyncEnabled),phase:"idle",setupIntent:Sh(a.setupIntent),startupFullReconcileCompletedAt:Js(a.startupFullReconcileCompletedAt),pullCursor:Js(a.pullCursor),lastPullAt:Js(a.lastPullAt),lastPushAt:Js(a.lastPushAt),lastSyncedAt:Js(a.lastSyncedAt),lastErrorMessage:o,pushBaseline:wh(a.pushBaseline)};c.phase=uw(a,c),c.enabled||(c.phase="idle",c.pullCursor=null);const d=Number(a.version||0)!==2||!!(a.enabled??a.cloudSyncEnabled)!==c.enabled||String(a.phase||"").trim()!==c.phase||Sh(a.setupIntent)!==c.setupIntent||Js(a.startupFullReconcileCompletedAt)!==c.startupFullReconcileCompletedAt||Js(a.pullCursor)!==c.pullCursor||Js(a.lastPullAt)!==c.lastPullAt||Js(a.lastPushAt)!==c.lastPushAt||Js(a.lastSyncedAt)!==c.lastSyncedAt||o!==c.lastErrorMessage||JSON.stringify(wh(a.pushBaseline))!==JSON.stringify(c.pushBaseline);return{state:c,changed:d}}const pw="taskforce.sync.lease.v1",fw="taskforce.sync.lease.v1",hw=2500,gw=9e3;function rd(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function sd(e){const t=String(e||"").trim();return t.length>0?t:null}function bp(e){return`${pw}.${e}`}function yw(e){if(!e)return null;try{const t=JSON.parse(e),a=String(t?.ownerId||"").trim(),s=String(t?.workspaceId||"").trim(),o=String(t?.operation||"").trim(),c=String(t?.heartbeatAt||"").trim(),i=String(t?.expiresAt||"").trim();return!a||!s||!c||!i||o!=="pull"&&o!=="push"&&o!=="repair"?null:{ownerId:a,workspaceId:s,operation:o,heartbeatAt:c,expiresAt:i}}catch{return null}}function kw(e,t,a,s){return{ownerId:e,workspaceId:t,operation:a,heartbeatAt:new Date(s).toISOString(),expiresAt:new Date(s+gw).toISOString()}}function vw(e,t=Date.now()){if(!e)return!0;const a=Date.parse(e.expiresAt);return!Number.isFinite(a)||a<=t}function _p(e,t){const a={...e,...t,version:2,phase:t.phase||e.phase,setupIntent:t.setupIntent===void 0?e.setupIntent??null:t.setupIntent??null,startupFullReconcileCompletedAt:t.startupFullReconcileCompletedAt===void 0?e.startupFullReconcileCompletedAt??null:sd(t.startupFullReconcileCompletedAt),pullCursor:t.pullCursor===void 0?e.pullCursor:sd(t.pullCursor),lastPullAt:t.lastPullAt===void 0?e.lastPullAt:sd(t.lastPullAt),lastPushAt:t.lastPushAt===void 0?e.lastPushAt:sd(t.lastPushAt),lastSyncedAt:t.lastSyncedAt===void 0?e.lastSyncedAt:sd(t.lastSyncedAt),lastErrorMessage:t.lastErrorMessage===void 0?e.lastErrorMessage:t.lastErrorMessage??null,pushBaseline:t.pushBaseline===void 0?e.pushBaseline??null:t.pushBaseline??null};return a.enabled||(a.phase="idle",a.setupIntent=null,a.pullCursor=null),a}function Sw(e){return{...e,pushBaseline:null}}function ww(e){const{currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:a,setWorkspaceSyncPhase:s,setWorkspaceSyncSetupIntent:o,setWorkspaceLastPullAt:c,setWorkspaceLastPushAt:i,setWorkspaceLastErrorMessage:d}=e,[m,y]=r.useState(null),k=r.useRef(null),S=r.useRef(null),h=r.useRef(0),g=r.useRef(!1),v=r.useRef(!1),_=r.useRef(""),I=r.useRef(""),A=r.useRef(new Set),D=r.useRef(new Set),U=r.useRef(new Map),W=r.useRef(null),Q=r.useRef(Xu()),le=r.useRef(""),ie=r.useRef(null),se=r.useRef(null),$=r.useRef(null),C=r.useRef(null);if(!le.current){const x=Date.now().toString(36),b=Math.random().toString(36).slice(2,10);le.current=`sync-lease-${x}-${b}`}const de=r.useCallback(()=>{h.current=0,S.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),y(null)},[]),ke=r.useCallback((x,b)=>{if(typeof window>"u")return;const R=Math.max(1,h.current+1);h.current=R;const B=FS(R),Y=Number(b?.minDelayMs),fe=Number.isFinite(Y)&&Y>0?Math.max(B,Math.floor(Y)):B,te=Date.now()+fe;S.current=te,y(new Date(te).toISOString()),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,S.current=null,y(null),x()},fe)},[]),K=r.useCallback(()=>{const x=S.current;return typeof x=="number"&&Number.isFinite(x)&&x>Date.now()},[]),j=r.useCallback(x=>{if(typeof window>"u")return null;const b=String(x||"").trim();return rd(b)?yw(window.localStorage.getItem(bp(b))):null},[]),H=r.useCallback(x=>{const b=String(x||"").trim();if(b)try{C.current?.postMessage({workspaceId:b})}catch{}},[]),ue=r.useCallback((x,b)=>{if(typeof window>"u")return null;const R=String(x||"").trim();if(!rd(R))return null;const B=kw(le.current,R,b,Date.now());try{window.localStorage.setItem(bp(R),JSON.stringify(B))}catch{return null}return H(R),B},[H]),ye=r.useCallback(()=>{$.current!==null&&typeof window<"u"&&(window.clearInterval($.current),$.current=null)},[]),G=r.useCallback((x,b)=>{if(typeof window>"u")return;const R=String(x||ie.current||"").trim();if(!R)return;const B=j(R),Y=B?.ownerId===le.current;if(!(!b?.force&&B&&!Y)){ye();try{window.localStorage.removeItem(bp(R))}catch{}ie.current=null,se.current=null,H(R)}},[H,j,ye]),je=r.useCallback((x,b)=>{typeof window>"u"||(ye(),$.current=window.setInterval(()=>{const R=String(ie.current||"").trim(),B=se.current;if(!R||!B){ye();return}if(j(R)?.ownerId!==le.current){ye(),ie.current=null,se.current=null;return}ue(R,B)},hw),ie.current=x,se.current=b)},[j,ye,ue]),be=r.useCallback(async(x,b)=>{if(typeof window>"u")return!0;const R=String(x||"").trim();if(!rd(R))return!1;const B=j(R);if(B?.ownerId===le.current)return ue(R,b)?(je(R,b),!0):!1;if(B&&!vw(B)||!ue(R,b))return!1;const te=j(R);return!te||te.ownerId!==le.current?!1:(je(R,b),!0)},[j,je,ue]),ce=r.useCallback(x=>{G(x,{force:!0})},[G]),me=r.useCallback(x=>{const b=Q.current,R=_p(b,{enabled:!!x.enabled,phase:x.phase||b.phase,setupIntent:x.setupIntent,pullCursor:x.pullCursor,lastPullAt:x.lastPullAt,lastPushAt:x.lastPushAt,lastSyncedAt:x.lastSyncedAt,lastErrorMessage:x.lastErrorMessage});Q.current=R,W.current=R.pullCursor,a(R.enabled),s(R.phase),o(R.setupIntent??null),c(R.lastPullAt),i(R.lastPushAt),d(R.lastErrorMessage??null)},[a,s,o,c,i,d]),Te=r.useCallback(x=>{const b=_p(Q.current,x);return me(b),b},[me]),Me=r.useCallback(()=>Q.current,[]),Pe=r.useCallback(async x=>{const b=_p(Q.current,x);Q.current=b,W.current=b.pullCursor;const R=await kf({workspaceId:t,stateKey:"workspace-sync",patch:Sw(b),throwOnError:!0,respectFailureCooldown:!1}),B=R.response,Y=R.payload;if(R.skipped)return me(b),b;if(!B)throw new Error("Failed to persist workspace sync state (missing response)");if(!B.ok||Y?.success===!1)throw new Error(Y?.error||`Failed to persist workspace sync state (${B.status})`);return me(b),b},[me,t]),Ee=r.useCallback(async()=>{if(!rd(t)){const x=Xu();Q.current=x,me(x);return}try{const x=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!x.ok)return;const b=await x.json().catch(()=>({})),R=mw(b?.state&&typeof b.state=="object"?b.state:null);Q.current=R.state,me(R.state),R.changed&&Pe(R.state)}catch{}},[me,t,Pe]),Z=r.useCallback(async(x,b)=>{if(!rd(t))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!x.enabled)return await Pe({enabled:!1,phase:"idle",setupIntent:null,pullCursor:null}),{success:!0};if(!b.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!b.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const R=await b.ensureCloudWorkspaceReadyForSync();return R.success?(await Pe({enabled:!0,phase:R.provisioned?"provision-local":"attach-cloud",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}),{success:!0}):{success:!1,error:R.error||"Workspace sync handshake failed."}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[t,Pe]);return r.useEffect(()=>{_.current="",I.current="",A.current=new Set,D.current=new Set,U.current=new Map,W.current=null,Q.current=Xu(),g.current=!1,v.current=!1,G(),de()},[de,t,G]),r.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const x=new BroadcastChannel(fw);return C.current=x,()=>{x.close(),C.current===x&&(C.current=null)}},[]),r.useEffect(()=>()=>{k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),G()},[G]),{workspaceRetryAt:m,isWorkspaceRetryPending:K,workspacePushInFlightRef:g,workspacePullInFlightRef:v,workspaceLastPushedSignatureRef:_,workspacePendingSignatureRef:I,workspaceLastPushedTaskIdsRef:A,workspaceDeletedTaskIdsRef:D,workspaceDeletedTaskWatermarksRef:U,workspacePullCursorRef:W,clearWorkspaceRetry:de,scheduleWorkspaceRetry:ke,persistWorkspaceSyncPatch:Pe,applyWorkspaceSyncPatchLocally:Te,readWorkspaceSyncStateSnapshot:Me,loadWorkspaceSyncState:Ee,applyWorkspaceSyncStateSnapshot:me,saveWorkspaceCloudSyncSettings:Z,acquireWorkspaceSyncLease:be,releaseWorkspaceSyncLease:G,forceClearWorkspaceSyncLease:ce,readWorkspaceSyncLease:j}}class bw{constructor(t=2048){this.maxSeenEventIds=t}seenEventIds=new Set;seenEventIdQueue=[];activeEpoch="";lastSeq=null;telemetry={accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0};process(t){const a=typeof t.eventId=="string"?t.eventId.trim():"";if(a&&this.seenEventIds.has(a))return this.telemetry.duplicateDiscarded+=1,{accepted:!1,reason:"duplicate",shouldRecover:!1};const s=typeof t.serverEpoch=="string"?t.serverEpoch.trim():"",o=Number(t.seq);if(!(s.length>0&&Number.isFinite(o)&&o>=0))return a?(this.rememberEventId(a),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!==s)return this.activeEpoch=s,this.lastSeq=i,a&&this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=s,this.lastSeq=i,a&&this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const d=this.lastSeq;if(typeof d=="number"){if(i<=d){this.telemetry.outOfOrderDiscarded+=i===d?0:1,this.telemetry.duplicateDiscarded+=i===d?1:0;const m=i<d;return m&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:i===d?"duplicate":"out-of-order",shouldRecover:m}}if(i>d+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=i,a&&this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}}getTelemetry(){return{...this.telemetry}}rememberEventId(t){for(this.seenEventIds.add(t),this.seenEventIdQueue.push(t);this.seenEventIdQueue.length>this.maxSeenEventIds;){const a=this.seenEventIdQueue.shift();a&&this.seenEventIds.delete(a)}}}function ay(e){const{enabled:t,workspaceId:a,websocketUrl:s,reconnectBaseMs:o=400,reconnectMaxMs:c=1e4,degradeAfterAttempts:i=5,replayLimit:d=200,onSignal:m,onTelemetry:y,userId:k}=e,[S,h]=r.useState("degraded-fallback"),g=r.useRef(null),v=r.useRef(null),_=r.useRef(0),I=r.useRef(""),A=r.useRef(!1),D=r.useRef(null),U=r.useRef(null),W=r.useRef(new bw),Q=r.useRef(m),le=r.useRef(y);r.useEffect(()=>{Q.current=m},[m]),r.useEffect(()=>{le.current=y},[y]);const[ie,se]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),$=r.useMemo(()=>String(a||"").trim(),[a]),C=r.useMemo(()=>String(s||"").trim(),[s]);return r.useEffect(()=>{let de=!1;const ke=()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},K=()=>{const me=g.current;if(g.current=null,me)try{me.close()}catch{}},j=me=>me==="taskforce:replay-gap"||me==="taskforce:replay-reset"?4:me==="taskforce:mutation"||me==="taskforce:replay"?3:1,H=me=>{const Te=U.current;if(Te){const Me=j(Te.type),Pe=j(me.type);if(Pe<Me||Pe===Me&&Te.eventId&&!me.eventId)return}U.current=me,D.current!==null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{D.current=null;const Me=Q.current;if(!U.current||typeof Me!="function")return;const Pe=U.current;U.current=null,Me(Pe)},80)},ue=me=>{try{const Te=JSON.parse(String(me.data||""));return!Te||typeof Te!="object"?null:Te}catch{return null}},ye=me=>{const Te=typeof me.serverEpoch=="string"?me.serverEpoch.trim():"",Me=Number(me.seq);!Te||!Number.isFinite(Me)||Me<0||(I.current=`${Te}:${Math.floor(Me)}`,A.current=!1)},G=()=>{const me=W.current.getTelemetry();se(me);const Te=le.current;typeof Te=="function"&&Te(me)},je=me=>{const Te={type:"taskforce:replay",workspaceId:$,limit:d},Me=I.current;Me&&(Te.cursor=Me),me.send(JSON.stringify(Te))},be=()=>{if(!t||de)return;ke(),_.current+=1;const me=_.current,Te=Math.max(50,Math.floor(o)),Me=Math.max(Te,Math.floor(c)),Pe=Math.min(Me,Te*Math.pow(2,Math.max(0,me-1)));h(me>=i?"degraded-fallback":"reconnecting"),v.current=window.setTimeout(()=>{de||(v.current=null,ce())},Pe)},ce=()=>{if(!t||de||!$||!C)return;K();let me;try{me=new WebSocket(C)}catch{be();return}g.current=me,me.addEventListener("open",()=>{_.current=0,h("connected"),me.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:$,userId:k||void 0})),je(me)}),me.addEventListener("message",Te=>{const Me=ue(Te);if(!Me||typeof Me.type!="string")return;const Pe=typeof Me.workspaceId=="string"?Me.workspaceId.trim():$;if(!(!Pe||Pe!==$)){if(Me.type==="taskforce:update"){H({type:"taskforce:update",workspaceId:$,eventId:typeof Me.eventId=="string"?Me.eventId.trim():void 0});return}if(Me.type==="taskforce:mutation"){const Ee=W.current.process({eventId:Me.eventId,serverEpoch:Me.serverEpoch,seq:Me.seq});if(!Ee.accepted){G(),Ee.shouldRecover&&(I.current="",A.current||(A.current=!0,H({type:"taskforce:replay-gap",workspaceId:$})));return}ye(Me),G(),H({type:Me.type,workspaceId:$,eventId:typeof Me.eventId=="string"?Me.eventId.trim():void 0});return}if(Me.type==="taskforce:replay"){const Ee=Array.isArray(Me.events)?Me.events:[];let Z=0;for(const x of Ee)W.current.process({eventId:x.eventId,serverEpoch:x.serverEpoch,seq:x.seq}).accepted&&(Z+=1,ye(x));A.current=!1,G(),(Z>0||Me.truncated===!0)&&H({type:"taskforce:replay",workspaceId:$}),Me.truncated===!0&&je(me);return}if(Me.type==="taskforce:replay-gap"||Me.type==="taskforce:replay-reset"){if(I.current="",A.current)return;A.current=!0,H({type:Me.type,workspaceId:$})}}}),me.addEventListener("close",Te=>{if(g.current===me&&(g.current=null),!de&&t){const Me=Number(Te?.code||0),Pe=String(Te?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${$} user=${String(k||"anonymous").trim()||"anonymous"} code=${Me}${Pe?` reason=${Pe}`:""}`)}be()}),me.addEventListener("error",()=>{try{me.close()}catch{}})};return!t||!$||!C?(h("degraded-fallback"),ke(),K(),()=>{ke(),K()}):(h("reconnecting"),ce(),()=>{de=!0,ke(),D.current!==null&&(window.clearTimeout(D.current),D.current=null),U.current=null,K()})},[t,$,C,o,c,i,d,k]),{connectionState:S,telemetry:ie}}const qp="taskforce:context-assets-mutated";function n$(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(qp,{detail:e}))}const Kp="taskforce:ai-profiles-mutated";function a$(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Kp,{detail:e}))}const _w=4,Ou=100;function ld(e,t,a){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(typeof e=="bigint")return e.toString();if(e instanceof Date)return e.toISOString();if(t>=_w)return"[MaxDepth]";if(typeof e=="function"||typeof e=="symbol"||typeof e>"u")return String(e);if(Array.isArray(e))return e.slice(0,Ou).map(s=>ld(s,t+1,a));if(e instanceof Set)return Array.from(e.values()).slice(0,Ou).map(s=>ld(s,t+1,a));if(e instanceof Map){const s={};for(const[o,c]of Array.from(e.entries()).slice(0,Ou))s[String(o)]=ld(c,t+1,a);return s}if(typeof e=="object"){if(a.has(e))return"[Circular]";a.add(e);const s={};for(const[o,c]of Object.entries(e).slice(0,Ou))s[o]=ld(c,t+1,a);return a.delete(e),s}return String(e)}function Nm(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return ld(e,0,new WeakSet)}function Cw(e){const t=Nm(e);if(!t)return"null";try{return JSON.stringify(t)}catch{return"[UnserializableSyncEventDetails]"}}const ry="taskforce.userGlobalSyncMeta.v1",Aw="taskforce.syncDebug.v1",xw=12e4,sy="taskforce.syncWatermarks.v3",Iw=300*1e3,bh="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function pi(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function Tw(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(Aw)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Ga(e,t){if(!Tw())return;console.info("[Taskforce Sync]",e,t&&typeof t=="object"?t:{})}function Rw(e){const t=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",avatarUrl:al(e?.avatarUrl??e?.avatar_url),avatarSourceUrl:al(e?.avatarSourceUrl??e?.avatar_source_url),avatarRevision:Number.isFinite(Number(e?.avatarRevision??e?.avatar_revision))?Math.max(0,Math.floor(Number(e?.avatarRevision??e?.avatar_revision))):0,avatarUpdatedAt:Hr(e?.avatarUpdatedAt??e?.avatar_updated_at),description:ha(e?.description),role:ha(e?.role),provider:ha(e?.provider),model:ha(e?.model),surfaceType:ey(e?.surfaceType??e?.surface_type),seatScope:ty(e?.seatScope??e?.seat_scope),providerMetadata:t&&typeof t=="object"&&!Array.isArray(t)?t:null,archivedAt:Hr(e?.archivedAt??e?.archived_at),archivedBy:mm(e?.archivedBy??e?.archived_by),archivedReason:ha(e?.archivedReason??e?.archived_reason),mergedIntoProfileId:mm(e?.mergedIntoProfileId??e?.merged_into_profile_id),rosterStateUpdatedAt:Hr(e?.rosterStateUpdatedAt??e?.roster_state_updated_at),createdAt:String(e?.createdAt||e?.created_at||"").trim(),updatedAt:String(e?.updatedAt||e?.updated_at||e?.createdAt||e?.created_at||"").trim(),lastActiveAt:Hr(e?.lastActiveAt??e?.last_active_at)}}function _h(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(ry);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Nw(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ry,JSON.stringify(e))}catch{}}function jw(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function Pw(e){return e.flatMap(t=>{const a=String(t?.id||"").trim();return!a||!Array.isArray(t?.comments)?[]:t.comments.map(s=>({id:String(s?.id||"").trim(),sessionId:a,body:String(s?.body||""),anchor:s?.anchor??null,order:Number.isFinite(Number(s?.order))?Math.max(0,Math.floor(Number(s.order))):0,authorActorId:typeof s?.authorActorId=="string"&&s.authorActorId.trim().length>0?s.authorActorId.trim():null,createdAt:String(s?.createdAt||"").trim(),updatedAt:String(s?.updatedAt||s?.createdAt||"").trim(),deletedAt:typeof s?.deletedAt=="string"&&s.deletedAt.trim().length>0?s.deletedAt.trim():null})).filter(s=>s.id.length>0&&s.sessionId.length>0)})}function $u(e,t,a=[],s=[]){const o=new Map;for(const c of[...e||[],...t||[]]){const i=Array.isArray(c?.taskEvents)?c.taskEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.taskId||c?.id||"").trim(),k=String(d?.workspaceId||"").trim(),S=String(d?.createdAt||"").trim();if(!m||!y||!k||!S)continue;const h={id:m,workspaceId:k,entityType:"task",entityId:y,taskId:y,action:String(d?.action||"").trim(),actor:String(d?.actor||"system").trim()||"system",actorType:d?.actorType==="ai"||d?.actorType==="human"||d?.actorType==="system"?d.actorType:"system",details:d?.details,createdAt:S},g=o.get(m);(!g||h.createdAt>g.createdAt)&&o.set(m,h)}}for(const c of a||[]){const i=Array.isArray(c?.entityEvents)?c.entityEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.entityId||c?.id||"").trim(),k=String(d?.workspaceId||"").trim(),S=String(d?.createdAt||"").trim();if(!m||!y||!k||!S)continue;const h={id:m,workspaceId:k,entityType:"initiative",entityId:y,action:String(d?.action||"").trim(),actor:String(d?.actor||"system").trim()||"system",actorType:d?.actorType==="ai"||d?.actorType==="human"||d?.actorType==="system"?d.actorType:"system",details:d?.details,createdAt:S},g=o.get(m);(!g||h.createdAt>g.createdAt)&&o.set(m,h)}}for(const c of s||[]){const i=Array.isArray(c?.entityEvents)?c.entityEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.entityId||c?.id||"").trim(),k=String(d?.workspaceId||"").trim(),S=String(d?.createdAt||"").trim();if(!m||!y||!k||!S)continue;const h={id:m,workspaceId:k,entityType:"workstream",entityId:y,action:String(d?.action||"").trim(),actor:String(d?.actor||"system").trim()||"system",actorType:d?.actorType==="ai"||d?.actorType==="human"||d?.actorType==="system"?d.actorType:"system",details:d?.details,createdAt:S},g=o.get(m);(!g||h.createdAt>g.createdAt)&&o.set(m,h)}}return Array.from(o.values()).sort((c,i)=>c.createdAt!==i.createdAt?c.createdAt.localeCompare(i.createdAt):c.id.localeCompare(i.id))}function oy(e){return{taskIds:Array.from(e.taskIds.values()),taskWatermarks:Array.from(e.taskWatermarks.entries()),taskChangeKeys:Array.from((e.taskChangeKeys||new Map).entries()),initiativeWatermarks:Array.from(e.initiativeWatermarks.entries()),workstreamWatermarks:Array.from(e.workstreamWatermarks.entries()),aiProfileWatermarks:Array.from(e.aiProfileWatermarks.entries()),aiProfileChangeKeys:Array.from((e.aiProfileChangeKeys||new Map).entries()),documentWatermarks:Array.from(e.documentWatermarks.entries()),assetWatermarks:Array.from(e.assetWatermarks.entries()),documentReviewSessionWatermarks:Array.from(e.documentReviewSessionWatermarks.entries()),documentReviewCommentWatermarks:Array.from(e.documentReviewCommentWatermarks.entries()),annotatedAttachmentSessionWatermarks:Array.from(e.annotatedAttachmentSessionWatermarks.entries()),taskEventWatermarks:Array.from(e.taskEventWatermarks.entries()),taxonomyStateFingerprint:typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:""}}function iy(e,t){if(!e||typeof e!="object")return null;const a=typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:"",s=!t||!a||a===t?new Map(Array.isArray(e.taskWatermarks)?e.taskWatermarks:[]):new Map;return{taskIds:new Set(Array.isArray(e.taskIds)?e.taskIds.map(c=>String(c||"").trim()).filter(c=>c.length>0):Array.from(s.keys())),taskWatermarks:s,taskChangeKeys:new Map(Array.isArray(e.taskChangeKeys)?e.taskChangeKeys:[]),initiativeWatermarks:new Map(Array.isArray(e.initiativeWatermarks)?e.initiativeWatermarks:[]),workstreamWatermarks:new Map(Array.isArray(e.workstreamWatermarks)?e.workstreamWatermarks:[]),aiProfileWatermarks:new Map(Array.isArray(e.aiProfileWatermarks)?e.aiProfileWatermarks:[]),aiProfileChangeKeys:new Map(Array.isArray(e.aiProfileChangeKeys)?e.aiProfileChangeKeys:[]),documentWatermarks:new Map(Array.isArray(e.documentWatermarks)?e.documentWatermarks:[]),assetWatermarks:new Map(Array.isArray(e.assetWatermarks)?e.assetWatermarks:[]),documentReviewSessionWatermarks:new Map(Array.isArray(e.documentReviewSessionWatermarks)?e.documentReviewSessionWatermarks:[]),documentReviewCommentWatermarks:new Map(Array.isArray(e.documentReviewCommentWatermarks)?e.documentReviewCommentWatermarks:[]),annotatedAttachmentSessionWatermarks:new Map(Array.isArray(e.annotatedAttachmentSessionWatermarks)?e.annotatedAttachmentSessionWatermarks:[]),taskEventWatermarks:new Map(Array.isArray(e.taskEventWatermarks)?e.taskEventWatermarks:[])}}function Ch(e,t){if(typeof window>"u")return null;try{const a=`${sy}.${e}`,s=window.localStorage.getItem(a);if(!s)return null;const o=JSON.parse(s);return!o||o.v!==2&&o.v!==3&&o.v!==4&&o.v!==5&&o.v!==6&&o.v!==7&&o.v!==8&&o.v!==9&&o.v!==10&&o.v!==11?null:iy(o,t)}catch{return null}}function Ah(e,t){if(typeof window>"u")return!1;try{const a=`${sy}.${e}`;return window.localStorage.setItem(a,JSON.stringify({v:11,savedAt:new Date().toISOString(),...oy(t)})),!0}catch{return!1}}function Mw({currentWorkspaceId:e,workspaceSyncPhase:t,clearWorkspaceRetry:a,setWorkspaceSyncBusy:s,setUserGlobalSyncStatus:o,setUserGlobalSyncError:c,setWorkspaceLastErrorMessage:i,setWorkspaceLastErrorAt:d,reportSyncEvent:m,setAuthBlocked:y,setIsAuthenticated:k,checkAuthSession:S,ensureCloudWorkspaceReadyForSync:h,scheduleWorkspaceSyncRetry:g,persistWorkspaceSyncPatchSafely:v}){const _=async(A,D)=>{a(),s(!1),o("error");const U="Session expired. Sign in again to resume cloud sync.";c(U),i(U),d(new Date().toISOString()),m(e,{eventType:A==="handshake"?"handshake":A,status:"error",statusCode:D,errorMessage:U}),y(!0),k(!1),await S()};return{handleSyncAuthFailure:_,ensureWorkspaceSyncReady:async()=>{if(!pi(e)){const U="Workspace sync blocked: local workspace ID is unresolved.";return i(U),d(new Date().toISOString()),c(U),o("error"),!1}const A=await h();if(A.success)return!0;if(A.statusCode===401)return await _("handshake",401),!1;const D=A.error||"Workspace sync handshake failed.";return i(D),d(new Date().toISOString()),c(D),o("error"),m(e,{eventType:"handshake",status:"error",statusCode:A.statusCode,errorMessage:D}),A.transient||Ms(A.statusCode)?g(A.retryAfterMs):(t==="active"||t==="attach-cloud"||t==="provision-local")&&v({phase:"error",lastErrorMessage:D}),!1}}}function Ew({workspaceSyncPhase:e,lastBootstrapPhaseRef:t,bootstrapPhaseStartedAtRef:a,bootstrapLastProgressAtRef:s}){if(e==="attach-cloud"||e==="provision-local"){t.current=e,a.current===null&&(a.current=Date.now()),s.current=null;return}a.current=null,s.current=null}function Dw({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:a,workspacePullInFlightRef:s,workspacePushInFlightRef:o,bootstrapPhaseStartedAtRef:c,bootstrapLastProgressAtRef:i,setWorkspaceLastErrorMessage:d,setWorkspaceLastErrorAt:m,setUserGlobalSyncStatus:y,setUserGlobalSyncError:k,setWorkspaceSyncBusy:S,persistWorkspaceSyncPatchSafely:h}){if(!t||a!=="attach-cloud"&&a!=="provision-local")return;const g=window.setInterval(()=>{if(a!=="attach-cloud"&&a!=="provision-local"||s.current||o.current)return;const v=Math.max(c.current??0,i.current??0);if(v>0&&Date.now()-v<xw)return;const I=`Workspace sync ${a==="attach-cloud"?"initial cloud pull":"initial cloud upload"} stalled. Press Repair to restart sync for this workspace.`;d(I),m(new Date().toISOString()),y("error"),k(I),S(!1),h({phase:"error",lastErrorMessage:I}),Ga("workspace_sync_bootstrap_timeout",{workspaceId:e,phase:a})},1e4);return()=>window.clearInterval(g)}function Lw(e){const{workspaceSyncPhase:t,lastBootstrapPhase:a,workspaceLastPullAt:s}=e;return t==="provision-local"?"provision-local":t==="attach-cloud"?"attach-cloud":t==="active"||a==="active"?"active":a==="provision-local"||a==="attach-cloud"?a:s?"attach-cloud":"provision-local"}const bf={allowed:!0};function ir(e,t){return{allowed:!1,reason:e,retainPendingSignature:t?.retainPendingSignature===!0}}function _f(e,t){return e.cloudAuthConfigured?e.runtimeMode!=="local"?ir("runtime-not-local"):e.workspaceCloudSyncEnabled?(t?.requireValidWorkspace??!0)&&!pi(e.currentWorkspaceId)?ir("invalid-workspace"):null:ir("sync-disabled"):ir("cloud-auth-unconfigured")}function Zp(e){const t=_f(e);return t||(e.repairModeActive&&!e.repairModeBypass?ir("repair-active",{retainPendingSignature:!0}):e.workspaceSyncPhase==="attach-cloud"?ir("attach-cloud",{retainPendingSignature:!0}):e.isAuthenticated?e.pushInFlight?ir("push-in-flight",{retainPendingSignature:!0}):e.pullInFlight?ir("pull-in-flight",{retainPendingSignature:!0}):bf:ir("auth-required"))}function Yp(e){const t=_f(e);return t||(e.repairModeActive&&!e.repairModeBypass?ir("repair-active"):e.workspaceSyncPhase==="provision-local"?ir("provision-local"):e.retryPending?ir("retry-pending"):e.isAuthenticated?e.pullInFlight?ir("pull-in-flight"):e.pushInFlight?ir("push-in-flight"):bf:ir("auth-required"))}function Jp(e){const t=_f(e,{requireValidWorkspace:!1});return t||(e.isAuthenticated?bf:ir("auth-required"))}function Bw(e){return ir("lease-held",{retainPendingSignature:e==="push"})}function Id(e){return e.cloudAuthConfigured&&e.runtimeMode==="local"&&e.workspaceCloudSyncEnabled&&e.authSessionResolved}function Ww({enabled:e,phase:t,busy:a,retryAt:s,lastErrorMessage:o}){return e?t==="provision-local"?{status:"syncing",summary:a?"Uploading this workspace to cloud for the first time.":"Preparing the first upload to cloud.",recommendedAction:"Keep this window open while the first upload finishes. If it seems stalled, press Sync."}:t==="attach-cloud"?{status:"syncing",summary:a?"Pulling the cloud workspace into this device.":"Waiting for the first cloud pull into this device.",recommendedAction:"Keep this window open for the first cloud pull. If it does not move, press Repair."}:s?{status:"attention",summary:"Sync hit a temporary problem and will retry automatically.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."}:o||t==="error"?{status:"attention",summary:"Sync needs attention before it can continue.",recommendedAction:"Press Sync to retry. If the same error keeps returning, press Repair."}:a?{status:"syncing",summary:"Sync is currently running.",recommendedAction:"No action needed."}:{status:"healthy",summary:"Sync is healthy.",recommendedAction:"No action needed."}:{status:"off",summary:"Sync is turned off for this workspace.",recommendedAction:"Turn on sync when you are ready to back up this workspace."}}function Fw(e){return Id(e)&&e.workspaceSyncPhase!=="attach-cloud"&&e.workspaceSyncReferenceSnapshotsReady}function Ow(e){return Id(e)&&e.workspaceSyncPhase==="active"&&e.workspaceSyncReferenceSnapshotsReady}function $w(e){return Id(e)?e.workspaceSyncPhase==="provision-local"||e.workspaceSyncPhase==="error"||e.retryPending?{shouldStart:!1,shouldKickOffImmediately:!1}:{shouldStart:!0,shouldKickOffImmediately:e.workspaceSyncPhase==="attach-cloud"||!e.lastPullAt}:{shouldStart:!1,shouldKickOffImmediately:!1}}function Uw(e){return Id(e)&&e.isAuthenticated&&e.workspaceSyncPhase==="active"}function zw(e){return Id(e)&&e.isAuthenticated&&e.workspaceSyncPhase!=="provision-local"&&e.workspaceSyncPhase!=="attach-cloud"&&!e.alreadyRan}function Hw({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:a,workspaceSyncPhase:s,workspacePullInFlightRef:o,realtimePullDebounceRef:c,realtimeSuppressedEventIdsRef:i,clearWorkspaceRetry:d,isWorkspaceRetryPending:m,pullWorkspaceChangesFromCloud:y}){return{handleRealtimeSignal:g=>{if(!e||t!=="local"||!a||s==="provision-local")return;const v=String(g?.eventId||"").trim();v&&i.current.delete(v)||o.current||(m()&&d(),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{c.current=null,y()},180))},recordSuppressedEventIds:(g,v)=>{const _=v?.queueRef,I=Number.isFinite(v?.maxQueueSize)?Math.max(1,Number(v?.maxQueueSize)):2048,A=Number.isFinite(v?.ttlMs)?Math.max(0,Number(v?.ttlMs)):null;for(const D of g){const U=String(D||"").trim();!U||i.current.has(U)||(i.current.add(U),_&&_.current.push(U),A!==null&&window.setTimeout(()=>{i.current.delete(U)},A))}if(_)for(;_.current.length>I;){const D=_.current.shift();D&&i.current.delete(D)}},clearRealtimePullDebounce:()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)}}}function cy(e){e.workspaceLastPushedWatermarksRef.current=new Map,e.workspaceLastPushedTaskChangeKeysRef.current=new Map,e.workspaceLastPushedInitiativeIdsRef.current=new Set,e.workspaceLastPushedInitiativeWatermarksRef.current=new Map,e.workspaceLastPushedWorkstreamIdsRef.current=new Set,e.workspaceLastPushedWorkstreamWatermarksRef.current=new Map,e.workspaceLastPushedAiProfileIdsRef.current=new Set,e.workspaceLastPushedAiProfileWatermarksRef.current=new Map,e.workspaceLastPushedAiProfileChangeKeysRef.current=new Map,e.workspaceLastPushedDocumentPathsRef.current=new Set,e.workspaceLastPushedDocumentWatermarksRef.current=new Map,e.workspaceLastPushedAssetPathsRef.current=new Set,e.workspaceLastPushedAssetWatermarksRef.current=new Map,e.workspaceBaselineResetReasonRef.current="repair-reset"}function Gw(e){cy(e),e.workspaceLastPushedDocumentPathsRef.current=new Set,e.workspaceLastPushedDocumentWatermarksRef.current=new Map,e.workspaceLastPushedAssetPathsRef.current=new Set,e.workspaceLastPushedAssetWatermarksRef.current=new Map,e.workspaceLastPushedDocumentReviewSessionIdsRef.current=new Set,e.workspaceLastPushedDocumentReviewSessionWatermarksRef.current=new Map,e.workspaceLastPushedDocumentReviewCommentIdsRef.current=new Set,e.workspaceLastPushedDocumentReviewCommentWatermarksRef.current=new Map,e.workspaceLastPushedAnnotatedAttachmentSessionIdsRef.current=new Set,e.workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef.current=new Map,e.workspaceLastPushedTaskEventWatermarksRef.current=new Map}function Vw({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:a,workspaceLastPullAt:s,lastBootstrapPhaseRef:o,workspaceRepairModeRef:c,workspaceForceFullAiProfilePushRef:i,workspaceStartupRepairRanRef:d,workspaceStartupFullReconcileRanRef:m,workspaceFullReconcileInFlightRef:y,workspacePullCursorRef:k,workspaceAttachBootstrapBaselineSignatureRef:S,workspaceCaptureAttachBootstrapBaselineRef:h,workspacePendingSignatureRef:g,workspaceLastPushedSignatureRef:v,workspaceLastPushedWatermarksRef:_,workspaceLastPushedTaskChangeKeysRef:I,workspaceLastPushedInitiativeIdsRef:A,workspaceLastPushedInitiativeWatermarksRef:D,workspaceLastPushedWorkstreamIdsRef:U,workspaceLastPushedWorkstreamWatermarksRef:W,workspaceLastPushedAiProfileIdsRef:Q,workspaceLastPushedAiProfileWatermarksRef:le,workspaceLastPushedAiProfileChangeKeysRef:ie,workspaceLastPushedDocumentPathsRef:se,workspaceLastPushedDocumentWatermarksRef:$,workspaceLastPushedAssetPathsRef:C,workspaceLastPushedAssetWatermarksRef:de,workspaceLastPushedDocumentReviewSessionIdsRef:ke,workspaceLastPushedDocumentReviewSessionWatermarksRef:K,workspaceLastPushedDocumentReviewCommentIdsRef:j,workspaceLastPushedDocumentReviewCommentWatermarksRef:H,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:ue,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ye,workspaceLastPushedTaskEventWatermarksRef:G,workspaceBaselineResetReasonRef:je,bootstrapPhaseStartedAtRef:be,bootstrapLastProgressAtRef:ce,acquireWorkspaceSyncLease:me,releaseWorkspaceSyncLease:Te,forceClearWorkspaceSyncLease:Me,clearWorkspaceRetry:Pe,clearWorkspaceIssue:Ee,reportWorkspaceWindowContention:Z,reportSyncEvent:x,persistWorkspaceSyncPatch:b,persistWorkspaceSyncWatermarksSnapshotBestEffort:R,buildWorkspaceSyncSignature:B,pullWorkspaceChangesFromCloud:Y,pushWorkspaceChangesToCloud:fe,cloudAuthConfigured:te,runtimeMode:Le,isAuthenticated:oe,checkAuthSession:L}){const X=a==="provision-local"?"push":a==="attach-cloud"?"bootstrap":"pull";return{retryWorkspaceCloudSync:async()=>{Pe();let ne=Jp({cloudAuthConfigured:te,runtimeMode:Le,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:oe});if(!ne.allowed&&ne.reason==="auth-required"){if(!await L())return x(e,{eventType:X,status:"error",errorMessage:"Manual sync retry blocked: sign in is required.",details:{source:"retry.blocked",reason:"auth-required",phase:a}}),!1;ne=Jp({cloudAuthConfigured:te,runtimeMode:Le,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:!0})}if(!ne.allowed)return x(e,{eventType:X,status:"error",errorMessage:`Manual sync retry blocked: ${ne.reason}.`,details:{source:"retry.blocked",reason:ne.reason,phase:a}}),!1;if(i.current=!0,a==="provision-local"){const Re=B();return Re?fe(Re,{forceAllAiProfiles:!0}):!1}const Ce=await Y();if(a==="attach-cloud")return Ce;const Ae=B();if(Ae){g.current=Ae;const Re=await fe(Ae,{forceAllAiProfiles:i.current===!0});return Ce||Re}return Ce},resetWorkspaceSyncCursorAndPull:async()=>{if(!await me(e,"repair")&&(Me(e),!await me(e,"repair"))){Z("repair"),x(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because another window is already syncing this workspace.",details:{source:"repair.blocked",reason:"lease-held",phase:a}});return}const Ce=Lw({workspaceSyncPhase:a,lastBootstrapPhase:o.current,workspaceLastPullAt:s}),Ae=Ce==="provision-local",Re=Ce==="active";Pe(),Ee();try{if(!t){x(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because workspace sync is turned off.",details:{source:"repair.blocked",reason:"sync-disabled",phase:a}});return}if(be.current=null,ce.current=null,k.current=null,S.current="",h.current=!1,g.current="",v.current="",i.current=!1,d.current=!1,m.current=!1,y.current=!1,Ae?Gw({workspaceLastPushedWatermarksRef:_,workspaceLastPushedTaskChangeKeysRef:I,workspaceLastPushedInitiativeIdsRef:A,workspaceLastPushedInitiativeWatermarksRef:D,workspaceLastPushedWorkstreamIdsRef:U,workspaceLastPushedWorkstreamWatermarksRef:W,workspaceLastPushedAiProfileIdsRef:Q,workspaceLastPushedAiProfileWatermarksRef:le,workspaceLastPushedAiProfileChangeKeysRef:ie,workspaceLastPushedDocumentPathsRef:se,workspaceLastPushedDocumentWatermarksRef:$,workspaceLastPushedAssetPathsRef:C,workspaceLastPushedAssetWatermarksRef:de,workspaceLastPushedDocumentReviewSessionIdsRef:ke,workspaceLastPushedDocumentReviewSessionWatermarksRef:K,workspaceLastPushedDocumentReviewCommentIdsRef:j,workspaceLastPushedDocumentReviewCommentWatermarksRef:H,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:ue,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ye,workspaceLastPushedTaskEventWatermarksRef:G,workspaceBaselineResetReasonRef:je}):Re&&cy({workspaceLastPushedWatermarksRef:_,workspaceLastPushedTaskChangeKeysRef:I,workspaceLastPushedInitiativeIdsRef:A,workspaceLastPushedInitiativeWatermarksRef:D,workspaceLastPushedWorkstreamIdsRef:U,workspaceLastPushedWorkstreamWatermarksRef:W,workspaceLastPushedAiProfileIdsRef:Q,workspaceLastPushedAiProfileWatermarksRef:le,workspaceLastPushedAiProfileChangeKeysRef:ie,workspaceLastPushedDocumentPathsRef:se,workspaceLastPushedDocumentWatermarksRef:$,workspaceLastPushedAssetPathsRef:C,workspaceLastPushedAssetWatermarksRef:de,workspaceBaselineResetReasonRef:je}),R(),c.current=!0,x(e,{eventType:"bootstrap",status:"success",errorMessage:"Manual sync repair started.",details:{source:"repair.started",phase:a,repairPhase:Ce,lastBootstrapPhase:o.current}}),await b({phase:Ce,pullCursor:null,startupFullReconcileCompletedAt:null,lastErrorMessage:null}),Ce==="provision-local"){const st=B();if(!st)return;await fe(st,{forceAllAiProfiles:!0,repairMode:!0});return}const $e=await Y({repairMode:!0});if(Ce!=="active"||!$e)return;const vt=B();if(!vt)return;g.current=vt,await fe(vt,{forceAllAiProfiles:!0,repairMode:!0})}finally{c.current=!1,Te(e)}}}}function qw({workspaceSyncPhase:e,forceCursorNull:t,currentCursor:a}){const s=e==="attach-cloud";return{bootstrap:s,cursor:s||t===!0?null:a,successEventType:s?"bootstrap":"pull"}}function Kw({workspaceSyncPhase:e,forceCursorNull:t,startupFullReconcileRan:a,pendingSignature:s,fallbackSignature:o,lastPushedSignature:c}){const i=e==="attach-cloud",d=s||o,m=!i&&d&&d!==c?d:null;return{successEventType:i?"bootstrap":"pull",shouldCaptureAttachBootstrapBaseline:i,shouldClearPendingSignature:i||m!==null,shouldRefreshReferenceSnapshots:i,shouldSeedWorkspaceSnapshotPushBaseline:i,shouldScheduleStartupFullReconcile:!t&&!i&&!a,deferredPushSignature:m}}function Zw({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:c,checkAuthSession:i,resolveCloudAuthUrl:d,ensureCloudWorkspaceReadyForSync:m,ensureWorkspaceSyncReady:y,handleSyncAuthFailure:k,clearWorkspaceRetry:S,clearWorkspaceIssue:h,isWorkspaceRetryPending:g,scheduleWorkspaceSyncRetry:v,persistWorkspaceSyncPatchSafely:_,persistWorkspaceSyncPatchBestEffort:I,persistWorkspaceSyncWatermarksSnapshotBestEffort:A,reportSyncEvent:D,acquireWorkspaceSyncLease:U,releaseWorkspaceSyncLease:W,reportWorkspaceWindowContention:Q,refreshWorkspaceSyncMarkdownDocumentsSnapshot:le,refreshWorkspaceSyncAiProfilesSnapshot:ie,refreshWorkspaceSyncAssetsSnapshot:se,refreshWorkspaceSyncPlanningEntitiesSnapshot:$,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:C,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:de,refreshLocalWorkspaceTaskCollections:ke,buildWorkspaceSyncPayload:K,buildWorkspaceSyncSignature:j,seedWorkspaceSnapshotPushBaseline:H,shouldSuppressAttachBootstrapPush:ue,recordSuppressedEventIds:ye,workspaceRepairModeRef:G,workspaceForceFullAiProfilePushRef:je,workspacePushInFlightRef:be,workspacePullInFlightRef:ce,workspacePendingPushReplayRef:me,workspaceLastPushedSignatureRef:Te,workspacePendingSignatureRef:Me,workspaceLastPushedTaskIdsRef:Pe,workspaceDeletedTaskIdsRef:Ee,workspaceDeletedTaskWatermarksRef:Z,workspacePullCursorRef:x,workspaceLastPushedWatermarksRef:b,workspaceLastPushedTaskChangeKeysRef:R,workspaceLastPushedInitiativeIdsRef:B,workspaceLastPushedInitiativeWatermarksRef:Y,workspaceLastPushedWorkstreamIdsRef:fe,workspaceLastPushedWorkstreamWatermarksRef:te,workspaceLastPushedAiProfileIdsRef:Le,workspaceLastPushedAiProfileWatermarksRef:oe,workspaceLastPushedAiProfileChangeKeysRef:L,workspaceLastPushedDocumentPathsRef:X,workspaceLastPushedDocumentWatermarksRef:M,workspaceLastPushedAssetPathsRef:V,workspaceLastPushedAssetWatermarksRef:ne,workspaceLastPushedDocumentReviewSessionIdsRef:Ce,workspaceLastPushedDocumentReviewSessionWatermarksRef:Ae,workspaceLastPushedDocumentReviewCommentIdsRef:Re,workspaceLastPushedDocumentReviewCommentWatermarksRef:$e,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:vt,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:st,workspaceLastPushedTaskEventWatermarksRef:kt,workspaceBaselineResetReasonRef:Ye,workspaceCaptureAttachBootstrapBaselineRef:Ct,workspaceStartupFullReconcileRanRef:dt,workspaceFullReconcileInFlightRef:Qe,bootstrapLastProgressAtRef:Tt,realtimeSuppressedEventQueueRef:ae,setWorkspaceSyncBusy:Ge,setUserGlobalSyncStatus:ft,setUserGlobalSyncError:it,setWorkspaceLastErrorMessage:Mt,setWorkspaceLastErrorAt:ht,setWorkspaceLastPullAt:Ft,setWorkspaceLastPushAt:Et,setWorkspaceSyncPendingChanges:We,setTasks:tt,setArchivedTasks:Oe}){const Ze=async(ot,re)=>{let Be=Zp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:c,repairModeActive:G.current===!0,repairModeBypass:re?.repairMode===!0,pushInFlight:be.current,pullInFlight:ce.current});if(!Be.allowed&&Be.reason==="auth-required"){if(!await i())return!1;Be=Zp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:G.current===!0,repairModeBypass:re?.repairMode===!0,pushInFlight:be.current,pullInFlight:ce.current})}if(!Be.allowed)return Be.retainPendingSignature&&(Me.current=ot),!1;if(ue(ot))return!1;if(!await U(s,"push")){const l=Bw("push");return!l.allowed&&l.retainPendingSignature&&(Me.current=ot),Q("push"),!1}be.current=!0,Ge(!0),ft("syncing"),it(null);const Rt=Date.now(),Bt=re?.forceAllAiProfiles===!0||je.current===!0,Ve=re?.repairMode===!0||G.current===!0;let Ot=null,yt=!1,E=ot;try{if(await le(),await ie(),await se(),await $(),await C(),!await y())return!1;const J=j();if(J&&(E=J),ue(E))return!1;const Se=me.current,Ke=Se&&Se.signature===E&&(!Bt||Se.forceAllAiProfiles===!0)&&(!Ve||Se.repairMode===!0)?Se:null,Je=Ke?.payload||K({forceAllAiProfiles:Bt});Ot=Je,yt=Ke!==null,We(Je.changes.length);const Ne=await LS({resolveCloudAuthUrl:d,workspaceId:s,payload:Je,ensureCloudWorkspaceReadyForSync:m,repairMode:Ke?.repairMode??Ve});if(!Ne.success){if(Ne.status===401)return me.current=null,await k("push",401),!1;let Pt=Ne.error?`Workspace sync push failed (${Ne.status||0}): ${Ne.error}`:`Workspace sync push failed (${Ne.status||0})`;return Ne.status===413&&(Pt="Workspace sync failed because the payload is too large. This usually happens when one or more attachments exceed the project limit."),ft("error"),it(Pt),Mt(Pt),ht(new Date().toISOString()),D(s,{eventType:"push",status:"error",statusCode:Ne.status,errorMessage:Pt,requestMs:Ne.requestMs,details:{payloadDiagnostics:Je.deltaDiagnostics||null,replayedPayload:yt}}),Me.current=E,Ne.transient||Ms(Ne.status)?(me.current={signature:E,payload:Je,forceAllAiProfiles:Ke?.forceAllAiProfiles??Bt,repairMode:Ke?.repairMode??Ve},v(Ne.retryAfterMs)):(me.current=null,o==="active"&&_({phase:"error",lastErrorMessage:Pt})),!1}me.current=null,Te.current=E,Pe.current=Ne.currentTaskIds,b.current=Ne.currentTaskWatermarks?new Map(Ne.currentTaskWatermarks):new Map(b.current),R.current=Ne.currentTaskChangeKeys?new Map(Ne.currentTaskChangeKeys):new Map(R.current),B.current=new Set(Ne.currentInitiativeIds),Y.current=new Map(Ne.currentInitiativeWatermarks),fe.current=new Set(Ne.currentWorkstreamIds),te.current=new Map(Ne.currentWorkstreamWatermarks),Le.current=new Set(Ne.currentAiProfileIds),oe.current=new Map(Ne.currentAiProfileWatermarks),L.current=Ne.currentAiProfileChangeKeys?new Map(Ne.currentAiProfileChangeKeys):new Map(L.current),X.current=new Set(Ne.currentDocumentPaths),M.current=new Map(Ne.currentDocumentWatermarks),V.current=new Set(Ne.currentAssetPaths),ne.current=new Map(Ne.currentAssetWatermarks),Ce.current=new Set(Ne.currentDocumentReviewSessionIds),Ae.current=new Map(Ne.currentDocumentReviewSessionWatermarks),Re.current=new Set(Ne.currentDocumentReviewCommentIds),$e.current=new Map(Ne.currentDocumentReviewCommentWatermarks),vt.current=new Set(Ne.currentAnnotatedAttachmentSessionIds),st.current=new Map(Ne.currentAnnotatedAttachmentSessionWatermarks),kt.current=new Map(Ne.currentTaskEventWatermarks),Bt&&(je.current=!1);for(const[Pt,Wt]of Ne.pushedWatermarks)b.current.set(Pt,Wt);for(const[Pt,Wt]of Ne.pushedTaskChangeKeys||new Map)R.current.set(Pt,Wt);if(Ne.deleteTaskIds.size>0)for(const Pt of Ne.deleteTaskIds)Ee.current.delete(Pt),Z.current.delete(Pt),b.current.delete(Pt),R.current.delete(Pt);const zt=await A();if(Ye.current=zt?null:"storage-write-failed",Array.isArray(Ne.emittedEventIds)&&Ne.emittedEventIds.length>0&&ye(Ne.emittedEventIds,{queueRef:ae,maxQueueSize:2048}),Array.isArray(Ne.appliedTaskUpserts)&&Ne.appliedTaskUpserts.length>0){const Pt=await Gp(s,Ne.appliedTaskUpserts.map(Wt=>({op:"upsert",archived:Wt.archived===!0,task:Wt.task})));if(Pt.ok){for(const Wt of Ne.appliedTaskUpserts){const Dt=String(Wt?.task?.id||"").trim(),Ht=String(Wt?.task?.updatedAt||Wt?.task?.createdAt||"").trim();!Dt||!Ht||b.current.set(Dt,Ht)}try{await ke()}catch{Ga("push_local_task_refresh_failed",{workspaceId:s,taskCount:Ne.appliedTaskUpserts.length})}}else Ga("push_local_task_apply_failed",{workspaceId:s,taskCount:Ne.appliedTaskUpserts.length,status:Pt.status,failures:Pt.failures})}S(),h();const Yt=Ne.syncedAt||new Date().toISOString();return Te.current=j(),Et(Yt),We(0),ft("idle"),_({phase:"active",lastPushAt:Yt,lastSyncedAt:Yt,lastErrorMessage:null}),D(s,{eventType:o==="provision-local"?"bootstrap":"push",status:"success",changeCount:Ne.changeCount,requestMs:Ne.requestMs,details:{payloadDiagnostics:Je.deltaDiagnostics||null,replayedPayload:yt}}),!0}catch(l){const J="Workspace sync push failed.";return ft("error"),it(J),Mt(J),ht(new Date().toISOString()),Me.current=E,Ot&&(me.current={signature:E,payload:Ot,forceAllAiProfiles:Bt,repairMode:Ve}),v(),D(s,{eventType:"push",status:"error",errorMessage:`${J} ${String(l?.message||"").trim()}`.trim(),details:{replayedPayload:yt}}),Ga("push_failed_exception",{workspaceId:s,elapsedMs:Date.now()-Rt}),!1}finally{be.current=!1,Ge(ce.current),W(s);const l=Me.current,J=j();l&&J&&J!==Te.current&&!ce.current&&!g()&&(Me.current="",window.setTimeout(()=>{Ze(J)},120))}},St=async ot=>{let re=Yp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:c,repairModeActive:G.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:g(),pullInFlight:ce.current,pushInFlight:be.current});if(!re.allowed&&re.reason==="auth-required"){if(!await i())return!1;re=Yp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:G.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:g(),pullInFlight:ce.current,pushInFlight:be.current})}if(!re.allowed)return!1;if(!await U(s,"pull"))return Q("pull"),!1;ce.current=!0,Ge(!0),ft("syncing"),it(null);const At=Date.now();try{if(!await y())return!1;const Bt=qw({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,currentCursor:x.current}),Ve=await BS({resolveCloudAuthUrl:d,workspaceId:s,cursor:Bt.cursor,bootstrap:Bt.bootstrap,ensureCloudWorkspaceReadyForSync:m,maxPages:20,repairMode:ot?.repairMode===!0||G.current===!0,onPagePulled:()=>{Tt.current=Date.now()},onChangesApplied:()=>{Tt.current=Date.now()}});if(!Ve.success){if(Ve.kind==="pull_http"&&Ve.status===401)return await k("pull",401),!1;if(Ve.kind==="apply_auth")return await k("apply",401),!1;if(Ve.kind==="pull_http"&&Ve.errorCode==="INVALID_SYNC_CURSOR"){const Se="Saved sync cursor was invalid. Clearing it and retrying from the beginning.";return x.current=null,_({pullCursor:null}),ft("error"),it(Se),Mt(Se),ht(new Date().toISOString()),D(s,{eventType:"pull",status:"error",statusCode:Ve.status,errorMessage:Se,requestMs:Ve.pullRequestMs,details:{recovery:"cursor-reset",...Ve.serverDiagnostics?{serverPullDiagnostics:Ve.serverDiagnostics}:{}}}),v(150),!1}let J=Ve.kind==="apply_payload"||Ve.kind==="apply_all_candidates"||Ve.kind==="exception"?String(Ve.error||"Workspace sync apply failed."):`Workspace sync pull failed (${Ve.status||0})`;return Ve.status===413&&(J="Local sync failed because the downloaded payload is too large. This usually happens when the workspace contains massive attachments."),ft("error"),it(J),Mt(J),ht(new Date().toISOString()),D(s,{eventType:Ve.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:Ve.status,errorMessage:J,requestMs:Ve.pullRequestMs,details:{pages:Ve.pages,applyMs:Ve.applyMs,...Ve.serverDiagnostics?{serverPullDiagnostics:Ve.serverDiagnostics}:{}}}),Ve.transient||Ve.hasTransientApplyFailure||Ms(Ve.status)?v(Ve.retryAfterMs):_({phase:"error",lastErrorMessage:J}),!1}Array.isArray(Ve.emittedEventIds)&&ye(Ve.emittedEventIds,{ttlMs:6e4}),Ve.pulledDeleteTaskIds.size>0&&(tt(J=>J.filter(Se=>!Ve.pulledDeleteTaskIds.has(String(Se.id||"")))),Oe(J=>J.filter(Se=>!Ve.pulledDeleteTaskIds.has(String(Se.id||"")))));const Ot=Array.isArray(Ve.documentDecryptFailures)?Ve.documentDecryptFailures.filter(J=>String(J||"").trim().length>0):[];if(Ot.length>0&&Ga("pull_document_decrypt_failures",{workspaceId:s,failureCount:Ot.length}),x.current=Ve.cursor||null,Ve.appliedChanges>0&&(Ve.pulledActiveUpserts||Ve.pulledArchivedUpserts||Ve.pulledTaskEventUpserts||Ve.pulledPlanningUpserts))try{await ke()}catch{Ga("pull_local_refresh_failed",{workspaceId:s,appliedChanges:Ve.appliedChanges})}S(),h();const yt=Ve.syncedAt||new Date().toISOString();Ft(yt),We(0),ft("idle");const E=Kw({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,startupFullReconcileRan:dt.current,pendingSignature:Me.current,fallbackSignature:j(),lastPushedSignature:Te.current});if(E.shouldCaptureAttachBootstrapBaseline&&(Ct.current=!0),E.shouldClearPendingSignature&&(Me.current="",me.current=null),await I({phase:"active",pullCursor:x.current,lastPullAt:yt,lastSyncedAt:yt,...ot?.forceCursorNull===!0?{startupFullReconcileCompletedAt:yt}:{},lastErrorMessage:null}),D(s,{eventType:E.successEventType,status:"success",changeCount:Ve.appliedChanges,requestMs:Ve.pullRequestMs,details:{pages:Ve.pages,applyMs:Ve.applyMs,...Ve.serverDiagnostics?{serverPullDiagnostics:Ve.serverDiagnostics}:{}}}),E.shouldRefreshReferenceSnapshots&&(await le(),await se(),await C(),await de()),E.shouldSeedWorkspaceSnapshotPushBaseline&&H(),E.shouldRefreshReferenceSnapshots||E.shouldSeedWorkspaceSnapshotPushBaseline)return!0;if(E.shouldScheduleStartupFullReconcile&&(dt.current=!0,window.setTimeout(()=>{Qe.current||(Qe.current=!0,St({forceCursorNull:!0}).finally(()=>{Qe.current=!1}))},250)),ot?.forceCursorNull===!0&&ot?.repairMode!==!0&&o==="active"){const J=j();J&&(je.current=!0,Me.current=J,window.setTimeout(()=>{Ze(J,{forceAllAiProfiles:!0})},120))}else if(E.deferredPushSignature){const J=E.deferredPushSignature;window.setTimeout(()=>{Ze(J)},120)}return!0}catch(Rt){const Bt=String(Rt?.message||"").trim(),Ve=Bt?`Workspace sync pull failed. ${Bt}`:"Workspace sync pull failed.";return ft("error"),it(Ve),Mt(Ve),ht(new Date().toISOString()),v(),D(s,{eventType:"pull",status:"error",errorMessage:Ve,requestMs:Date.now()-At}),Ga("pull_failed_exception",{workspaceId:s,elapsedMs:Date.now()-At,error:Bt||null}),!1}finally{ce.current=!1,Ge(be.current),W(s)}};return{pushWorkspaceChangesToCloud:Ze,pullWorkspaceChangesFromCloud:St}}const xh={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1};function Yw(e){const{currentWorkspaceId:t,cloudAuthConfigured:a,runtimeMode:s,authSessionResolved:o,isAuthenticated:c,authUserId:i,projectName:d,resolveCloudAuthUrl:m,resolveWebSocketUrl:y,realtimeSyncEnabled:k,tasks:S,archivedTasks:h,deletedTasks:g=[],initiatives:v,workstreams:_,taxonomies:I,taxonomyState:A,setupState:D,globalTheme:U,locale:W,globalWeekStartsOn:Q,themeUseGlobalDefault:le,setTasks:ie,setArchivedTasks:se,setAuthBlocked:$,setIsAuthenticated:C,checkAuthSession:de,setGlobalTheme:ke,setCurrentTheme:K,setSetupState:j,setLocale:H,setGlobalWeekStartsOn:ue,fetchPlanningEntities:ye}=e,G=r.useMemo(()=>jw(A),[A]),[je,be]=r.useState("disconnected"),[ce,me]=r.useState(null),[Te,Me]=r.useState(null),[Pe,Ee]=r.useState(null),[Z,x]=r.useState(null),[b,R]=r.useState(null),[B,Y]=r.useState(!1),[fe,te]=r.useState("idle"),[Le,oe]=r.useState(null),[L,X]=r.useState(!1),[M,V]=r.useState(0),[ne,Ce]=r.useState([]),[Ae,Re]=r.useState(""),$e=r.useRef(S||[]),vt=r.useRef(h||[]),st=r.useRef(v||[]),kt=r.useRef(_||[]),Ye=r.useRef([]),Ct=r.useRef(new Set),[dt,Qe]=r.useState([]),[Tt,ae]=r.useState(""),[Ge,ft]=r.useState(null),[it,Mt]=r.useState(null),[ht,Ft]=r.useState(0),[Et,We]=r.useState(null),tt=r.useRef([]),[Oe,Ze]=r.useState([]),[St,ot]=r.useState(""),re=r.useRef([]),Be=r.useRef(new Set),[At,Rt]=r.useState([]),[Bt,Ve]=r.useState(""),Ot=r.useRef([]),yt=r.useRef([]),[E,l]=r.useState([]),[J,Se]=r.useState(""),Ie=r.useRef([]),[Ke,Je]=r.useState(xh),[Ne,zt]=r.useState("degraded-fallback"),[Yt,Pt]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),Wt=r.useRef(!1),Dt=r.useRef(null),Ht=r.useRef("missing-baseline"),sn=r.useRef(0),Vt=r.useRef(!1),Vn=r.useRef(new Set),qn=r.useRef(""),Kn=r.useRef(""),ga=r.useRef(""),ge=r.useRef(""),at=r.useRef(""),xe=r.useRef(""),jt=r.useRef(!1),pt=r.useRef(null),bt=r.useRef(new Set),An=r.useRef([]),vn=r.useRef(null),dn=r.useRef(()=>Promise.resolve(!1)),un=r.useRef(async()=>{}),Bn=r.useRef(null),gt=r.useRef(null),cr=r.useRef("idle"),fn=r.useCallback(()=>{Dt.current!==null&&(window.clearTimeout(Dt.current),Dt.current=null)},[]),nn=r.useCallback(T=>{if(typeof window>"u")return;fn();const N=Math.max(1,Math.floor(sn.current)+1);sn.current=N;const rt=1500*2**Math.max(0,N-1),wt=Number.isFinite(Number(T))?Math.max(0,Math.floor(Number(T))):0,we=Math.max(Math.min(12e4,rt),wt);Dt.current=window.setTimeout(()=>{Dt.current=null,un.current({preferCloudOnFirstSync:!1})},we)},[fn]),bn=r.useCallback(T=>{Je(N=>N[T]?N:{...N,[T]:!0})},[]),Kt=Object.values(Ke).every(Boolean),{workspaceRetryAt:_r,isWorkspaceRetryPending:Pn,workspacePushInFlightRef:aa,workspacePullInFlightRef:Mn,workspaceLastPushedSignatureRef:Zt,workspacePendingSignatureRef:Zn,workspaceLastPushedTaskIdsRef:an,workspaceDeletedTaskIdsRef:ra,workspaceDeletedTaskWatermarksRef:Ea,workspacePullCursorRef:Da,clearWorkspaceRetry:hn,scheduleWorkspaceRetry:Va,persistWorkspaceSyncPatch:os,applyWorkspaceSyncPatchLocally:qa,readWorkspaceSyncStateSnapshot:Ca,loadWorkspaceSyncState:Wn,applyWorkspaceSyncStateSnapshot:Vr,saveWorkspaceCloudSyncSettings:Aa,acquireWorkspaceSyncLease:sa,releaseWorkspaceSyncLease:la,forceClearWorkspaceSyncLease:Fn}=ww({currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:Y,setWorkspaceSyncPhase:te,setWorkspaceSyncSetupIntent:oe,setWorkspaceLastPullAt:Me,setWorkspaceLastPushAt:Ee,setWorkspaceLastErrorMessage:R}),Nt=r.useCallback(T=>{(T.phase==="attach-cloud"||T.phase==="provision-local")&&(cr.current=T.phase,Bn.current===null&&(Bn.current=Date.now()),gt.current=null),Vr(T)},[Vr]),ya=r.useRef(new Map),On=r.useRef(new Map),lr=r.useRef(new Set),$n=r.useRef(new Map),La=r.useRef(new Set),xa=r.useRef(new Map),Sn=r.useRef(new Set),Dn=r.useRef(new Map),Ba=r.useRef(new Map),gn=r.useRef(new Set),Jt=r.useRef(new Map),Ka=r.useRef(new Set),xn=r.useRef(new Map),En=r.useRef(new Set),Za=r.useRef(new Map),In=r.useRef(new Set),Mr=r.useRef(new Map),cn=r.useRef(new Set),mn=r.useRef(new Map),ka=r.useRef(new Map),Yn=r.useCallback(T=>T?(an.current=new Set(T.taskIds),ya.current=T.taskWatermarks,On.current=T.taskChangeKeys||new Map,lr.current=new Set(Array.from(T.initiativeWatermarks.keys())),$n.current=T.initiativeWatermarks,La.current=new Set(Array.from(T.workstreamWatermarks.keys())),xa.current=T.workstreamWatermarks,Sn.current=new Set(Array.from(T.aiProfileWatermarks.keys())),Dn.current=T.aiProfileWatermarks,Ba.current=T.aiProfileChangeKeys||new Map,gn.current=new Set(Array.from(T.documentWatermarks.keys())),Jt.current=T.documentWatermarks,Ka.current=new Set(Array.from(T.assetWatermarks.keys())),xn.current=T.assetWatermarks,En.current=new Set(Array.from(T.documentReviewSessionWatermarks.keys())),Za.current=T.documentReviewSessionWatermarks,In.current=new Set(Array.from(T.documentReviewCommentWatermarks.keys())),Mr.current=T.documentReviewCommentWatermarks,cn.current=new Set(Array.from(T.annotatedAttachmentSessionWatermarks.keys())),mn.current=T.annotatedAttachmentSessionWatermarks,ka.current=T.taskEventWatermarks,Ht.current=null,!0):!1,[an]),Cr=r.useCallback(()=>({taskIds:an.current,taskWatermarks:ya.current,taskChangeKeys:On.current,initiativeWatermarks:$n.current,workstreamWatermarks:xa.current,aiProfileWatermarks:Dn.current,aiProfileChangeKeys:Ba.current,documentWatermarks:Jt.current,assetWatermarks:xn.current,documentReviewSessionWatermarks:Za.current,documentReviewCommentWatermarks:Mr.current,annotatedAttachmentSessionWatermarks:mn.current,taskEventWatermarks:ka.current}),[]),Er=r.useRef(!1),Xt=r.useRef(!1),Ia=r.useRef(!1),Wa=r.useRef(""),dr=r.useRef(!1),Ar=3e4,Ya=k?3e4:15e3,Ja=Math.max(3e4,Ya),xr=r.useMemo(()=>{const T=Te?Date.parse(Te):NaN,N=Pe?Date.parse(Pe):NaN;return Number.isFinite(T)&&Number.isFinite(N)?T>=N?Te:Pe:Number.isFinite(T)?Te:Number.isFinite(N)?Pe:null},[Te,Pe]),Jn=r.useMemo(()=>Ww({enabled:B,phase:fe,busy:L,retryAt:_r,lastErrorMessage:b}),[B,fe,L,_r,b]),Ta=Jn.status,ur=Jn.summary,oa=Jn.recommendedAction,qr=r.useCallback(T=>{const N=String(T||"").trim();if(!N)return null;const wt=_h()[N]?.updatedAt;return typeof wt=="string"&&wt.trim().length>0?wt.trim():null},[]),ia=r.useCallback((T,N)=>{const rt=String(T||"").trim(),wt=String(N||"").trim();if(!rt||!wt)return;const we=_h();we[rt]={updatedAt:wt},Nw(we)},[]),Dr=r.useCallback(()=>{const T=D?.mode==="operations"?"operations":"core";return{theme:U,operatingMode:T,localization:{locale:W,weekStartsOn:Q}}},[U,D?.mode,W,Q]),Kr=r.useCallback(async T=>{if(!(!T||typeof T!="object")){Vt.current=!0;try{const N={},rt=Yc(T.theme);if(rt&&(ke(rt),le&&K(rt),N.theme=rt),(T.operatingMode==="core"||T.operatingMode==="operations")&&(j(wt=>wt&&{...wt,mode:T.operatingMode}),N.setup={mode:T.operatingMode}),T.localization&&typeof T.localization=="object"){const wt={};if(typeof T.localization.locale=="string"&&T.localization.locale.trim().length>0){const ee=Ug(T.localization.locale.trim());H(ee)}const we=String(T.localization.weekStartsOn||"").trim().toLowerCase();(we==="sunday"||we==="monday")&&(ue(we),wt.weekStartsOn=we),Object.keys(wt).length>0&&(N.schedulePreferences=wt)}Object.keys(N).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(N)})}finally{Vt.current=!1}}},[le,ke,K,j,H,ue]),va=r.useCallback(async T=>{const N=T?.preferCloudOnFirstSync!==!1;if(!a)return;if(s!=="local"||!c){fn(),sn.current=0,be("disconnected");return}const rt=String(i||"").trim();if(!rt||rt==="anonymous"){fn(),sn.current=0,be("disconnected");return}if(!Wt.current){be("syncing"),me(null),Wt.current=!0;try{const wt=await WS({resolveCloudAuthUrl:m,userId:rt,preferCloudOnFirstSync:N,getLocalUpdatedAt:qr,buildLocalSettings:Dr,applyRemoteSettings:Kr});if(!wt.success){be("error"),wt.transient?(me(wt.error||"Sync failed temporarily. Retrying automatically."),nn(wt.retryAfterMs)):(fn(),sn.current=0,me(wt.error||"Sync failed."));return}fn(),sn.current=0;const we=String(wt.updatedAt||"").trim()||new Date().toISOString();ia(rt,we),be("idle"),me(null),Vn.current.add(rt),wt.mode==="pulled"&&(qn.current="")}catch{be("error"),me("Sync failed temporarily. Retrying automatically."),nn()}finally{Wt.current=!1}}},[a,s,c,i,m,qr,Dr,Kr,ia,fn,nn]);r.useEffect(()=>{un.current=va},[va]),r.useEffect(()=>()=>{fn()},[fn]);const Ir=r.useCallback(()=>{R(null),x(null)},[]),Ra=r.useCallback(T=>{R(bh),x(new Date().toISOString()),be("error"),me(bh),Ga("workspace_sync_window_contention",{workspaceId:t,operation:T})},[t]),Sa=r.useCallback(async T=>{try{return await os(T)}catch{return qa(T)}},[qa,os]),Fa=r.useCallback(T=>{Sa(T).catch(()=>{})},[Sa]),Zr=r.useCallback(()=>{const T={...Cr(),taxonomyStateFingerprint:G},N=Ah(t,T);return Sa({pushBaseline:oy(T)}).catch(()=>{}),N},[Cr,t,Sa,G]);r.useEffect(()=>{Kn.current="",ga.current="",ge.current="",at.current="",xe.current="",Wa.current="",dr.current=!1,Ce([]),Re(""),tt.current=[],Qe([]),ae(""),Ze([]),ot(""),Ot.current=[],yt.current=[],Rt([]),Ve(""),Ie.current=[],l([]),Se(""),Je(xh),R(null),x(null),V(0),bt.current=new Set,An.current=[],ya.current=new Map,On.current=new Map,lr.current=new Set,$n.current=new Map,La.current=new Set,xa.current=new Map,Sn.current=new Set,Dn.current=new Map,Ba.current=new Map,gn.current=new Set,Jt.current=new Map,Ka.current=new Set,xn.current=new Map,En.current=new Set,Za.current=new Map,In.current=new Set,Mr.current=new Map,cn.current=new Set,mn.current=new Map,ka.current=new Map,Xt.current=!!Ca().startupFullReconcileCompletedAt,Tn.current=!1;const T=Ch(t,G);Yn(T)||(Ht.current="missing-baseline")},[t,Yn,G]),r.useEffect(()=>{if(Ht.current!=="missing-baseline")return;const T=Ch(t,G);if(Yn(T))return;const N=iy(Ca().pushBaseline,G);Yn(N)&&Ah(t,{...Cr(),taxonomyStateFingerprint:G})},[Cr,t,Yn,Ca,G,B,fe]),r.useEffect(()=>{Xt.current=!!Ca().startupFullReconcileCompletedAt},[t,Ca,Te,fe]);const Ds=r.useCallback(T=>{Va(()=>dn.current(),{minDelayMs:T})},[Va]);r.useEffect(()=>{Ew({workspaceSyncPhase:fe,lastBootstrapPhaseRef:cr,bootstrapPhaseStartedAtRef:Bn,bootstrapLastProgressAtRef:gt})},[fe]),r.useEffect(()=>Dw({currentWorkspaceId:t,workspaceCloudSyncEnabled:B,workspaceSyncPhase:fe,workspacePullInFlightRef:Mn,workspacePushInFlightRef:aa,bootstrapPhaseStartedAtRef:Bn,bootstrapLastProgressAtRef:gt,setWorkspaceLastErrorMessage:T=>R(T),setWorkspaceLastErrorAt:T=>x(T),setUserGlobalSyncStatus:be,setUserGlobalSyncError:T=>me(T),setWorkspaceSyncBusy:X,persistWorkspaceSyncPatchSafely:Fa}),[t,B,fe,Fa,Mn,aa]);const et=r.useCallback(async()=>ES({cloudAuthConfigured:a,runtimeMode:s,isAuthenticated:c,resolveCloudAuthUrl:m,workspaceId:t,workspaceName:d||t,allowProvisionOnMismatch:fe!=="attach-cloud"}),[a,s,c,m,t,d,fe]);r.useEffect(()=>{$e.current=S||[]},[S]),r.useEffect(()=>{vt.current=h||[]},[h]),r.useEffect(()=>{ra.current=new Set((g||[]).map(T=>String(T?.taskId||"").trim()).filter(T=>T.length>0)),Ea.current=new Map((g||[]).map(T=>[String(T?.taskId||"").trim(),String(T?.deletedAt||"").trim()]).filter(([T,N])=>T.length>0&&Number.isFinite(Date.parse(N))))},[g,ra,Ea]),r.useEffect(()=>{st.current=v||[]},[v]),r.useEffect(()=>{kt.current=_||[]},[_]);const $t=r.useRef(!1),Tn=r.useRef(!1),_n=r.useCallback(T=>{const N=T?.forceAllAiProfiles===!0;return iw({tasks:$e.current,archivedTasks:vt.current,taskEvents:$u($e.current,vt.current,st.current,kt.current),lastPushedTaskIds:an.current,pendingDeletedTaskIds:ra.current,pendingDeletedTaskWatermarks:Ea.current,initiatives:st.current,workstreams:kt.current,taxonomies:I||[],taxonomyState:A,lastPushedInitiativeIds:lr.current,lastPushedInitiativeWatermarks:$n.current,lastPushedWorkstreamIds:La.current,lastPushedWorkstreamWatermarks:xa.current,aiProfiles:tt.current,lastPushedAiProfileIds:N?new Set:Sn.current,lastPushedAiProfileWatermarks:N?new Map:Dn.current,lastPushedAiProfileChangeKeys:N?new Map:Ba.current,documents:Ye.current,assets:re.current,currentDocumentPaths:Ct.current,currentAssetPaths:Be.current,documentReviewSessions:Ot.current,documentReviewComments:yt.current,annotatedAttachmentSessions:Ie.current,lastPushedDocumentPaths:gn.current,lastPushedDocumentWatermarks:Jt.current,lastPushedAssetPaths:Ka.current,lastPushedAssetWatermarks:xn.current,lastPushedDocumentReviewSessionIds:En.current,lastPushedDocumentReviewSessionWatermarks:Za.current,lastPushedDocumentReviewCommentIds:In.current,lastPushedDocumentReviewCommentWatermarks:Mr.current,lastPushedAnnotatedAttachmentSessionIds:cn.current,lastPushedAnnotatedAttachmentSessionWatermarks:mn.current,lastPushedTaskEventWatermarks:ka.current,baselineResetReason:Ht.current,lastPushedWatermarks:ya.current,lastPushedTaskChangeKeys:On.current})},[I,A]),wn=r.useCallback((T,N)=>{if(s==="local")try{const rt={...N,workspaceId:T,details:Nm(N.details)};fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(rt)}).catch(wt=>{Ga("sync_event_post_failed",{workspaceId:T,eventType:N.eventType,status:N.status,error:String(wt?.message||wt||"")})})}catch(rt){Ga("sync_event_post_failed",{workspaceId:T,eventType:N.eventType,status:N.status,error:String(rt?.message||rt||"")})}},[s]),Na=r.useCallback(()=>cw({workspaceId:t,tasks:$e.current,archivedTasks:vt.current,taskEvents:$u($e.current,vt.current,st.current,kt.current),pendingDeletedTaskIds:ra.current,initiatives:st.current,workstreams:kt.current,taxonomies:I||[],aiProfiles:tt.current,documents:Ye.current,assets:re.current,documentReviewSessions:Ot.current,documentReviewComments:yt.current,annotatedAttachmentSessions:Ie.current}),[t,I,A]),Qa=r.useMemo(()=>JSON.stringify({tasks:(S||[]).map(T=>({id:String(T.id||"").trim(),updatedAt:String(T.updatedAt||T.createdAt||"").trim(),status:String(T.status||"").trim(),referenceNumber:T.referenceNumber??null,localReferenceNumber:T.localReferenceNumber??null})).sort((T,N)=>T.id.localeCompare(N.id)),archivedTasks:(h||[]).map(T=>({id:String(T.id||"").trim(),updatedAt:String(T.updatedAt||T.createdAt||"").trim(),status:String(T.status||"").trim(),referenceNumber:T.referenceNumber??null,localReferenceNumber:T.localReferenceNumber??null})).sort((T,N)=>T.id.localeCompare(N.id)),initiatives:(v||[]).map(T=>({id:String(T.id||"").trim(),updatedAt:String(T.updatedAt||T.createdAt||"").trim(),isArchived:!!T.isArchived})).sort((T,N)=>T.id.localeCompare(N.id)),workstreams:(_||[]).map(T=>({id:String(T.id||"").trim(),updatedAt:String(T.updatedAt||T.createdAt||"").trim(),initiativeId:typeof T.initiativeId=="string"?T.initiativeId.trim():"",isArchived:!!T.isArchived})).sort((T,N)=>T.id.localeCompare(N.id)),taskEvents:$u(S||[],h||[],v||[],_||[]).map(T=>({id:String(T.id||"").trim(),entityType:String(T.entityType||"task").trim(),entityId:String(T.entityId||T.taskId||"").trim(),createdAt:String(T.createdAt||"").trim(),action:String(T.action||"").trim()})).sort((T,N)=>T.id.localeCompare(N.id)),deletedTasks:(g||[]).map(T=>({taskId:String(T?.taskId||"").trim(),deletedAt:String(T?.deletedAt||"").trim()})).filter(T=>T.taskId.length>0&&Number.isFinite(Date.parse(T.deletedAt))).sort((T,N)=>T.taskId.localeCompare(N.taskId)),taxonomies:Array.isArray(I)?I:[],taxonomyState:A&&typeof A=="object"?A:null}),[S,h,g,v,_,I,A]),ys=r.useMemo(()=>{const T=[];for(const N of S||[]){const rt=Array.isArray(N.attachments)?N.attachments.length:0;rt>0&&T.push(`${N.id}:${rt}`)}return T.join("|")},[S]),wa=r.useCallback(T=>{if(!T)return!1;if(dr.current)return dr.current=!1,Wa.current=T,Zt.current=T,V(0),!0;const N=Wa.current;return N?T===N?(Zt.current=T,V(0),!0):(Wa.current="",!1):!1},[]),Oa=r.useCallback(async()=>{if(s==="local"&&pi(t)&&!(a&&(!o||!c)))try{const T=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const N=await T.json().catch(()=>({})),rt=Array.isArray(N?.documents)?N.documents.map(ee=>({path:String(ee?.path||"").trim(),updatedAt:String(ee?.updatedAt||"").trim(),content:typeof ee?.content=="string"?ee.content:"",assetId:typeof ee?.assetId=="string"&&ee.assetId.trim().length>0?ee.assetId.trim():void 0,documentId:typeof ee?.documentId=="string"&&ee.documentId.trim().length>0?ee.documentId.trim():null,referenceNumber:Number.isFinite(Number(ee?.referenceNumber))?Math.max(1,Math.floor(Number(ee.referenceNumber))):null,version:Number.isFinite(Number(ee?.version))?Math.max(1,Math.floor(Number(ee.version))):null,taskId:typeof ee?.taskId=="string"&&ee.taskId.trim().length>0?ee.taskId.trim():null,logicalName:typeof ee?.logicalName=="string"&&ee.logicalName.trim().length>0?ee.logicalName.trim():null,caption:typeof ee?.caption=="string"&&ee.caption.trim().length>0?ee.caption.trim():null,originalFilename:typeof ee?.originalFilename=="string"&&ee.originalFilename.trim().length>0?ee.originalFilename.trim():null,linkRole:ee?.linkRole==="reference"?"reference":"attachment"})).filter(ee=>ee.path.length>0):[],wt=new Set(Array.isArray(N?.knownPaths)?N.knownPaths.map(ee=>String(ee||"").trim()).filter(ee=>ee.length>0):rt.map(ee=>ee.path)),we=typeof N?.fingerprint=="string"?N.fingerprint:JSON.stringify(rt.map(ee=>`${ee.path}:${ee.updatedAt}:${ee.content.length}`).sort());if(we===Kn.current)return;Kn.current=we,Ye.current=rt,Ct.current=wt,Ce(rt),Re(we)}catch(T){Ga("documents_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{bn("documents")}},[s,t,a,o,c,bn]),mr=r.useCallback(async()=>{if(s!=="local"){We("runtime-not-local");return}if(!pi(t)){We("workspace-id-invalid");return}if(a&&(!o||!c)){We(o?"auth-required":"auth-unresolved");return}We(null);try{const T=await fetch(`/api/taskforce/sync/workspace/ai-profiles?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok){Mt(`HTTP ${T.status}`),ft(new Date().toISOString());return}const N=await T.json().catch(()=>({})),rt=Array.isArray(N?.aiProfiles)?N.aiProfiles:[];Ft(rt.length);const wt=Array.isArray(N?.aiProfiles)?N.aiProfiles.map(ee=>Rw(ee)).filter(ee=>ee.id.length>0&&ee.workspaceId.length>0):[];Mt(null),ft(new Date().toISOString());const we=typeof N?.fingerprint=="string"?N.fingerprint:JSON.stringify(wt.map(ee=>[ee.id,ee.updatedAt,ee.name,ee.username,ee.archivedAt??"",ee.archivedReason??"",ee.mergedIntoProfileId??"",ee.rosterStateUpdatedAt??""].join(":")).sort());if(we===ga.current)return;ga.current=we,tt.current=wt,Qe(wt),ae(we)}catch(T){Mt(String(T?.message||T||"unknown-error")),ft(new Date().toISOString()),Ga("ai_profiles_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{bn("aiProfiles")}},[s,t,a,o,c,bn]),Gt=r.useCallback(async()=>{if(s==="local"&&pi(t)&&!(a&&(!o||!c)))try{const T=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const N=await T.json().catch(()=>({})),rt=Array.isArray(N?.assets)?N.assets.map(ee=>({path:String(ee?.path||"").trim(),updatedAt:String(ee?.updatedAt||"").trim(),contentBase64:typeof ee?.contentBase64=="string"?ee.contentBase64:"",assetId:typeof ee?.assetId=="string"&&ee.assetId.trim().length>0?ee.assetId.trim():void 0,kind:ee?.kind==="image"?"image":"file",mimeType:typeof ee?.mimeType=="string"&&ee.mimeType.trim().length>0?ee.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(ee?.referenceNumber))?Math.max(1,Math.floor(Number(ee.referenceNumber))):null,taskId:typeof ee?.taskId=="string"&&ee.taskId.trim().length>0?ee.taskId.trim():null,logicalName:typeof ee?.logicalName=="string"&&ee.logicalName.trim().length>0?ee.logicalName.trim():null,caption:typeof ee?.caption=="string"&&ee.caption.trim().length>0?ee.caption.trim():null,originalFilename:typeof ee?.originalFilename=="string"&&ee.originalFilename.trim().length>0?ee.originalFilename.trim():null,linkRole:ee?.linkRole==="reference"?"reference":ee?.linkRole==="image"?"image":"attachment"})).filter(ee=>ee.path.length>0&&ee.contentBase64.length>0):[],wt=new Set(Array.isArray(N?.knownPaths)?N.knownPaths.map(ee=>String(ee||"").trim()).filter(ee=>ee.length>0):rt.map(ee=>ee.path)),we=typeof N?.fingerprint=="string"?N.fingerprint:JSON.stringify(rt.map(ee=>`${ee.path}:${ee.updatedAt}:${ee.contentBase64.length}`).sort());if(we===ge.current)return;ge.current=we,re.current=rt,Be.current=wt,Ze(rt),ot(we)}catch(T){Ga("assets_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{bn("assets")}},[s,t,a,o,c,bn]),ja=r.useCallback(async()=>{if(s==="local"&&pi(t)&&!(a&&(!o||!c)))try{const T=await fetch(`/api/taskforce/planning/bootstrap?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const N=await T.json().catch(()=>({})),rt=Array.isArray(N?.initiatives)?N.initiatives.filter(we=>!!(we&&typeof we=="object"&&typeof we.id=="string")):[],wt=Array.isArray(N?.workstreams)?N.workstreams.filter(we=>!!(we&&typeof we=="object"&&typeof we.id=="string")):[];st.current=rt,kt.current=wt}catch(T){Ga("planning_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}},[s,t,a,o,c]),da=r.useCallback(async()=>{if(s==="local"&&pi(t)&&!(a&&(!o||!c)))try{const T=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const N=await T.json().catch(()=>({})),rt=Array.isArray(N?.sessions)?N.sessions.map(ee=>({id:String(ee?.id||"").trim(),assetId:String(ee?.assetId||"").trim(),documentId:typeof ee?.documentId=="string"&&ee.documentId.trim().length>0?ee.documentId.trim():null,documentVersion:Number.isFinite(Number(ee?.documentVersion))?Math.max(1,Math.floor(Number(ee.documentVersion))):null,title:typeof ee?.title=="string"&&ee.title.trim().length>0?ee.title.trim():null,status:ee?.status==="resolved"?"resolved":"open",comments:Array.isArray(ee?.comments)?ee.comments:[],createdByActorId:typeof ee?.createdByActorId=="string"&&ee.createdByActorId.trim().length>0?ee.createdByActorId.trim():null,updatedByActorId:typeof ee?.updatedByActorId=="string"&&ee.updatedByActorId.trim().length>0?ee.updatedByActorId.trim():null,createdAt:String(ee?.createdAt||"").trim(),updatedAt:String(ee?.updatedAt||ee?.createdAt||"").trim(),deletedAt:typeof ee?.deletedAt=="string"&&ee.deletedAt.trim().length>0?ee.deletedAt.trim():null})).filter(ee=>ee.id.length>0&&ee.assetId.length>0):[],wt=Array.isArray(N?.comments)?N.comments.map(ee=>({id:String(ee?.id||"").trim(),sessionId:String(ee?.sessionId||"").trim(),body:typeof ee?.body=="string"?ee.body:"",anchor:ee?.anchor??null,order:Number.isFinite(Number(ee?.order))?Math.max(0,Math.floor(Number(ee.order))):0,authorActorId:typeof ee?.authorActorId=="string"&&ee.authorActorId.trim().length>0?ee.authorActorId.trim():null,createdAt:String(ee?.createdAt||"").trim(),updatedAt:String(ee?.updatedAt||ee?.createdAt||"").trim(),deletedAt:typeof ee?.deletedAt=="string"&&ee.deletedAt.trim().length>0?ee.deletedAt.trim():null})).filter(ee=>ee.id.length>0&&ee.sessionId.length>0):Pw(rt),we=typeof N?.fingerprint=="string"?N.fingerprint:JSON.stringify([...rt.map(ee=>`${ee.id}:${ee.updatedAt}:${ee.status}:${ee.deletedAt||""}:${ee.comments.length}`).sort(),...wt.map(ee=>`${ee.id}:${ee.sessionId}:${ee.updatedAt}:${ee.deletedAt||""}`).sort()]);if(we===at.current)return;at.current=we,Ot.current=rt,yt.current=wt,Rt(rt),Ve(we)}catch(T){Ga("document_review_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{bn("documentReviewSessions")}},[s,t,a,o,c,bn]),Un=r.useCallback(async()=>{if(s==="local"&&pi(t)&&!(a&&(!o||!c)))try{const T=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const N=await T.json().catch(()=>({})),rt=Array.isArray(N?.sessions)?N.sessions.map(we=>({id:String(we?.id||"").trim(),workspaceId:String(we?.workspaceId||"").trim(),taskId:String(we?.taskId||"").trim(),baseImageAssetId:String(we?.baseImageAssetId||"").trim(),title:typeof we?.title=="string"&&we.title.trim().length>0?we.title.trim():null,globalInstruction:typeof we?.globalInstruction=="string"&&we.globalInstruction.trim().length>0?we.globalInstruction.trim():null,annotations:Array.isArray(we?.annotations)?we.annotations:[],createdByActorId:typeof we?.createdByActorId=="string"&&we.createdByActorId.trim().length>0?we.createdByActorId.trim():null,updatedByActorId:typeof we?.updatedByActorId=="string"&&we.updatedByActorId.trim().length>0?we.updatedByActorId.trim():null,createdAt:String(we?.createdAt||"").trim(),updatedAt:String(we?.updatedAt||we?.createdAt||"").trim(),deletedAt:typeof we?.deletedAt=="string"&&we.deletedAt.trim().length>0?we.deletedAt.trim():null})).filter(we=>we.id.length>0&&we.workspaceId.length>0&&we.taskId.length>0&&we.baseImageAssetId.length>0):[],wt=typeof N?.fingerprint=="string"?N.fingerprint:JSON.stringify(rt.map(we=>`${we.id}:${we.updatedAt}:${we.taskId}:${we.baseImageAssetId}:${we.annotations.length}:${we.deletedAt||""}`).sort());if(wt===xe.current)return;xe.current=wt,Ie.current=rt,l(rt),Se(wt)}catch(T){Ga("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{bn("annotatedAttachmentSessions")}},[s,t,a,o,c,bn]),Lr=r.useCallback(()=>{an.current=new Set([...$e.current,...vt.current].map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),ya.current=new Map([...$e.current,...vt.current].map(N=>[String(N?.id||"").trim(),fs.getWatermark(N)]).filter(([N])=>N.length>0)),On.current=new Map([...$e.current.map(N=>[String(N?.id||"").trim(),fs.getChangeKey({...N,isArchived:!1})]),...vt.current.map(N=>[String(N?.id||"").trim(),fs.getChangeKey({...N,isArchived:!0})])].filter(([N])=>N.length>0)),lr.current=new Set(st.current.map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),$n.current=new Map(st.current.map(N=>[String(N?.id||"").trim(),String(N?.updatedAt||N?.createdAt||"").trim()]).filter(([N])=>N.length>0)),La.current=new Set(kt.current.map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),xa.current=new Map(kt.current.map(N=>[String(N?.id||"").trim(),String(N?.updatedAt||N?.createdAt||"").trim()]).filter(([N])=>N.length>0)),Sn.current=new Set(tt.current.map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),Dn.current=new Map(tt.current.map(N=>[String(N?.id||"").trim(),gd.getWatermark(N)]).filter(([N])=>N.length>0)),Ba.current=new Map(tt.current.map(N=>[String(N?.id||"").trim(),gd.getChangeKey(N)]).filter(([N])=>N.length>0)),gn.current=new Set(Ye.current.map(N=>String(N?.path||"").trim()).filter(N=>N.length>0)),Jt.current=new Map(Ye.current.map(N=>[String(N?.path||"").trim(),String(N?.updatedAt||"").trim()]).filter(([N])=>N.length>0)),Ka.current=new Set(re.current.map(N=>String(N?.path||"").trim()).filter(N=>N.length>0)),xn.current=new Map(re.current.map(N=>[String(N?.path||"").trim(),String(N?.updatedAt||"").trim()]).filter(([N])=>N.length>0)),En.current=new Set(Ot.current.map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),Za.current=new Map(Ot.current.map(N=>[String(N?.id||"").trim(),String(N?.updatedAt||N?.createdAt||"").trim()]).filter(([N])=>N.length>0)),In.current=new Set(yt.current.map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),Mr.current=new Map(yt.current.map(N=>[String(N?.id||"").trim(),String(N?.updatedAt||N?.createdAt||"").trim()]).filter(([N])=>N.length>0)),cn.current=new Set(Ie.current.map(N=>String(N?.id||"").trim()).filter(N=>N.length>0)),mn.current=new Map(Ie.current.map(N=>[String(N?.id||"").trim(),String(N?.updatedAt||N?.createdAt||"").trim()]).filter(([N])=>N.length>0)),ka.current=new Map($u($e.current,vt.current,st.current,kt.current).map(N=>[String(N?.id||"").trim(),String(N?.createdAt||"").trim()]).filter(([N])=>N.length>0));const T=Zr();Ht.current=T?null:"storage-write-failed"},[Zr]),Br=r.useCallback(async()=>{const[T,N]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(T.ok){const rt=await T.json().catch(()=>({})),wt=Array.isArray(rt?.tasks)?rt.tasks.map(we=>No(we)):[];ie(wt)}if(N.ok){const rt=await N.json().catch(()=>({})),wt=Array.isArray(rt?.archived)?rt.archived.map(we=>({...No(we),isArchived:!0})):[];se(wt)}await ye().catch(()=>{Ga("refresh_planning_entities_failed",{workspaceId:t})})},[t,ye,se,ie]),{handleSyncAuthFailure:pr,ensureWorkspaceSyncReady:fr}=r.useMemo(()=>Mw({currentWorkspaceId:t,workspaceSyncPhase:fe,clearWorkspaceRetry:hn,setWorkspaceSyncBusy:X,setUserGlobalSyncStatus:be,setUserGlobalSyncError:T=>me(T),setWorkspaceLastErrorMessage:T=>R(T),setWorkspaceLastErrorAt:T=>x(T),reportSyncEvent:wn,setAuthBlocked:$,setIsAuthenticated:C,checkAuthSession:de,ensureCloudWorkspaceReadyForSync:et,scheduleWorkspaceSyncRetry:Ds,persistWorkspaceSyncPatchSafely:Fa}),[t,fe,hn,wn,$,C,de,et,Ds,Fa]),ks=r.useMemo(()=>Zw({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,currentWorkspaceId:t,workspaceSyncPhase:fe,isAuthenticated:c,checkAuthSession:de,resolveCloudAuthUrl:m,ensureCloudWorkspaceReadyForSync:et,ensureWorkspaceSyncReady:fr,handleSyncAuthFailure:pr,clearWorkspaceRetry:hn,clearWorkspaceIssue:Ir,isWorkspaceRetryPending:Pn,scheduleWorkspaceSyncRetry:Ds,persistWorkspaceSyncPatchSafely:Fa,persistWorkspaceSyncPatchBestEffort:Sa,persistWorkspaceSyncWatermarksSnapshotBestEffort:Zr,reportSyncEvent:wn,acquireWorkspaceSyncLease:sa,releaseWorkspaceSyncLease:la,reportWorkspaceWindowContention:Ra,refreshWorkspaceSyncMarkdownDocumentsSnapshot:Oa,refreshWorkspaceSyncAiProfilesSnapshot:mr,refreshWorkspaceSyncAssetsSnapshot:Gt,refreshWorkspaceSyncPlanningEntitiesSnapshot:ja,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:da,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:Un,refreshLocalWorkspaceTaskCollections:Br,buildWorkspaceSyncPayload:_n,buildWorkspaceSyncSignature:Na,seedWorkspaceSnapshotPushBaseline:Lr,shouldSuppressAttachBootstrapPush:wa,recordSuppressedEventIds:(...T)=>no.current.recordSuppressedEventIds(...T),workspaceRepairModeRef:Ia,workspaceForceFullAiProfilePushRef:$t,workspacePushInFlightRef:aa,workspacePullInFlightRef:Mn,workspacePendingPushReplayRef:vn,workspaceLastPushedSignatureRef:Zt,workspacePendingSignatureRef:Zn,workspaceLastPushedTaskIdsRef:an,workspaceDeletedTaskIdsRef:ra,workspaceDeletedTaskWatermarksRef:Ea,workspacePullCursorRef:Da,workspaceLastPushedWatermarksRef:ya,workspaceLastPushedTaskChangeKeysRef:On,workspaceLastPushedInitiativeIdsRef:lr,workspaceLastPushedInitiativeWatermarksRef:$n,workspaceLastPushedWorkstreamIdsRef:La,workspaceLastPushedWorkstreamWatermarksRef:xa,workspaceLastPushedAiProfileIdsRef:Sn,workspaceLastPushedAiProfileWatermarksRef:Dn,workspaceLastPushedAiProfileChangeKeysRef:Ba,workspaceLastPushedDocumentPathsRef:gn,workspaceLastPushedDocumentWatermarksRef:Jt,workspaceLastPushedAssetPathsRef:Ka,workspaceLastPushedAssetWatermarksRef:xn,workspaceLastPushedDocumentReviewSessionIdsRef:En,workspaceLastPushedDocumentReviewSessionWatermarksRef:Za,workspaceLastPushedDocumentReviewCommentIdsRef:In,workspaceLastPushedDocumentReviewCommentWatermarksRef:Mr,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:cn,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:mn,workspaceLastPushedTaskEventWatermarksRef:ka,workspaceBaselineResetReasonRef:Ht,workspaceCaptureAttachBootstrapBaselineRef:dr,workspaceStartupFullReconcileRanRef:Xt,workspaceFullReconcileInFlightRef:Tn,bootstrapLastProgressAtRef:gt,realtimeSuppressedEventQueueRef:An,setWorkspaceSyncBusy:X,setUserGlobalSyncStatus:be,setUserGlobalSyncError:me,setWorkspaceLastErrorMessage:R,setWorkspaceLastErrorAt:x,setWorkspaceLastPullAt:Me,setWorkspaceLastPushAt:Ee,setWorkspaceSyncPendingChanges:V,setTasks:ie,setArchivedTasks:se}),[a,s,B,t,fe,G,c,de,m,et,fr,pr,hn,Ir,Ds,Fa,Sa,Zr,wn,sa,la,Ra,Oa,mr,Gt,ja,da,Un,Br,_n,Na,Lr,wa,ie,se]),{pushWorkspaceChangesToCloud:ba,pullWorkspaceChangesFromCloud:ua}=ks,no=r.useRef({handleRealtimeSignal:()=>{},recordSuppressedEventIds:()=>{},clearRealtimePullDebounce:()=>{}}),vs=r.useMemo(()=>Hw({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,workspaceSyncPhase:fe,workspacePullInFlightRef:Mn,realtimePullDebounceRef:pt,realtimeSuppressedEventIdsRef:bt,clearWorkspaceRetry:hn,isWorkspaceRetryPending:Pn,pullWorkspaceChangesFromCloud:ua}),[a,s,B,fe,hn,Pn,ua]);no.current=vs;const hr=y("/taskforce-ws"),F=String(i||"").trim(),xt=ay({enabled:!!(k&&a&&s==="local"&&B&&o&&c&&F&&F!=="anonymous"&&hr),workspaceId:t,websocketUrl:hr,onSignal:vs.handleRealtimeSignal,onTelemetry:Pt,userId:F||void 0});r.useEffect(()=>{zt(xt.connectionState)},[xt.connectionState]),r.useEffect(()=>()=>vs.clearRealtimePullDebounce(),[vs]);const Lt=r.useCallback(async T=>Aa(T,{cloudAuthConfigured:a,isAuthenticated:c,ensureCloudWorkspaceReadyForSync:et}),[Aa,a,c,et]),Rn=r.useCallback(async()=>{await va({preferCloudOnFirstSync:!1})},[va]),Tr=r.useMemo(()=>Vw({currentWorkspaceId:t,workspaceCloudSyncEnabled:B,workspaceSyncPhase:fe,workspaceLastPullAt:Te,lastBootstrapPhaseRef:cr,workspaceRepairModeRef:Ia,workspaceForceFullAiProfilePushRef:$t,workspaceStartupRepairRanRef:Er,workspaceStartupFullReconcileRanRef:Xt,workspaceFullReconcileInFlightRef:Tn,workspacePullCursorRef:Da,workspaceAttachBootstrapBaselineSignatureRef:Wa,workspaceCaptureAttachBootstrapBaselineRef:dr,workspacePendingSignatureRef:Zn,workspaceLastPushedSignatureRef:Zt,workspaceLastPushedWatermarksRef:ya,workspaceLastPushedTaskChangeKeysRef:On,workspaceLastPushedInitiativeIdsRef:lr,workspaceLastPushedInitiativeWatermarksRef:$n,workspaceLastPushedWorkstreamIdsRef:La,workspaceLastPushedWorkstreamWatermarksRef:xa,workspaceLastPushedAiProfileIdsRef:Sn,workspaceLastPushedAiProfileWatermarksRef:Dn,workspaceLastPushedAiProfileChangeKeysRef:Ba,workspaceLastPushedDocumentPathsRef:gn,workspaceLastPushedDocumentWatermarksRef:Jt,workspaceLastPushedAssetPathsRef:Ka,workspaceLastPushedAssetWatermarksRef:xn,workspaceLastPushedDocumentReviewSessionIdsRef:En,workspaceLastPushedDocumentReviewSessionWatermarksRef:Za,workspaceLastPushedDocumentReviewCommentIdsRef:In,workspaceLastPushedDocumentReviewCommentWatermarksRef:Mr,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:cn,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:mn,workspaceLastPushedTaskEventWatermarksRef:ka,workspaceBaselineResetReasonRef:Ht,bootstrapPhaseStartedAtRef:Bn,bootstrapLastProgressAtRef:gt,acquireWorkspaceSyncLease:sa,releaseWorkspaceSyncLease:la,forceClearWorkspaceSyncLease:Fn,clearWorkspaceRetry:hn,clearWorkspaceIssue:Ir,reportWorkspaceWindowContention:Ra,reportSyncEvent:wn,persistWorkspaceSyncPatch:os,persistWorkspaceSyncWatermarksSnapshotBestEffort:Zr,buildWorkspaceSyncSignature:Na,pullWorkspaceChangesFromCloud:ua,pushWorkspaceChangesToCloud:ba,cloudAuthConfigured:a,runtimeMode:s,isAuthenticated:c,checkAuthSession:de}),[t,G,B,fe,Te,sa,la,Fn,hn,Ir,Ra,wn,os,Zr,Na,ua,ba,a,s,c,de]),{retryWorkspaceCloudSync:Wr,resetWorkspaceSyncCursorAndPull:ao}=Tr,Qn=r.useCallback(()=>{const T=Zp({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,currentWorkspaceId:t,workspaceSyncPhase:fe,isAuthenticated:c,repairModeActive:Ia.current===!0,repairModeBypass:!1,pushInFlight:aa.current,pullInFlight:Mn.current}),N=Pn(),rt=Yp({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,currentWorkspaceId:t,workspaceSyncPhase:fe,isAuthenticated:c,repairModeActive:Ia.current===!0,repairModeBypass:!1,retryPending:N,pushInFlight:aa.current,pullInFlight:Mn.current}),wt=Jp({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,currentWorkspaceId:t,isAuthenticated:c});return{workspaceId:t,enabled:B,phase:fe,status:Ta,summary:ur,lastSuccessfulSyncAt:xr,lastPullAt:Te,lastPushAt:Pe,lastErrorAt:Z,pendingChanges:M,lastErrorMessage:b,recommendedAction:oa,pushBlockedReason:T.allowed?null:T.reason,pullBlockedReason:rt.allowed?null:rt.reason,retryBlockedReason:wt.allowed?null:wt.reason,repairActive:Ia.current===!0,pushInFlight:aa.current===!0,pullInFlight:Mn.current===!0,retryPending:N,documentSnapshotCount:ne.length,aiProfileSnapshotCount:dt.length,aiProfileSnapshotRawCount:ht,aiProfileSnapshotLastFetchAt:Ge,aiProfileSnapshotLastFetchError:it,aiProfileSnapshotLastSkipReason:Et,assetSnapshotCount:Oe.length,documentReviewSessionSnapshotCount:At.length,documentReviewSessionSnapshotFingerprint:Bt,annotatedAttachmentSessionSnapshotCount:E.length,annotatedAttachmentSessionSnapshotFingerprint:J,lastPushedAiProfileCount:Sn.current.size,lastPushedAiProfileWatermarkCount:Dn.current.size,forceFullAiProfilePushQueued:$t.current===!0}},[a,t,s,B,fe,c,Ta,ur,xr,Te,Pe,Z,M,b,oa,ne.length,dt.length,ht,Ge,it,Et,Oe.length,At.length,Bt,E.length,J,Pn]);r.useEffect(()=>{dn.current=Wr},[Wr]);const ma=r.useCallback(()=>{Oa(),Gt()},[Oa,Gt]);return r.useEffect(()=>{if(!a||s!=="local"||!B||!o||!c)return;Oa(),mr(),Gt(),da(),Un();const T=Pa=>{const $a=Pa.detail;(String($a?.workspaceId||"").trim()||"default")===t&&ma()},N=Pa=>{const $a=Pa.detail;(String($a?.workspaceId||"").trim()||"default")===t&&(mr(),Gt())};window.addEventListener(qp,T),window.addEventListener(Kp,N);const rt=window.setInterval(()=>{Oa()},Ar),wt=window.setInterval(()=>{mr()},Ar),we=window.setInterval(()=>{Gt()},Ar),ee=window.setInterval(()=>{da()},Ar),gr=window.setInterval(()=>{Un()},Ar);return()=>{window.removeEventListener(qp,T),window.removeEventListener(Kp,N),window.clearInterval(rt),window.clearInterval(wt),window.clearInterval(we),window.clearInterval(ee),window.clearInterval(gr)}},[a,s,B,o,c,t,ma,Oa,mr,Gt,da,Un,Ar]),r.useEffect(()=>{!a||s!=="local"||!B||!o||!c||ys&&ma()},[a,s,B,o,c,ys,ma]),r.useEffect(()=>{if(!Fw({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,authSessionResolved:o,workspaceSyncPhase:fe,workspaceSyncReferenceSnapshotsReady:Kt}))return;const T=Na();if(wa(T)||!T||T===Zt.current)return;const N=_n();if(V(N.changes.length),aa.current||Mn.current){Zn.current=T;return}const rt=window.setTimeout(()=>{ba(T)},1500);return()=>window.clearTimeout(rt)},[a,s,B,o,fe,Kt,Na,wa,_n,Qa,Tt,Ae,St,Bt,J,ba,aa,Mn]),r.useEffect(()=>{if(!Ow({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,authSessionResolved:o,workspaceSyncPhase:fe,workspaceSyncReferenceSnapshotsReady:Kt}))return;const T=window.setInterval(()=>{if(aa.current||Mn.current||Pn())return;const N=Zn.current||Na();if(!N||N===Zt.current)return;const rt=_n();V(rt.changes.length),rt.changes.length!==0&&ba(N)},Ja);return()=>window.clearInterval(T)},[a,s,B,o,fe,Kt,Na,_n,ba,Pn,Ja]),r.useEffect(()=>{a&&s==="local"&&B||(hn(),X(!1))},[a,s,B,hn]),r.useEffect(()=>{const T=$w({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,authSessionResolved:o,workspaceSyncPhase:fe,lastPullAt:Te,retryPending:Pn()});if(!T.shouldStart)return;T.shouldKickOffImmediately&&ua();const N=window.setInterval(()=>{ua()},Ya);return()=>{window.clearInterval(N)}},[a,s,B,o,fe,Te,Pn,ua,Ya]),r.useEffect(()=>{if(!Uw({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,authSessionResolved:o,isAuthenticated:c,workspaceSyncPhase:fe}))return;const T=window.setInterval(()=>{Tn.current||(Tn.current=!0,ua({forceCursorNull:!0}).finally(()=>{Tn.current=!1}))},Iw);return()=>window.clearInterval(T)},[a,s,B,o,c,fe,ua]),r.useEffect(()=>{s!=="local"||!c||!i||i==="anonymous"||va({preferCloudOnFirstSync:!0})},[s,c,i,va]),r.useEffect(()=>{if(s!=="local"||!c||!i||i==="anonymous"||!Vn.current.has(i)||Vt.current)return;const T=Dr(),N=JSON.stringify(T);if(!qn.current){qn.current=N;return}if(N===qn.current)return;qn.current=N,ia(i,new Date().toISOString());const rt=window.setTimeout(()=>{va({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(rt)},[s,c,i,Dr,ia,va]),r.useEffect(()=>{zw({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:B,authSessionResolved:o,isAuthenticated:c,workspaceSyncPhase:fe,alreadyRan:Er.current})&&(Er.current=!0,fetch("/api/taskforce/sync/workspace/repair-startup",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t})}).then(async T=>{if(!T.ok)return;const N=await T.json().catch(()=>({}));N?.applied>0&&(Ga("startup_repair_applied",{workspaceId:t,applied:N.applied,skipped:N.skipped,failed:N.failed}),Oa(),mr(),Gt(),da())}).catch(()=>{}))},[a,s,B,o,c,fe,t,Oa,mr,Gt,da]),{userGlobalSyncStatus:je,setUserGlobalSyncStatus:be,userGlobalSyncError:ce,setUserGlobalSyncError:me,workspaceLastPullAt:Te,workspaceLastPushAt:Pe,workspaceLastErrorAt:Z,workspaceLastErrorMessage:b,workspaceLastSuccessfulSyncAt:xr,workspaceCloudSyncEnabled:B,workspaceSyncPhase:fe,workspaceSyncSetupIntent:Le,workspaceSyncStatus:Ta,workspaceSyncSummary:ur,workspaceSyncRecommendedAction:oa,workspaceSyncBusy:L,workspaceSyncPendingChanges:M,syncInFlightRef:jt,workspaceRetryAt:_r,isWorkspaceRetryPending:Pn,workspacePushInFlightRef:aa,workspacePullInFlightRef:Mn,workspaceLastPushedSignatureRef:Zt,workspacePendingSignatureRef:Zn,workspaceLastPushedTaskIdsRef:an,workspaceDeletedTaskIdsRef:ra,workspaceDeletedTaskWatermarksRef:Ea,workspacePullCursorRef:Da,clearWorkspaceRetry:hn,persistWorkspaceSyncPatch:os,loadWorkspaceSyncState:Wn,applyWorkspaceSyncStateSnapshot:Nt,syncUserGlobalSettings:va,buildWorkspaceSyncSignature:Na,pushWorkspaceChangesToCloud:ba,pullWorkspaceChangesFromCloud:ua,saveWorkspaceCloudSyncSettings:Lt,retryUserGlobalSettingsSync:Rn,retryWorkspaceCloudSync:Wr,resetWorkspaceSyncCursorAndPull:ao,getWorkspaceSyncDiagnostics:Qn}}function Jw(e,t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e==="error"?3600:2600}function Qw(){const[e,t]=r.useState(null),a=r.useRef(null),s=r.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null),t(null)},[]),o=r.useCallback((c,i="info",d)=>{if(!c)return;a.current!==null&&(window.clearTimeout(a.current),a.current=null),t({message:c,tone:i,ttlMs:d});const m=Jw(i,d);a.current=window.setTimeout(()=>{a.current=null,t(null)},m)},[]);return r.useEffect(()=>()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),{uiNotice:e,pushNotice:o,clearNotice:s}}function Xw({storagePath:e,shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:a}){const[s,o]=r.useState("antigravity"),[c,i]=r.useState([]),[d,m]=r.useState(".agent/workflows"),[y,k]=r.useState(null),[S,h]=r.useState(null),g=r.useRef(null),v=t||a;r.useEffect(()=>{const D=c.find(U=>U.id===s);D&&m(D.directory)},[s,c]);const _=r.useCallback(()=>{typeof window>"u"||(g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null,h(null)},5e3))},[]),I=r.useCallback(async()=>{if(v)return;const D=await fetch("/api/taskforce/environments");if(!D.ok)return;const U=await D.json().catch(()=>({}));U.environments&&i(U.environments)},[v]),A=r.useCallback(async(D,U)=>{k("workflows"),h(null);try{const Q=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:D,workflowNames:U,variables:{STORAGE_PATH:e.replace(/\/$/,"")||".Taskforce"}})})).json();Q.success?h({type:"success",message:`Successfully exported ${Q.count} workflows to ${D}`}):h({type:"error",message:Q.error||"Export failed"})}catch{h({type:"error",message:"Network error exporting workflows"})}finally{k(null),_()}},[_,e]);return r.useEffect(()=>()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),{exportEnvironment:s,setExportEnvironment:o,availableEnvironments:c,loadAvailableEnvironments:I,exportWorkflowsPath:d,setExportWorkflowsPath:m,exportingResource:y,exportResult:S,handleExportWorkflows:A}}function eb(e){const{resolveCloudAuthUrl:t,currentWorkspaceId:a,normalizedCloudAuthBaseUrl:s,normalizedCloudMcpBaseUrl:o,mergedConfig:c,availableWorkspaces:i,currentTheme:d,configLoaded:m,globalTheme:y,themeUseGlobalDefault:k,keyShortcut:S,jsonBackupEnabled:h,globalJsonBackupEnabled:g,globalWeekStartsOn:v,locale:_,supportedLocales:I,jsonBackupUseGlobalDefault:A,manualComplexityEnabled:D,checklistDropdownEnabled:U,showTaskCardStatusLabel:W,exportWorkflowsPath:Q,exportingResource:le,exportResult:ie,pathSaved:se,settingsSection:$,exportEnvironment:C,setupState:de,buildInfo:ke,saveSetupMode:K,saveWorkspaceProfile:j,setCurrentTheme:H,handleSaveTheme:ue,handleSaveGlobalTheme:ye,setKeyShortcut:G,handleJsonBackupEnabledChange:je,handleSaveGlobalJsonBackupEnabled:be,handleSaveGlobalWeekStartsOn:ce,handleSaveLocale:me,handleManualComplexityEnabledChange:Te,handleChecklistDropdownEnabledChange:Me,handleShowTaskCardStatusLabelChange:Pe,handleResetProjectToGlobal:Ee,handleSaveSettings:Z,setExportWorkflowsPath:x,setExportEnvironment:b,availableWorkflows:R,initiativeTemplates:B,availableEnvironments:Y,fetchWorkflows:fe,fetchInitiativeTemplates:te,createInitiativeFromTemplate:Le,fetchWorkflowTemplate:oe,fetchWorkflowOverrideNames:L,saveWorkflowTemplateDraft:X,resetWorkflowTemplateDraft:M,handleExportWorkflows:V,setShowFolderBrowser:ne,setBrowserTarget:Ce,fetchFolders:Ae,activeCategories:Re,pathValidation:$e,taxonomyDisplayLabels:vt,handleUpdateCategory:st,handleRemoveCategory:kt,handleSaveCategory:Ye,handleAddPath:Ct,handleRemovePath:dt,handleUpdateCategoryIcon:Qe,handleUpdateCategoryColor:Tt,activeTypes:ae,handleSaveType:Ge,handleRemoveType:ft,handleUpdateType:it,taxonomies:Mt,handleUpdateTaxonomies:ht,priorities:Ft,handleUpdatePriorities:Et,analyzeSystemTaxonomyPack:We,handleApplySystemTaxonomyPack:tt,handleUpdateTaxonomyDisplayLabels:Oe,projectRoot:Ze,projectName:St,mcpHostRoot:ot,serverHostRoot:re,mcpScriptPath:Be,tenantId:At,runtimeMode:Rt,workspaceSwitchingEnabled:Bt,deleteWorkspace:Ve,setMcpHostRoot:Ot,isAuthenticated:yt}=e,E=r.useCallback(async(J,Se)=>{const Ie=t(J),Ke=new Headers(Se?.headers||void 0);if(J.startsWith("/api/taskforce/settings/mcp/")){const Ne=String(a||"").trim();Ne&&Ne!=="default"&&!Ke.has("x-taskforce-workspace-id")&&Ke.set("x-taskforce-workspace-id",Ne)}const Je={...Se,headers:Ke,credentials:Se?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(Ie))try{new URL(Ie,window.location.origin).origin!==window.location.origin&&Je.mode===void 0&&(Je.mode="cors")}catch{}return fetch(Ie,Je)},[a,t]),l=i.find(J=>J.id===a);return{fetchCloudAuthApi:E,currentTheme:d,configLoaded:m,globalTheme:y,themeUseGlobalDefault:k,keyShortcut:S,jsonBackupEnabled:h,globalJsonBackupEnabled:g,globalWeekStartsOn:v,locale:_,supportedLocales:I,jsonBackupUseGlobalDefault:A,manualComplexityEnabled:D,checklistDropdownEnabled:U,showTaskCardStatusLabel:W,exportWorkflowsPath:Q,exportingResource:le,exportResult:ie,pathSaved:se,initialSection:$,exportEnvironment:C,setupState:de,buildInfo:ke,onSaveSetupMode:K,onSaveWorkspaceProfile:j,onThemeChange:H,onSaveTheme:ue,onSaveGlobalTheme:ye,onKeyShortcutChange:G,onJsonBackupEnabledChange:je,onSaveGlobalJsonBackupEnabled:be,onSaveGlobalWeekStartsOn:ce,onSaveLocale:me,onManualComplexityEnabledChange:Te,onChecklistDropdownEnabledChange:Me,onShowTaskCardStatusLabelChange:Pe,onResetProjectToGlobal:Ee,onSaveSettings:Z,onExportWorkflowsPathChange:x,onExportEnvironmentChange:b,availableWorkflows:R,initiativeTemplates:B,availableEnvironments:Y,onRefreshWorkflows:fe,onRefreshInitiativeTemplates:te,onCreateInitiativeFromTemplate:Le,onFetchWorkflowTemplate:oe,onFetchWorkflowOverrideNames:L,onSaveWorkflowTemplateDraft:X,onResetWorkflowTemplateDraft:M,onExportWorkflows:V,onShowFolderBrowserChange:ne,onBrowserTargetChange:Ce,onFetchFolders:Ae,categories:Re,pathValidation:$e,taxonomyDisplayLabels:vt,onUpdateCategory:st,onRemoveCategory:kt,onSaveCategory:Ye,onAddPath:Ct,onRemovePath:dt,onUpdateCategoryIcon:Qe,onUpdateCategoryColor:Tt,types:ae,onSaveType:Ge,onRemoveType:ft,onUpdateType:it,taxonomies:Mt,onUpdateTaxonomies:ht,priorities:Ft,onUpdatePriorities:Et,onAnalyzeSystemTaxonomyPack:We,onApplySystemTaxonomyPack:tt,onUpdateTaxonomyDisplayLabels:Oe,projectRoot:Ze,projectName:St,mcpHostRoot:ot,serverHostRoot:re,mcpScriptPath:Be,tenantId:At,workspaceId:a,runtimeMode:Rt,cloudAuthBaseUrl:s||c.cloudAuthBaseUrl,cloudMcpBaseUrl:o||void 0,workspaceSwitchingEnabled:Bt,currentWorkspaceRole:l?.role||"member",currentWorkspaceName:String(l?.name||""),onDeleteWorkspace:Ve,onMcpHostRootChange:Ot,isAuthenticated:yt}}function tb(e){const{keyShortcut:t,themeUseGlobalDefault:a,runtimeMode:s,jsonBackupUseGlobalDefault:o,globalTheme:c,globalJsonBackupEnabled:i,setCurrentTheme:d,setThemeUseGlobalDefault:m,setGlobalTheme:y,setJsonBackupEnabled:k,setJsonBackupUseGlobalDefault:S,setGlobalJsonBackupEnabled:h,setGlobalWeekStartsOn:g,setLocale:v,setManualComplexityEnabled:_,setChecklistDropdownEnabled:I,setShowTaskCardStatusLabel:A,setShowChecklist:D}=e,U=r.useCallback(async()=>{try{const j=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:t})});if(!j.ok)throw new Error(`Failed to save global settings (${j.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[t]),W=r.useCallback(async j=>{d(j),m(!1);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:j})});if(!H.ok)throw new Error(`Failed to save config (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project theme"),!1}},[d,m]),Q=r.useCallback(async j=>{y(j),a&&d(j);try{const H=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:j})});if(!H.ok)throw new Error(`Failed to save global settings (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global theme"),!1}},[y,a,d]),le=r.useCallback(async j=>{if(s==="cloud")return k(!1),S(!1),!1;k(j),S(!1);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:j})});if(!H.ok)throw new Error(`Failed to save config (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project backup setting"),!1}},[s,k,S]),ie=r.useCallback(async j=>{if(s==="cloud")return h(!1),o&&k(!1),!1;h(j),o&&k(j);try{const H=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:j})});if(!H.ok)throw new Error(`Failed to save global settings (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global backup setting"),!1}},[s,h,o,k]),se=r.useCallback(async j=>{g(j);try{const H=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:j}})});if(!H.ok)throw new Error(`Failed to save global settings (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save regional week start setting"),!1}},[g]),$=r.useCallback(async j=>{const H=Ug(j);return v(H),!0},[v]),C=r.useCallback(async j=>{_(j);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:j})});if(!H.ok)throw new Error(`Failed to save config (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save manual complexity setting"),!1}},[_]),de=r.useCallback(async j=>{I(j),j||D(!1);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:j})});if(!H.ok)throw new Error(`Failed to save config (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save checklist dropdown setting"),!1}},[I,D]),ke=r.useCallback(async j=>{A(j);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:j})});if(!H.ok)throw new Error(`Failed to save config (${H.status})`);return!0}catch{return console.error("[Taskforce] Failed to save task card status label setting"),!1}},[A]),K=r.useCallback(async()=>{m(!0),S(!0),d(c),k(i),_(!1),I(!0),A(!0),D(!1);try{const j=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(!j.ok)throw new Error(`Failed to save config (${j.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[m,S,d,c,k,i,_,I,A,D]);return{handleSaveSettings:U,handleSaveTheme:W,handleSaveGlobalTheme:Q,handleJsonBackupEnabledChange:le,handleSaveGlobalJsonBackupEnabled:ie,handleSaveGlobalWeekStartsOn:se,handleSaveLocale:$,handleManualComplexityEnabledChange:C,handleChecklistDropdownEnabledChange:de,handleShowTaskCardStatusLabelChange:ke,handleResetProjectToGlobal:K}}function nb(e){const{activeCategories:t,activeTab:a,activeTypes:s,archivedTasks:o,browserTarget:c,category:i,configLoaded:d,customCategories:m,refreshTaskCollections:y,fetchTasks:k,filterCategories:S,getCategoryPaths:h,normalizePath:g,pathValidation:v,setBrowserTarget:_,setCategory:I,setCustomCategories:A,setCustomTypes:D,setFilterCategories:U,setPathValidation:W,setPriorities:Q,setShowFolderBrowser:le,setTaxonomies:ie,tasks:se}=e,$=r.useCallback(async(x,b)=>{const R=await x.json().catch(()=>({}));return String(R?.error||b)},[]),C=r.useCallback(()=>[...se,...o],[o,se]),de=r.useCallback(x=>x.priorities.find(b=>b.value===2)?.value||x.priorities[0]?.value||2,[]),ke=r.useCallback(async x=>{if(x.length!==0)try{const b=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:x})});if(b.ok){const R=await b.json();W(B=>({...B,...R.results}))}}catch(b){console.error("[Taskforce] Failed to validate paths:",b)}},[W]);r.useEffect(()=>{if(a!=="settings"||!d)return;const x=[];t.forEach(R=>{h(R).forEach(Y=>{x.includes(Y)||x.push(Y)})});const b=x.filter(R=>!v[R]);b.length>0&&ke(b)},[t,a,d,h,v,ke]);const K=r.useCallback(async(x,b)=>{if(d){A(R=>(R.length>0?R:t).map(Y=>Y.value===x.value?x:Y)),b&&b!==x.label&&(i===b&&I(x.label),S.includes(b)&&U(R=>R.map(B=>B===b?x.label:B)));try{const Y={categories:(m.length>0?m:t).map(fe=>fe.value===x.value?x:fe)};b&&b!==x.label&&(Y.reassignFrom=b,Y.reassignTo=x.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}),b&&await k()}catch(R){console.error("[Taskforce] Failed to update category",R)}}},[t,i,d,m,k,S,I,A,U]),j=r.useCallback(async x=>{if(!d)return;const b=x.trim().toLowerCase().replace(/\s+/g,"-");if(t.some(B=>B.value===b))return;const R={value:b,label:x.trim(),color:"blue-200",icon:"Folder"};A(B=>[...B.length>0?B:t,R]);try{const Y=[...m.length>0?m:t,R];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:Y})})}catch(B){console.error("[Taskforce] Failed to create category",B)}},[t,d,m,A]),H=r.useCallback((x,b)=>{if(!b.trim())return;const R=t.find(te=>te.value===x);if(!R)return;const B=h(R),Y=b.trim();if(B.includes(Y))return;const fe=[...B,Y];K({...R,path:void 0,paths:fe}),ke(fe)},[t,h,K,ke]),ue=r.useCallback((x,b)=>{const R=t.find(B=>B.value===x);R&&K({...R,icon:b})},[t,K]),ye=r.useCallback((x,b)=>{const R=t.find(B=>B.value===x);R&&K({...R,color:b})},[t,K]),G=r.useCallback((x,b)=>{const R=t.find(fe=>fe.value===x);if(!R)return;const Y=h(R).filter(fe=>fe!==b);K({...R,path:void 0,paths:Y})},[t,h,K]),je=r.useCallback(x=>{const b=g(x);if(c&&typeof c=="object"&&c.type==="category"){const R=t.find(B=>B.value===c.value);if(R){const B=h(R);if(!B.includes(b)){const Y=[...B,b];K({...R,path:void 0,paths:Y})}}}le(!1),_(null)},[t,c,h,K,g,_,le]),be=r.useCallback(async x=>{if(!d)return;const b=el,R=t.find(te=>te.value===b),B=R?{...R}:{value:b,label:Im,icon:"Inbox"},Y=B.label,fe=t.find(te=>te.value===x);A(te=>{let oe=(te.length>0?te:t).filter(L=>L.value!==x);return oe.some(L=>L.value===b)||(oe=[B,...oe]),oe}),fe&&((i===fe.label||i===fe.value)&&I(b),(S.includes(fe.label)||S.includes(fe.value))&&U(te=>{const Le=te.filter(oe=>oe!==fe.label&&oe!==fe.value);return Le.includes(b)?Le:[...Le,b]}));try{let te=(m.length>0?m:t).filter(Le=>Le.value!==x);te.some(Le=>Le.value===b)||(te=[B,...te]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:te,reassignFrom:fe?.label||x,reassignTo:Y})}),await k()}catch(te){console.error("[Taskforce] Failed to remove category",te)}},[t,i,d,m,k,S,I,A,U]),ce=r.useCallback(async x=>{if(!x.trim())return;const b=x.trim().toLowerCase().replace(/\s+/g,"-");if(s.some(B=>B.value===b))return;const R=[...s,{value:b,label:x.trim(),status:"active"}];D(R);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:R})})}catch(B){console.error("Failed to save type",B)}},[s,D]),me=r.useCallback(async x=>{const b=s.map(R=>R.value===x?{...R,status:"retired"}:R);D(b);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:b})}),await k()}catch(R){console.error("Failed to save type",R)}},[s,k,D]),Te=r.useCallback(async(x,b)=>{const R=s.find(te=>te.value===x);if(!R)return;const B=typeof b.label=="string"?b.label.trim():R.label;if(!B)return;const Y=s.map(te=>te.value===x?{...te,...b,label:B}:te);if(JSON.stringify(Y)!==JSON.stringify(s)){D(Y);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:Y})})}catch(te){console.error("Failed to update type",te)}}},[s,D]),Me=r.useCallback(async x=>{if(d){ie(x);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:x})})}catch(b){console.error("[Taskforce] Failed to save taxonomies",b)}}},[d,ie]),Pe=r.useCallback(async x=>{if(d){Q(x);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:x})})}catch(b){console.error("[Taskforce] Failed to save priorities",b)}}},[d,Q]),Ee=r.useCallback(x=>{const b=C(),R=new Set(x.categories.map(oe=>oe.value)),B=new Set(x.types.map(oe=>oe.value)),Y=new Set(x.priorities.map(oe=>Number(oe.value))),fe=Array.from(new Set(b.map(oe=>String(oe.category||"").trim()).filter(oe=>oe.length>0&&!R.has(oe)))).sort(),te=Array.from(new Set(b.map(oe=>String(oe.type||"").trim()).filter(oe=>oe.length>0&&!B.has(oe)))).sort(),Le=Array.from(new Set(b.map(oe=>Number(oe.priority)).filter(oe=>Number.isFinite(oe)&&oe>0&&!Y.has(oe)))).sort((oe,L)=>oe-L);return{unmatchedCategoryValues:fe,unmatchedTypeValues:te,incompatiblePriorityValues:Le}},[C]),Z=r.useCallback(async x=>{if(!d)return{success:!1,error:"Settings are still loading."};const{pack:b,sections:R,remapExistingValuesToDefault:B,workspaceIdOverride:Y}=x,fe=String(Y||"").trim(),te=fe.length>0,Le=te?[]:C(),oe=X=>{if(!fe)return X;const M=X.includes("?")?"&":"?";return`${X}${M}workspaceId=${encodeURIComponent(fe)}`},L=()=>{const X={"Content-Type":"application/json"};return fe&&(X["x-taskforce-workspace-id"]=fe),X};try{if(R.categories){const X=new Set(b.categories.map(ne=>ne.value)),M=B?[...b.categories]:[...b.categories,...t.filter(ne=>!X.has(ne.value)).map(ne=>({...ne,disabled:!0}))];te||A(M);const V=await fetch(oe("/api/taskforce/categories"),{method:"POST",headers:L(),body:JSON.stringify({categories:M})});if(!V.ok)return{success:!1,error:await $(V,"Failed to apply category library pack.")}}if(R.types){const X=new Set(b.types.map(Ce=>Ce.value)),M=b.types.find(Ce=>Ce.value===Gr)?.value||b.types[0]?.value||Gr;if(B){const Ce=Le.filter(Ae=>Ae.type&&!X.has(String(Ae.type))).map(Ae=>({id:Ae.id,type:M}));if(Ce.length>0){const Ae=await fetch(oe("/api/taskforce/bulk-update-fields"),{method:"POST",headers:L(),body:JSON.stringify({updates:Ce})});if(!Ae.ok)return{success:!1,error:await $(Ae,"Failed to remap task types to the pack default.")}}}const V=B?[...b.types]:[...b.types,...s.filter(Ce=>!X.has(Ce.value)).map(Ce=>({...Ce,status:"retired"}))];te||D(V);const ne=await fetch(oe("/api/taskforce/types"),{method:"POST",headers:L(),body:JSON.stringify({types:V})});if(!ne.ok)return{success:!1,error:await $(ne,"Failed to apply task type library pack.")}}if(R.priorities){const X=new Set(b.priorities.map(Ce=>Ce.value)),M=Array.from(new Set(Le.map(Ce=>Number(Ce.priority)).filter(Ce=>Number.isFinite(Ce)&&Ce>0&&!X.has(Ce)))).sort((Ce,Ae)=>Ce-Ae);if(M.length>0&&!B)return{success:!1,error:`This workspace still uses priority levels ${M.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(M.length>0){const Ce=de(b),Ae=Le.filter(Re=>M.includes(Number(Re.priority))).map(Re=>({id:Re.id,priority:Ce}));if(Ae.length>0){const Re=await fetch(oe("/api/taskforce/bulk-update-fields"),{method:"POST",headers:L(),body:JSON.stringify({updates:Ae})});if(!Re.ok)return{success:!1,error:await $(Re,"Failed to remap task priorities to the pack default.")}}}const V=b.priorities.map(Ce=>({...Ce,value:Number(Ce.value)}));te||Q(V);const ne=await fetch(oe("/api/taskforce/priorities"),{method:"POST",headers:L(),body:JSON.stringify({priorities:V})});if(!ne.ok)return{success:!1,error:await $(ne,"Failed to apply priority library pack.")}}return te||await y({isSilent:!0}),{success:!0}}catch(X){return console.error("[Taskforce] Failed to apply system taxonomy pack",X),{success:!1,error:X instanceof Error?X.message:"Failed to apply system taxonomy pack."}}},[t,s,d,C,de,$,y,A,D,Q]);return{getCategoryPaths:h,validatePaths:ke,handleUpdateCategory:K,handleSaveCategory:j,handleAddPath:H,handleUpdateCategoryIcon:ue,handleUpdateCategoryColor:ye,handleRemovePath:G,handleSelectPath:je,handleRemoveCategory:be,handleSaveType:ce,handleRemoveType:me,handleUpdateType:Te,handleUpdateTaxonomies:Me,handleUpdatePriorities:Pe,analyzeSystemTaxonomyPack:Ee,handleApplySystemTaxonomyPack:Z}}function ab({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:t}){const[a,s]=r.useState([]),[o,c]=r.useState([]),i=e||t,d=r.useCallback(async()=>{if(!i)try{const g=await fetch("/api/taskforce/workflow-templates");if(g.ok){const v=await g.json();s(v.templates||[])}}catch{}},[i]),m=r.useCallback(async()=>{if(i)return[];try{const g=await fetch("/api/taskforce/initiative-templates");if(!g.ok)return[];const v=await g.json(),_=Array.isArray(v?.templates)?v.templates:[];return c(_),_}catch{return[]}},[i]),y=r.useCallback(async g=>{if(!g||i)return null;const v=[`/api/taskforce/workflow-template/${encodeURIComponent(g)}`,`/api/taskforce/workflow-templates/${encodeURIComponent(g)}`];try{for(const _ of v){const I=await fetch(_);if(!I.ok)continue;const A=await I.json();if(A?.template)return A.template}return null}catch{return null}},[i]),k=r.useCallback(async()=>{if(i)return[];try{const g=await fetch("/api/taskforce/workflow-editor/overrides");if(!g.ok)return[];const v=await g.json();return Array.isArray(v?.names)?v.names:[]}catch{return[]}},[i]),S=r.useCallback(async(g,v)=>{try{const _=await fetch("/api/taskforce/workflow-editor/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g,draft:v})}),I=await _.json().catch(()=>({}));return!_.ok||!I.success?{success:!1,error:I.error||`Save failed (${_.status})`}:(d(),{success:!0})}catch(_){return{success:!1,error:_.message}}},[d]),h=r.useCallback(async g=>{try{const v=await fetch(`/api/taskforce/workflow-editor/reset/${encodeURIComponent(g)}`,{method:"POST"}),_=await v.json().catch(()=>({}));return!v.ok||!_.success?{success:!1,error:_.error||`Reset failed (${v.status})`}:(d(),{success:!0})}catch(v){return{success:!1,error:v.message}}},[d]);return{availableWorkflows:a,initiativeTemplates:o,fetchWorkflows:d,fetchInitiativeTemplates:m,fetchWorkflowTemplate:y,fetchWorkflowOverrideNames:k,saveWorkflowTemplateDraft:S,resetWorkflowTemplateDraft:h}}function rb(){const[e,t]=r.useState(!1),a=r.useCallback(async()=>{if(!document.fullscreenElement){try{await document.documentElement.requestFullscreen(),t(!0)}catch(s){console.error(`Error attempting to enable full-screen mode: ${s}`)}return}document.exitFullscreen&&(await document.exitFullscreen(),t(!1))},[]);return r.useEffect(()=>{const s=()=>{t(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",s),()=>document.removeEventListener("fullscreenchange",s)},[]),{zenMode:e,setZenModeState:t,toggleZenMode:a}}async function sb(e,t,a){if(e.current){t.current=!0;return}e.current=!0;try{do t.current=!1,await a();while(t.current)}finally{e.current=!1}}function ob({tasks:e,archivedTasks:t,setTasks:a,setArchivedTasks:s,setLoadingTasks:o,getCurrentWorkspaceId:c,workspaceResetKey:i,shouldDeferProtectedApiCalls:d,shouldBlockProtectedApiCalls:m,handleUnauthorized:y,authRequiredForApi:k}){const S=r.useRef(new Map),h=r.useRef(!1),g=r.useRef([]),v=r.useRef([]),_=r.useRef(!1),I=r.useRef(!1),A=r.useRef(null),D=r.useRef(null);r.useEffect(()=>{g.current=e},[e]),r.useEffect(()=>{v.current=t},[t]);const U=r.useCallback(j=>`${j.updatedAt||j.createdAt||""}|${j.status}|${j.priority}|${j.title}`,[]),W=r.useCallback((j,H)=>H.aborted?j===H.reason?!0:j instanceof DOMException?j.name==="AbortError":String(j?.name||"").toLowerCase()==="aborterror":!1,[]),[Q,le]=r.useState([]),ie=r.useRef(new Map),se=r.useCallback(j=>{!j.length||typeof window>"u"||(le(H=>Array.from(new Set([...H,...j]))),j.forEach(H=>{const ue=ie.current.get(H);ue&&window.clearTimeout(ue);const ye=window.setTimeout(()=>{ie.current.delete(H),le(G=>G.filter(je=>je!==H))},4e3);ie.current.set(H,ye)}))},[]);r.useEffect(()=>()=>{typeof window>"u"||(ie.current.forEach(j=>window.clearTimeout(j)),ie.current.clear())},[]),r.useEffect(()=>{S.current=new Map,h.current=!1,_.current=!1,I.current=!1,A.current?.abort("workspace-reset"),A.current=null,D.current?.abort("workspace-reset"),D.current=null,typeof window<"u"&&(ie.current.forEach(j=>window.clearTimeout(j)),ie.current.clear()),le([])},[i]);const $=r.useCallback(async(j=!1,H)=>{if(!(H?.ignoreAuthGuard===!0)&&(d||m))return;o(!j);const ye=String(c()||"").trim();A.current?.abort("superseded");const G=new AbortController;A.current=G;try{const je=await fetch("/api/taskforce/tasks",{signal:G.signal});if(je.status===401){y(),a([]),j||o(!1);return}if(je.ok){const ce=((await je.json()).tasks||[]).map(Pe=>No(Pe));if(String(c()||"").trim()!==ye)return;const Te=new Map,Me=[];for(const Pe of ce){const Ee=U(Pe);if(Te.set(Pe.id,Ee),!h.current)continue;const Z=S.current.get(Pe.id);(!Z||Z!==Ee)&&Me.push(Pe.id)}S.current=Te,h.current?se(Me):h.current=!0,a(ce)}}catch(je){if(W(je,G.signal))return;console.error("[Taskforce] Failed to fetch tasks:",je)}finally{A.current===G&&(A.current=null,o(!1))}},[U,c,se,y,a,o,k,d,m]),C=r.useCallback(async(j=!1,H)=>{if(!(H?.ignoreAuthGuard===!0)&&(d||m))return;const ye=String(c()||"").trim();D.current?.abort("superseded");const G=new AbortController;D.current=G;try{const je=await fetch("/api/taskforce/archive",{signal:G.signal});if(je.ok){const be=await je.json();if(String(c()||"").trim()!==ye)return;const me=(be.archived||[]).map(Te=>({...No(Te),isArchived:!0}));s(me)}}catch(je){if(W(je,G.signal))return;console.error("[Taskforce] Failed to fetch archive:",je)}finally{D.current===G&&(D.current=null)}},[c,W,s,d,m]),de=r.useCallback(async j=>{const H=j?.isSilent!==!1,ue=j?.ignoreAuthGuard===!0;await Promise.all([$(H,{ignoreAuthGuard:ue}),C(H,{ignoreAuthGuard:ue})])},[C,$]),ke=r.useCallback(async()=>{await sb(_,I,async()=>{await de({isSilent:!0})})},[de]),K=r.useCallback(j=>{const H=Fv(j,g.current,v.current);g.current=H.tasks,v.current=H.archivedTasks,a(H.tasks),s(H.archivedTasks)},[a,s]);return{tasksRef:g,archivedTasksRef:v,recentlyChangedTaskIds:Q,markRecentlyChangedTasks:se,fetchTasks:$,fetchArchive:C,refreshTaskCollections:de,refreshTaskCollectionsFromInvalidation:ke,mergeTaskFromServer:K,getTaskRevisionKey:U}}function ib(e){const{editingTaskId:t,relationshipTasks:a,initiatives:s=[],workstreams:o=[],supplementalTasks:c=[],setComments:i}=e,d=r.useMemo(()=>{if(c.length===0)return a;const S=new Map;return a.forEach(h=>S.set(h.id,h)),c.forEach(h=>S.set(h.id,h)),Array.from(S.values())},[a,c]),m=r.useMemo(()=>{if(t)return d.find(S=>S.id===t)},[d,t]);r.useEffect(()=>{t&&i(m?.comments||[])},[t,m?.id,m?.updatedAt,m?.comments,i]);const y=r.useMemo(()=>{if(m?.workstreamId)return o.find(S=>S.id===m.workstreamId)},[m,o]),k=r.useMemo(()=>{if(y?.initiativeId)return s.find(S=>S.id===y.initiativeId)},[y,s]);return{currentTask:m,currentTaskWorkstream:y,currentTaskInitiative:k}}const Cf="WS-",Af="IN-";function Ro(e){return nl(Cf,e)}function ly(e){return mf(Cf,e)}function fm(e){return Tm(Cf,e)}function rs(e){return nl(Af,e)}function cb(e){return mf(Af,e)}function dy(e){return Tm(Af,e)}function Cp(e,t){const a=String(t||"").trim();if(!a)return null;const s=cb(a);return e.find(o=>o.id===a||rs(o)===a||s!==null&&o.referenceNumber===s)||null}function lb(e){const t={};return e.forEach(a=>{const s=a.defaultValue;if(s!=null){if(Array.isArray(s)){s.length>0&&(t[a.id]=s.map(o=>typeof o=="number"?o:String(o)));return}t[a.id]=typeof s=="number"?s:String(s)}}),t}function db(e,t){return e.filter(a=>{const s=t[a.id],o=Array.isArray(s)?s.length>0:s!=null&&s!=="";return a.status==="retired"&&!o?!1:a.formEnabled!==!1||a.isRequired===!0||o})}function ub(e){const{activeCategories:t,activeTypes:a,activeTab:s,attachments:o,checklistItems:c,comments:i,description:d,editingTaskId:m,flushPendingAutoSave:y,getPreferredCategoryValue:k,lastUsedCategory:S,newCommentText:h,relationshipTasks:g,workstreams:v,showArchive:_,taxonomies:I,setActiveTab:A,setApproach:D,setAssignee:U,setAttachments:W,setAttachmentsDirty:Q,setCategory:le,setChecklistItems:ie,setComments:se,setComplexity:$,setDescription:C,setDueDate:de,setEditingTaskId:ke,setError:K,setFormTaxonomies:j,setIsOpen:H,setNewCommentText:ue,setPendingNavigation:ye,setWorkstreamInput:G,setPriority:je,setScheduledDate:be,setShowArchive:ce,setStatus:me,setTaskReturnTrail:Te,setTitle:Me,setType:Pe,setUnsavedModalOpen:Ee,taskReturnTrail:Z,title:x}=e,b=r.useCallback(()=>a.find(M=>String(M.value||"").trim().length>0)?.value||Gr,[a]),R=r.useCallback(M=>{if(m){y(),M();return}if(!(x.trim()!==""||d.trim()!==""||c.length>0||h.trim()!==""||i.length>0||o.length>0)){M();return}ye(()=>M),Ee(!0)},[o,i.length,d,m,y,c,h,ye,Ee,x]),B=r.useCallback(()=>{H(!1)},[H]),Y=r.useCallback(()=>{ke(null),Me(""),C("");const M=S,V=t.some(ne=>ne.label===M||ne.value===M);if(M&&V){const ne=t.find(Ce=>Ce.label===M||Ce.value===M);le(ne?.value||M)}else le(k(t));Pe(b()),je(2),$(3),me("task"),D("default"),U("unassigned"),be(""),de(""),G(""),ie([]),j(lb(I)),se([]),ue(""),W([]),Q(!1),K("")},[t,k,b,S,D,U,W,Q,le,ie,se,$,C,de,ke,K,j,ue,je,be,me,Me,Pe,I]),fe=r.useCallback(M=>{const V=M.trim();if(!V)return null;const ne=Lg(V);if(ne){const Re=g.find($e=>$e.referenceNumber===ne);if(Re)return Re}const Ce=g.find(Re=>Re.id===V);if(Ce)return Ce;const Ae=g.find(Re=>nc(Re)===V);return Ae||null},[g]),te=r.useCallback(M=>{const V=M.trim();if(!V)return null;const ne=V.toLowerCase(),Ce=ly(V);if(Ce){const $e=v.find(vt=>vt.referenceNumber===Ce);if($e)return $e}const Ae=v.find($e=>$e.id===V);if(Ae)return Ae;const Re=v.find($e=>$e.title.trim().toLowerCase()===ne);return Re||null},[v]),Le=r.useCallback((M,V)=>{V?.preserveReturnTrail||Te([]),ke(M.id),Me(M.title),C(M.description||""),le(M.category||k(t)),Pe(M.type||b()),je(typeof M.priority=="number"?M.priority:2),$(typeof M.complexity=="number"?M.complexity:3),me(M.status||"task"),D(M.approach||"default"),U(M.assignee||"unassigned"),be(M.scheduledDate||""),de(M.dueDate||"");const ne=M.workstreamId&&v.find(Ce=>Ce.id===M.workstreamId)||null;G(ne?Ro(ne)||ne.id:""),ie(M.checklistItems||[]),se(M.comments||[]),j(M.taxonomies||{}),M.taxonomies?.approach&&D(M.taxonomies.approach),W(M.attachments||[]),Q(!1),A("add")},[t,k,b,A,D,U,W,Q,le,ie,se,$,C,de,ke,j,je,be,me,Te,Me,Pe,v]),oe=r.useCallback(M=>{const V=g.find(ne=>ne.id===M);V&&(s==="add"&&m&&m!==V.id&&Te(ne=>ne[ne.length-1]===m?ne:[...ne,m]),V.isArchived&&!_&&ce(!0),Le(V,{preserveReturnTrail:!0}))},[s,m,Le,g,ce,Te,_]),L=r.useCallback(()=>{if(s!=="add"||!m||Z.length===0)return!1;const M=[...Z];for(;M.length>0;){const V=M.pop();if(!V)continue;const ne=g.find(Ce=>Ce.id===V);if(ne)return ne.isArchived&&!_&&ce(!0),Te(M),Le(ne,{preserveReturnTrail:!0}),!0}return Te([]),!1},[s,m,Le,g,ce,Te,_,Z]),X=r.useCallback(()=>{Te([])},[Te]);return{handleNavigation:R,handleClose:B,resetForm:Y,resolveTaskIdInput:fe,resolveWorkstreamIdInput:te,handleEdit:Le,handleOpenTaskById:oe,returnToPreviousTask:L,clearReturnToParentTask:X}}function mb(e){return e.map(t=>({...t}))}function pb(e){return e.map(t=>({...t}))}function fb(e){return e.map(t=>({...t}))}const hb={id:"software-development",label:"Software Development",description:"A software-oriented starter pack with developer-focused work types and a 4-level priority scale.",isDefaultStarter:!0,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"}]},gb=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",categories:[{value:el,label:Im,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"}]},hb];function uy(){return gb.map(e=>({...e,categories:mb(e.categories),types:pb(e.types),priorities:fb(e.priorities)}))}const Qc=[{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"}],Xs=Qc.map(({value:e,label:t,icon:a,color:s})=>({value:e,label:t,icon:a,color:s}));function yd(e){const t=String(e||"task").trim().toLowerCase();return t==="completed"?Qc.find(a=>a.value==="done")||Qc[0]:Qc.find(a=>a.value===t)||Qc[0]}const my=["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"],rc=my.reduce((e,t)=>(e[t]=hs[t]||ec,e),{}),r$=my,hm=Object.fromEntries(uy().flatMap(e=>e.types).filter(e=>e.icon&&e.color).reduce((e,t)=>(e.some(([a])=>a===t.value)||e.push([t.value,{icon:t.icon,color:t.color}]),e),[])),yb={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"},Ih={"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"},s$=["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 Ma(e){if(e)return Ih[e]?Ih[e]:e}function kb(e){const t=String(e||"").trim().toLowerCase();return Ma(hm[t]?.color)||Ma("violet-200")||"#9c7aeb"}function o$(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 vb(e){const t=String(e||"").trim().toUpperCase();return Ma(yb[t])||"var(--text-muted)"}const Sb=/[\u2010-\u2015\u2212]/g;function xf(e){return String(e??"").trim().replace(Sb,"-").replace(/\s+/g," ").toLowerCase()}function jm(e){const t=xf(e);if(!t)return null;const a=t.match(/^(l\s*t|t)\s*(?:-\s*)?(\d+)$/i);return a?`${a[1].replace(/\s+/g,"").toLowerCase()}-${a[2]}`:null}function Pm(e){const t=xf(e);return{raw:t,tokens:t?t.split(" ").filter(Boolean):[],referenceToken:jm(e)}}function as(e,t){const a=String(t??"").trim();a&&e.push(a)}function Kc(e,t,a){const s=String(a??"").trim();if(!s)return;const o=t?.find(c=>String(c.value)===s);as(e,o?.label)}function wb(e,t={}){const a=[];return as(a,e.title),as(a,e.description),as(a,e.id),as(a,nc(e)),as(a,e.category),as(a,e.type),as(a,e.priority),as(a,e.status),as(a,e.assignee||"unassigned"),as(a,e.canceledReason),Kc(a,t.categories,e.category),Kc(a,t.types,e.type),Kc(a,t.priorities,e.priority),Kc(a,Xs,e.status),Kc(a,t.assigneeOptions,e.assignee||"unassigned"),Object.entries(e.taxonomies||{}).forEach(([s,o])=>{const c=t.taxonomies?.find(d=>d.id===s);as(a,c?.label),(Array.isArray(o)?o:[o]).forEach(d=>{as(a,d),Kc(a,c?.options,d)})}),a}function gm(e,t,a={}){const s=typeof t=="string"?Pm(t):t;if(!s.raw)return!0;const o=wb(e,a),i=o.map(xf).filter(Boolean).join(" ");return i.includes(s.raw)||s.referenceToken&&o.map(jm).some(m=>m?.includes(s.referenceToken))?!0:s.tokens.length>0&&s.tokens.every(d=>i.includes(d))}function bb(e,t){const a=e.taxonomies?.[t];return a==null||a===""?!1:Array.isArray(a)?a.some(s=>String(s).trim().length>0):String(a).trim().length>0}function Td(e,t){const a=e.filter(o=>o.status!=="retired"),s=e.filter(o=>o.status==="retired"&&t.some(c=>bb(c,o.id)));return[...a,...s.filter(o=>!a.some(c=>c.id===o.id))]}function py(e,t=[]){return Td(e,t).filter(a=>a.sortEnabled===!0).map(a=>({value:`taxonomy:${a.id}`,label:a.status==="retired"?`${a.label} (Retired)`:a.label}))}function Th(e,t){const a=e.taxonomies?.[t.id];if(a==null||a==="")return null;const s=Array.isArray(a)?a.map(o=>String(o)):[String(a)];for(let o=0;o<t.options.length;o+=1)if(s.includes(String(t.options[o]?.value)))return o;return null}function qi(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()}function ym(e,t,a,s,o=[]){let c=0;if(a==="created")return c=qi(e,t),s==="desc"?c:-c;if(a==="updated"){const i=e.updatedAt||e.createdAt,d=t.updatedAt||t.createdAt;return c=new Date(d).getTime()-new Date(i).getTime(),s==="desc"?c:-c}if(a==="priority"){const i=cm(e.priority),d=cm(t.priority);return c=i!==d?d-i:qi(e,t),s==="desc"?c:-c}if(a==="complexity"){const i=typeof e.complexity=="number"?e.complexity:3,d=typeof t.complexity=="number"?t.complexity:3;return c=i!==d?d-i:qi(e,t),s==="desc"?c:-c}if(a.startsWith("taxonomy:")){const i=a.slice(9),d=o.find(k=>k.id===i);if(!d)return c=qi(e,t),s==="desc"?c:-c;const m=Th(e,d),y=Th(t,d);return m===null&&y===null?qi(e,t):m===null?1:y===null?-1:m!==y?s==="desc"?y-m:m-y:qi(e,t)}return c=qi(e,t),s==="desc"?c:-c}function _b(e,t,a){const s=e.taxonomies?.[t];return s==null||s===""?!1:Array.isArray(s)?s.some(o=>String(o)===String(a)):String(s)===String(a)}function If(e,t){const a=e.options.filter(o=>o.status!=="retired"),s=e.options.filter(o=>o.status==="retired"&&t.some(c=>_b(c,e.id,o.value)));return[...a,...s.filter(o=>!a.some(c=>String(c.value)===String(o.value)))]}function Cb({tasks:e,archivedTasks:t,activeCategories:a,activeTypes:s,priorities:o,taxonomies:c,configLoaded:i,referenceDataLoaded:d,assigneeOptionsLoaded:m,assigneeOptions:y}){const k=r.useMemo(()=>Kg(y),[y]),S=r.useMemo(()=>Td(c,[...e,...t]).filter(oe=>oe.filterEnabled!==!1).map(oe=>({...oe,options:If(oe,[...e,...t])})),[t,e,c]),h=r.useMemo(()=>k.map(oe=>oe.value),[k]),[g,v]=r.useState(""),[_,I]=r.useState([]),[A,D]=r.useState([]),[U,W]=r.useState([]),[Q,le]=r.useState(!1),[ie,se]=r.useState(Xs.map(oe=>oe.value)),[$,C]=r.useState(h),[de,ke]=r.useState(!0),[K,j]=r.useState({}),[H,ue]=r.useState("created"),[ye,G]=r.useState("desc"),je=r.useCallback(()=>{G(oe=>oe==="asc"?"desc":"asc")},[]),[be,ce]=r.useState("status"),[me,Te]=r.useState("show"),[Me,Pe]=r.useState({}),Ee=r.useCallback((oe,L)=>L.length===0?!0:L.every(X=>oe.includes(X)),[]),Z=r.useCallback((oe,L)=>oe.length===L.length&&oe.every((X,M)=>X===L[M]),[]);r.useEffect(()=>{be==="approach"&&ce("status")},[be]),r.useEffect(()=>{if(!(!i||!d)&&m&&!Q&&a.length>0&&s.length>0&&o.length>0){I(a.map(L=>L.value)),D(o.map(L=>L.value)),W(s.map(L=>L.value)),C(h),ke(!0);const oe={};S.forEach(L=>{oe[L.id]=L.options.map(X=>X.value)}),j(oe),le(!0)}},[i,d,m,a,s,o,S,Q,h]),r.useEffect(()=>{if(!Q||!m)return;const oe=new Set(h),L=$.filter(V=>oe.has(V)),X=de?h:L.length>0||$.length===0?L:h;(X.length!==$.length||X.some((V,ne)=>V!==$[ne]))&&C(X)},[h,$,de,Q,m]),r.useEffect(()=>{if(!Q||!m)return;const oe=$.filter(X=>h.includes(X)),L=h.length>0&&h.every(X=>oe.includes(X));L!==de&&ke(L)},[h,$,de,Q,m]),r.useEffect(()=>{if(!i||!d||!Q||a.length===0)return;const oe=$v(_,a);(oe.length!==_.length||oe.some((X,M)=>X!==_[M]))&&I(oe)},[i,d,a,Q,_]),r.useEffect(()=>{if(!i||!d||!Q||o.length===0||A.length===0)return;const oe=Ov(A,o),L=Array.from(new Set(A.map(M=>Number(M)).filter(M=>Number.isFinite(M))));(oe.length!==L.length||oe.some((M,V)=>M!==L[V]))&&D(oe)},[i,d,Q,o,A]),r.useEffect(()=>{if(!i||!d||!Q||s.length===0)return;const oe=new Set(s.map(M=>M.value)),L=U.filter(M=>oe.has(M)),X=L.length>0||U.length===0?L:s.map(M=>M.value);Z(X,U)||W(X)},[s,i,U,Q,Z,d]),r.useEffect(()=>{if(!i||!d||!Q)return;const oe={};S.forEach(ne=>{const Ce=ne.options.map($e=>$e.value);if(Ce.length===0)return;const Ae=Array.isArray(K[ne.id])?K[ne.id]:[],Re=Ae.filter($e=>Ce.includes($e));oe[ne.id]=Re.length>0||Ae.length===0?Re:Ce});const L=Object.keys(K).sort(),X=Object.keys(oe).sort(),M=L.length!==X.length||L.some((ne,Ce)=>ne!==X[Ce]),V=X.some(ne=>!Z(K[ne]||[],oe[ne]||[]));(M||V)&&j(oe)},[i,K,S,Q,Z,d]);const x=r.useCallback(()=>{v(""),I(a.map(L=>L.value)),D(o.map(L=>L.value)),W(s.map(L=>L.value)),se(Xs.map(L=>L.value)),C(h),ke(!0);const oe={};S.forEach(L=>{oe[L.id]=L.options.map(X=>X.value)}),j(oe),ue("created"),G("desc")},[a,o,s,S,h]),b=r.useCallback(oe=>{C(L=>{const X=typeof oe=="function"?oe(L):oe,M=Array.from(new Set(X.filter(ne=>typeof ne=="string"&&ne.trim().length>0))),V=h.length>0&&h.every(ne=>M.includes(ne));return ke(V),M})},[h]),R=r.useMemo(()=>Pm(g),[g]),B=r.useMemo(()=>({categories:a,types:s,priorities:o,assigneeOptions:k,taxonomies:c}),[a,s,o,k,c]),Y=r.useMemo(()=>{const oe=Ee(_,a.map(V=>V.value)),L=Ee(U,s.map(V=>V.value)),X=Ee(Array.from(new Set(A.map(V=>Number(V)).filter(V=>Number.isFinite(V)))),o.map(V=>Number(V.value)).filter(V=>Number.isFinite(V))),M=Ee(ie,Xs.map(V=>V.value));return e.filter(V=>{const ne=gm(V,R,B),Ce=!Q||oe||_.includes(V.category),Ae=!Q||X||gp(V.priority,A),Re=!Q||L||U.includes(V.type||Gr),$e=!Q||M||ie.includes(V.status),vt=!Q||de||$.includes(V.assignee||"unassigned"),st=Object.entries(K).every(([kt,Ye])=>{const Ct=S.find(Tt=>Tt.id===kt);if(!Ct)return!0;const dt=Ct?.options.every(Tt=>Ye.includes(Tt.value))??!0;if(dt)return!0;const Qe=V.taxonomies?.[kt];return Qe?Array.isArray(Qe)?Qe.some(Tt=>Ye.includes(Tt)):Ye.includes(Qe):dt||Ye.includes("")});return ne&&Ce&&Ae&&Re&&$e&&vt&&st}).sort((V,ne)=>ym(V,ne,H,ye,c))},[e,t,R,B,_,A,U,ie,$,de,K,H,ye,Q,S,a,s,o,Ee,c]),fe=r.useMemo(()=>{const oe=Ee(_,a.map(V=>V.value)),L=Ee(U,s.map(V=>V.value)),X=Ee(Array.from(new Set(A.map(V=>Number(V)).filter(V=>Number.isFinite(V)))),o.map(V=>Number(V.value)).filter(V=>Number.isFinite(V))),M=Ee(ie,Xs.map(V=>V.value));return e.filter(V=>{const ne=!Q||oe||_.includes(V.category),Ce=!Q||X||gp(V.priority,A),Ae=!Q||L||U.includes(V.type||Gr),Re=!Q||M||ie.includes(V.status),$e=!Q||de||$.includes(V.assignee||"unassigned"),vt=Object.entries(K).every(([st,kt])=>{const Ye=S.find(Qe=>Qe.id===st);if(!Ye)return!0;const Ct=Ye?.options.every(Qe=>kt.includes(Qe.value))??!0;if(Ct)return!0;const dt=V.taxonomies?.[st];return dt?Array.isArray(dt)?dt.some(Qe=>kt.includes(Qe)):kt.includes(dt):Ct||kt.includes("")});return ne&&Ce&&Ae&&Re&&$e&&vt})},[e,t,_,A,U,ie,$,de,K,Q,S,a,s,o,Ee]),te=r.useMemo(()=>{const oe=a.every(M=>_.includes(M.value)),L=Ee(U,s.map(M=>M.value)),X=Ee(Array.from(new Set(A.map(M=>Number(M)).filter(M=>Number.isFinite(M)))),o.map(M=>Number(M.value)).filter(M=>Number.isFinite(M)));return t.filter(M=>{const V=gm(M,R,B),ne=!Q||oe||_.includes(M.category),Ce=!Q||X||gp(M.priority,A),Ae=!Q||L||U.includes(M.type||Gr),Re=!Q||de||$.includes(M.assignee||"unassigned"),$e=Object.entries(K).every(([vt,st])=>{const kt=S.find(dt=>dt.id===vt);if(!kt)return!0;const Ye=kt?.options.every(dt=>st.includes(dt.value))??!0;if(Ye)return!0;const Ct=M.taxonomies?.[vt];return Ct?Array.isArray(Ct)?Ct.some(dt=>st.includes(dt)):st.includes(Ct):Ye||st.includes("")});return V&&ne&&Ce&&Ae&&Re&&$e}).sort((M,V)=>ym(M,V,H,ye,c))},[t,R,B,_,A,U,$,de,K,H,ye,Q,a,s,o,S,Ee,c]),Le=r.useMemo(()=>{const oe={};return Y.forEach(L=>{const X=a.find(V=>V.value===L.category),M=X?X.label:L.category||"General";oe[M]||(oe[M]=[]),oe[M].push(L)}),oe},[Y,a]);return{searchQuery:g,setSearchQuery:v,filterCategories:_,setFilterCategories:I,filterPriorities:A,setFilterPriorities:D,filterTypes:U,setFilterTypes:W,filterStatus:ie,setFilterStatus:se,filterAssignees:$,setFilterAssignees:b,filterAssigneesAllSelected:de,setFilterAssigneesAllSelected:ke,filterTaxonomies:K,setFilterTaxonomies:j,hasInitedFilters:Q,setHasInitedFilters:le,sortBy:H,setSortBy:ue,sortOrder:ye,setSortOrder:G,toggleSortOrder:je,groupBy:be,setGroupBy:ce,emptyColumnMode:me,setEmptyColumnMode:Te,collapsedCategories:Me,setCollapsedCategories:Pe,clearFilters:x,filteredTasks:Y,searchAgnosticTasks:fe,filteredArchive:te,groupedTasks:Le}}const Ab=Cb;function xb(e){const{activeCategories:t,activeTab:a,apiEndpoint:s,approach:o,assignee:c,attachments:i,attachmentsDirty:d,category:m,checklistItems:y,comments:k,complexity:S,description:h,dueDate:g,editingTaskId:v,fetchTasks:_,formTaxonomies:I,getPreferredCategoryValue:A,mergeTaskFromServer:D,workstreamInput:U,priority:W,pushNotice:Q,queueWorkspaceSyncFromAuthoritativeTaskState:le,relationshipTasks:ie,resetForm:se,resolveWorkstreamIdInput:$,scheduledDate:C,setActiveTab:de,setAttachmentsDirty:ke,setComments:K,setError:j,setLastUsedCategory:H,setLoading:ue,setNewCommentText:ye,status:G,title:je,taxonomies:be,type:ce}=e,[me,Te]=r.useState(null),[Me,Pe]=r.useState("idle"),[Ee,Z]=r.useState(null),x=r.useRef(null),b=r.useCallback(()=>JSON.stringify({title:je.trim(),description:h||"",category:typeof m=="string"?m:m.label||A(t),type:typeof ce=="string"?ce:ce.label||Gr,priority:Number(W),complexity:Number(S)||3,approach:o||"default",assignee:c||"agent",scheduledDate:C||"",dueDate:g||"",workstreamInput:U.trim(),checklistItems:y,comments:k,taxonomies:I,attachments:i}),[t,o,c,i,m,y,k,S,h,g,I,A,W,C,je,ce,U]),R=r.useCallback(()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null)},[]),B=r.useCallback(async X=>{const M=X?.quiet??!1,V=X?.source??"manual";if(!je.trim())return j("Title is required"),v&&Pe(V==="autosave"?"error":"idle"),!1;const ne=be.filter(Ce=>Ce.isRequired).filter(Ce=>{const Ae=I[Ce.id];return Array.isArray(Ae)?Ae.filter(Re=>String(Re).trim().length>0).length===0:typeof Ae!="string"&&typeof Ae!="number"||String(Ae).trim().length===0}).map(Ce=>Ce.label);if(ne.length>0)return j(`Required taxonomy values are missing: ${ne.join(", ")}`),v&&Pe(V==="autosave"?"error":"idle"),!1;if(v&&ie.find(Ae=>Ae.id===v)?.isArchived)return j("Archived tasks are read-only. Unarchive first to make changes."),Pe(V==="autosave"?"error":"idle"),!1;ue(!0),j(""),v&&Pe("saving");try{const Ce=v?`/api/taskforce/task/${v}`:s.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),Ae=v?"PATCH":"POST",Re=typeof m=="string"?m:m.label||A(t),$e=typeof ce=="string"?ce:ce.label||Gr,vt=U.trim()?$(U):null,st={title:je,description:h||null,category:Re||A(t),type:$e,priority:W,complexity:Number(S)||3,status:v?void 0:G,completedAt:v?void 0:G==="done"?new Date().toISOString():null,approach:o||"default",assignee:c||"agent",scheduledDate:C||null,dueDate:g||null,workstreamId:U.trim()?vt?.id||U.trim():null,checklistItems:y,comments:k,taxonomies:I,...v?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};(!v||d)&&(st.attachments=i),v&&(st.saveSource=V);const kt=await fetch(Ce,{method:Ae,headers:{"Content-Type":"application/json"},body:JSON.stringify(st)});if(!kt.ok){const dt=(await kt.json()).message||`Failed to ${v?"update":"save"} task`;return j(dt),M||Q(dt,"error"),ue(!1),v&&Pe("error"),!1}const Ye=await kt.json().catch(()=>null);return v&&Ye&&typeof Ye=="object"&&(D(Ye),le()),H(Re),ke(!1),ue(!1),v&&Pe("saved"),!0}catch{return j("Failed to connect to server"),M||Q("Failed to connect to server","error"),ue(!1),v&&Pe("error"),!1}},[t,s,o,c,i,d,m,y,k,S,h,g,v,I,A,D,U,W,Q,le,$,ke,j,H,ue,C,G,je,be,ce]),Y=r.useCallback(async()=>{await B({source:"manual"})&&(v||Q("Task added successfully","success"),a==="add"&&!v&&(se(),de("tasks"),await _()))},[a,v,_,Q,se,B,de]);r.useEffect(()=>{if(R(),!v){Z(null),Pe("idle");return}Z(b()),Pe("idle")},[R,v]);const fe=r.useCallback(async()=>{if(R(),!v||Ee===null)return;const X=b();if(X===Ee||!je.trim()||g&&C&&g<C)return;await B({quiet:!0,source:"autosave"})&&Z(X)},[b,R,g,v,Ee,B,C,je]);r.useEffect(()=>{if(!v||Ee===null)return;const X=b();if(X!==Ee){if(!je.trim()){Pe("idle");return}if(g&&C&&g<C){Pe("error");return}return Pe(M=>M==="error"?"error":"idle"),R(),x.current=window.setTimeout(async()=>{await B({quiet:!0,source:"autosave"})&&Z(X)},700),()=>{R()}}},[b,R,g,v,Ee,B,C,je]);const te=r.useCallback(async X=>{if(X.preventDefault(),g&&C&&g<C){Te({dueDate:g,scheduledDate:C});return}await Y()},[g,Y,C]),Le=r.useCallback(async()=>{Te(null),await Y()},[Y]),oe=r.useCallback(()=>{Te(null)},[]),L=r.useCallback(async X=>{if(!v||!X.trim())return;const M=X.trim();try{const V=await fetch(`/api/taskforce/task/${v}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:M,author:"user"})});if(!V.ok){const Ae=(await V.json().catch(()=>({}))).error||"Failed to add comment.";j(Ae),Q(Ae,"error");return}const ne=await V.json().catch(()=>null);if(ye(""),ne&&typeof ne=="object"){const Ce=No(ne);K(Ce.comments||[]),D(ne),Z(b()),Pe("saved")}else await _(!0);le()}catch(V){console.error("Failed to add comment",V),j("Failed to add comment."),Q("Failed to add comment.","error")}},[v,_,b,D,Q,le,K,j,ye]);return{autoSaveState:Me,flushAutoSave:fe,scheduleWarningPrompt:me,saveTask:B,handleSubmit:te,confirmScheduleWarning:Le,cancelScheduleWarning:oe,handleAddComment:L}}function Ib(e){const{editingTaskId:t,fetchTasks:a,mergeTaskFromServer:s,workstreamInput:o,pushNotice:c,queueWorkspaceSyncFromAuthoritativeTaskState:i,relationshipTasks:d,resolveWorkstreamIdInput:m,setError:y}=e;return{handleSetWorkstreamForCurrentTask:r.useCallback(async S=>{if(!t)return;const h=d.find(I=>I.id===t);if(!h)return;const g=typeof S=="string"?S.trim():S===null?"":o.trim(),v=g?m(g):null,_=g.length>0?v?.id||g:null;if((h.workstreamId||null)===_){c(_?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const I=await fetch(`/api/taskforce/task/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:_})});if(!I.ok){const U=(await I.json().catch(()=>({}))).error||"Failed to set workstream.";y(U),c(U,"error");return}y(""),c(_?"Workstream set":"Workstream removed","info");const A=await I.json().catch(()=>null);A?(s(A),i()):(await a(!0),i())}catch{y("Failed to set workstream."),c("Failed to set workstream.","error")}},[t,a,s,o,c,i,d,m,y])}}function Tb({tasks:e,archivedTasks:t,editingTaskId:a,setTasks:s,setArchivedTasks:o,setDeletedTasks:c,setError:i,resetForm:d,setActiveTab:m,fetchTasks:y,fetchArchive:k,fetchDeletedTasks:S,mergeTaskFromServer:h,pushNotice:g,cloudAuthConfigured:v,runtimeMode:_,isAuthenticated:I,workspaceCloudSyncEnabled:A,buildWorkspaceSyncSignature:D,pushWorkspaceChangesToCloud:U,workspacePendingSignatureRef:W,workspaceDeletedTaskIdsRef:Q,workspaceDeletedTaskWatermarksRef:le}){const[ie,se]=r.useState(null),$=r.useRef(null),C=r.useRef(null),de=r.useRef(null);r.useEffect(()=>()=>{typeof window>"u"||(C.current!==null&&(window.clearTimeout(C.current),C.current=null),de.current=null)},[]);const ke=r.useCallback((Z=0)=>{if(!(v&&_==="local"&&I&&A)||typeof window>"u")return;const x=Math.max(0,Z),b=Date.now()+x,R=de.current;if(C.current!==null){if(x<=0||R!==null&&R>=b)return;window.clearTimeout(C.current),C.current=null}de.current=b,C.current=window.setTimeout(()=>{C.current=null,de.current=null;const B=D();B&&(W.current=B,U(B))},x)},[v,_,I,A,D,W,U]),K=r.useCallback(async(Z,x)=>{let b=await fetch(`/api/taskforce/deleted${Z}`,x);return b.status===404&&(b=await fetch(`/api/taskforce/trash${Z}`,x)),b},[]),j=async(Z,x=!1,b={})=>{if(!b.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const R=x||t.some(B=>B.id===Z);try{const B=await fetch(`/api/taskforce/task/${Z}`,{method:"DELETE"});if(!B.ok){const Le=(await B.json().catch(()=>({}))).error||"Failed to delete task.";return i(Le),g(Le,"error"),!1}const Y=await B.json().catch(()=>({})),fe=Y?.deleted&&typeof Y.deleted=="object"&&Y.deleted.taskSnapshot?{...Y.deleted,taskSnapshot:No(Y.deleted.taskSnapshot)}:null;if(window.location.search.includes(Z)){const te=new URL(window.location.href);te.searchParams.delete("task"),window.history.pushState({},"",te.toString())}if(R?o(te=>te.filter(Le=>Le.id!==Z)):s(te=>te.filter(Le=>Le.id!==Z)),fe){c(Le=>[fe,...Le.filter(oe=>oe.taskId!==Z)]);const te=String(fe.deletedAt||"").trim();Number.isFinite(Date.parse(te))&&le.current.set(Z,te)}else await S(!0),le.current.set(Z,new Date().toISOString());if(Q.current.add(Z),v&&_==="local"&&I&&A){const te=D();W.current=te,U(te)}return a===Z&&(d(),m("tasks")),i(""),g("Task moved to Trash.","info"),!0}catch(B){return console.error("Failed to delete task:",B),i("Failed to delete task."),g("Failed to delete task.","error"),!1}},H=r.useCallback(async Z=>{try{const x=await K(`/${Z}/restore`,{method:"POST"});if(!x.ok){const Y=(await x.json().catch(()=>({}))).error||"Failed to restore deleted task.";return i(Y),g(Y,"error"),null}const b=await x.json().catch(()=>null);b?h(b):await y(!0),c(B=>B.filter(Y=>Y.id!==Z&&Y.taskId!==Z));const R=String(b?.id||"").trim();return Q.current.delete(Z),le.current.delete(Z),R&&(Q.current.delete(R),le.current.delete(R)),ke(),i(""),g("Task restored from Trash.","info"),b?No(b):null}catch(x){return console.error("Failed to restore deleted task:",x),i("Failed to restore deleted task."),g("Failed to restore deleted task.","error"),null}},[y,h,g,ke,K,c,i]),ue=r.useCallback(async Z=>{try{const x=await K(`/${Z}`,{method:"DELETE"});if(!x.ok){const R=(await x.json().catch(()=>({}))).error||"Failed to permanently delete deleted task.";return i(R),g(R,"error"),!1}return c(b=>b.filter(R=>R.id!==Z&&R.taskId!==Z)),ke(),i(""),g("Deleted task permanently removed.","info"),!0}catch(x){return console.error("Failed to permanently delete deleted task:",x),i("Failed to permanently delete deleted task."),g("Failed to permanently delete deleted task.","error"),!1}},[g,ke,K,c,i]),ye=r.useCallback(async()=>{try{const Z=await K("/empty",{method:"POST"});if(!Z.ok){const B=(await Z.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return i(B),g(B,"error"),null}const x=await Z.json().catch(()=>({})),b=Number(x?.deleted||0);return c([]),ke(),i(""),g(b===1?"Deleted task permanently removed.":`${b} deleted tasks permanently removed.`,"info"),b}catch(Z){return console.error("Failed to empty deleted tasks:",Z),i("Failed to permanently delete deleted tasks."),g("Failed to permanently delete deleted tasks.","error"),null}},[g,ke,K,c,i]),G=r.useCallback(async(Z,x)=>{const b=e,R=t;s(B=>B.map(Y=>Y.id===Z?{...Y,...x}:Y)),o(B=>B.map(Y=>Y.id===Z?{...Y,...x}:Y));try{const B=await fetch(`/api/taskforce/task/${Z}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});if(!B.ok){const te=(await B.json().catch(()=>({}))).error||`Failed to update task ${Z}.`;i(te),g(te,"error"),s(b),o(R);return}const Y=await B.json().catch(()=>null);h(Y),ke(x.attachments!==void 0?150:0),i("")}catch(B){console.error("Failed to update task",B);const Y=`Failed to update task ${Z}.`;i(Y),g(Y,"error"),s(b),o(R)}},[e,t,g,h,ke]);return{copiedId:ie,handleDelete:j,handleUpdateTask:G,handleToggleComplete:async Z=>{const x=Z.status==="done"?"task":"done",b=x==="done"?new Date().toISOString():void 0,R={status:x,completedAt:b,completed:x==="done",inProgress:!1,readyForReview:!1,cancelled:!1},B=e,Y=t;s(fe=>fe.map(te=>te.id===Z.id?{...te,...R}:te)),o(fe=>fe.map(te=>te.id===Z.id?{...te,...R}:te));try{const fe=await fetch(`/api/taskforce/task/${Z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:x,completedAt:b})});if(!fe.ok){const oe=(await fe.json().catch(()=>({}))).error||"Failed to update task status.";i(oe),g(oe,"error"),s(B),o(Y);return}const te=await fe.json().catch(()=>null);te?(h(te),ke()):(await y(!0),ke()),i("")}catch(fe){console.error("Failed to toggle complete",fe),i("Failed to update task status."),g("Failed to update task status.","error"),s(B),o(Y)}},handleToggleCancel:async Z=>{const x=Z.status==="cancelled"?"task":"cancelled";try{const b=await fetch(`/api/taskforce/task/${Z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:x})});if(!b.ok){const Y=(await b.json().catch(()=>({}))).error||"Failed to update task status.";i(Y),g(Y,"error"),await y(!0);return}const R=await b.json().catch(()=>null);R?(h(R),ke()):(await y(!0),ke()),i("")}catch(b){console.error("Failed to toggle cancel",b),i("Failed to update task status."),g("Failed to update task status.","error"),y()}},handleToggleInProgress:async Z=>{const x=Z.status==="in-progress"?"task":"in-progress";s(b=>b.map(R=>R.id===Z.id?{...R,status:x}:R));try{const b=await fetch(`/api/taskforce/task/${Z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:x})});if(!b.ok){await y(!0);return}const R=await b.json().catch(()=>null);h(R),ke()}catch{y()}},handleToggleReview:async Z=>{const x=Z.status==="review"?"task":"review";s(b=>b.map(R=>R.id===Z.id?{...R,status:x}:R));try{const b=await fetch(`/api/taskforce/task/${Z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:x})});if(!b.ok){await y(!0);return}const R=await b.json().catch(()=>null);h(R),ke()}catch{y()}},handleArchiveTask:async Z=>{try{const b=Z.status==="cancelled"?"cancel":"complete",R=await fetch(`/api/taskforce/task/${Z.id}/${b}`,{method:"POST"});if(R.ok){const B=await R.json().catch(()=>null),Y=[];if(B&&typeof B=="object"&&Y.push(B),Y.length>0){for(const te of Y)h(te);ke()}else k();const fe=new Set(Y.map(te=>String(te?.id||"").trim()).filter(te=>te.length>0));a&&fe.has(a)&&(d(),m("tasks"))}else{const Y=(await R.json().catch(()=>({}))).error||"Failed to archive task.";i(Y),g(Y,"error")}}catch(x){console.error("Failed to archive",x),i("Failed to archive task."),g("Failed to archive task.","error")}},handleBulkArchive:async()=>{const Z=e.filter(x=>x.status==="done"||x.status==="cancelled");if(Z.length!==0&&confirm(`Archive ${Z.length} completed/cancelled tasks?`))try{const x=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:Z.map(b=>b.id)})});if(x.ok){const b=await x.json(),R=Array.isArray(b?.results?.archived)?b.results.archived:[];if(R.length>0){for(const B of R)h(B);ke()}else s(B=>B.filter(Y=>!["done","cancelled"].includes(Y.status))),k();g(`${b.archived||Z.length} tasks archived`,"info"),i("")}else{const R=(await x.json().catch(()=>({}))).error||"Failed to bulk archive tasks.";i(R),g(R,"error")}}catch(x){console.error("Failed to bulk archive",x),i("Failed to bulk archive tasks."),g("Failed to bulk archive tasks.","error")}},handleUnarchive:async Z=>{try{const x=await fetch(`/api/taskforce/task/${Z}/unarchive`,{method:"POST"});if(x.ok){const b=await x.json().catch(()=>null);b?(h(b),ke()):(o(R=>R.filter(B=>B.id!==Z)),await y(!0),ke()),i(""),g("Task restored from archive.","info")}}catch(x){console.error("Failed to unarchive",x),i("Failed to unarchive task."),g("Failed to unarchive task.","error")}},handleRestoreDeletedTask:H,handlePermanentlyDeleteDeletedTask:ue,handleEmptyDeletedTasks:ye,handleCopyId:(Z,x)=>{Z.stopPropagation(),navigator.clipboard.writeText(x),se(x),$.current!==null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{$.current=null,se(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:ke}}const Rb=Tb;function Uu(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function Nb(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 jb({currentWorkspaceIdRef:e,resolveApiUrl:t,runtimeMode:a}){r.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const s=window.fetch.bind(window),o=c=>{if(typeof c=="string")return a!=="cloud"?c:c.startsWith("/api/taskforce")&&!Uu(c)?t(c):c;if(c instanceof URL)return a!=="cloud"?c:c.origin===window.location.origin&&c.pathname.startsWith("/api/taskforce")?Uu(c.pathname)?c:new URL(t(`${c.pathname}${c.search}${c.hash}`)):c;if(typeof Request<"u"&&c instanceof Request){if(a!=="cloud")return c;const i=new URL(c.url,window.location.origin);if(i.origin===window.location.origin&&i.pathname.startsWith("/api/taskforce"))return Uu(i.pathname)?c:t(`${i.pathname}${i.search}${i.hash}`)}return c};return window.fetch=((c,i)=>{const d=o(c),m=Nb(d);if(!!!(m&&m.pathname.startsWith("/api/taskforce")&&!Uu(m.pathname)))return s(d,i);const k=String(e.current||"").trim();if(typeof Request<"u"&&d instanceof Request){const h=new Headers(d.headers);i?.headers&&new Headers(i.headers).forEach((_,I)=>h.set(I,_)),k&&k!=="default"&&!h.has("x-taskforce-workspace-id")&&(h.set("x-taskforce-workspace-id",k),h.set("x-taskforce-workspace-authoritative","1"));const g=new Request(d,{...i,headers:h});return s(g)}const S=new Headers(i?.headers);return k&&k!=="default"&&!S.has("x-taskforce-workspace-id")&&(S.set("x-taskforce-workspace-id",k),S.set("x-taskforce-workspace-authoritative","1")),s(d,{...i,headers:S})}),()=>{window.fetch=s}},[e,t,a])}const dd=12e3,Pb=3e4,Mb=2e4;function zu(e){return e==="cloud"?Pb:dd}function Rh(){return typeof performance<"u"?performance.now():Date.now()}function Eb({runtimeConfigReady:e,shouldProbeCloudAuth:t,authSessionResolved:a,resolveCloudAuthUrl:s,authOnlyCloudMode:o,authRequiredError:c,runtimeMode:i,workspaceSelectionScope:d,markBootstrapPhase:m,markBootstrapStalled:y,setRuntimeMode:k,setAuthRequiredForApi:S,setIsAuthenticated:h,setAuthUserId:g,setAuthWorkspaceId:v,setAuthUserEmail:_,setAuthUserDisplayName:I,setAuthUserAvatarUrl:A,setUserGlobalSyncStatus:D,setUserGlobalSyncError:U,setHasBetaAccess:W,setAvailableWorkspaces:Q,setHydratedWorkspaceRole:le,setAssigneeOptions:ie,setAuthBlocked:se,setAuthSessionResolved:$,setError:C,applyResolvedWorkspaceId:de,readPersistedWorkspaceId:ke,authSessionRequestRef:K,authSessionEpochRef:j,authSessionLastCheckedAtRef:H,authSessionLastResultRef:ue,isLoopbackHost:ye,setAuthStateReadyRefs:G}){const je=r.useCallback(async ce=>{const me=ce?.force===!0;if(m("auth"),!e)return ue.current;if(!t)return k("local"),S(!1),h(!1),g("anonymous"),v(""),cd(null),_(""),I(""),A(""),D("disconnected"),U(null),W(!0),Q([]),le(null),ie(gi()),se(!1),$(!0),G(!1,!0,!1),ue.current=!1,H.current=Date.now(),!1;const Te=s("/api/taskforce/auth/session"),Me=Date.now();if(!me&&K.current)return K.current;if(!me&&a&&Me-H.current<1500)return ue.current;const Pe=++j.current;let Ee=null;return Ee=(async()=>{const Z=Rh(),x=new AbortController,b=typeof window<"u"?window.setTimeout(()=>x.abort(),Mb):null,R=()=>j.current!==Pe,B=(Y,fe)=>{Ut(Y,{durationMs:Math.max(0,Math.round(Rh()-Z)),force:me,sessionUrl:Te,...fe})};try{const Y=await fetch(Te,{method:"GET",credentials:"include",mode:"cors",signal:x.signal});if(R())return ue.current;if(Y.status===429)return $(!0),G(ue.current,!0,!1),B("auth_session_rate_limited",{status:Y.status}),ue.current;if(!Y.ok)return R()?ue.current:(ye&&cd(null),$(!0),G(!1,!0,!1),ue.current=!1,B("auth_session_request_failed",{status:Y.status}),!1);const fe=await Y.json();if(R())return ue.current;const te=!!fe.authRequiredForApi,Le=!!fe.authenticated,oe=Le?fe.betaAccess!==!1:!0,L=typeof fe.workspaceId=="string"&&fe.workspaceId.trim().length>0?fe.workspaceId.trim():"",X=typeof fe.userId=="string"&&fe.userId.trim().length>0?fe.userId.trim():"anonymous",M=typeof fe.email=="string"&&fe.email.trim().length>0?fe.email.trim().toLowerCase():"",V=typeof fe.displayName=="string"?fe.displayName.trim():"",ne=typeof fe.avatarUrl=="string"?fe.avatarUrl.trim():"",Ce=i==="local",Ae=i==="local"||o,Re=o||Ce?!1:te;return S(Re),h(Le),g(Le?X:"anonymous"),v(Le?L:""),ye&&cd(Le?X:null),_(Le?M:""),I(Le?V:""),A(Le?ne:""),Le&&C($e=>$e===c?"":$e),D(Le?"idle":"disconnected"),U(null),W(oe),Ae||de(L||ke(d)||"default",{preserveNonDefaultDefault:!0}),se(o||Ce?!1:te&&!Le),$(!0),G(Le,!0,Re),ue.current=Le,Le&&m("ready"),B("auth_session_resolved",{status:Y.status,authenticated:Le,workspaceId:Le?L:"",userId:Le?X:"anonymous",authRequiredForApi:Re}),Le}catch(Y){return R()||(ye&&cd(null),$(!0),G(!1,!0,!1),ue.current=!1,y("Unable to verify your session."),B("auth_session_exception",{error:Y instanceof Error?Y.message:String(Y)})),ue.current}finally{b!==null&&typeof window<"u"&&window.clearTimeout(b),R()||(H.current=Date.now()),Ee&&K.current===Ee&&(K.current=null)}})(),K.current=Ee,Ee},[e,t,a,s,o,c,i,d,m,y,k,S,h,g,v,_,I,A,D,U,W,Q,le,ie,se,$,C,de,ke,K,j,H,ue,ye,G]),be=i==="local"&&ye&&t?Sf():"";return r.useEffect(()=>{be&&(h(!0),$(!0),g(be),G(!0,!0,!1),ue.current=!0)},[be,$,G,g,h,ue]),r.useEffect(()=>{if(i!=="local"||!t||typeof window>"u")return;const ce=()=>{je()},me=()=>{document.visibilityState==="visible"&&ce()};window.addEventListener("focus",ce),window.addEventListener("online",ce),document.addEventListener("visibilitychange",me);const Te=window.setInterval(ce,3e4);return()=>{window.removeEventListener("focus",ce),window.removeEventListener("online",ce),document.removeEventListener("visibilitychange",me),window.clearInterval(Te)}},[i,t,je]),{checkAuthSession:je}}function Db(e){const t=e.runtimeMode==="cloud",a=!!(e.shouldGateProtectedApiCalls&&t&&!e.authSessionResolved),s=!!(e.shouldGateProtectedApiCalls&&t&&e.authSessionResolved&&e.authRequiredForApi&&!e.isAuthenticated);return{shouldDeferProtectedApiCalls:a,shouldBlockProtectedApiCalls:s,canCallProtectedApi:!(a||s)}}function Lb(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function Bb(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}function Nh(e){if(!Array.isArray(e))return;const t=e.filter(a=>typeof a=="string"&&a.trim().length>0).map(a=>a.trim());return t.length>0?t:void 0}function Wb(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return Array.isArray(t.categories)||Array.isArray(t.types)||Array.isArray(t.priorities)||Array.isArray(t.taxonomies)||!!t.displayLabels&&typeof t.displayLabels=="object"&&!Array.isArray(t.displayLabels)}function Fb(e){const t=e||{};return{categories:Array.isArray(t.categories)?t.categories.map(s=>typeof s=="string"?{value:s.toLowerCase().replace(/\s+/g,"-"),label:s}:s):[],types:Array.isArray(t.types)?t.types.map(s=>({...Cv(s.value),...s,aliases:Array.isArray(s.aliases)?s.aliases.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):void 0,status:s.status==="retired"?"retired":"active"})):[],priorities:Array.isArray(t.priorities)?t.priorities:[],taxonomies:Array.isArray(t.taxonomies)?t.taxonomies.map(s=>({...s,aliases:Nh(s.aliases),options:Array.isArray(s.options)?s.options.map(o=>({...o,aliases:Nh(o.aliases),status:o.status==="retired"?"retired":"active"})):[],status:s.status==="retired"?"retired":"active",formEnabled:s.formEnabled!==!1,filterEnabled:s.filterEnabled!==!1,sortEnabled:s.sortEnabled===!0})):[],displayLabels:{category:typeof t.displayLabels?.category=="string"&&t.displayLabels.category.trim().length>0?t.displayLabels.category.trim():void 0,type:typeof t.displayLabels?.type=="string"&&t.displayLabels.type.trim().length>0?t.displayLabels.type.trim():void 0,priority:typeof t.displayLabels?.priority=="string"&&t.displayLabels.priority.trim().length>0?t.displayLabels.priority.trim():void 0}}}function Nn(){return typeof performance<"u"?performance.now():Date.now()}function Ob(e){const{shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:a,getWorkspaceRequestState:s,isWorkspaceRequestStale:o,isWorkspaceEpochStale:c,isAbortError:i,isBootstrapTimeoutError:d,fetchWithTimeout:m,handleUnauthorized:y,applyBootstrapConfig:k,loadPersistedUiState:S,fetchBuildInfo:h,markBootstrapPhase:g,markBootstrapStalled:v,fetchWorkflows:_,fetchInitiativeTemplates:I,loadAvailableEnvironments:A,setReferenceDataLoaded:D,setCustomCategories:U,setCustomTypes:W,setPriorities:Q,setTaxonomies:le,setTaxonomyDisplayLabels:ie,setConfigLoaded:se,hasLoadedUiStateRef:$,currentWorkspaceIdRef:C,referenceDataRequestRef:de,referenceDataAbortRef:ke,bootstrapConfigAbortRef:K,workspaceListAbortRef:j,assigneeOptionsAbortRef:H,workspaceListHydratedRef:ue,setAvailableWorkspaces:ye,runtimeMode:G,applyResolvedWorkspaceId:je,workspaceSwitchingEnabled:be,authSessionResolved:ce,isAuthenticated:me,authUserId:Te,authUserAvatarUrl:Me,setHydratedWorkspaceRole:Pe,setAssigneeOptions:Ee,setAssigneeOptionsLoaded:Z,commitCurrentWorkspaceId:x,currentWorkspaceId:b,workspaceSelectionScope:R,abortWorkspaceScopedRequests:B,setWorkspaceBootstrapPending:Y,checkAuthSession:fe,lastConfigRefreshKeyRef:te,lastAssigneeOptionsLoadKeyRef:Le,lastWorkspaceSyncStateLoadKeyRef:oe,lastTaskSurfaceLoadKeyRef:L,lastSettingsSurfaceLoadKeyRef:X,isOpen:M,activeTab:V,showArchive:ne,taskScope:Ce,settingsSection:Ae,workspaceBootstrapPending:Re,fetchTasks:$e,fetchArchive:vt,fetchPlanningEntities:st,refreshTaskCollections:kt,loadWorkspaceSyncState:Ye,archiveBootstrapTimerRef:Ct,hasBootstrappedDataRef:dt}=e,Qe=r.useCallback(async We=>{const tt=We?.ignoreAuthGuard===!0,Oe=We?.force===!0;if(!tt&&(t||a)){Ut("bootstrap_reference_data_skipped",{reason:a?"auth_blocked":"auth_deferred",runtimeMode:G,workspaceId:String(s().workspaceId||"").trim()||"default",force:Oe});return}const Ze=s(),St=String(Ze.workspaceId||"").trim()||"default";if(!(G!=="cloud"||!ce||!me||St!==""&&St!=="default")){Ut("bootstrap_reference_data_skipped",{reason:"workspace_unresolved",runtimeMode:G,workspaceId:St,force:Oe});return}if(!Oe&&de.current?.workspaceId===Ze.workspaceId){Ut("bootstrap_reference_data_reused",{workspaceId:St,force:Oe}),await de.current.promise;return}D(!1);const re=Nn(),Be=new AbortController;ke.current=Be;const At=(async()=>{await Promise.allSettled([(async()=>{let Rt="empty-taxonomy-state";const Bt=await fetch("/api/taskforce/taxonomy-state",{signal:Be.signal});if(!Bt.ok)return;const Ve=await Bt.json().catch(()=>({}));if(Wb(Ve))Rt="taxonomy-state";else{Rt="fallback-endpoints";const[yt,E,l,J]=await Promise.all([fetch("/api/taskforce/categories",{signal:Be.signal}),fetch("/api/taskforce/types",{signal:Be.signal}),fetch("/api/taskforce/priorities",{signal:Be.signal}),fetch("/api/taskforce/taxonomies",{signal:Be.signal})]),[Se,Ie,Ke,Je]=await Promise.all([yt.ok?yt.json().catch(()=>({})):Promise.resolve({}),E.ok?E.json().catch(()=>({})):Promise.resolve({}),l.ok?l.json().catch(()=>({})):Promise.resolve({}),J.ok?J.json().catch(()=>({})):Promise.resolve({})]);Ve.categories=Se.categories,Ve.types=Ie.types,Ve.priorities=Ke.priorities,Ve.taxonomies=Je.taxonomies}const Ot=Fb(Ve);if(o(Ze)){Ut("bootstrap_reference_data_stale_drop",{workspaceId:St,source:Rt});return}Ot.categories.length>0&&U(Ot.categories),Ot.types.length>0&&W(Ot.types),Ot.priorities.length>0&&Q(Ot.priorities),le(Ot.taxonomies),ie(Ot.displayLabels||{}),Ut("bootstrap_reference_data_source",{workspaceId:St,source:Rt,categories:Ot.categories.length,types:Ot.types.length,priorities:Ot.priorities.length,taxonomies:Ot.taxonomies.length})})(),_(),I(),A()]),!o(Ze)&&(D(!0),Ut("bootstrap_reference_data_loaded",{durationMs:Math.max(0,Math.round(Nn()-re)),workspaceId:St,force:Oe}))})();de.current={workspaceId:Ze.workspaceId,promise:At};try{await At}finally{de.current?.promise===At&&(de.current=null),ke.current===Be&&(ke.current=null)}},[ce,I,_,s,me,o,A,ke,de,G,U,W,Q,D,le,ie,a,t]),Tt=r.useCallback(async We=>{if(!(We?.ignoreAuthGuard===!0)&&(t||a))return;g("config");const Oe=s(),Ze=Nn(),St=new AbortController;K.current=St;try{const ot=await m("/api/taskforce/config",void 0,zu(G),{signal:St.signal});if(c(Oe))return;if(ot.status===401){y(),se(!0);return}let re="";if(ot.ok){const Be=await ot.json();if(c(Oe))return;re=typeof Be?.workspaceId=="string"&&Be.workspaceId.trim().length>0?Be.workspaceId.trim():"",k(Be)}if(c(Oe)){const Be=String(C.current||"default").trim()||"default";if(!re||Be!==re)return}if($.current||($.current=!0,await S(re||Oe.workspaceId)),c(Oe)){const Be=String(C.current||"default").trim()||"default";if(!re||Be!==re)return}se(!0),g("ready"),Ut("bootstrap_config_loaded",{durationMs:Math.max(0,Math.round(Nn()-Ze)),status:ot.status,workspaceId:re||Oe.workspaceId}),h()}catch(ot){if(i(ot)||c(Oe))return;$.current||($.current=!0,await S(Oe.workspaceId)),v(d(ot)?"Startup checks timed out.":"Unable to finish startup checks."),se(!0),Ut("bootstrap_config_failed",{durationMs:Math.max(0,Math.round(Nn()-Ze)),workspaceId:Oe.workspaceId,error:ot instanceof Error?ot.message:String(ot)})}finally{K.current===St&&(K.current=null)}},[k,K,C,h,m,s,y,$,i,d,c,S,g,v,G,se,a,t]),ae=r.useCallback(async We=>{await Tt(We),await Qe(We)},[Tt,Qe]),Ge=r.useCallback(()=>{typeof window>"u"||(Ct.current!==null&&window.clearTimeout(Ct.current),Ct.current=window.setTimeout(()=>{Ct.current=null,vt(!0).then(()=>Ut("bootstrap_archive_loaded_deferred",{}))},1500))},[Ct,vt]),ft=r.useCallback(async()=>{if(!be)return ye([]),ue.current=!1,{success:!0,workspaces:[]};const We=s(),tt=Nn(),Oe=new AbortController;j.current=Oe;try{const Ze=await m("/api/taskforce/workspaces",{method:"GET",credentials:"include"},zu(G),{signal:Oe.signal});if(c(We))return{success:!1,error:"Workspace changed while loading workspaces."};if(Ze.status===401)return ye([]),ue.current=!1,{success:!1,error:"Authentication required."};const St=await Ze.json().catch(()=>({}));if(c(We))return{success:!1,error:"Workspace changed while loading workspaces."};if(!Ze.ok||St?.success===!1)return ye([]),ue.current=!1,{success:!1,error:St?.error||`Failed to load workspaces (${Ze.status})`};const ot=Array.isArray(St?.workspaces)?St.workspaces.map(re=>({id:String(re?.id||"").trim(),name:String(re?.name||"").trim(),role:String(re?.role||"member").trim().toLowerCase(),slug:typeof re?.slug=="string"?re.slug:null,description:typeof re?.description=="string"?re.description:null,status:typeof re?.status=="string"?re.status:"",betaAccess:re?.betaAccess===!0})).filter(re=>re.id&&re.name):[];return ye(ot),ue.current=!0,G!=="local"&&typeof St?.currentWorkspaceId=="string"&&St.currentWorkspaceId.trim().length>0&&je(St.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),Ut("bootstrap_workspaces_loaded",{durationMs:Math.max(0,Math.round(Nn()-tt)),workspaceId:We.workspaceId,count:ot.length,status:Ze.status}),{success:!0,workspaces:ot}}catch(Ze){return d(Ze)&&v("Startup checks timed out."),ye([]),ue.current=!1,Ut("bootstrap_workspaces_failed",{durationMs:Math.max(0,Math.round(Nn()-tt)),workspaceId:We.workspaceId,error:Ze instanceof Error?Ze.message:String(Ze)}),{success:!1,error:i(Ze)?"Workspace list request aborted.":"Failed to load workspaces."}}finally{j.current===Oe&&(j.current=null)}},[je,m,s,i,d,c,v,G,ye,j,ue,be]),it=r.useCallback(async()=>{const We=s(),tt=Nn(),Oe=new AbortController;H.current=Oe,Z(!1);try{const[Ze,St]=await Promise.all([m("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},zu(G),{signal:Oe.signal}),ce&&me?m("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},zu(G),{signal:Oe.signal}).catch(()=>null):Promise.resolve(null)]);if(o(We))return{success:!1,error:"Workspace changed while loading assignee options."};if(Ze.status===401)return Ee(gi()),Z(!0),{success:!1,error:"Authentication required."};const ot=await Ze.json().catch(()=>({}));if(o(We))return{success:!1,error:"Workspace changed while loading assignee options."};if(!Ze.ok)return Ee(gi()),Z(!0),{success:!1,error:ot?.error||`Failed to load assignee options (${Ze.status})`};const re=String(Te||"").trim(),Be=String(Me||"").trim(),At=(E,l)=>{const J=typeof E?.avatarUrl=="string"&&E.avatarUrl.trim().length>0?E.avatarUrl.trim():"";if(J)return J;const Se=String(E?.userId||l||"").trim();return re&&Se===re&&Be?Be:null},Rt=Array.isArray(ot?.assignees)?ot.assignees:[],Bt=Rt.map(E=>{const l=String(E?.value||"").trim(),J=String(E?.kind||"").trim().toLowerCase();return l?J==="agent"||J==="ai"?{value:l,label:String(E?.label||l).trim()||l,icon:String(E?.icon||"Bot"),color:String(E?.color||"#8b5cf6"),kind:"agent",avatarUrl:typeof E?.avatarUrl=="string"&&E.avatarUrl.trim().length>0?E.avatarUrl.trim():null,avatarRevision:Number.isFinite(Number(E?.avatarRevision))?Math.max(0,Math.floor(Number(E.avatarRevision))):null,avatarUpdatedAt:typeof E?.avatarUpdatedAt=="string"&&E.avatarUpdatedAt.trim().length>0?E.avatarUpdatedAt.trim():null,username:typeof E?.username=="string"&&E.username.trim().length>0?E.username.trim():null,archivedAt:typeof E?.archivedAt=="string"&&E.archivedAt.trim().length>0?E.archivedAt.trim():null,createdAt:typeof E?.createdAt=="string"&&E.createdAt.trim().length>0?E.createdAt.trim():null,updatedAt:typeof E?.updatedAt=="string"&&E.updatedAt.trim().length>0?E.updatedAt.trim():null}:J==="member"||J==="human"?{value:l,label:String(E?.label||l).trim()||l,icon:String(E?.icon||"User"),color:String(E?.color||"#22c55e"),kind:"member",avatarUrl:At(E,l)}:null:null}).filter(Boolean),Ve=Rt.map(E=>({userId:String(E?.userId||"").trim(),email:String(E?.email||"").trim().toLowerCase(),displayName:typeof E?.displayName=="string"?E.displayName:null,avatarUrl:At(E)})).filter(E=>E.userId);let Ot=Ve;if(St?.ok){const E=await St.json().catch(()=>({})),l=Array.isArray(E?.users)?E.users:[],J=l.find(Ke=>String(Ke?.userId||"").trim()===re),Se=String(J?.role||"").trim().toLowerCase();Se==="owner"||Se==="admin"||Se==="member"||Se==="read-only"?Pe(Se):!be&&l.length===0&&Pe(null);const Ie=l.map(Ke=>({userId:String(Ke?.userId||"").trim(),email:String(Ke?.email||"").trim().toLowerCase(),displayName:typeof Ke?.displayName=="string"?Ke.displayName:null,avatarUrl:At(Ke)})).filter(Ke=>Ke.userId);Ot=Array.from(new Map([...Ve,...Ie].map(Ke=>[Ke.userId,Ke])).values())}else!be&&!Ve.length&&Pe(null);const yt=_d([...Bt,...uS(Ot).filter(E=>E.kind==="member")]);return o(We)?{success:!1,error:"Workspace changed while loading assignee options."}:(Ee(yt),Z(!0),Ut("bootstrap_assignee_options_loaded",{durationMs:Math.max(0,Math.round(Nn()-tt)),workspaceId:We.workspaceId,count:yt.length}),{success:!0})}catch(Ze){return o(We)||(Ee(gi()),Z(!0)),Ut("bootstrap_assignee_options_failed",{durationMs:Math.max(0,Math.round(Nn()-tt)),workspaceId:We.workspaceId,error:Ze instanceof Error?Ze.message:String(Ze)}),{success:!1,error:i(Ze)?"Assignee options request aborted.":"Failed to load assignee options."}}finally{H.current===Oe&&(H.current=null)}},[H,ce,Me,Te,m,s,i,me,o,G,Ee,Z,Pe,be]),Mt=r.useCallback(async(We,tt)=>{if(!be)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const Oe=String(We||"").trim();if(!Oe)return{success:!1,error:"workspaceId is required."};const Ze=String(C.current||"").trim()||"default",St=Nn();try{Ut("bootstrap_workspace_switch_started",{fromWorkspaceId:Ze,toWorkspaceId:Oe,hydrate:tt?.hydrate!==!1});const ot=await fetch("/api/taskforce/session/workspace",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Oe})}),re=await ot.json().catch(()=>({}));if(!ot.ok||re?.success===!1)return{success:!1,error:re?.error||`Failed to switch workspace (${ot.status})`,code:re?.code};x(Oe,{clearExplicitSelection:!1}),B(),Y(!0),g("workspace");const Be=await fe({force:!0});return tt?.hydrate===!1?await ft():(te.current=`${G}:${Oe}:${R}`,Le.current=`${G}:${Be?"auth":"guest"}:${Oe}`,oe.current=Oe,M&&V==="tasks"&&(L.current=`${Oe}:${V}:${ne?"archive":"active"}:${Ce}`),M&&V==="settings"&&(X.current=`${Oe}:${V}:${Ae}`),await Promise.all([ae(),ft(),kt({isSilent:!1}),Ye()]),st({ignoreAuthGuard:!0})),Ut("bootstrap_workspace_switch_completed",{fromWorkspaceId:Ze,toWorkspaceId:Oe,hydrate:tt?.hydrate!==!1,durationMs:Math.max(0,Math.round(Nn()-St))}),{success:!0}}catch(ot){return Ut("bootstrap_workspace_switch_failed",{fromWorkspaceId:Ze,toWorkspaceId:Oe,hydrate:tt?.hydrate!==!1,durationMs:Math.max(0,Math.round(Nn()-St)),error:ot instanceof Error?ot.message:String(ot)}),{success:!1,error:"Failed to switch workspace."}}finally{Y(!1)}},[B,V,fe,x,C,ae,st,ft,M,Le,te,X,L,oe,Ye,g,kt,G,Ae,Y,ne,Ce,R,be]),ht=r.useCallback(async We=>{g("workspace"),Y(!0);try{if(!be){const At=String(b||"").trim()||"default";return x(At),{success:!0,workspaceSetupRequired:!1,workspaceId:At}}const tt=String(We?.preferredWorkspaceId||"").trim(),Oe=zp(R),Ze=await ft();if(!Ze.success)return{success:!1,workspaceSetupRequired:!1,error:Ze.error||"Failed to load workspaces after authentication."};const St=Array.isArray(Ze.workspaces)?Ze.workspaces:[];if(St.length===0)return x("default"),{success:!0,workspaceSetupRequired:!0};const ot=new Set(St.map(At=>String(At.id||"").trim()).filter(Boolean)),re=String(C.current||"").trim(),Be=(tt&&ot.has(tt)?tt:"")||(re&&ot.has(re)?re:"")||(Oe&&ot.has(Oe)?Oe:"")||String(St[0]?.id||"").trim();if(!Be)return x("default"),{success:!0,workspaceSetupRequired:!0};if(re!==Be){const At=await Mt(Be,{hydrate:!1});if(!At.success)return{success:!1,workspaceSetupRequired:!1,error:At.error||"Failed to set workspace after authentication.",code:At.code}}else x(Be);return{success:!0,workspaceSetupRequired:!1,workspaceId:Be}}catch{return v("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{Y(!1)}},[x,b,C,ft,g,v,Y,Mt,R,be]),Ft=r.useCallback(async()=>{g("auth");const We=Nn();Ut("bootstrap_retry_started",{workspaceId:String(C.current||"default").trim()||"default"});const tt=await fe({force:!0});let Oe=!1;if(be&&tt){const Ze=await ht();if(!Ze.success||Ze.workspaceSetupRequired){await ae({ignoreAuthGuard:!0}),Ut("bootstrap_retry_completed",{workspaceId:String(C.current||"default").trim()||"default",authenticated:tt,workspaceSetupRequired:Ze.workspaceSetupRequired===!0,success:Ze.success,durationMs:Math.max(0,Math.round(Nn()-We))});return}}Y(!0);try{await ae({ignoreAuthGuard:!0}),tt&&!Oe&&(await Promise.all([$e(!0,{ignoreAuthGuard:!0}),Qe({ignoreAuthGuard:!0,force:!0})]),st({ignoreAuthGuard:!0})),Ut("bootstrap_retry_completed",{workspaceId:String(C.current||"default").trim()||"default",authenticated:tt,workspaceSetupRequired:Oe,success:!0,durationMs:Math.max(0,Math.round(Nn()-We))})}finally{Y(!1)}},[fe,C,ae,st,Qe,$e,g,ht,Y,be]),Et=r.useCallback(async We=>{const tt=We?.reason||"initial-load",Oe=We?.ignoreAuthGuard===!0,Ze=We?.tasksSilent!==!1,St=We?.includeDeferredArchive!==!1,ot=Nn();if(g("auth"),!await fe({force:!0}))return await ae({ignoreAuthGuard:!0}),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(Nn()-ot)),authenticated:!1,workspaceSetupRequired:!1,success:!1}),{success:!1,authenticated:!1,workspaceSetupRequired:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};if(be){const Be=await ht();if(!Be.success)return await ae({ignoreAuthGuard:!0}),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(Nn()-ot)),authenticated:!0,workspaceSetupRequired:!1,success:!1,error:Be.error||"Workspace resolution failed."}),{success:!1,authenticated:!0,workspaceSetupRequired:!1,error:Be.error||"Unable to resolve workspace access.",code:Be.code};if(Be.workspaceSetupRequired)return await ae({ignoreAuthGuard:!0}),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(Nn()-ot)),authenticated:!0,workspaceSetupRequired:!0,success:!0}),{success:!0,authenticated:!0,workspaceSetupRequired:!0}}Y(!0);try{await Tt({ignoreAuthGuard:Oe});const Be=String(C.current||"default").trim()||"default",At=Nn();return $e(Ze,{ignoreAuthGuard:Oe}).then(()=>{Ut("cloud_bootstrap_tasks_loaded_deferred",{reason:tt,workspaceId:Be,durationMs:Math.max(0,Math.round(Nn()-At))})}).catch(Rt=>{Ut("cloud_bootstrap_tasks_deferred_failed",{reason:tt,workspaceId:Be,error:Rt instanceof Error?Rt.message:String(Rt)})}),Qe({ignoreAuthGuard:Oe}).then(()=>{Ut("cloud_bootstrap_reference_data_loaded_deferred",{reason:tt,workspaceId:Be,durationMs:Math.max(0,Math.round(Nn()-At))})}).catch(Rt=>{Ut("cloud_bootstrap_reference_data_deferred_failed",{reason:tt,workspaceId:Be,error:Rt instanceof Error?Rt.message:String(Rt)})}),st({ignoreAuthGuard:Oe}),St&&Ge(),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(Nn()-ot)),authenticated:!0,workspaceSetupRequired:!1,success:!0,workspaceId:Be}),{success:!0,authenticated:!0,workspaceSetupRequired:!1}}finally{Y(!1)}},[fe,C,Tt,st,Qe,$e,g,ht,Ge,Y,be]);return r.useEffect(()=>{!t&&!a&&!dt.current&&(dt.current=!0,(async()=>{const We=Nn();if(G==="cloud"&&ce&&me){const tt=await Et({reason:"initial-load",tasksSilent:!1,includeDeferredArchive:!0});if(!tt.success||tt.workspaceSetupRequired)return}else await Promise.all([Tt(),$e(!1),Qe()]),st();G!=="cloud"&&Ge(),Ut("bootstrap_initial_load_completed",{durationMs:Math.max(0,Math.round(Nn()-We)),runtimeMode:G,workspaceId:String(C.current||"default").trim()||"default"})})())},[ce,C,Tt,st,Qe,$e,dt,me,Et,G,Ge,a,t]),r.useEffect(()=>{if(t||a||Re||R==="bootstrap"||!dt.current)return;const We=`${G}:${b}:${R}`;te.current!==We&&(te.current=We,ae())},[b,ae,dt,te,G,a,t,Re,R]),r.useEffect(()=>{if(t||a||Re)return;const We=b;oe.current!==We&&(oe.current=We,Ye())},[b,oe,Ye,a,t,Re]),r.useEffect(()=>{if(G!=="cloud"||!ce||!me){G!=="cloud"&&ye([]),ue.current=!1;return}Re||!dt.current||ue.current||ft()},[ce,ft,dt,me,G,ye,Re,ue]),{fetchReferenceData:Qe,fetchBootstrapConfig:Tt,fetchConfig:ae,fetchWorkspaces:ft,fetchAssigneeOptions:it,switchWorkspace:Mt,resolveWorkspaceAfterAuth:ht,retryBootstrapChecks:Ft,runCloudBootstrap:Et}}function $b({isOpen:e,authBlocked:t,authRequiredForApi:a,isAuthenticated:s,canCallProtectedApi:o,shouldGateProtectedApiCalls:c,authSessionResolvedRef:i,authRequiredForApiRef:d,isAuthenticatedRef:m,dataVersionRef:y,refreshTaskCollectionsForDataVersion:k}){r.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||Lb({isOpen:e,authBlocked:t,authRequiredForApi:a,isAuthenticated:s,canCallProtectedApi:o}))return;let S=!1;const h=async()=>{if(!(S||document.visibilityState!=="visible")&&!Bb({shouldGateProtectedApiCalls:c,authSessionResolved:i.current,authRequiredForApi:d.current,isAuthenticated:m.current}))try{const _=await fetch("/api/taskforce/data-version");if(!_.ok)return;const I=await _.json(),A=Number(I?.dataVersion);if(!Number.isFinite(A))return;if(y.current===null){y.current=A;return}A!==y.current&&(y.current=A,await k())}catch{}},g=()=>{document.visibilityState==="visible"&&h()},v=window.setInterval(()=>{h()},3e3);return document.addEventListener("visibilitychange",g),h(),()=>{S=!0,window.clearInterval(v),document.removeEventListener("visibilitychange",g)}},[e,t,a,s,o,c,i,d,m,y,k])}const Ub={};function mi(e,t){const a=e.findIndex(s=>s.id===t.id);return a===-1?[...e,t]:e.map((s,o)=>o===a?t:s)}const xo=yf(Ub),Ap=(()=>{const e=xo.baseUrl,t=xo.cloudAuthBaseUrl;if(t)return t;const a=xo.apiBaseUrl;return a||e||"https://app.taskforcehq.ai"})(),Hu=2e4,zb=new Set(["external-abort","superseded","workspace-reset","workspace-transition"]);function em(e){return typeof DOMException<"u"&&e instanceof DOMException?e.name==="AbortError":String(e?.name||"").toLowerCase()==="aborterror"}function Qp(e){return typeof e=="string"&&zb.has(e)}function xp(e,t){return t.aborted?e===t.reason||Qp(e)||Qp(t.reason)?!0:em(e):!1}function jh(e){const t=new Error(`Startup checks timed out after ${e}ms.`);return t.name="BootstrapTimeoutError",t}function Ph(e){const t=e&&typeof e=="object"?e:{},a=Array.isArray(t.initiatives)?t.initiatives.filter(c=>!!(c&&typeof c=="object"&&typeof c.id=="string")):[],s=Array.isArray(t.workstreams)?t.workstreams.filter(c=>!!(c&&typeof c=="object"&&typeof c.id=="string")):[],o=Array.isArray(t.workstreamTaskSummaries)?t.workstreamTaskSummaries.flatMap(c=>{if(!c||typeof c!="object")return[];const i=String(c.workstreamId||"").trim();if(!i)return[];const d=Array.isArray(c.tasks)?c.tasks:[],m=Math.max(0,Number(c.taskCount)||0),y=Math.max(0,Number(c.completedTaskCount)||0);return[{workstreamId:i,taskCount:m,completedTaskCount:y,tasks:d.filter(k=>!!(k&&typeof k=="object"&&typeof k.id=="string")).map(k=>({id:String(k.id||"").trim(),referenceNumber:typeof k.referenceNumber=="number"?k.referenceNumber:null,title:String(k.title||"").trim()||"Untitled Task",status:typeof k.status=="string"?k.status:null}))}]}):[];return{initiatives:a,workstreams:s,workstreamTaskSummaries:o}}function Hb({config:e={},initialTaskId:t,onTaskCountChange:a,onClose:s}){const o={...Iv,...e},{categories:c,types:i,apiEndpoint:d,apiBaseUrl:m,cloudAuthBaseUrl:y,cloudMcpBaseUrl:k,wsBaseUrl:S,shortcut:h}=o,g=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",v=g==="localhost"||g==="127.0.0.1"||g==="::1",_=typeof window<"u"&&!v,[I,A]=r.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[D,U]=r.useState(!1),W=r.useCallback(p=>typeof p=="string"?p.trim().replace(/\/+$/,""):"",[]);r.useEffect(()=>{if(typeof window>"u"){U(!0);return}let p=!1;return(async()=>{try{const O=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!O.ok)return;const z=await O.json().catch(()=>({})),q=z?.config&&typeof z.config=="object"?z.config:{};if(p)return;const De=String(q.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",Ue=String(q.workspaceMode||"").trim(),en=Ue==="single-local"||Ue==="multi-cloud"?Ue:De==="cloud"?"multi-cloud":"single-local";R(De),A({cloudEnvironment:typeof q.cloudEnvironment=="string"?String(q.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:W(q.cloudBaseUrl),cloudMcpBaseUrl:W(q.cloudMcpBaseUrl),baseUrl:W(q.baseUrl),apiBaseUrl:W(q.apiBaseUrl),cloudAuthBaseUrl:W(q.cloudAuthBaseUrl),wsBaseUrl:W(q.wsBaseUrl),cloudAuthViaLocalProxy:!!q.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:en,workspaceSwitchingEnabled:typeof q.workspaceSwitchingEnabled=="boolean"?!!q.workspaceSwitchingEnabled:en==="multi-cloud"})}catch{}finally{p||U(!0)}})(),()=>{p=!0}},[W]);const Q=typeof window>"u"?"":v?Ap:"",le=W(xo.baseUrl),ie=W(xo.apiBaseUrl),se=W(xo.cloudBaseUrl),$=W(xo.cloudMcpBaseUrl),C=W(xo.cloudAuthBaseUrl),de=W(xo.wsBaseUrl),ke=W(m),K=W(y),j=W(k),H=I.apiBaseUrl||I.baseUrl,ye=ke||H||(v?"":ie||le)||"",G=K||C||le,je=I.cloudAuthBaseUrl||I.baseUrl,ce=((v?je||G:G||je)||ye||Q).trim().replace(/\/+$/,""),me=W(aS(I.cloudMcpBaseUrl||I.cloudAuthBaseUrl||I.cloudBaseUrl||j||K||$||C||se||ce)),Te=(I.cloudMcpBaseUrl||j||me||I.cloudBaseUrl||$||se||ce||Q).trim().replace(/\/+$/,""),Me=!_&&!!ce&&!ye,Pe=_||D&&!!(ce||ye),Ee=Pe&&!Me,Z=!!(ce||ye||_),x=_?"cloud":"local",[b,R]=r.useState(()=>x),B=x==="local"&&v&&Z?Sf():"",Y=B.length>0,fe=r.useCallback(p=>!p||/^https?:\/\//i.test(p)||!ye||!p.startsWith("/")?p:`${ye}${p}`,[ye]),te=r.useCallback(p=>{if(!p||/^https?:\/\//i.test(p)||!p.startsWith("/"))return p;const O=p.startsWith("/api/taskforce/auth/")||p.startsWith("/api/taskforce/account/")||p.startsWith("/api/taskforce/billing/")||p.startsWith("/api/taskforce/sync/")||p.startsWith("/api/taskforce/settings/mcp/");if(!_&&O&&(b==="cloud"||!D||I.cloudAuthViaLocalProxy||I.workspaceMode==="multi-cloud"))return p;const z=ce||ye;if(z){const q=`${z}${p}`;if(typeof window<"u"&&!_&&O)try{if(new URL(q,window.location.origin).origin===window.location.origin)return`${Ap}${p}`}catch{return`${Ap}${p}`}return q}return p},[D,I.cloudAuthViaLocalProxy,I.workspaceMode,ce,ye,_,b]),Le=r.useCallback(p=>{const O=String(p||"").trim()||"/taskforce-ws",z=O.startsWith("/")?O:`/${O}`,q=String(S||I.wsBaseUrl||de||ye||"").trim().replace(/\/+$/,""),Fe=typeof window<"u"?window.location.origin:"",De=q||Fe;if(!De)return"";try{const Ue=new URL(z,De);return Ue.protocol==="https:"&&(Ue.protocol="wss:"),Ue.protocol==="http:"&&(Ue.protocol="ws:"),Ue.toString()}catch{return""}},[S,I.wsBaseUrl,de,ye]),[oe,L]=r.useState("tasks"),[X,M]=r.useState(!1),[V,ne]=r.useState(!1),[Ce,Ae]=r.useState("open"),[Re,$e]=r.useState(Yc(o.theme)||im),[vt,st]=r.useState(Yc(o.theme)||im),[kt,Ye]=r.useState(!0),[Ct]=r.useState(".taskforce"),dt=!1,[Qe,Tt]=r.useState(!1),[ae,Ge]=r.useState([]),[ft,it]=r.useState([]),[Mt,ht]=r.useState(""),[Ft,Et]=r.useState(null),[We,tt]=r.useState(null),[Oe,Ze]=r.useState(""),[St,ot]=r.useState(""),re=r.useMemo(()=>Yv({projectRoot:Oe,runtimeMode:x}),[Oe,x]),[Be,At]=r.useState(""),[Rt,Bt]=r.useState(""),Ve=eS(b),Ot=I.workspaceMode==="single-local"||I.workspaceMode==="multi-cloud"?I.workspaceMode:Ve.workspaceMode,yt=typeof I.workspaceSwitchingEnabled=="boolean"?I.workspaceSwitchingEnabled:Ve.workspaceSwitchingEnabled,[E,l]=r.useState(!1),[J,Se]=r.useState(!1),[Ie,Ke]=r.useState(Y),[Je,Ne]=r.useState(Y?B:"anonymous"),[zt,Yt]=r.useState(""),[Pt,Wt]=r.useState(""),[Dt,Ht]=r.useState(""),[sn,Vt]=r.useState([]),[Vn,qn]=r.useState(""),[Kn,ga]=r.useState(!0),[ge,at]=r.useState(null),[xe,jt]=r.useState(()=>{if(x==="local")return"default";const p=zp(re);return p&&p.toLowerCase()!=="default"?p:"default"}),pt=r.useMemo(()=>Jv({projectRoot:Oe,runtimeMode:b,workspaceId:xe}),[Oe,b,xe]),[bt,An]=r.useState([]),[vn,dn]=r.useState(()=>gi()),[un,Bn]=r.useState(!1),[gt,cr]=r.useState(Y),[fn,nn]=r.useState("idle"),[bn,Kt]=r.useState(null),[_r,Pn]=r.useState(null),aa=r.useRef(null),Mn=r.useRef(0),Zt=r.useRef(0),Zn=r.useRef(Y),an=r.useRef(xe),ra=r.useRef(null),Ea=r.useRef(null),Da=r.useRef(0),hn=r.useRef((typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`).replace(/[^A-Za-z0-9_-]+/g,"").slice(0,12)||"session"),[Va,os]=r.useState(0),qa=r.useRef(null),Ca=r.useRef(null),Wn=r.useRef(null),Vr=r.useRef(null),Aa=r.useRef(null),sa=r.useRef(null),la=r.useRef(null),Fn=r.useCallback((p,O)=>{const z=String(p||"").trim();if(!z)return;const q=String(an.current||"").trim();q&&q!==z&&(Da.current+=1,os(Da.current)),an.current=z,O?.clearExplicitSelection!==!1&&(Ea.current=null),jt(z)},[]);r.useEffect(()=>{an.current=xe},[xe]);const Nt=r.useCallback(p=>{const O=String(p||"").trim();O&&jt(()=>{const z=String(Ea.current||"").trim();let q=O;return z&&z!==O&&(q=z),an.current=q,q})},[]),ya=r.useCallback(()=>({workspaceId:String(an.current||"default").trim()||"default",epoch:Da.current}),[]),On=r.useCallback(p=>(String(an.current||"default").trim()||"default")!==p.workspaceId||Da.current!==p.epoch,[]),lr=r.useCallback(p=>Da.current!==p.epoch,[]),$n=r.useCallback(p=>em(p)||Qp(p),[]),La=r.useCallback(()=>{[qa,Ca,Wn,Vr,Aa,sa].forEach(p=>{p.current?.abort("workspace-transition"),p.current=null}),la.current!==null&&typeof window<"u"&&(window.clearTimeout(la.current),la.current=null),Ei.current=null},[]),xa=r.useMemo(()=>Db({shouldGateProtectedApiCalls:Ee,runtimeMode:b,authSessionResolved:gt,authRequiredForApi:E,isAuthenticated:Ie}),[Ee,b,gt,E,Ie]),Sn=xa.shouldDeferProtectedApiCalls,Dn=xa.shouldBlockProtectedApiCalls,[Ba,gn]=r.useState(null),[Jt,Ka]=r.useState(null),[xn,En]=r.useState(!1),[Za,In]=r.useState("unknown"),[Mr,cn]=r.useState(null),[mn,ka]=r.useState(o.shortcut||"Alt+T"),[Yn,Cr]=r.useState(o.priorities||[]),[Er]=r.useState(Mg()),[Xt,Ia]=r.useState(""),[Wa,dr]=r.useState(!1),[Ar,Ya]=r.useState(!1),[Ja,xr]=r.useState(!0),[Jn,Ta]=r.useState(()=>qv()),ur=r.useMemo(()=>Vv(),[]),[oa,qr]=r.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[ia,Dr]=r.useState(!1),[Kr,va]=r.useState(!0),[Ir,Ra]=r.useState(!0),[Sa,Fa]=r.useState(""),[Zr,Ds]=r.useState(null);jb({currentWorkspaceIdRef:an,resolveApiUrl:fe,runtimeMode:b});const{availableWorkflows:et,initiativeTemplates:$t,fetchWorkflows:Tn,fetchInitiativeTemplates:_n,fetchWorkflowTemplate:wn,fetchWorkflowOverrideNames:Na,saveWorkflowTemplateDraft:Qa,resetWorkflowTemplateDraft:ys}=ab({shouldDeferProtectedApiCalls:Sn,shouldBlockProtectedApiCalls:Dn}),{zenMode:wa,setZenModeState:Oa,toggleZenMode:mr}=rb(),{exportEnvironment:Gt,setExportEnvironment:ja,availableEnvironments:da,loadAvailableEnvironments:Un,exportWorkflowsPath:Lr,setExportWorkflowsPath:Br,exportingResource:pr,exportResult:fr,handleExportWorkflows:ks}=Xw({storagePath:Ct,shouldDeferProtectedApiCalls:Sn,shouldBlockProtectedApiCalls:Dn}),[ba,ua]=r.useState(!1),[no,vs]=r.useState(null),{uiNotice:hr,pushNotice:F,clearNotice:He}=Qw(),[xt,Lt]=r.useState([]),Rn=r.useRef(null),[Tr,Wr]=r.useState(0),ao=r.useCallback(p=>!p||!Oe?p:p.startsWith(Oe)?p.slice(Oe.length).replace(/^[/\\]+/,""):p,[Oe]),[Qn,ma]=r.useState([]),[T,N]=r.useState([]),[rt,wt]=r.useState([]),[we,ee]=r.useState([]),[gr,Pa]=r.useState([]),[$a,Rr]=r.useState([]),[jo,Xa]=r.useState(!1),[er,ro]=r.useState(null),[Po,Mo]=r.useState(!1),[so,ic]=r.useState([]),[Xn,cc]=r.useState(!1),[oo,lc]=r.useState({}),Fr=r.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});r.useEffect(()=>{Fr.current={authSessionResolved:gt,configLoaded:Xn,workspaceBootstrapPending:un}},[gt,Xn,un]);const Eo=r.useCallback(p=>{nn(p),p!=="ready"&&(Kt(null),Pn(Date.now()))},[]),Ss=r.useCallback(p=>{const O=Fr.current;O.authSessionResolved&&O.configLoaded&&!O.workspaceBootstrapPending||(nn("stalled"),Kt(p),Pn(z=>z??Date.now()))},[]),Do=r.useCallback(async(p,O,z=dd,q)=>{const Fe=new AbortController,De=q?.signal,Ue=Number(z)>0?Number(z):dd,en=ya(),rn=p.startsWith("/api/taskforce/")?Sp(O,ch({workspaceId:en.workspaceId,epoch:en.epoch,seed:hn.current})):O,Ln=typeof window<"u"?window.setTimeout(()=>Fe.abort("bootstrap-timeout"),Ue):null,fa=()=>{Fe.abort(De?.reason||"external-abort")};De&&(De.aborted?fa():De.addEventListener("abort",fa,{once:!0}));try{return await fetch(p,{...rn||{},signal:Fe.signal})}catch(sr){throw De?.aborted&&xp(sr,De)?De.reason||sr:em(sr)||sr==="bootstrap-timeout"?jh(Ue):sr}finally{De&&De.removeEventListener("abort",fa),Ln!==null&&typeof window<"u"&&window.clearTimeout(Ln)}},[ya]),Ls=r.useMemo(()=>{const p=!gt,O=fn==="stalled",z=gt&&(!Xn||un||O);let q="Checking account, workspace access, and setup status...";return fn==="auth"?q="Verifying session...":fn==="workspace"?q="Resolving workspace access...":fn==="config"&&(q="Loading configuration..."),{phase:fn,auth:{resolved:gt,pending:p},config:{loaded:Xn},workspace:{pending:un},pending:p||z,authPending:p,appPending:z,ready:gt&&Xn&&!un&&fn==="ready",stalled:O,subtitle:q,error:bn,startedAt:_r}},[gt,bn,fn,_r,Xn,un]),io=r.useCallback(p=>String(p?.name||"")==="BootstrapTimeoutError",[]),[Yr,yi]=r.useState([]),[ws,Lo]=r.useState({}),[Nr,co]=r.useState(o.taxonomies||[]),yn=r.useMemo(()=>(so.length>0?so:c||[]).map(O=>typeof O=="string"?{value:O.toLowerCase().replace(/\s+/g,"-"),label:O}:O).sort((O,z)=>O.label.localeCompare(z.label)),[so,c]),Bs=r.useMemo(()=>({categories:yn,types:Yr,priorities:Yn,taxonomies:Nr,displayLabels:ws}),[yn,Yr,Yn,Nr,ws]);r.useMemo(()=>yn.filter(p=>!p.disabled),[yn]);const pn=r.useCallback(p=>p.find(z=>z.value==="default"||z.value==="general"||z.label==="General"||z.value==="Taskforce"||z.label==="Taskforce")?.value||p[0]?.value||"default",[]),ea=Yr.length>0?Yr:i,[Jr,lo]=r.useState(!1),[il,Qr]=r.useState(""),is="Authentication required. Sign in to continue.",[yr,bs]=r.useState(!1),[pa,Bo]=r.useState(!1),kr=r.useCallback(()=>{Se(b==="cloud"),Ke(!1),Wt(""),Ht(""),qn(""),Qr(is)},[is,b]),{recentlyChangedTaskIds:Wo,fetchTasks:Ws,fetchArchive:Fo,refreshTaskCollections:Fs,refreshTaskCollectionsFromInvalidation:Oo,mergeTaskFromServer:_s}=ob({tasks:Qn,archivedTasks:T,setTasks:ma,setArchivedTasks:N,setLoadingTasks:Xa,getCurrentWorkspaceId:()=>an.current,workspaceResetKey:`${xe}:${Va}`,shouldDeferProtectedApiCalls:Sn,shouldBlockProtectedApiCalls:Dn,handleUnauthorized:kr,authRequiredForApi:E});r.useEffect(()=>{Va!==0&&(Ei.current=null,ei.current="",vo.current="",xc.current="",ti.current="",ni.current="",So.current="",Rc(!1),bs(!1),dn(gi()),Bo(!1),Rr([]),ma([]),N([]),Xa(!1),jr.current!==null&&typeof window<"u"&&(window.clearTimeout(jr.current),jr.current=null),ta.current!==null&&typeof window<"u"&&(window.clearTimeout(ta.current),ta.current=null))},[N,Xa,ma,Va]);const cs=r.useCallback(async(p=!1,O)=>{if(!(O?.ignoreAuthGuard===!0)&&(Sn||Dn))return;p||Xa(!0);const q=ya(),Fe=new AbortController;Aa.current=Fe;try{let De=await fetch("/api/taskforce/deleted",{signal:Fe.signal});if(De.status===404&&(De=await fetch("/api/taskforce/trash",{signal:Fe.signal})),De.status===401){kr(),Rr([]);return}if(De.status===404){Rr([]);return}if(De.ok){const Ue=await De.json();if(On(q))return;const en=Array.isArray(Ue?.deleted)?Ue.deleted.map(rn=>{const Ln=rn?.taskSnapshot&&typeof rn.taskSnapshot=="object"?No(rn.taskSnapshot):null;return Ln?{...rn,taskSnapshot:Ln}:null}).filter(rn=>!!rn):[];Rr(en)}}catch(De){if(xp(De,Fe.signal)||$n(De))return;console.error("[Taskforce] Failed to fetch deleted tasks:",De)}finally{Aa.current===Fe&&(Aa.current=null),p||Xa(!1)}},[ya,kr,$n,On,Sn,Dn]),ln=r.useCallback(async p=>{if(!(p?.ignoreAuthGuard===!0)&&(Sn||Dn))return;const z=ya();sa.current?.abort("superseded"),la.current!==null&&typeof window<"u"&&(window.clearTimeout(la.current),la.current=null);const q=new AbortController;sa.current=q;try{const Fe=ch({workspaceId:z.workspaceId,epoch:z.epoch,seed:hn.current}),De=async rn=>{if(typeof window>"u")return fetch(rn,Sp({signal:q.signal},Fe));const Ln=new AbortController,fa=window.setTimeout(()=>Ln.abort("planning-timeout"),Hu),sr=()=>Ln.abort(q.signal.reason||"external-abort");q.signal.aborted?sr():q.signal.addEventListener("abort",sr,{once:!0});try{return await fetch(rn,Sp({signal:Ln.signal},Fe))}catch(Pr){if(q.signal.aborted)throw q.signal.reason||Pr;if(em(Pr)||Pr==="planning-timeout")return null;throw Pr}finally{window.clearTimeout(fa),q.signal.removeEventListener("abort",sr)}};let Ue=null;const en=await De("/api/taskforce/planning/bootstrap");if(en?.status===401){kr(),wt([]),ee([]),Pa([]);return}if(en===null)throw jh(Hu);if(en.ok)Ue=Ph(await en.json().catch(()=>({})));else{const[rn,Ln]=await Promise.all([De("/api/taskforce/initiatives"),De("/api/taskforce/workstreams")]);if(!rn||!Ln)throw new Error("Planning endpoints timed out during startup.");if(rn.status===401||Ln.status===401){kr(),wt([]),ee([]),Pa([]);return}const[fa,sr]=await Promise.all([rn.ok?rn.json().catch(()=>[]):[],Ln.ok?Ln.json().catch(()=>[]):[]]);Ue=Ph({initiatives:fa,workstreams:sr,workstreamTaskSummaries:[]})}if(On(z))return;wt(Ue.initiatives),ee(Ue.workstreams),Pa(Ue.workstreamTaskSummaries)}catch(Fe){if(xp(Fe,q.signal)||$n(Fe))return;io(Fe)?(Ut("planning_bootstrap_timeout",{workspaceId:z.workspaceId,epoch:z.epoch,timeoutMs:Hu}),console.warn("[Taskforce] Planning bootstrap timed out during startup; retrying in background.")):console.error("[Taskforce] Failed to fetch planning entities:",Fe),typeof window<"u"&&!On(z)&&rt.length===0&&we.length===0&&(la.current=window.setTimeout(()=>{la.current=null,ln(p)},3e3))}finally{sa.current===q&&(sa.current=null)}},[dd,Hu,rt.length,ya,kr,$n,On,Sn,Dn,we.length]),zn=r.useCallback(async(p=!1,O)=>{await Ws(p,O)},[Ws]),tr=r.useCallback(async(p=!1,O)=>{await Fo(p,O)},[Fo]),cl=r.useCallback(async p=>{const O=p?.isSilent!==!1,z=p?.ignoreAuthGuard===!0;await Promise.all([Fs({isSilent:O,ignoreAuthGuard:z}),cs(O,{ignoreAuthGuard:z}),ln({ignoreAuthGuard:z})])},[cs,ln,Fs]),Xr=r.useCallback(async()=>{await Oo(),await cs(!0),await ln()},[cs,ln,Oo]),dc=r.useRef(()=>{}),ll=r.useRef(()=>{}),ki=r.useRef(async()=>!1),Hn=r.useCallback(p=>ki.current(p),[]),{userGlobalSyncStatus:vi,setUserGlobalSyncStatus:Os,userGlobalSyncError:Si,setUserGlobalSyncError:Rd,workspaceLastPullAt:dl,workspaceLastPushAt:Em,workspaceLastErrorAt:ul,workspaceLastErrorMessage:nr,workspaceLastSuccessfulSyncAt:uo,workspaceCloudSyncEnabled:ls,workspaceSyncPhase:wi,workspaceSyncSetupIntent:Dm,workspaceSyncStatus:Nd,workspaceSyncSummary:$o,workspaceSyncRecommendedAction:Lm,workspaceSyncBusy:jd,workspaceSyncPendingChanges:Pd,workspacePendingSignatureRef:$s,workspaceDeletedTaskIdsRef:Md,workspaceDeletedTaskWatermarksRef:ml,loadWorkspaceSyncState:Ed,applyWorkspaceSyncStateSnapshot:pl,syncUserGlobalSettings:uc,buildWorkspaceSyncSignature:Uo,pushWorkspaceChangesToCloud:mo,saveWorkspaceCloudSyncSettings:mc,retryUserGlobalSettingsSync:Us,retryWorkspaceCloudSync:bi,resetWorkspaceSyncCursorAndPull:zo,getWorkspaceSyncDiagnostics:_i}=Yw({currentWorkspaceId:xe,cloudAuthConfigured:Z,runtimeMode:b,authSessionResolved:gt,isAuthenticated:Ie,authUserId:Je,projectName:St,resolveCloudAuthUrl:te,resolveWebSocketUrl:Le,realtimeSyncEnabled:xn,tasks:Qn,archivedTasks:T,deletedTasks:$a,initiatives:rt,workstreams:we,taxonomies:Nr,taxonomyState:yr?Bs:void 0,setupState:Ba,globalTheme:vt,locale:Jn,globalWeekStartsOn:oa,themeUseGlobalDefault:kt,setTasks:ma,setArchivedTasks:N,setAuthBlocked:Se,setIsAuthenticated:Ke,checkAuthSession:Hn,setGlobalTheme:st,setCurrentTheme:$e,setSetupState:gn,setLocale:Ta,setGlobalWeekStartsOn:qr,fetchPlanningEntities:ln}),Ho=r.useCallback((p=ea)=>p.find(O=>String(O.value||"").trim().length>0)?.value||Gr,[ea]),[Or,Cs]=r.useState(()=>pn(yn)),[ds,on]=r.useState(()=>Ho(ea)),[Go,pc]=r.useState(2),[fl,hl]=r.useState(3),[po,gl]=r.useState("task"),[yl,kl]=r.useState("default"),[Ci,Ua]=r.useState("unassigned"),[As,Dd]=r.useState(""),[Ld,ar]=r.useState(""),[Vo,fc]=r.useState(""),[qo,vl]=r.useState(""),[hc,fo]=r.useState(""),[Ai,Bd]=r.useState([]),[gc,Ko]=r.useState([]),[Sl,xi]=r.useState(""),[_t,wl]=r.useState({}),Wd=r.useRef(null),[Zo,yc]=r.useState(!1),[ho,bl]=r.useState("");r.useEffect(()=>{if(er)return;const p=String(ds||"").trim();ea.some(z=>String(z.value||"").trim()===p)||on(Ho(ea))},[ea,er,Ho,ds]);const{searchQuery:_l,setSearchQuery:Fd,filterCategories:vr,setFilterCategories:Gn,filterPriorities:Ii,setFilterPriorities:Cl,filterTypes:Al,setFilterTypes:go,filterStatus:xl,setFilterStatus:Od,filterAssignees:$r,setFilterAssignees:$d,filterAssigneesAllSelected:Il,setFilterAssigneesAllSelected:Ud,filterTaxonomies:Yo,setFilterTaxonomies:yo,hasInitedFilters:Jo,setHasInitedFilters:kc,sortBy:Ti,setSortBy:zd,sortOrder:Tl,setSortOrder:ko,toggleSortOrder:zs,groupBy:za,setGroupBy:Qo,emptyColumnMode:Hs,setEmptyColumnMode:vc,collapsedCategories:Rl,setCollapsedCategories:Bm,clearFilters:Sc,filteredTasks:wc,searchAgnosticTasks:Hd,filteredArchive:Gd,groupedTasks:Nl}=Ab({tasks:Qn,archivedTasks:T,activeCategories:yn,activeTypes:ea,priorities:Yn,taxonomies:Nr,configLoaded:Xn,referenceDataLoaded:yr,assigneeOptionsLoaded:pa,assigneeOptions:vn});dc.current=Os,ll.current=Rd;const{checkAuthSession:Wm}=Eb({runtimeConfigReady:D,shouldProbeCloudAuth:Pe,authSessionResolved:gt,resolveCloudAuthUrl:te,authOnlyCloudMode:Me,authRequiredError:is,runtimeMode:b,workspaceSelectionScope:re,markBootstrapPhase:Eo,markBootstrapStalled:Ss,setRuntimeMode:R,setAuthRequiredForApi:l,setIsAuthenticated:Ke,setAuthUserId:Ne,setAuthWorkspaceId:Yt,setAuthUserEmail:Wt,setAuthUserDisplayName:Ht,setAuthUserAvatarUrl:qn,setUserGlobalSyncStatus:p=>dc.current(p),setUserGlobalSyncError:p=>ll.current(p),setHasBetaAccess:ga,setAvailableWorkspaces:An,setHydratedWorkspaceRole:at,setAssigneeOptions:dn,setAuthBlocked:Se,setAuthSessionResolved:cr,setError:Qr,applyResolvedWorkspaceId:Nt,readPersistedWorkspaceId:zp,authSessionRequestRef:aa,authSessionEpochRef:Mn,authSessionLastCheckedAtRef:Zt,authSessionLastResultRef:Zn,isLoopbackHost:v,setAuthStateReadyRefs:(p,O,z)=>{Pi.current=O,Mi.current=z,Ac.current=p}});ki.current=Wm;const[Ri,jl]=r.useState("tasks"),[Vd,Fm]=r.useState(!1),[Ni,bc]=r.useState(!1),[_c,qd]=r.useState(!1),[Xo,Kd]=r.useState([]),[Cc,Pl]=r.useState(!1),ji=r.useRef(null),jr=r.useRef(null),ta=r.useRef(null),Zd=r.useRef(!1),Pi=r.useRef(gt),Mi=r.useRef(E),Ac=r.useRef(Ie),Ml=r.useRef(!1),ei=r.useRef(""),vo=r.useRef(""),xc=r.useRef(""),ti=r.useRef(""),ni=r.useRef(""),So=r.useRef(""),El=r.useRef(!1),Ic=r.useRef(!1),Ei=r.useRef(null),Yd=r.useRef(!1),Tc=r.useRef(!1),[xs,Rc]=r.useState(!1),Om=r.useCallback(p=>{xs||(Ic.current=!0),jl(p)},[xs]),{handleSaveSettings:Dl,handleSaveTheme:$m,handleSaveGlobalTheme:Um,handleJsonBackupEnabledChange:zm,handleSaveGlobalJsonBackupEnabled:Hm,handleSaveGlobalWeekStartsOn:Gm,handleSaveLocale:Jd,handleManualComplexityEnabledChange:_a,handleChecklistDropdownEnabledChange:Ll,handleShowTaskCardStatusLabelChange:Qd,handleResetProjectToGlobal:Xd}=tb({keyShortcut:mn,themeUseGlobalDefault:kt,runtimeMode:b,jsonBackupUseGlobalDefault:Ja,globalTheme:vt,globalJsonBackupEnabled:Ar,setCurrentTheme:$e,setThemeUseGlobalDefault:Ye,setGlobalTheme:st,setJsonBackupEnabled:dr,setJsonBackupUseGlobalDefault:xr,setGlobalJsonBackupEnabled:Ya,setGlobalWeekStartsOn:qr,setLocale:Ta,setManualComplexityEnabled:Dr,setChecklistDropdownEnabled:va,setShowTaskCardStatusLabel:Ra,setShowChecklist:yc});r.useEffect(()=>{b==="cloud"&&re!==ac&&vS(xe,re)},[b,xe,re]),r.useEffect(()=>{Pi.current=gt,Mi.current=E,Ac.current=Ie},[gt,E,Ie]);const Is=r.useMemo(()=>yr?hS({categories:yn,types:ea,priorities:Yn,taxonomies:Nr}):null,[yn,ea,Yn,yr,Nr]),wo=r.useCallback((p,O)=>{if(!p){ra.current=null;return}const z=Array.isArray(p.filterCategories)||Array.isArray(p.filterPriorities)||Array.isArray(p.filterTypes)||p.filterTaxonomies&&typeof p.filterTaxonomies=="object";z||(ra.current=null);const q=Array.isArray(p.filterCategories)||Array.isArray(p.filterPriorities)||Array.isArray(p.filterTypes)||Array.isArray(p.filterStatus)||Array.isArray(p.filterAssignees)||typeof p.filterAssigneesAllSelected=="boolean"||p.filterTaxonomies&&typeof p.filterTaxonomies=="object",Fe=Is!==null;z&&!Fe&&(ra.current={state:p,skipActiveWorkspaceModule:O?.skipActiveWorkspaceModule});const De=z&&Fe&&gS(p.filterTaxonomySignature,Is),Ue=z&&Fe&&!De,en=!z||De||Ue;O?.skipActiveWorkspaceModule||(typeof p.activeWorkspaceModule=="string"?jl(p.activeWorkspaceModule):p.groupBy==="docs"&&jl("docs")),p.groupBy&&p.groupBy!=="docs"&&Qo(p.groupBy),(p.emptyColumnMode==="show"||p.emptyColumnMode==="collapse"||p.emptyColumnMode==="hide")&&vc(p.emptyColumnMode),typeof p.zenMode=="boolean"&&Oa(p.zenMode),typeof p.searchQuery=="string"&&Fd(p.searchQuery),De?(Array.isArray(p.filterCategories)&&Gn(p.filterCategories),Array.isArray(p.filterPriorities)&&Cl(p.filterPriorities),Array.isArray(p.filterTypes)&&go(p.filterTypes),p.filterTaxonomies&&typeof p.filterTaxonomies=="object"&&yo(p.filterTaxonomies)):Ue&&(Gn(yn.map(rn=>rn.value)),Cl(Yn.map(rn=>rn.value)),go(ea.map(rn=>rn.value)),yo({})),Array.isArray(p.filterStatus)&&Od(p.filterStatus),Array.isArray(p.filterAssignees)&&$d(p.filterAssignees),typeof p.filterAssigneesAllSelected=="boolean"&&Ud(p.filterAssigneesAllSelected),(p.sortBy==="created"||p.sortBy==="priority"||p.sortBy==="updated"||p.sortBy==="complexity")&&zd(p.sortBy),(p.sortOrder==="asc"||p.sortOrder==="desc")&&ko(p.sortOrder),Ue?kc(!0):typeof p.hasInitedFilters=="boolean"&&en?kc(p.hasInitedFilters):q&&en&&kc(!0),typeof p.showChecklist=="boolean"&&yc(p.showChecklist),typeof p.lastCategory=="string"&&bl(p.lastCategory),typeof p.exportEnvironment=="string"&&p.exportEnvironment.trim().length>0&&ja(p.exportEnvironment.trim())},[yn,ea,Is,Yn]);r.useEffect(()=>{if(!Is||!ra.current)return;const p=ra.current;ra.current=null,wo(p.state,{skipActiveWorkspaceModule:p.skipActiveWorkspaceModule})},[wo,Is]);const Nc=r.useCallback(async p=>{const O=String(p||an.current||xe||"default").trim()||"default",z=`${b}:${pt}:${O}`;try{const q=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(O)}`,{method:"GET",credentials:"include"}),Fe=q.ok?await q.json().catch(()=>({})):{},De=Fe?.state&&typeof Fe.state=="object"?Fe.state:null,Ue=uh(pt),en=De||Ue?{...Ue||{},...De||{}}:null;if(an.current!==O)return;wo(en,{skipActiveWorkspaceModule:Ic.current}),ei.current=z}catch{const q=uh(pt);an.current===O&&(wo(q,{skipActiveWorkspaceModule:Ic.current}),ei.current=z)}finally{if(an.current!==O)return;Ic.current=!1,El.current=!0,Rc(!0)}},[wo,xe,b,pt]);r.useEffect(()=>{const p=`${b}:${pt}:${xe}`;Ml.current&&ei.current!==p&&(Rc(!1),Nc(xe))},[xe,Nc,b,pt]),r.useEffect(()=>{if(!xs)return;if(El.current){El.current=!1;return}const p={groupBy:za,activeWorkspaceModule:Ri,emptyColumnMode:Hs,zenMode:wa,searchQuery:_l,filterCategories:vr,filterPriorities:Ii,filterTypes:Al,filterStatus:xl,filterAssignees:$r,filterAssigneesAllSelected:Il,filterTaxonomies:Yo,...Is?{filterTaxonomySignature:Is}:{},sortBy:Ti,sortOrder:Tl,hasInitedFilters:Jo,showChecklist:Zo,lastCategory:ho||"",exportEnvironment:Gt};SS(p,pt);const O=window.setTimeout(async()=>{try{await kf({stateKey:"app",workspaceId:an.current,patch:p})}catch{}},250);return()=>window.clearTimeout(O)},[xs,za,Ri,Hs,wa,_l,vr,Ii,Al,xl,$r,Il,Yo,Is,Ti,Tl,Jo,Zo,ho,Gt,pt]);const jc=r.useCallback(p=>{const O=p.runtimeMode==="cloud"?"cloud":"local",z=!!p.authRequiredForApi,q=typeof p.userId=="string"&&p.userId.trim().length>0?p.userId.trim():"anonymous",Fe=O==="cloud"&&q!=="anonymous",De=Fe||Ac.current,Ue=Pi.current;if(R(O),l(z),Fe&&(Ke(!0),Ne(q),Se(!1),Ue||cr(!0)),typeof p.workspaceId=="string"&&p.workspaceId.trim().length>0){const ed=p.workspaceId.trim();O==="local"?Fn(ed):Nt(ed)}Se(O==="cloud"&&z?!De:!1),p.setupState&&typeof p.setupState=="object"?gn(p.setupState):gn(null),p.runtimeCapabilities&&typeof p.runtimeCapabilities=="object"?Ka(p.runtimeCapabilities):Ka(null),En(!!p.realtimeSyncEnabled);const en=String(p.realtimeSyncFlagSource||"").trim().toLowerCase();In(en==="env"||en==="settings"||en==="default"?en:"unknown"),typeof p.shortcut=="string"&&p.shortcut.trim().length>0&&ka(p.shortcut);const rn=Yc(p.theme);rn&&$e(rn);const Ln=Yc(p.globalTheme);Ln&&st(Ln),typeof p.themeUseGlobalDefault=="boolean"&&Ye(p.themeUseGlobalDefault);const fa=p.runtimeMode==="cloud"?"cloud":"local";typeof p.projectRoot=="string"?Ze(p.projectRoot):fa==="cloud"&&Ze(""),typeof p.tenantId=="string"?Bt(p.tenantId.trim()):fa==="cloud"&&Bt("");const sr=fa==="cloud"?String(p.projectName||"").trim():p.projectName||p.paths?.projectName||"";(String(sr||"").trim().length>0||fa==="cloud")&&ot(sr),typeof p.mcpScript=="string"?At(p.mcpScript):fa==="cloud"&&At(""),typeof p.hostRoot=="string"?Fa(p.hostRoot):fa==="cloud"&&Fa(""),typeof p.jsonBackupEnabled=="boolean"&&dr(p.jsonBackupEnabled),typeof p.globalJsonBackupEnabled=="boolean"&&Ya(p.globalJsonBackupEnabled),typeof p.jsonBackupUseGlobalDefault=="boolean"&&xr(p.jsonBackupUseGlobalDefault);const Pr=p?.schedulePreferences?.weekStartsOn;(Pr==="sunday"||Pr==="monday")&&qr(Pr),typeof p.manualComplexityEnabled=="boolean"&&Dr(p.manualComplexityEnabled),typeof p.checklistDropdownEnabled=="boolean"?va(p.checklistDropdownEnabled):va(!0),typeof p.showTaskCardStatusLabel=="boolean"?Ra(p.showTaskCardStatusLabel):Ra(!0)},[Nt,Fn]),Vm=r.useCallback(async()=>{const p=typeof performance<"u"?performance.now():Date.now();try{const O=await Do("/api/taskforce/version",void 0,dd);if(!O.ok)return;const z=await O.json().catch(()=>({}));z?.build&&typeof z.build=="object"&&cn({version:String(z.build.version||""),gitSha:z.build.gitSha?String(z.build.gitSha):null,buildTime:z.build.buildTime?String(z.build.buildTime):null,deployId:z.build.deployId?String(z.build.deployId):null}),Ut("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-p)})}catch(O){io(O)&&Ut("build_info_timeout",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-p)})}},[Do,io]),{fetchReferenceData:Ts,fetchConfig:rr,fetchWorkspaces:Gs,fetchAssigneeOptions:Bl,switchWorkspace:es,resolveWorkspaceAfterAuth:ai,retryBootstrapChecks:qm,runCloudBootstrap:ri}=Ob({shouldDeferProtectedApiCalls:Sn,shouldBlockProtectedApiCalls:Dn,getWorkspaceRequestState:ya,isWorkspaceRequestStale:On,isWorkspaceEpochStale:lr,isAbortError:$n,isBootstrapTimeoutError:io,fetchWithTimeout:Do,handleUnauthorized:kr,applyBootstrapConfig:jc,loadPersistedUiState:Nc,fetchBuildInfo:Vm,markBootstrapPhase:Eo,markBootstrapStalled:Ss,fetchWorkflows:Tn,fetchInitiativeTemplates:_n,loadAvailableEnvironments:Un,setReferenceDataLoaded:bs,setCustomCategories:ic,setCustomTypes:yi,setPriorities:Cr,setTaxonomies:co,setTaxonomyDisplayLabels:Lo,setConfigLoaded:cc,hasLoadedUiStateRef:Ml,currentWorkspaceIdRef:an,referenceDataRequestRef:Ei,referenceDataAbortRef:Ca,bootstrapConfigAbortRef:qa,workspaceListAbortRef:Wn,assigneeOptionsAbortRef:Vr,workspaceListHydratedRef:Yd,setAvailableWorkspaces:An,runtimeMode:b,applyResolvedWorkspaceId:Nt,workspaceSwitchingEnabled:yt,authSessionResolved:gt,isAuthenticated:Ie,authUserId:Je,authUserAvatarUrl:Vn,setHydratedWorkspaceRole:at,setAssigneeOptions:dn,setAssigneeOptionsLoaded:Bo,commitCurrentWorkspaceId:(p,O)=>{Ea.current=p,Fn(p,O),O?.clearExplicitSelection!==!1&&(Ea.current=null)},currentWorkspaceId:xe,workspaceSelectionScope:re,abortWorkspaceScopedRequests:La,setWorkspaceBootstrapPending:Bn,checkAuthSession:Hn,lastConfigRefreshKeyRef:xc,lastAssigneeOptionsLoadKeyRef:vo,lastWorkspaceSyncStateLoadKeyRef:ti,lastTaskSurfaceLoadKeyRef:ni,lastSettingsSurfaceLoadKeyRef:So,isOpen:X,activeTab:oe,showArchive:V,taskScope:Ce,settingsSection:We,workspaceBootstrapPending:un,fetchTasks:zn,fetchArchive:tr,fetchPlanningEntities:ln,refreshTaskCollections:cl,loadWorkspaceSyncState:Ed,archiveBootstrapTimerRef:ta,hasBootstrappedDataRef:Tc}),si=r.useCallback(async()=>{await Hn(),await rr()},[Hn,rr]);r.useEffect(()=>{if(!Xn||un)return;const p=`${b}:${Ie?"auth":"guest"}:${xe}:${Vn||"no-avatar"}`;pa&&vo.current===p||(vo.current=p,Bl())},[pa,Vn,Xn,xe,Bl,Ie,b,un]),r.useEffect(()=>{if(!gt||!Ie)return;const p=String(Je||"").trim();if(!p||p==="anonymous")return;const O=String(Vn||"").trim()||null;dn(z=>{let q=!1;const Fe=z.map(De=>De.kind!=="member"||String(De.value||"").trim()!==p||(typeof De.avatarUrl=="string"&&De.avatarUrl.trim().length>0?De.avatarUrl.trim():null)===O?De:(q=!0,{...De,avatarUrl:O}));return q?Fe:z})},[gt,Vn,Je,Ie]);const Wl=r.useMemo(()=>yt?bt.find(O=>O.id===xe)?.role??null:ge,[bt,xe,ge,yt]);r.useEffect(()=>{Ie||at(null)},[Ie]);const oi=r.useCallback(async()=>{Kt(null);const p=await ri({reason:"post-plans",ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return p.authenticated?p.success?p.workspaceSetupRequired?{success:!0,destination:"setup"}:{success:!0,destination:"app"}:{success:!1,destination:"app",error:p.error||"Unable to resolve workspace after plan selection.",code:p.code}:{success:!1,destination:"login",error:p.error||"Sign in required.",code:p.code||"AUTH_REQUIRED"}},[ri]),ca=r.useCallback(async p=>{const O=p?.reason||"retry",z=typeof p?.preferredWorkspaceId=="string"?p.preferredWorkspaceId.trim():"",q=p?.allowCommercialGate===!0;if(z&&yt){if(!await Hn({force:!0}))return await rr({ignoreAuthGuard:!0}),{success:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};const Ue=await ai({preferredWorkspaceId:z});if(!Ue.success)return await rr({ignoreAuthGuard:!0}),{success:!1,error:Ue.error||"Unable to resolve workspace access.",code:Ue.code};if(Ue.workspaceSetupRequired)return await rr({ignoreAuthGuard:!0}),{success:!0,workspaceSetupRequired:!0}}const Fe=await ri({reason:O,ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return Fe.authenticated?Fe.success?Fe.workspaceSetupRequired?q?{success:!0,workspaceSetupRequired:!1}:{success:!0,workspaceSetupRequired:!0}:(q||uc({preferCloudOnFirstSync:!0}),{success:!0,workspaceSetupRequired:!1}):{success:!1,error:Fe.error||"Unable to resolve workspace access.",code:Fe.code}:{success:!1,error:Fe.error||"Sign in required.",code:Fe.code||"AUTH_REQUIRED"}},[Hn,rr,ai,ri,uc,yt]),ii=r.useCallback(async(p,O)=>{if(!yt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const z=String(p||"").trim();if(!z)return{success:!1,error:"Workspace name is required."};try{const q=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:z,description:typeof O=="string"?O:void 0})}),Fe=await q.json().catch(()=>({}));if(!q.ok||Fe?.success===!1)return{success:!1,error:Fe?.error||`Failed to create workspace (${q.status})`,code:Fe?.code};const De=Fe?.workspace;if(await Gs(),De?.id){const Ue=await es(De.id);if(!Ue.success)return{success:!1,error:Ue.error||"Workspace created but failed to activate.",code:Ue.code}}return{success:!0,workspace:De}}catch{return{success:!1,error:"Failed to create workspace."}}},[Gs,es,yt]),Fl=r.useCallback(async p=>{if(!yt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const O=String(p||"").trim();if(!O)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const z=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(O)}`,{method:"DELETE",credentials:"include"}),q=await z.json().catch(()=>({}));if(!z.ok||q?.success===!1)return{success:!1,error:q?.error||`Failed to delete workspace (${z.status})`,code:q?.code};await Hn({force:!0}),await Promise.all([rr(),Gs()]);const Fe=typeof q?.nextWorkspaceId=="string"?q.nextWorkspaceId.trim():"";return Fe&&Fn(Fe),{success:!0,nextWorkspaceId:Fe||void 0,workspaceSetupRequired:q?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(q?.cleanupWarnings)?q.cleanupWarnings.map(De=>String(De||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[Hn,Fn,rr,Gs,yt]),eu=r.useCallback(async p=>{const O=p==="operations"?"operations":"core";try{const z=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:O}})}),q=await z.json().catch(()=>({}));return!z.ok||q?.success===!1?!1:(await si(),!0)}catch{return!1}},[si]),tu=r.useCallback(async p=>{const O=String(p?.name||"").trim(),z=typeof p?.workspaceId=="string"?p.workspaceId.trim():"";if(!O)return{success:!1,error:"Workspace name is required.",code:"WORKSPACE_NAME_REQUIRED"};try{const q=await fetch("/api/taskforce/workspace-profile",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-runtime-mode":b},credentials:"include",body:JSON.stringify({workspaceId:z&&z!=="default"?z:void 0,name:O,description:typeof p.description=="string"?p.description:void 0,allowCreate:!0})}),Fe=await q.json().catch(()=>({}));if(!q.ok||Fe?.success===!1)return{success:!1,error:Fe?.error||`Failed to save workspace (${q.status})`,code:Fe?.code};const De=String(Fe?.workspace?.id||"").trim();if(De&&(Fn(De),await new Promise(Ue=>window.setTimeout(Ue,0)),b==="cloud"&&Ie&&De!==xe)){const Ue=await es(De);if(!Ue.success)return{success:!1,error:Ue.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await si(),{success:!0,workspaceId:De||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[Fn,si,b,Ie,xe,es]),Ol=r.useCallback(async(p,O)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const z=p.trim().toLowerCase(),q=O;if(!z||!q)return{success:!1,error:"Email and password are required."};try{const Fe=await fetch(te("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:z,password:q})}),De=await Fe.json().catch(()=>({}));if(!Fe.ok||!De?.success)return{success:!1,error:De?.error||"Sign in failed.",code:De?.code};Qr("");const Ue=await ca();return Ue.success?{success:!0,workspaceSetupRequired:Ue.workspaceSetupRequired===!0}:{success:!1,error:Ue.error||"Unable to resolve workspace after sign in.",code:Ue.code}}catch{return{success:!1,error:"Sign in failed."}}},[te,Z,ca]),nu=r.useCallback((p,O,z)=>{const q=O&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(O)?O:"/";let Fe=`/api/taskforce/auth/oauth/${encodeURIComponent(p)}/start?return_to=${encodeURIComponent(q)}`;z&&(Fe+=`&invite_token=${encodeURIComponent(z)}`),window.location.href=te(Fe)},[te]),ts=r.useCallback(async(p,O,z)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const q=p.trim().toLowerCase(),Fe=O;if(!q||!Fe)return{success:!1,error:"Email and password are required."};try{const De=await fetch(te("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:q,password:Fe,...typeof z?.displayName=="string"&&z.displayName.trim()?{displayName:z.displayName.trim()}:{},...typeof z?.planId=="string"&&z.planId.trim()?{planId:z.planId.trim()}:{},...typeof z?.planVersionId=="string"&&z.planVersionId.trim()?{planVersionId:z.planVersionId.trim()}:{},...typeof z?.interval=="string"&&z.interval.trim()?{interval:z.interval.trim()}:{}})}),Ue=await De.json().catch(()=>({}));if(!De.ok||!Ue?.success)return{success:!1,error:Ue?.error||"Create account failed.",code:Ue?.code,verificationRequired:!!Ue?.verificationRequired,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0};const en=Ue?.planSelectionRequired===!0,rn=Ue?.checkoutPending===!0,Ln=typeof Ue?.commercialState=="string"?Ue.commercialState:null,fa=!!Ue?.verificationRequired;if(!fa){if(Qr(""),!!(en||rn||Ln==="pending_plan_selection"||Ln==="checkout_pending"))return await Hn({force:!0})?{success:!0,workspaceSetupRequired:!1,planSelectionRequired:en,checkoutPending:rn,commercialState:Ln,verificationRequired:fa,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0}:{success:!1,error:"Unable to resolve workspace after registration.",code:"AUTH_REQUIRED"};const Pr=await ca({allowCommercialGate:!1});return Pr.success?{success:!0,workspaceSetupRequired:Pr.workspaceSetupRequired===!0,planSelectionRequired:en,checkoutPending:rn,commercialState:Ln,verificationRequired:fa,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0}:{success:!1,error:Pr.error||"Unable to resolve workspace after registration.",code:Pr.code}}return{success:!0,workspaceSetupRequired:!!Ue?.workspaceSetupRequired,planSelectionRequired:en,checkoutPending:rn,commercialState:Ln,verificationRequired:fa,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[Hn,te,Z,ca]),au=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=String(p.displayName||"").trim(),z=typeof p.avatarDraftId=="string"?p.avatarDraftId.trim():"",q=p.clearAvatar===!0;if(!O)return{success:!1,error:"Display name is required."};try{const Fe=await fetch(te("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:O,...z?{avatarDraftId:z}:{},...q?{clearAvatar:!0}:{}})}),De=await Fe.json().catch(()=>({}));if(!Fe.ok||!De?.success)return{success:!1,error:De?.error||"Failed to update profile.",code:De?.code};const Ue={userId:typeof De?.profile?.userId=="string"?De.profile.userId:Je,email:typeof De?.profile?.email=="string"?De.profile.email:Pt,displayName:typeof De?.profile?.displayName=="string"?De.profile.displayName:null,avatarUrl:typeof De?.profile?.avatarUrl=="string"?De.profile.avatarUrl:null};return Ht(Ue.displayName||""),qn(Ue.avatarUrl||""),{success:!0,profile:Ue}}catch{return{success:!1,error:"Failed to update profile."}}},[te,Z,Pt,Je]),ns=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=p.trim().toLowerCase();if(!O)return{success:!1,error:"Email is required."};try{const z=await fetch(te("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:O})}),q=await z.json().catch(()=>({}));return!z.ok||!q?.success?{success:!1,error:q?.error||"Failed to request verification email.",code:q?.code}:{success:!0,verificationToken:q?.verificationToken??null,emailSent:q?.emailSent!==!1,deliveryAttempted:q?.deliveryAttempted===!0||typeof q?.verificationToken=="string"&&q.verificationToken.trim().length>0,emailError:typeof q?.emailError=="string"?q.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[te,Z]),ru=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=p.trim();if(!O)return{success:!1,error:"Token is required."};try{const z=await fetch(te("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:O})}),q=await z.json().catch(()=>({}));return!z.ok||!q?.success?{success:!1,error:q?.error||"Verification failed.",code:q?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[te,Z]),su=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=p.trim().toLowerCase();if(!O)return{success:!1,error:"Email is required."};try{const z=await fetch(te("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:O})}),q=await z.json().catch(()=>({}));return!z.ok||!q?.success?{success:!1,error:q?.error||"Failed to request password reset.",code:q?.code}:{success:!0,resetToken:q?.resetToken??null,emailSent:q?.emailSent!==!1,deliveryAttempted:q?.deliveryAttempted===!0||typeof q?.resetToken=="string"&&q.resetToken.trim().length>0,emailError:typeof q?.emailError=="string"?q.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[te,Z]),Di=r.useCallback(async(p,O)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const z=p.trim(),q=O;if(!z||!q)return{success:!1,error:"Token and password are required."};try{const Fe=await fetch(te("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:z,password:q})}),De=await Fe.json().catch(()=>({}));return!Fe.ok||!De?.success?{success:!1,error:De?.error||"Failed to reset password.",code:De?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[te,Z]),$l=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=p.trim();if(!O)return{success:!1,error:"Token is required."};try{const z=await fetch(te("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:O})}),q=await z.json().catch(()=>({}));return!z.ok||!q?.success?{success:!1,error:q?.error||"Invite inspection failed.",code:q?.code,state:q?.state}:{success:!0,state:q?.state,email:typeof q?.email=="string"?q.email:void 0,workspaceId:typeof q?.workspaceId=="string"?q.workspaceId:void 0,inviteeKind:q?.inviteeKind==="existing_user"?"existing_user":"new_user",passwordRequired:q?.passwordRequired===!0,inviteeState:q?.inviteeState==="existing_account"?"existing_account":"pending_setup",availableMethods:Array.isArray(q?.availableMethods)?q.availableMethods:[]}}catch{return{success:!1,error:"Invite inspection failed."}}},[te,Z]),Li=r.useCallback(async(p,O)=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const z=p.trim(),q=O;if(!z||!q)return{success:!1,error:"Token and password are required."};try{const Fe=await fetch(te("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:z,password:q})}),De=await Fe.json().catch(()=>({}));if(!Fe.ok||!De?.success)return{success:!1,error:De?.error||"Invite acceptance failed.",code:De?.code};Qr("");const Ue=typeof De?.workspaceId=="string"?De.workspaceId:null;if(Ue&&yt){const rn=await es(Ue,{hydrate:!1});if(!rn.success)return{success:!1,error:rn.error||"Unable to resolve workspace after invite acceptance.",code:rn.code}}const en=await ca({preferredWorkspaceId:Ue});return en.success?(Ue&&an.current!==Ue&&Fn(Ue,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:en.workspaceSetupRequired===!0}):{success:!1,error:en.error||"Unable to resolve workspace after invite acceptance.",code:en.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[Fn,te,Z,an,ca,es,yt]),Km=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=p.trim();if(!O)return{success:!1,error:"Token is required."};try{const z=await fetch(te("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:O})}),q=await z.json().catch(()=>({}));if(!z.ok||!q?.success)return{success:!1,error:q?.error||"Invite join failed.",code:q?.code};Qr("");const Fe=typeof q?.workspaceId=="string"?q.workspaceId:null;if(Fe&&yt){const Ue=await es(Fe,{hydrate:!1});if(!Ue.success)return{success:!1,error:Ue.error||"Unable to resolve workspace after invite join.",code:Ue.code}}const De=await ca({preferredWorkspaceId:Fe});return De.success?(Fe&&an.current!==Fe&&Fn(Fe,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:De.workspaceSetupRequired===!0}):{success:!1,error:De.error||"Unable to resolve workspace after invite join.",code:De.code}}catch{return{success:!1,error:"Invite join failed."}}},[Fn,te,Z,an,ca,es,yt]),ci=r.useCallback(async()=>{if(!Z)return{success:!1,error:"Cloud auth not configured."};try{const p=await fetch(te("/api/taskforce/account/login-methods"),{credentials:"include"}),O=await p.json().catch(()=>({}));return!p.ok||!O?.success?{success:!1,error:O?.error||"Failed to fetch login methods."}:{success:!0,methods:Array.isArray(O?.methods)?O.methods:[]}}catch{return{success:!1,error:"Failed to fetch login methods."}}},[te,Z]),Ul=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth not configured."};try{const O=await fetch(te(`/api/taskforce/account/login-methods/${encodeURIComponent(p)}`),{method:"DELETE",credentials:"include"}),z=await O.json().catch(()=>({}));return!O.ok||!z?.success?{success:!1,error:z?.error||"Unlink failed.",code:z?.code}:{success:!0}}catch{return{success:!1,error:"Unlink failed."}}},[te,Z]),ou=r.useCallback(async p=>{if(!Z)return{success:!1,error:"Cloud auth not configured."};try{const O=await fetch(te("/api/taskforce/account/login-methods/password"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({password:p})}),z=await O.json().catch(()=>({}));return!O.ok||!z?.success?{success:!1,error:z?.error||"Failed to add password.",code:z?.code}:{success:!0}}catch{return{success:!1,error:"Failed to add password."}}},[te,Z]),Zm=r.useCallback((p,O)=>{const z=O&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(O)?O:"/",q=`/api/taskforce/auth/oauth/${encodeURIComponent(p)}/start?flow=link&return_to=${encodeURIComponent(z)}`;window.location.href=te(q)},[te]),zl=r.useCallback(()=>{La(),Ei.current=null,ei.current="",vo.current="",xc.current="",ti.current="",ni.current="",So.current="",Rc(!1),bs(!1),dn(gi()),Bo(!1),Rr([]),ma([]),N([]),wt([]),ee([]),Pa([]),Xa(!1),jr.current!==null&&typeof window<"u"&&(window.clearTimeout(jr.current),jr.current=null),ta.current!==null&&typeof window<"u"&&(window.clearTimeout(ta.current),ta.current=null)},[La,N,ma]),iu=r.useCallback(async()=>{try{Z&&await fetch(te("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if(La(),Mn.current+=1,aa.current=null,Zn.current=!1,Zt.current=Date.now(),Ke(!1),cr(!0),Ne("anonymous"),Yt(""),cd(null),Wt(""),Ht(""),qn(""),Os("disconnected"),Rd(null),ga(!0),ot(""),cc(!1),bs(!1),gn(null),nn("idle"),Kt(null),Ml.current=!1,b!=="local"&&dh(re),Se(b==="cloud"&&E),Fn("default"),An([]),Yd.current=!1,at(null),b==="local"){await Promise.allSettled([rr({ignoreAuthGuard:!0}),zn(!0,{ignoreAuthGuard:!0}),ln({ignoreAuthGuard:!0}),Ts({ignoreAuthGuard:!0,force:!0})]);return}Tc.current=!1,zl()}},[La,E,dh,Fn,te,Z,re,b,rr,ln,Ts,zn,zl]),cu=r.useCallback(async p=>{try{const O=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}),z=await O.json().catch(()=>({}));return!O.ok||!z?.success?{success:!1,error:z?.error||`Create failed (${O.status})`}:(await zn(!0),{success:!0,result:z?.results})}catch(O){return{success:!1,error:O.message}}},[zn]),Hl=r.useCallback(async p=>{const O=await fetch("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p||{})}),z=await O.json().catch(()=>({}));if(!O.ok)throw new Error(z?.error||`Failed to create initiative (${O.status})`);return await ln(),wt(q=>mi(q,z)),z},[ln]),lu=r.useCallback(async(p,O)=>{const z=await fetch(`/api/taskforce/initiative/${encodeURIComponent(p)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(O||{})}),q=await z.json().catch(()=>({}));if(!z.ok)throw new Error(q?.error||`Failed to update initiative (${z.status})`);return await ln(),wt(Fe=>mi(Fe,q)),q},[ln]),Pc=r.useCallback(()=>{ln()},[ln]),Ym=r.useCallback(async p=>{const O=await fetch(`/api/taskforce/initiative/${encodeURIComponent(p)}/archive`,{method:"POST"}),z=await O.json().catch(()=>({}));if(!O.ok)throw new Error(z?.error||`Failed to archive initiative (${O.status})`);return wt(q=>mi(q,z)),Pc(),z},[Pc]),Gl=r.useCallback(async p=>{const O=await fetch(`/api/taskforce/initiative/${encodeURIComponent(p)}/unarchive`,{method:"POST"}),z=await O.json().catch(()=>({}));if(!O.ok)throw new Error(z?.error||`Failed to unarchive initiative (${O.status})`);return wt(q=>mi(q,z)),Pc(),z},[Pc]),Mc=r.useCallback(async p=>{const O=await fetch("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p||{})}),z=await O.json().catch(()=>({}));if(!O.ok)throw new Error(z?.error||`Failed to create workstream (${O.status})`);return await ln(),ee(q=>mi(q,z)),z},[ln]),li=r.useCallback(async(p,O)=>{const z=await fetch(`/api/taskforce/workstream/${encodeURIComponent(p)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(O||{})}),q=await z.json().catch(()=>({}));if(!z.ok)throw new Error(q?.error||`Failed to update workstream (${z.status})`);return await ln(),ee(Fe=>mi(Fe,q)),q},[ln]),Ec=r.useCallback(async p=>{const O=await fetch(`/api/taskforce/workstream/${encodeURIComponent(p)}/archive`,{method:"POST"}),z=await O.json().catch(()=>({}));if(!O.ok)throw new Error(z?.error||`Failed to archive workstream (${O.status})`);return await ln(),ee(q=>mi(q,z)),z},[ln]),Ur=r.useCallback(async p=>{const O=await fetch(`/api/taskforce/workstream/${encodeURIComponent(p)}/unarchive`,{method:"POST"}),z=await O.json().catch(()=>({}));if(!O.ok)throw new Error(z?.error||`Failed to unarchive workstream (${O.status})`);return await ln(),ee(q=>mi(q,z)),z},[ln]),Vs=r.useRef(!1);r.useEffect(()=>{M(!0),!Vs.current&&(Vs.current=!0,Hn())},[Hn]),r.useEffect(()=>{D&&Hn()},[D,Hn]),r.useEffect(()=>{if(!Z)return;let p=!1;const O=new AbortController,z=typeof window<"u"?window.setTimeout(()=>O.abort(),5e3):null;return fetch(te("/api/taskforce/auth/providers"),{credentials:"include",signal:O.signal}).then(q=>q.ok?q.json():null).then(q=>{!p&&Array.isArray(q?.providers)&&Vt(q.providers)}).catch(()=>{}).finally(()=>{z!==null&&typeof window<"u"&&window.clearTimeout(z)}),()=>{p=!0,O.abort()}},[Z,te]),r.useEffect(()=>{if(b!=="local"||!Pe||typeof window>"u")return;const p=()=>{Hn()},O=()=>{document.visibilityState==="visible"&&p()};window.addEventListener("focus",p),window.addEventListener("online",p),document.addEventListener("visibilitychange",O);const z=window.setInterval(p,3e4);return()=>{window.removeEventListener("focus",p),window.removeEventListener("online",p),document.removeEventListener("visibilitychange",O),window.clearInterval(z)}},[b,Pe,Hn]),r.useEffect(()=>{a&&a(Qn.length)},[Qn.length,a]);const qs=r.useRef(null);r.useEffect(()=>{if(!t){qs.current=null;return}if(qs.current===t||Qn.length===0)return;const p=Qn.find(O=>O.id.endsWith(t)||O.id===t);p&&(qs.current=t,Oi(p),Bi("add"))},[t,Qn]);const Vl=r.useRef(!1);r.useEffect(()=>{if(!Xn)return;if(!Vl.current&&yn.length>0){Vl.current=!0;const O=ho,z=yn.some(q=>q.label===O||q.value===O);if(O&&z){const q=yn.find(Fe=>Fe.label===O||Fe.value===O);Cs(q?.value||O)}else Cs(pn(yn));return}const p=yn.some(O=>O.value===Or);yn.length>0&&!p&&Cs(pn(yn))},[Xn,yn,Or,pn,ho]),r.useEffect(()=>{if(!Xn||yn.length===0)return;const p=q=>!yn.some(Fe=>Fe.value===q.category),O=Qn.some(p),z=T.some(p);if(O||z){const q=pn(yn);O&&ma(Fe=>Fe.map(De=>p(De)?{...De,category:q}:De)),z&&N(Fe=>Fe.map(De=>p(De)?{...De,category:q}:De))}},[Xn,yn,Qn,T,pn]),r.useEffect(()=>()=>{ta.current!==null&&typeof window<"u"&&(window.clearTimeout(ta.current),ta.current=null),jr.current!==null&&typeof window<"u"&&(window.clearTimeout(jr.current),jr.current=null)},[]),r.useEffect(()=>{},[cl]);const Jm=r.useCallback(async()=>{await Xr()},[Xr]),ql=String(xe||"").trim(),Dc=String(Je||"").trim(),Qm=Le("/taskforce-ws"),Lc=!!(Z&&b==="cloud"&>&&Ie&&Dc&&Dc!=="anonymous"&&ql&&!hf(ql)&&Qm),du=r.useCallback(()=>{b==="cloud"&&(Xr(),!(typeof window>"u")&&(jr.current!==null&&window.clearTimeout(jr.current),jr.current=window.setTimeout(()=>{jr.current=null,Xr()},250)))},[b,Xr]);ay({enabled:Lc,workspaceId:ql,websocketUrl:Qm,onSignal:du,userId:Dc||void 0}),$b({isOpen:X,authBlocked:J,authRequiredForApi:E,isAuthenticated:Ie,canCallProtectedApi:xa.canCallProtectedApi,shouldGateProtectedApiCalls:Ee,authSessionResolvedRef:Pi,authRequiredForApiRef:Mi,isAuthenticatedRef:Ac,dataVersionRef:ji,refreshTaskCollectionsForDataVersion:Jm});const Bc=r.useMemo(()=>{const p=new Map;for(const O of T)p.set(O.id,O);for(const O of Qn)p.set(O.id,O);return Array.from(p.values())},[Qn,T]),Kl=r.useMemo(()=>$a.map(p=>({...p.taskSnapshot,isDeleted:!0,deletedRecordId:p.id})),[$a]);r.useEffect(()=>{if(!(Sn||Dn)&&X&&!un){if(oe==="tasks"){const p=`${xe}:${oe}:${V?"archive":"active"}:${Ce}`;if(!Zd.current){Zd.current=!0,ni.current=p;return}if(ni.current===p)return;ni.current=p,zn(),ln(),(V||Ce==="archived")&&tr(!0),Ce==="deleted"&&cs();return}if(oe==="settings"){const p=`${xe}:${oe}:${We}`;if(So.current===p)return;So.current=p,rr(),(We==="commands"||We==="resources")&&Tn()}}},[xe,X,oe,We,V,Ce,zn,ln,tr,cs,rr,Tn,Sn,Dn,un]);const Wc=r.useCallback(async(p="")=>{try{const O=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(p)}`);if(O.ok){const z=await O.json();Ge(z.folders||[]),it(z.files||[]),ht(p)}}catch(O){console.error("[Taskforce] Failed to fetch folders:",O)}},[]),uu=r.useCallback(p=>{const O=[];if(p.path&&O.push(p.path),p.paths&&p.paths.length>0)for(const z of p.paths)O.includes(z)||O.push(z);return O},[]),{validatePaths:Ks,handleUpdateCategory:mu,handleSaveCategory:Zl,handleAddPath:pu,handleUpdateCategoryIcon:Yl,handleUpdateCategoryColor:Rs,handleRemovePath:fu,handleSelectPath:Xm,handleRemoveCategory:hu,handleSaveType:gu,handleRemoveType:yu,handleUpdateType:zr,handleUpdateTaxonomies:Fc,handleUpdatePriorities:di,analyzeSystemTaxonomyPack:Ns,handleApplySystemTaxonomyPack:ep}=nb({activeCategories:yn,activeTab:oe,activeTypes:ea,archivedTasks:T,browserTarget:Ft,category:Or,configLoaded:Xn,customCategories:so,refreshTaskCollections:cl,fetchTasks:zn,filterCategories:vr,getCategoryPaths:uu,normalizePath:ao,pathValidation:oo,setBrowserTarget:Et,setCategory:Cs,setCustomCategories:ic,setCustomTypes:yi,setFilterCategories:Gn,setPathValidation:lc,setPriorities:Cr,setShowFolderBrowser:Tt,setTaxonomies:co,tasks:Qn}),Oc=r.useCallback(async p=>{const O=ws,z={...O,...p};Lo(z);try{const q=await fetch("/api/taskforce/taxonomy-display-labels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLabels:p})});if(!q.ok)throw new Error(`Failed to save taxonomy display labels (${q.status})`);const Fe=await q.json().catch(()=>({}));Fe?.displayLabels&&typeof Fe.displayLabels=="object"&&Lo({...z,...Fe.displayLabels})}catch(q){console.error("[Taskforce] Failed to update taxonomy display labels",q),Lo(O)}},[ws]),Bi=r.useCallback(p=>{oe==="tasks"&&Rn.current&&Wr(Rn.current.scrollTop),L(p)},[oe]),Jl=r.useRef(async()=>{}),{handleNavigation:tp,handleClose:Wi,resetForm:js,resolveWorkstreamIdInput:Fi,handleEdit:Oi,handleOpenTaskById:$i,returnToPreviousTask:$c,clearReturnToParentTask:np}=ub({activeCategories:yn,activeTypes:ea,activeTab:oe,attachments:Xo,checklistItems:Ai,comments:gc,description:hc,editingTaskId:er,flushPendingAutoSave:()=>Jl.current(),getPreferredCategoryValue:pn,lastUsedCategory:ho,newCommentText:Sl,relationshipTasks:Bc,workstreams:we,showArchive:V,taxonomies:Nr,setActiveTab:Bi,setApproach:kl,setAssignee:Ua,setAttachments:Kd,setAttachmentsDirty:Pl,setCategory:Cs,setChecklistItems:Bd,setComments:Ko,setComplexity:hl,setDescription:fo,setDueDate:ar,setEditingTaskId:ro,setError:Qr,setFormTaxonomies:wl,setIsOpen:M,setNewCommentText:xi,setPendingNavigation:vs,setWorkstreamInput:fc,setPriority:pc,setScheduledDate:Dd,setShowArchive:ne,setStatus:gl,setTaskReturnTrail:Lt,setTitle:vl,setType:on,setUnsavedModalOpen:ua,taskReturnTrail:xt,title:qo}),{copiedId:ap,handleDelete:Uc,handleUpdateTask:bo,handleToggleComplete:Ql,handleToggleCancel:Ui,handleToggleInProgress:Xl,handleToggleReview:zi,handleArchiveTask:zc,handleBulkArchive:ku,handleUnarchive:Zs,handleRestoreDeletedTask:vu,handlePermanentlyDeleteDeletedTask:Su,handleEmptyDeletedTasks:wu,handleCopyId:rp,queueWorkspaceSyncFromAuthoritativeTaskState:bu}=Rb({tasks:Qn,archivedTasks:T,editingTaskId:er,setTasks:ma,setArchivedTasks:N,setDeletedTasks:Rr,setError:Qr,resetForm:js,setActiveTab:Bi,fetchTasks:zn,fetchArchive:tr,fetchDeletedTasks:cs,mergeTaskFromServer:_s,pushNotice:F,cloudAuthConfigured:Z,runtimeMode:b,isAuthenticated:Ie,workspaceCloudSyncEnabled:ls,buildWorkspaceSyncSignature:Uo,pushWorkspaceChangesToCloud:mo,workspacePendingSignatureRef:$s,workspaceDeletedTaskIdsRef:Md,workspaceDeletedTaskWatermarksRef:ml}),{autoSaveState:sp,flushAutoSave:_u,scheduleWarningPrompt:ui,handleSubmit:Hi,confirmScheduleWarning:Cu,cancelScheduleWarning:Au,handleAddComment:xu}=xb({activeCategories:yn,activeTab:oe,apiEndpoint:d,approach:yl,assignee:Ci,attachments:Xo,attachmentsDirty:Cc,category:Or,checklistItems:Ai,comments:gc,complexity:fl,description:hc,dueDate:Ld,editingTaskId:er,fetchTasks:zn,formTaxonomies:_t,getPreferredCategoryValue:pn,mergeTaskFromServer:_s,workstreamInput:Vo,priority:Go,pushNotice:F,queueWorkspaceSyncFromAuthoritativeTaskState:bu,relationshipTasks:Bc,resetForm:js,resolveWorkstreamIdInput:Fi,scheduledDate:As,setActiveTab:Bi,setAttachmentsDirty:Pl,setComments:Ko,setError:Qr,setLastUsedCategory:bl,setLoading:lo,setNewCommentText:xi,status:po,title:qo,taxonomies:Nr,type:ds});r.useEffect(()=>{Jl.current=_u},[_u]);const{handleSetWorkstreamForCurrentTask:us}=Ib({editingTaskId:er,mergeTaskFromServer:_s,workstreamInput:Vo,pushNotice:F,queueWorkspaceSyncFromAuthoritativeTaskState:bu,relationshipTasks:Bc,resolveWorkstreamIdInput:Fi,setError:Qr,fetchTasks:zn}),{currentTask:ms,currentTaskWorkstream:Iu,currentTaskInitiative:Tu}=ib({editingTaskId:er,relationshipTasks:Bc,initiatives:rt,workstreams:we,supplementalTasks:Kl,setComments:Ko}),Ru=eb({resolveCloudAuthUrl:te,currentWorkspaceId:xe,normalizedCloudAuthBaseUrl:ce,normalizedCloudMcpBaseUrl:Te,mergedConfig:o,availableWorkspaces:bt,currentTheme:Re,configLoaded:Xn,globalTheme:vt,themeUseGlobalDefault:kt,keyShortcut:mn,jsonBackupEnabled:Wa,globalJsonBackupEnabled:Ar,globalWeekStartsOn:oa,locale:Jn,supportedLocales:ur,jsonBackupUseGlobalDefault:Ja,manualComplexityEnabled:ia,checklistDropdownEnabled:Kr,showTaskCardStatusLabel:Ir,exportWorkflowsPath:Lr,exportingResource:pr,exportResult:fr,pathSaved:dt,settingsSection:We,exportEnvironment:Gt,setupState:Ba,buildInfo:Mr,saveSetupMode:eu,saveWorkspaceProfile:tu,setCurrentTheme:$e,handleSaveTheme:$m,handleSaveGlobalTheme:Um,setKeyShortcut:ka,handleJsonBackupEnabledChange:zm,handleSaveGlobalJsonBackupEnabled:Hm,handleSaveGlobalWeekStartsOn:Gm,handleSaveLocale:Jd,handleManualComplexityEnabledChange:_a,handleChecklistDropdownEnabledChange:Ll,handleShowTaskCardStatusLabelChange:Qd,handleResetProjectToGlobal:Xd,handleSaveSettings:Dl,setExportWorkflowsPath:Br,setExportEnvironment:ja,availableWorkflows:et,initiativeTemplates:$t,availableEnvironments:da,fetchWorkflows:Tn,fetchInitiativeTemplates:_n,createInitiativeFromTemplate:cu,fetchWorkflowTemplate:wn,fetchWorkflowOverrideNames:Na,saveWorkflowTemplateDraft:Qa,resetWorkflowTemplateDraft:ys,handleExportWorkflows:ks,setShowFolderBrowser:Tt,setBrowserTarget:Et,fetchFolders:Wc,activeCategories:yn,pathValidation:oo,taxonomyDisplayLabels:ws,handleUpdateCategory:mu,handleRemoveCategory:hu,handleSaveCategory:Zl,handleAddPath:pu,handleRemovePath:fu,handleUpdateCategoryIcon:Yl,handleUpdateCategoryColor:Rs,activeTypes:ea,handleSaveType:gu,handleRemoveType:yu,handleUpdateType:zr,taxonomies:Nr,handleUpdateTaxonomies:Fc,priorities:Yn,handleUpdatePriorities:di,analyzeSystemTaxonomyPack:Ns,handleApplySystemTaxonomyPack:ep,handleUpdateTaxonomyDisplayLabels:Oc,projectRoot:Oe,projectName:St,mcpHostRoot:Xt,serverHostRoot:Sa,mcpScriptPath:Be,tenantId:Rt,runtimeMode:b,workspaceSwitchingEnabled:yt,deleteWorkspace:Fl,setMcpHostRoot:Ia,isAuthenticated:Ie});r.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:Qn,archivedTasks:T,runtimeMode:b,currentWorkspaceId:xe,isAuthenticated:Ie,workspaceCloudSyncEnabled:ls,realtimeSyncEnabled:xn,fetchTasks:zn,fetchArchive:tr,retryWorkspaceCloudSync:bi,resetWorkspaceSyncCursorAndPull:zo,getSyncDiagnostics:_i,__dispatch:{handleUpdateTask:bo,handleToggleComplete:Ql,handleArchiveTask:zc,handleToggleCancel:Ui,handleToggleInProgress:Xl,handleToggleReview:zi,handleSubmit:Hi,handleDelete:Uc}})},[Qn,T,b,xe,Ie,ls,xn,zn,tr,bi,zo,_i,bo,Ql,zc,Ui,Xl,zi,Hi,Uc]);const op=hr&&hr.tone!=="error"?{message:hr.message,type:"info"}:null,_o=String(S||I.wsBaseUrl||ye||"").trim().replace(/\/+$/,"");return{config:{...o,cloudEnvironment:I.cloudEnvironment||o.cloudEnvironment||"",apiBaseUrl:ye||o.apiBaseUrl,cloudAuthBaseUrl:ce||o.cloudAuthBaseUrl,wsBaseUrl:_o||o.wsBaseUrl},isOpen:X,setIsOpen:M,activeTab:oe,setActiveTab:Bi,currentTheme:Re,setCurrentTheme:$e,configLoaded:Xn,storagePath:Ct,saveSettings:Dl,pathSaved:dt,keyShortcut:mn,setKeyShortcut:ka,globalWeekStartsOn:oa,locale:Jn,supportedLocales:ur,saveLocale:Jd,jsonBackupEnabled:Wa,setJsonBackupEnabled:dr,manualComplexityEnabled:ia,checklistDropdownEnabled:Kr,showTaskCardStatusLabel:Ir,setManualComplexityEnabled:Dr,mcpHostRoot:Xt,setMcpHostRoot:Ia,settingsSection:We,setSettingsSection:tt,runtimeMode:b,workspaceMode:Ot,workspaceSwitchingEnabled:yt,cloudAuthConfigured:Z,authRequiredForApi:E,authBlocked:J,isAuthenticated:Ie,authUserId:Je,authUserEmail:Pt,authUserDisplayName:Dt,authUserAvatarUrl:Vn,authWorkspaceId:zt,userGlobalSyncStatus:vi,workspaceLastPullAt:dl,workspaceLastPushAt:Em,workspaceLastErrorAt:ul,userGlobalSyncError:Si,workspaceLastErrorMessage:nr,workspaceLastSuccessfulSyncAt:uo,workspaceSyncPhase:wi,workspaceSyncSetupIntent:Dm,workspaceSyncStatus:Nd,workspaceSyncSummary:$o,workspaceSyncRecommendedAction:Lm,workspaceSyncBusy:jd,workspaceSyncPendingChanges:Pd,retryUserGlobalSettingsSync:Us,retryWorkspaceCloudSync:bi,resetWorkspaceSyncCursorAndPull:zo,getWorkspaceSyncDiagnostics:_i,hasBetaAccess:Kn,realtimeSyncEnabled:xn,realtimeSyncFlagSource:Za,currentWorkspaceId:xe,currentWorkspaceRole:Wl,availableWorkspaces:bt,assigneeOptions:vn,workspaceCloudSyncEnabled:ls,saveWorkspaceCloudSyncSettings:mc,applyWorkspaceSyncStateSnapshot:pl,bootstrapState:Ls,authSessionResolved:gt,workspaceBootstrapPending:un,bootstrapPhase:fn,bootstrapError:bn,bootstrapStartedAt:_r,setupState:Ba,runtimeCapabilities:Jt,refreshSetupContext:si,retryBootstrapChecks:qm,continueAfterCommercialOnboarding:oi,saveWorkspaceProfile:tu,fetchWorkspaces:Gs,createWorkspace:ii,deleteWorkspace:Fl,switchWorkspace:es,loginWithCredentials:Ol,beginOAuthLogin:nu,availableAuthProviders:sn,fetchLoginMethods:ci,unlinkLoginMethod:Ul,addPasswordToAccount:ou,beginOAuthLink:Zm,registerWithCredentials:ts,updateCurrentUserProfile:au,requestEmailVerification:ns,confirmEmailVerification:ru,requestPasswordReset:su,confirmPasswordReset:Di,inspectInviteAcceptance:$l,acceptInviteWithToken:Li,joinInviteWithToken:Km,logout:iu,showFolderBrowser:Qe,setShowFolderBrowser:Tt,folders:ae,files:ft,currentBrowsePath:Mt,fetchFolders:Wc,browserTarget:Ft,setBrowserTarget:Et,groupBy:za,setGroupBy:Qo,activeWorkspaceModule:Ri,setActiveWorkspaceModule:Om,emptyColumnMode:Hs,setEmptyColumnMode:vc,zenMode:wa,setZenMode:mr,handleSelectPath:Xm,handleAddPath:pu,handleRemovePath:fu,tasks:Qn,loadingTasks:jo,archivedTasks:T,initiatives:rt,workstreams:we,planningBootstrapTaskSummaries:gr,deletedTasks:$a,activeCategories:yn,activeTypes:ea,priorities:Yn,taxonomyDisplayLabels:ws,approaches:Er,taxonomies:Nr,searchQuery:_l,setSearchQuery:Fd,filterCategories:vr,setFilterCategories:Gn,filterTypes:Al,setFilterTypes:go,filterPriorities:Ii,setFilterPriorities:Cl,filterStatus:xl,setFilterStatus:Od,filterAssignees:$r,setFilterAssignees:$d,filterTaxonomies:Yo,setFilterTaxonomies:yo,hasInitedFilters:Jo,sortBy:Ti,setSortBy:zd,sortOrder:Tl,setSortOrder:ko,toggleSortOrder:zs,showArchive:V,setShowArchive:ne,taskScope:Ce,setTaskScope:Ae,clearFilters:Sc,filteredTasks:wc,searchAgnosticTasks:Hd,filteredArchive:Gd,groupedTasks:Nl,collapsedCategories:Rl,setCollapsedCategories:Bm,fetchTasks:zn,fetchArchive:tr,fetchDeletedTasks:cs,fetchPlanningEntities:ln,fetchAssigneeOptions:Bl,createInitiative:Hl,updateInitiative:lu,archiveInitiative:Ym,unarchiveInitiative:Gl,createWorkstream:Mc,updateWorkstream:li,archiveWorkstream:Ec,unarchiveWorkstream:Ur,handleEdit:Oi,handleDelete:Uc,handleCopyId:rp,handleToggleComplete:Ql,handleToggleCancel:Ui,handleToggleInProgress:Xl,handleToggleReview:zi,handleArchiveTask:zc,handleBulkArchive:ku,handleUnarchive:Zs,handleRestoreDeletedTask:vu,handlePermanentlyDeleteDeletedTask:Su,handleEmptyDeletedTasks:wu,handleUpdateTask:bo,editingTaskId:er,loading:Jr,error:il,title:qo,setTitle:vl,description:hc,setDescription:fo,checklistItems:Ai,setChecklistItems:Bd,category:Or,setCategory:Cs,type:ds,setType:on,priority:Go,setPriority:pc,complexity:fl,setComplexity:hl,status:po,setStatus:gl,approach:yl,setApproach:kl,assignee:Ci,setAssignee:Ua,scheduledDate:As,setScheduledDate:Dd,dueDate:Ld,setDueDate:ar,workstreamInput:Vo,setWorkstreamInput:fc,formTaxonomies:_t,setFormTaxonomies:wl,comments:gc,newCommentText:Sl,setNewCommentText:xi,attachments:Xo,setAttachments:Kd,attachmentsDirty:Cc,setAttachmentsDirty:Pl,descriptionFocused:Ni,setDescriptionFocused:bc,showMarkdownHelp:Po,setShowMarkdownHelp:Mo,showChecklist:Zo,setShowChecklist:yc,showComments:Vd,setShowComments:Fm,isCapturingScreenshot:_c,setIsCapturingScreenshot:qd,handleSubmit:Hi,resetForm:js,handleAddComment:xu,handleSetWorkstreamForCurrentTask:us,handleOpenTaskById:$i,returnToPreviousTask:$c,autoSaveState:sp,unsavedModalOpen:ba,setUnsavedModalOpen:ua,pendingNavigation:no,handleNavigation:tp,handleClose:Wi,uiNotice:hr,pushNotice:F,clearNotice:He,successBanner:op,taskReturnTrail:xt,clearReturnToParentTask:np,copiedId:ap,recentlyChangedTaskIds:Wo,scheduleWarningPrompt:ui,confirmScheduleWarning:Cu,cancelScheduleWarning:Au,tasksScrollRef:Rn,setTasksScrollPos:Wr,exportEnvironment:Gt,setExportEnvironment:ja,exportWorkflowsPath:Lr,setExportWorkflowsPath:Br,exportResult:fr,exportingResource:pr,handleUpdateCategory:mu,handleRemoveCategory:hu,handleSaveCategory:Zl,handleUpdateCategoryIcon:Yl,handleUpdateCategoryColor:Rs,handleSaveType:gu,handleRemoveType:yu,handleUpdateType:zr,handleUpdateTaxonomies:Fc,handleUpdatePriorities:di,handleUpdateTaxonomyDisplayLabels:Oc,pathValidation:oo,validatePaths:Ks,getCategoryPaths:uu,customCategories:so,setCustomCategories:ic,projectRoot:Oe,projectName:St,mcpScriptPath:Be,serverHostRoot:Sa,commentsEndRef:Wd,currentTask:ms,currentTaskWorkstream:Iu,currentTaskInitiative:Tu,availableWorkflows:et,initiativeTemplates:$t,availableEnvironments:da,fetchWorkflows:Tn,fetchInitiativeTemplates:_n,createInitiativeFromTemplate:cu,fetchWorkflowTemplate:wn,fetchWorkflowOverrideNames:Na,saveWorkflowTemplateDraft:Qa,resetWorkflowTemplateDraft:ys,onExportWorkflows:ks,settingsModel:Ru}}const Gb="modulepreload",Vb=function(e){return"/taskforce/"+e},Mh={},gs=function(t,a,s){let o=Promise.resolve();if(a&&a.length>0){let m=function(y){return Promise.all(y.map(k=>Promise.resolve(k).then(S=>({status:"fulfilled",value:S}),S=>({status:"rejected",reason:S}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),d=i?.nonce||i?.getAttribute("nonce");o=m(a.map(y=>{if(y=Vb(y),y in Mh)return;Mh[y]=!0;const k=y.endsWith(".css"),S=k?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${y}"]${S}`))return;const h=document.createElement("link");if(h.rel=k?"stylesheet":Gb,k||(h.as="script"),h.crossOrigin="",h.href=y,d&&h.setAttribute("nonce",d),document.head.appendChild(h),k)return new Promise((g,v)=>{h.addEventListener("load",g),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${y}`)))})}))}function c(i){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=i,window.dispatchEvent(d),!d.defaultPrevented)throw i}return o.then(i=>{for(const d of i||[])d.status==="rejected"&&c(d.reason);return t().catch(c)})},qb="_filterGlow_gi2cd_8",Kb="_floatingButton_gi2cd_18",Zb="_badge_gi2cd_49",Yb="_configBadge_gi2cd_66",Jb="_configBadgeActive_gi2cd_76",Qb="_configBadgeRevoked_gi2cd_82",Xb="_configBadgeExpired_gi2cd_88",e_="_header_gi2cd_98",t_="_headerTitle_gi2cd_113",n_="_brandIcon_gi2cd_131",a_="_brandHomeButton_gi2cd_137",r_="_brandHomeStatic_gi2cd_138",s_="_brandCloudSuffix_gi2cd_164",o_="_projectSlash_gi2cd_169",i_="_projectNameGroup_gi2cd_176",c_="_projectNameGroupHidden_gi2cd_183",l_="_projectName_gi2cd_176",d_="_taskCountBadge_gi2cd_210",u_="_taskCountBadgeIcon_gi2cd_227",m_="_taskCountBadgeAlert_gi2cd_231",p_="_headerActions_gi2cd_237",f_="_sortDirectionBtn_gi2cd_244",h_="_sortDirectionBtnWidget_gi2cd_251",g_="_form_gi2cd_259",y_="_topRow_gi2cd_271",k_="_field_gi2cd_277",v_="_labelRow_gi2cd_283",S_="_label_gi2cd_283",w_="_manageLink_gi2cd_297",b_="_input_gi2cd_316",__="_select_gi2cd_317",C_="_textarea_gi2cd_318",A_="_taskIdInlineLink_gi2cd_352",x_="_readOnly_gi2cd_371",I_="_selectWithConfig_gi2cd_379",T_="_configBtn_gi2cd_389",R_="_configBtnActive_gi2cd_419",N_="_hasPath_gi2cd_427",j_="_pathIndicator_gi2cd_432",P_="_formActions_gi2cd_438",M_="_hasCancel_gi2cd_445",E_="_submitBtn_gi2cd_449",D_="_cancelBtn_gi2cd_465",L_="_successMessage_gi2cd_497",B_="_errorMessage_gi2cd_503",W_="_successIcon_gi2cd_515",F_="_spinner_gi2cd_535",O_="_spin_gi2cd_535",$_="_boardRefreshIndicator_gi2cd_539",U_="_destructiveBtn_gi2cd_569",z_="_warningBtn_gi2cd_592",H_="_viewTab_gi2cd_615",G_="_deleteBtn_gi2cd_626",V_="_loading_gi2cd_636",q_="_emptyState_gi2cd_642",K_="_taskList_gi2cd_652",Z_="_taskIdBadge_gi2cd_658",Y_="_taskIdBadgeLabel_gi2cd_680",J_="_copiedId_gi2cd_699",Q_="_highlight_gi2cd_705",X_="_modal_gi2cd_717",eC="_priorityEmoji_gi2cd_725",tC="_metaItem_gi2cd_729",nC="_taskFormDateInput_gi2cd_743",aC="_metaBadge_gi2cd_753",rC="_complexityPill_gi2cd_768",sC="_complexityDots_gi2cd_772",oC="_dot_gi2cd_778",iC="_dotFilled_gi2cd_786",cC="_typePill_gi2cd_792",lC="_type_bug_gi2cd_796",dC="_type_feature_gi2cd_800",uC="_type_chore_gi2cd_804",mC="_type_refactor_gi2cd_808",pC="_type_documentation_gi2cd_812",fC="_type_research_gi2cd_816",hC="_type_security_gi2cd_824",gC="_approachPill_gi2cd_829",yC="_approach_evaluate_gi2cd_834",kC="_approach_collaborate_gi2cd_840",vC="_approach_plan_gi2cd_846",SC="_approachActive_gi2cd_852",wC="_statusActionsGroup_gi2cd_857",bC="_statusActionsGroupCompact_gi2cd_863",_C="_statusSelectWrap_gi2cd_867",CC="_statusTaxonomyDropdownWrap_gi2cd_873",AC="_statusTaxonomyDropdown_gi2cd_873",xC="_statusTaxonomyDropdownCompact_gi2cd_881",IC="_statusTaxonomyDropdownIconOnly_gi2cd_885",TC="_taxonomyDropdownButton_gi2cd_890",RC="_taxonomyDropdownButtonContent_gi2cd_907",NC="_statusTaxonomyDropdownIconOnlyPanel_gi2cd_911",jC="_actionBtn_gi2cd_917",PC="_startWorkBtn_gi2cd_941",MC="_workingBtn_gi2cd_950",EC="_pulse_gi2cd_1",DC="_reviewBtn_gi2cd_956",LC="_reviewActiveBtn_gi2cd_966",BC="_reviewPill_gi2cd_972",WC="_archiveTaskBtn_gi2cd_979",FC="_bulkArchiveBtn_gi2cd_988",OC="_bulkDeleteBtn_gi2cd_1010",$C="_completeBtn_gi2cd_1051",UC="_completeActiveBtn_gi2cd_1061",zC="_deleteActiveBtn_gi2cd_1067",HC="_disabledBtn_gi2cd_1073",GC="_archiveList_gi2cd_1080",VC="_archiveHeader_gi2cd_1088",qC="_settingsTab_gi2cd_1099",KC="_settingsTabMcpOnly_gi2cd_1108",ZC="_settingsTabs_gi2cd_1117",YC="_settingsLayout_gi2cd_1131",JC="_settingsLayoutMcpOnly_gi2cd_1138",QC="_settingsSidebar_gi2cd_1144",XC="_settingsSidebarHeader_gi2cd_1154",eA="_settingsSidebarNav_gi2cd_1163",tA="_settingsSidebarBtn_gi2cd_1172",nA="_settingsSidebarBtnActive_gi2cd_1196",aA="_settingsSidebarGroup_gi2cd_1203",rA="_settingsSidebarGroupBtn_gi2cd_1209",sA="_settingsSidebarGroupLabel_gi2cd_1213",oA="_settingsSidebarGroupChevron_gi2cd_1217",iA="_settingsSidebarSubnav_gi2cd_1223",cA="_settingsSidebarSubBtn_gi2cd_1230",lA="_appScrollbar_gi2cd_1253",dA="_settingsTabBtn_gi2cd_1257",uA="_settingsTabBtnActive_gi2cd_1283",mA="_settingsContent_gi2cd_1289",pA="_mcpRegistrationHint_gi2cd_1315",fA="_mcpRegistrationPrompt_gi2cd_1326",hA="_mcpCodexTrustNote_gi2cd_1345",gA="_mcpCodexTrustHeader_gi2cd_1356",yA="_mcpCodexTrustTitle_gi2cd_1363",kA="_mcpCodexTrustCode_gi2cd_1369",vA="_mcpAuthRequiredCard_gi2cd_1384",SA="_mcpAuthRequiredIcon_gi2cd_1396",wA="_mcpAuthRequiredBody_gi2cd_1409",bA="_mcpAuthRequiredActions_gi2cd_1416",_A="_settingsToast_gi2cd_1460",CA="_settingsToastSuccess_gi2cd_1477",AA="_settingsToastError_gi2cd_1483",xA="_inputWithPrefix_gi2cd_1489",IA="_pathHint_gi2cd_1496",TA="_settingGroup_gi2cd_1509",RA="_settingTitle_gi2cd_1515",NA="_settingTitleRow_gi2cd_1524",jA="_settingTitleActionBtn_gi2cd_1531",PA="_themeOptions_gi2cd_1551",MA="_buttonGrid_gi2cd_1556",EA="_themeBtn_gi2cd_1568",DA="_activeTheme_gi2cd_1592",LA="_pathInputGroup_gi2cd_1600",BA="_saveSettingsBtn_gi2cd_1609",WA="_shortcutInputWrapper_gi2cd_1630",FA="_inputIcon_gi2cd_1635",OA="_settingHelper_gi2cd_1644",$A="_browseBtn_gi2cd_1651",UA="_inlineCategoryManager_gi2cd_1670",zA="_categoryManager_gi2cd_1681",HA="_categoryList_gi2cd_1687",GA="_categoryChip_gi2cd_1699",VA="_categoryChipLabel_gi2cd_1712",qA="_chipActionBtn_gi2cd_1720",KA="_removeCategoryBtn_gi2cd_1740",ZA="_addCategoryForm_gi2cd_1760",YA="_addCategoryBtn_gi2cd_1765",JA="_filesList_gi2cd_1790",QA="_helpLink_gi2cd_1817",XA="_inlineCode_gi2cd_1838",ex="_codeBlock_gi2cd_1849",tx="_taskChildrenSummaryBadges_gi2cd_1873",nx="_taskChildrenProgressBar_gi2cd_1881",ax="_taskChildrenProgressBarSegmentDone_gi2cd_1892",rx="_taskChildrenProgressBarSegmentReview_gi2cd_1898",sx="_taskChildrenProgressBarSegmentInProgress_gi2cd_1904",ox="_taskChildrenProgressBarSegmentBlocked_gi2cd_1910",ix="_taskChildrenProgressText_gi2cd_1916",cx="_taskChildUnlinkBtn_gi2cd_1925",lx="_aboutText_gi2cd_1943",dx="_versionInfo_gi2cd_1950",ux="_filterBar_gi2cd_1958",mx="_kanbanHintText_gi2cd_1972",px="_searchContainer_gi2cd_1978",fx="_searchIcon_gi2cd_1985",hx="_searchInput_gi2cd_1993",gx="_searchActive_gi2cd_2019",yx="_searchCount_gi2cd_2024",kx="_clearSearchBtn_gi2cd_2040",vx="_filterRow_gi2cd_2062",Sx="_sortLabel_gi2cd_2068",wx="_archiveToggle_gi2cd_2076",bx="_filterContainer_gi2cd_2113",_x="_filterButton_gi2cd_2118",Cx="_filterActive_gi2cd_2143",Ax="_filterDropdown_gi2cd_2149",xx="_filterOption_gi2cd_2164",Ix="_filterDivider_gi2cd_2194",Tx="_filterSelect_gi2cd_2200",Rx="_filterToggleBtn_gi2cd_2241",Nx="_inProgressToggle_gi2cd_2263",jx="_activeInProgress_gi2cd_2281",Px="_activeFilter_gi2cd_2290",Mx="_resetFiltersBtn_gi2cd_2300",Ex="_categoryChip_disabled_gi2cd_2333",Dx="_categoryVisibilityToggle_gi2cd_2343",Lx="_editCategoryInput_gi2cd_2356",Bx="_categoryChipActionBtn_gi2cd_2367",Wx="_categoryChipActionBtn_active_gi2cd_2385",Fx="_categoryGroup_gi2cd_2390",Ox="_categoryHeader_gi2cd_2398",$x="_categoryTitle_gi2cd_2412",Ux="_categoryCount_gi2cd_2422",zx="_categoryItems_gi2cd_2428",Hx="_priorityItem_low_gi2cd_2437",Gx="_priorityItem_medium_gi2cd_2441",Vx="_priorityItem_high_gi2cd_2445",qx="_priorityItem_critical_gi2cd_2449",Kx="_priorityPill_low_gi2cd_2453",Zx="_priorityPill_medium_gi2cd_2459",Yx="_priorityPill_high_gi2cd_2465",Jx="_priorityPill_critical_gi2cd_2471",Qx="_selectPriority_low_gi2cd_2486",Xx="_selectPriority_medium_gi2cd_2491",eI="_selectPriority_high_gi2cd_2496",tI="_selectPriority_critical_gi2cd_2501",nI="_levelSelect_gi2cd_2510",aI="_levelOption_gi2cd_2523",rI="_levelOptionFilled_gi2cd_2540",sI="_levelOption_priority_low_gi2cd_2547",oI="_levelOption_priority_medium_gi2cd_2552",iI="_levelOption_priority_high_gi2cd_2557",cI="_levelOption_priority_critical_gi2cd_2562",lI="_levelOption_complexity_tiny_gi2cd_2569",dI="_levelOption_complexity_low_gi2cd_2574",uI="_levelOption_complexity_medium_gi2cd_2579",mI="_levelOption_complexity_high_gi2cd_2584",pI="_levelOption_complexity_epic_gi2cd_2589",fI="_levelOptionActive_gi2cd_2596",hI="_levelOptionSelected_gi2cd_2601",gI="_levelLabel_gi2cd_2609",yI="_fadeIn_gi2cd_1",kI="_closeConfigBtn_gi2cd_2634",vI="_configItem_gi2cd_2656",SI="_settingsLabel_gi2cd_2662",wI="_settingsHint_gi2cd_2671",bI="_pathList_gi2cd_2678",_I="_pathChip_gi2cd_2685",CI="_pathValid_gi2cd_2698",AI="_pathInvalid_gi2cd_2703",xI="_pathValidIcon_gi2cd_2708",II="_pathInvalidIcon_gi2cd_2713",TI="_pathText_gi2cd_2718",RI="_removePathBtn_gi2cd_2725",NI="_pathCount_gi2cd_2747",jI="_specialistSection_gi2cd_2770",PI="_toggleHeading_gi2cd_2778",MI="_dropdownList_gi2cd_2818",EI="_specialistBadge_gi2cd_2827",DI="_iconGrid_gi2cd_2857",LI="_iconPickerBtn_gi2cd_2868",BI="_iconPickerBtnActive_gi2cd_2887",WI="_categorySubConfig_gi2cd_2894",FI="_colorPickerRow_gi2cd_2902",OI="_colorPickerGrid_gi2cd_2908",$I="_colorSwatch_gi2cd_2915",UI="_colorSwatchActive_gi2cd_2934",zI="_categoryChipIcon_gi2cd_2940",HI="_fieldIconWrapper_gi2cd_2945",GI="_fieldIcon_gi2cd_2945",VI="_field_dynamic_gi2cd_2967",qI="_fieldIcon_dynamic_gi2cd_2973",KI="_categoryTitleIcon_gi2cd_2977",ZI="_editActionsHeader_gi2cd_2983",YI="_editActionsGroup_gi2cd_2992",JI="_urlInputGroup_gi2cd_2999",QI="_iconBtn_gi2cd_3012",XI="_stickyActionHeader_gi2cd_3033",eT="_taskHierarchyHeader_gi2cd_3050",tT="_taskHierarchyBadgeRow_gi2cd_3057",nT="_taskHierarchyDivider_gi2cd_3065",aT="_taskHierarchySegment_gi2cd_3071",rT="_taskHierarchyMeta_gi2cd_3078",sT="_taskHierarchyActionBtn_gi2cd_3091",oT="_taskHierarchyEditor_gi2cd_3097",iT="_taskHierarchyInput_gi2cd_3104",cT="_taskSaveStatus_gi2cd_3113",lT="_taskSaveStatusCenter_gi2cd_3124",dT="_taskSaveStatusError_gi2cd_3132",uT="_headerSuccessFeedback_gi2cd_3136",mT="_slideInUp_gi2cd_1",pT="_successCheck_gi2cd_3148",fT="_scaleIn_gi2cd_1",hT="_primaryUpdateBtn_gi2cd_3184",gT="_secondaryHeaderBtn_gi2cd_3212",yT="_secondaryHeaderBtnDestructive_gi2cd_3233",kT="_commentSection_gi2cd_3246",vT="_attachmentCaptureContainer_gi2cd_3282",ST="_capturePrompt_gi2cd_3290",wT="_previewContainer_gi2cd_3304",bT="_previewHeader_gi2cd_3310",_T="_attachmentCapturePreview_gi2cd_3320",CT="_actions_gi2cd_3327",AT="_primaryButton_gi2cd_3333",xT="_secondaryButton_gi2cd_3348",IT="_iconButton_gi2cd_3363",TT="_attachmentGrid_gi2cd_3385",RT="_attachmentCard_gi2cd_3392",NT="_attachmentPreviewContainer_gi2cd_3406",jT="_contextFileLink_gi2cd_3427",PT="_attachmentActions_gi2cd_3453",MT="_attachmentActionBtn_gi2cd_3467",ET="_attachmentCaptionInput_gi2cd_3489",DT="_hiddenInput_gi2cd_3507",LT="_contextUploadPanel_gi2cd_3511",BT="_contextUploadActions_gi2cd_3519",WT="_contextDropzone_gi2cd_3527",FT="_contextDropzoneActive_gi2cd_3543",OT="_contextDropzonePulse_gi2cd_1",$T="_contextLinkRow_gi2cd_3551",UT="_contextNotice_gi2cd_3557",zT="_documentAttachmentList_gi2cd_3563",HT="_documentAttachmentItem_gi2cd_3570",GT="_documentAttachmentRow_gi2cd_3577",VT="_documentAttachmentLink_gi2cd_3585",qT="_documentAttachmentMain_gi2cd_3599",KT="_documentAttachmentText_gi2cd_3606",ZT="_documentAttachmentIcon_gi2cd_3614",YT="_documentAttachmentName_gi2cd_3625",JT="_documentAttachmentType_gi2cd_3634",QT="_documentAttachmentActions_gi2cd_3647",XT="_documentAttachmentActionBtn_gi2cd_3653",eR="_documentAttachmentCaptionInput_gi2cd_3674",tR="_brokenImage_gi2cd_3702",nR="_brokenImagePlaceholder_gi2cd_3710",aR="_regionOverlay_gi2cd_3724",rR="_selectionBox_gi2cd_3735",sR="_exportRow_gi2cd_3743",oR="_exportItem_gi2cd_3748",iR="_taxonomyDrillDown_gi2cd_3757",cR="_drillDownList_gi2cd_3767",lR="_drillDownSection_gi2cd_3775",dR="_drillDownSectionHeader_gi2cd_3781",uR="_drillDownSectionTitle_gi2cd_3788",mR="_drillDownItem_gi2cd_3797",pR="_drillDownItemDimmed_gi2cd_3819",fR="_drillDownItemActive_gi2cd_3827",hR="_drillDownItemInfo_gi2cd_3832",gR="_drillDownItemText_gi2cd_3838",yR="_drillDownItemLabel_gi2cd_3843",kR="_drillDownItemSubtext_gi2cd_3848",vR="_addTaxonomyBtnSmall_gi2cd_3853",SR="_taxonomyDetailView_gi2cd_3875",wR="_slideIn_gi2cd_1",bR="_detailHeader_gi2cd_3895",_R="_detailTitle_gi2cd_3904",CR="_detailContent_gi2cd_3911",AR="_createOverlay_gi2cd_3918",xR="_createDialog_gi2cd_3930",IR="_zoomIn_gi2cd_1",TR="_dialogActions_gi2cd_3958",RR="_settingsGroup_gi2cd_3976",NR="_settingsItem_gi2cd_3982",jR="_settingLabelGroup_gi2cd_3988",PR="_settingLabel_gi2cd_3988",MR="_settingDescription_gi2cd_4000",ER="_settingInput_gi2cd_4007",DR="_codeBlockWrapper_gi2cd_4030",LR="_codeHeader_gi2cd_4039",BR="_codeHeaderActions_gi2cd_4050",WR="_codeLabel_gi2cd_4057",FR="_codeHeaderDescription_gi2cd_4065",OR="_mcpTokenCardBody_gi2cd_4073",$R="_mcpTokenFormGrid_gi2cd_4081",UR="_mcpTokenOutputWrap_gi2cd_4088",zR="_mcpTokenValueField_gi2cd_4095",HR="_mcpTokenValueText_gi2cd_4105",GR="_mcpTokenValueInput_gi2cd_4118",VR="_mcpTokenActionRow_gi2cd_4123",qR="_copyBtn_gi2cd_4146",KR="_copyBtnActive_gi2cd_4167",ZR="_copyBtnNeutralActive_gi2cd_4173",YR="_headerDivider_gi2cd_4191",JR="_groupByContainer_gi2cd_4197",QR="_groupByLabel_gi2cd_4205",XR="_groupBySelect_gi2cd_4210",eN="_viewSwitcher_gi2cd_4232",tN="_selectWithIcon_gi2cd_4240",nN="_marginBottom16_gi2cd_4244",aN="_headerDraggable_gi2cd_4249",rN="_headerDragging_gi2cd_4253",sN="_filterSelectSort_gi2cd_4261",oN="_archiveRow_gi2cd_4265",iN="_taskScopeToggle_gi2cd_4271",cN="_taskScopeTabs_gi2cd_4279",lN="_taskScopeTab_gi2cd_4279",dN="_taskScopeTabActive_gi2cd_4312",uN="_taskToolbarAction_gi2cd_4324",mN="_overlayHighZ_gi2cd_4340",pN="_savedText_gi2cd_4350",fN="_shortcutInput_gi2cd_1630",hN="_saveSettingsBtnWrapper_gi2cd_4358",gN="_marginBottom12_gi2cd_4362",yN="_exportRowGrid_gi2cd_4366",kN="_settingSubtitleCustom_gi2cd_4371",vN="_capitalize_gi2cd_4377",SN="_marginTop12_gi2cd_4381",wN="_marginTop16_gi2cd_4385",bN="_labelGroupFlex_gi2cd_4389",_N="_codeBlockWrapperCustom_gi2cd_4395",CN="_kanbanWrapper_gi2cd_4401",AN="_kanbanContainer_gi2cd_4409",xN="_kanbanTopScroll_gi2cd_4431",IN="_kanbanTopScrollSpacer_gi2cd_4440",TN="_kanbanColumn_gi2cd_4444",RN="_kanbanColumnSticky_gi2cd_4460",NN="_kanbanColumnCollapsed_gi2cd_4466",jN="_kanbanColumnPast_gi2cd_4471",PN="_kanbanColumnSelectedDay_gi2cd_4476",MN="_kanbanHeader_gi2cd_4483",EN="_kanbanCount_gi2cd_4493",DN="_kanbanHeaderDraggable_gi2cd_4513",LN="_kanbanHeaderPanning_gi2cd_4517",BN="_kanbanQuickAdd_gi2cd_4521",WN="_kanbanColorDot_gi2cd_4542",FN="_kanbanDroppable_gi2cd_4554",ON="_kanbanDroppableScroll_gi2cd_4563",$N="_kanbanEmpty_gi2cd_4573",UN="_kanbanCard_gi2cd_4583",zN="_kanbanCardWrapper_gi2cd_4593",HN="_taxonomyDropdownActive_gi2cd_4601",GN="_kanbanCardWrapperRaised_gi2cd_4605",VN="_kanbanCardTitle_gi2cd_4609",qN="_kanbanBadges_gi2cd_4613",KN="_kanbanBadge_gi2cd_4613",ZN="_headerFlex_gi2cd_4629",YN="_marginBottom8_gi2cd_4636",JN="_marginBottom20_gi2cd_4640",QN="_configPanel_gi2cd_4644",XN="_configPanelLarge_gi2cd_4653",ej="_subLabelBlock_gi2cd_4657",tj="_subLabelBlock12_gi2cd_4664",nj="_flexBetween_gi2cd_4668",aj="_flexBetweenCenter_gi2cd_4675",rj="_deleteBtnSmall_gi2cd_4680",sj="_deleteBtnMedium_gi2cd_4686",oj="_trashIcon_gi2cd_4693",ij="_gridConfig_gi2cd_4697",cj="_flexColGap4_gi2cd_4704",lj="_flexColGap4Center_gi2cd_4710",dj="_flex1_gi2cd_4717",uj="_flexCol_gi2cd_4704",mj="_flexGrow1_gi2cd_4727",pj="_inputLabel_gi2cd_4731",fj="_inputLabelBlock_gi2cd_4735",hj="_checkboxInput_gi2cd_4741",gj="_configDividerMargin_gi2cd_4747",yj="_configDividerMargin24_gi2cd_4752",kj="_pathListMargin_gi2cd_4757",vj="_cancelBtnRed_gi2cd_4761",Sj="_code_gi2cd_1849",wj="_workflowList_gi2cd_4788",bj="_workflowActions_gi2cd_4796",_j="_textBtn_gi2cd_4805",Cj="_workflowGrid_gi2cd_4819",Aj="_checkboxLabel_gi2cd_4827",xj="_checkboxSmall_gi2cd_4841",Ij="_docWorkspace_gi2cd_4860",Tj="_docIndexPanel_gi2cd_4871",Rj="_docWorkspaceTrayMode_gi2cd_4883",Nj="_docViewerPanel_gi2cd_4883",jj="_docWorkspaceTrayOpen_gi2cd_4888",Pj="_docTrayPanel_gi2cd_4892",Mj="_docTrayPanelOpen_gi2cd_4916",Ej="_docSpinning_gi2cd_4924",Dj="_docSpin_gi2cd_4924",Lj="_docViewerEmpty_gi2cd_4943",Bj="_agentsModuleRoot_gi2cd_4958",Wj="_agentsModuleWithTray_gi2cd_4970",Fj="_agentsModuleTrayOpen_gi2cd_4974",Oj="_agentTrayPanel_gi2cd_4978",$j="_agentTrayPanelOpen_gi2cd_5001",Uj="_agentTrayHeader_gi2cd_5009",zj="_agentTrayTitle_gi2cd_5024",Hj="_agentTrayContent_gi2cd_5036",Gj="_agentTrayContentInner_gi2cd_5044",Vj="_agentsModuleContent_gi2cd_5048",qj="_agentsModuleGroup_gi2cd_5053",Kj="_marginTop24_gi2cd_5057",Zj="_settingSubTitle_gi2cd_5061",Yj="_dangerBtn_gi2cd_5070",Jj="_aiProfilesExplorer_gi2cd_5086",Qj="_aiProfilesListPane_gi2cd_5097",Xj="_aiProfilesList_gi2cd_5097",eP="_aiProfilesSection_gi2cd_5116",tP="_aiProfilesSectionHeader_gi2cd_5122",nP="_aiProfileGroup_gi2cd_5130",aP="_aiProfileGroupSelected_gi2cd_5153",rP="_aiProfileGroupDuplicate_gi2cd_5162",sP="_aiProfileGroupHeader_gi2cd_5167",oP="_aiProfileGroupAvatar_gi2cd_5175",iP="_aiProfileGroupIdentity_gi2cd_5197",cP="_aiProfileName_gi2cd_5206",lP="_aiProfileHandle_gi2cd_5214",dP="_aiProfileRole_gi2cd_5215",uP="_aiProfileSeatSummary_gi2cd_5226",mP="_aiProfileSeatScopeIcon_gi2cd_5235",pP="_aiProfileSeatScopeIconDetail_gi2cd_5246",fP="_aiProfileSeatScopeIconCloud_gi2cd_5251",hP="_aiProfileSeatScopeIconLocal_gi2cd_5255",gP="_aiProfileDuplicateBadge_gi2cd_5259",yP="_aiProfileMergeSection_gi2cd_5271",kP="_aiProfileMergeRow_gi2cd_5278",vP="_aiProfileIdChip_gi2cd_5285",SP="_aiProfileKeepBadge_gi2cd_5297",wP="_aiProfileMergeActions_gi2cd_5311",bP="_aiProfileDetailPane_gi2cd_5318",_P="_aiProfileDetailCard_gi2cd_5324",CP="_aiProfileDetailHero_gi2cd_5336",AP="_aiProfileDetailIcon_gi2cd_5342",xP="_aiProfileDetailAvatar_gi2cd_5356",IP="_aiProfileDetailHeading_gi2cd_5360",TP="_aiProfileDetailTitleRow_gi2cd_5365",RP="_aiProfileDetailTitle_gi2cd_5365",NP="_aiProfileDetailMetaRow_gi2cd_5380",jP="_aiProfileDetailHandle_gi2cd_5388",PP="_aiProfileDetailRole_gi2cd_5393",MP="_aiProfileDetailLinkedCount_gi2cd_5400",EP="_aiProfileDetailDescription_gi2cd_5405",DP="_aiProfileSignatureColor_gi2cd_5412",LP="_aiProfileSignatureSwatch_gi2cd_5422",BP="_aiProfileDetailDataList_gi2cd_5432",WP="_aiProfileDetailDataGroup_gi2cd_5441",FP="_aiProfileDetailDateGroup_gi2cd_5448",OP="_aiProfileDetailDataRow_gi2cd_5453",$P="_aiProfileDetailDataLabel_gi2cd_5462",UP="_aiProfileDetailDataValue_gi2cd_5469",zP="_aiProfileStatusSelect_gi2cd_5475",HP="_aiProfileInstanceSection_gi2cd_5517",GP="_aiProfileInstanceSectionHeader_gi2cd_5523",VP="_aiProfileInstanceList_gi2cd_5533",qP="_aiProfileInstanceCard_gi2cd_5539",KP="_aiProfileIdFooter_gi2cd_5552",ZP="_aiProfileIdFooterValue_gi2cd_5562",YP="_aiProfileDangerTextButton_gi2cd_5572",JP="_aiProfileInstanceTopRow_gi2cd_5604",QP="_aiProfileInstanceName_gi2cd_5611",XP="_aiProfileInstanceMeta_gi2cd_5618",e0="_aiProfileInlineError_gi2cd_5626",f={filterGlow:qb,floatingButton:Kb,badge:Zb,configBadge:Yb,configBadgeActive:Jb,configBadgeRevoked:Qb,configBadgeExpired:Xb,header:e_,headerTitle:t_,brandIcon:n_,brandHomeButton:a_,brandHomeStatic:r_,brandCloudSuffix:s_,projectSlash:o_,projectNameGroup:i_,projectNameGroupHidden:c_,projectName:l_,taskCountBadge:d_,taskCountBadgeIcon:u_,taskCountBadgeAlert:m_,headerActions:p_,sortDirectionBtn:f_,sortDirectionBtnWidget:h_,form:g_,topRow:y_,field:k_,labelRow:v_,label:S_,manageLink:w_,input:b_,select:__,textarea:C_,taskIdInlineLink:A_,readOnly:x_,selectWithConfig:I_,configBtn:T_,configBtnActive:R_,hasPath:N_,pathIndicator:j_,formActions:P_,hasCancel:M_,submitBtn:E_,cancelBtn:D_,successMessage:L_,errorMessage:B_,successIcon:W_,spinner:F_,spin:O_,boardRefreshIndicator:$_,destructiveBtn:U_,warningBtn:z_,viewTab:H_,deleteBtn:G_,loading:V_,emptyState:q_,taskList:K_,taskIdBadge:Z_,taskIdBadgeLabel:Y_,copiedId:J_,highlight:Q_,modal:X_,priorityEmoji:eC,metaItem:tC,taskFormDateInput:nC,metaBadge:aC,complexityPill:rC,complexityDots:sC,dot:oC,dotFilled:iC,typePill:cC,type_bug:lC,type_feature:dC,type_chore:uC,type_refactor:mC,type_documentation:pC,type_research:fC,"type_ui-ux":"_type_ui-ux_gi2cd_820",type_security:hC,approachPill:gC,approach_evaluate:yC,approach_collaborate:kC,approach_plan:vC,approachActive:SC,statusActionsGroup:wC,statusActionsGroupCompact:bC,statusSelectWrap:_C,statusTaxonomyDropdownWrap:CC,statusTaxonomyDropdown:AC,statusTaxonomyDropdownCompact:xC,statusTaxonomyDropdownIconOnly:IC,taxonomyDropdownButton:TC,taxonomyDropdownButtonContent:RC,statusTaxonomyDropdownIconOnlyPanel:NC,actionBtn:jC,startWorkBtn:PC,workingBtn:MC,pulse:EC,reviewBtn:DC,reviewActiveBtn:LC,reviewPill:BC,archiveTaskBtn:WC,bulkArchiveBtn:FC,bulkDeleteBtn:OC,completeBtn:$C,completeActiveBtn:UC,deleteActiveBtn:zC,disabledBtn:HC,archiveList:GC,archiveHeader:VC,settingsTab:qC,settingsTabMcpOnly:KC,settingsTabs:ZC,settingsLayout:YC,settingsLayoutMcpOnly:JC,settingsSidebar:QC,settingsSidebarHeader:XC,settingsSidebarNav:eA,settingsSidebarBtn:tA,settingsSidebarBtnActive:nA,settingsSidebarGroup:aA,settingsSidebarGroupBtn:rA,settingsSidebarGroupLabel:sA,settingsSidebarGroupChevron:oA,settingsSidebarSubnav:iA,settingsSidebarSubBtn:cA,appScrollbar:lA,settingsTabBtn:dA,settingsTabBtnActive:uA,settingsContent:mA,mcpRegistrationHint:pA,mcpRegistrationPrompt:fA,mcpCodexTrustNote:hA,mcpCodexTrustHeader:gA,mcpCodexTrustTitle:yA,mcpCodexTrustCode:kA,mcpAuthRequiredCard:vA,mcpAuthRequiredIcon:SA,mcpAuthRequiredBody:wA,mcpAuthRequiredActions:bA,settingsToast:_A,settingsToastSuccess:CA,settingsToastError:AA,inputWithPrefix:xA,pathHint:IA,settingGroup:TA,settingTitle:RA,settingTitleRow:NA,settingTitleActionBtn:jA,themeOptions:PA,buttonGrid:MA,themeBtn:EA,activeTheme:DA,pathInputGroup:LA,saveSettingsBtn:BA,shortcutInputWrapper:WA,inputIcon:FA,settingHelper:OA,browseBtn:$A,inlineCategoryManager:UA,categoryManager:zA,categoryList:HA,categoryChip:GA,categoryChipLabel:VA,chipActionBtn:qA,removeCategoryBtn:KA,addCategoryForm:ZA,addCategoryBtn:YA,filesList:JA,helpLink:QA,inlineCode:XA,codeBlock:ex,taskChildrenSummaryBadges:tx,taskChildrenProgressBar:nx,taskChildrenProgressBarSegmentDone:ax,taskChildrenProgressBarSegmentReview:rx,taskChildrenProgressBarSegmentInProgress:sx,taskChildrenProgressBarSegmentBlocked:ox,taskChildrenProgressText:ix,taskChildUnlinkBtn:cx,aboutText:lx,versionInfo:dx,filterBar:ux,kanbanHintText:mx,searchContainer:px,searchIcon:fx,searchInput:hx,searchActive:gx,searchCount:yx,clearSearchBtn:kx,filterRow:vx,sortLabel:Sx,archiveToggle:wx,filterContainer:bx,filterButton:_x,filterActive:Cx,filterDropdown:Ax,filterOption:xx,filterDivider:Ix,filterSelect:Tx,filterToggleBtn:Rx,inProgressToggle:Nx,activeInProgress:jx,activeFilter:Px,resetFiltersBtn:Mx,categoryChip_disabled:Ex,categoryVisibilityToggle:Dx,editCategoryInput:Lx,categoryChipActionBtn:Bx,categoryChipActionBtn_active:Wx,categoryGroup:Fx,categoryHeader:Ox,categoryTitle:$x,categoryCount:Ux,categoryItems:zx,priorityItem_low:Hx,priorityItem_medium:Gx,priorityItem_high:Vx,priorityItem_critical:qx,priorityPill_low:Kx,priorityPill_medium:Zx,priorityPill_high:Yx,priorityPill_critical:Jx,selectPriority_low:Qx,selectPriority_medium:Xx,selectPriority_high:eI,selectPriority_critical:tI,"critical-glow":"_critical-glow_gi2cd_1",levelSelect:nI,levelOption:aI,levelOptionFilled:rI,levelOption_priority_low:sI,levelOption_priority_medium:oI,levelOption_priority_high:iI,levelOption_priority_critical:cI,levelOption_complexity_tiny:lI,levelOption_complexity_low:dI,levelOption_complexity_medium:uI,levelOption_complexity_high:mI,levelOption_complexity_epic:pI,levelOptionActive:fI,levelOptionSelected:hI,levelLabel:gI,fadeIn:yI,closeConfigBtn:kI,configItem:vI,settingsLabel:SI,settingsHint:wI,pathList:bI,pathChip:_I,pathValid:CI,pathInvalid:AI,pathValidIcon:xI,pathInvalidIcon:II,pathText:TI,removePathBtn:RI,pathCount:NI,specialistSection:jI,toggleHeading:PI,dropdownList:MI,specialistBadge:EI,iconGrid:DI,iconPickerBtn:LI,iconPickerBtnActive:BI,categorySubConfig:WI,colorPickerRow:FI,colorPickerGrid:OI,colorSwatch:$I,colorSwatchActive:UI,categoryChipIcon:zI,fieldIconWrapper:HI,fieldIcon:GI,field_dynamic:VI,fieldIcon_dynamic:qI,categoryTitleIcon:KI,editActionsHeader:ZI,editActionsGroup:YI,urlInputGroup:JI,iconBtn:QI,stickyActionHeader:XI,taskHierarchyHeader:eT,taskHierarchyBadgeRow:tT,taskHierarchyDivider:nT,taskHierarchySegment:aT,taskHierarchyMeta:rT,taskHierarchyActionBtn:sT,taskHierarchyEditor:oT,taskHierarchyInput:iT,taskSaveStatus:cT,taskSaveStatusCenter:lT,taskSaveStatusError:dT,headerSuccessFeedback:uT,slideInUp:mT,successCheck:pT,scaleIn:fT,primaryUpdateBtn:hT,secondaryHeaderBtn:gT,secondaryHeaderBtnDestructive:yT,commentSection:kT,attachmentCaptureContainer:vT,capturePrompt:ST,previewContainer:wT,previewHeader:bT,attachmentCapturePreview:_T,actions:CT,primaryButton:AT,secondaryButton:xT,iconButton:IT,attachmentGrid:TT,attachmentCard:RT,attachmentPreviewContainer:NT,contextFileLink:jT,attachmentActions:PT,attachmentActionBtn:MT,attachmentCaptionInput:ET,hiddenInput:DT,contextUploadPanel:LT,contextUploadActions:BT,contextDropzone:WT,contextDropzoneActive:FT,contextDropzonePulse:OT,contextLinkRow:$T,contextNotice:UT,documentAttachmentList:zT,documentAttachmentItem:HT,documentAttachmentRow:GT,documentAttachmentLink:VT,documentAttachmentMain:qT,documentAttachmentText:KT,documentAttachmentIcon:ZT,documentAttachmentName:YT,documentAttachmentType:JT,documentAttachmentActions:QT,documentAttachmentActionBtn:XT,documentAttachmentCaptionInput:eR,brokenImage:tR,brokenImagePlaceholder:nR,regionOverlay:aR,selectionBox:rR,exportRow:sR,exportItem:oR,taxonomyDrillDown:iR,drillDownList:cR,drillDownSection:lR,drillDownSectionHeader:dR,drillDownSectionTitle:uR,drillDownItem:mR,drillDownItemDimmed:pR,drillDownItemActive:fR,drillDownItemInfo:hR,drillDownItemText:gR,drillDownItemLabel:yR,drillDownItemSubtext:kR,addTaxonomyBtnSmall:vR,taxonomyDetailView:SR,slideIn:wR,detailHeader:bR,detailTitle:_R,detailContent:CR,createOverlay:AR,createDialog:xR,zoomIn:IR,dialogActions:TR,settingsGroup:RR,settingsItem:NR,settingLabelGroup:jR,settingLabel:PR,settingDescription:MR,settingInput:ER,codeBlockWrapper:DR,codeHeader:LR,codeHeaderActions:BR,codeLabel:WR,codeHeaderDescription:FR,mcpTokenCardBody:OR,mcpTokenFormGrid:$R,mcpTokenOutputWrap:UR,mcpTokenValueField:zR,mcpTokenValueText:HR,mcpTokenValueInput:GR,mcpTokenActionRow:VR,copyBtn:qR,copyBtnActive:KR,copyBtnNeutralActive:ZR,headerDivider:YR,groupByContainer:JR,groupByLabel:QR,groupBySelect:XR,viewSwitcher:eN,selectWithIcon:tN,marginBottom16:nN,headerDraggable:aN,headerDragging:rN,filterSelectSort:sN,archiveRow:oN,taskScopeToggle:iN,taskScopeTabs:cN,taskScopeTab:lN,taskScopeTabActive:dN,taskToolbarAction:uN,overlayHighZ:mN,savedText:pN,shortcutInput:fN,saveSettingsBtnWrapper:hN,marginBottom12:gN,exportRowGrid:yN,settingSubtitleCustom:kN,capitalize:vN,marginTop12:SN,marginTop16:wN,labelGroupFlex:bN,codeBlockWrapperCustom:_N,kanbanWrapper:CN,kanbanContainer:AN,kanbanTopScroll:xN,kanbanTopScrollSpacer:IN,kanbanColumn:TN,kanbanColumnSticky:RN,kanbanColumnCollapsed:NN,kanbanColumnPast:jN,kanbanColumnSelectedDay:PN,kanbanHeader:MN,kanbanCount:EN,kanbanHeaderDraggable:DN,kanbanHeaderPanning:LN,kanbanQuickAdd:BN,kanbanColorDot:WN,kanbanDroppable:FN,kanbanDroppableScroll:ON,kanbanEmpty:$N,kanbanCard:UN,kanbanCardWrapper:zN,taxonomyDropdownActive:HN,kanbanCardWrapperRaised:GN,kanbanCardTitle:VN,kanbanBadges:qN,kanbanBadge:KN,headerFlex:ZN,marginBottom8:YN,marginBottom20:JN,configPanel:QN,configPanelLarge:XN,subLabelBlock:ej,subLabelBlock12:tj,flexBetween:nj,flexBetweenCenter:aj,deleteBtnSmall:rj,deleteBtnMedium:sj,trashIcon:oj,gridConfig:ij,flexColGap4:cj,flexColGap4Center:lj,flex1:dj,flexCol:uj,flexGrow1:mj,inputLabel:pj,inputLabelBlock:fj,checkboxInput:hj,configDividerMargin:gj,configDividerMargin24:yj,pathListMargin:kj,cancelBtnRed:vj,code:Sj,workflowList:wj,workflowActions:bj,textBtn:_j,workflowGrid:Cj,checkboxLabel:Aj,checkboxSmall:xj,docWorkspace:Ij,docIndexPanel:Tj,docWorkspaceTrayMode:Rj,docViewerPanel:Nj,docWorkspaceTrayOpen:jj,docTrayPanel:Pj,docTrayPanelOpen:Mj,docSpinning:Ej,docSpin:Dj,docViewerEmpty:Lj,agentsModuleRoot:Bj,agentsModuleWithTray:Wj,agentsModuleTrayOpen:Fj,agentTrayPanel:Oj,agentTrayPanelOpen:$j,agentTrayHeader:Uj,agentTrayTitle:zj,agentTrayContent:Hj,agentTrayContentInner:Gj,agentsModuleContent:Vj,agentsModuleGroup:qj,marginTop24:Kj,settingSubTitle:Zj,dangerBtn:Yj,aiProfilesExplorer:Jj,aiProfilesListPane:Qj,aiProfilesList:Xj,aiProfilesSection:eP,aiProfilesSectionHeader:tP,aiProfileGroup:nP,aiProfileGroupSelected:aP,aiProfileGroupDuplicate:rP,aiProfileGroupHeader:sP,aiProfileGroupAvatar:oP,aiProfileGroupIdentity:iP,aiProfileName:cP,aiProfileHandle:lP,aiProfileRole:dP,aiProfileSeatSummary:uP,aiProfileSeatScopeIcon:mP,aiProfileSeatScopeIconDetail:pP,aiProfileSeatScopeIconCloud:fP,aiProfileSeatScopeIconLocal:hP,aiProfileDuplicateBadge:gP,aiProfileMergeSection:yP,aiProfileMergeRow:kP,aiProfileIdChip:vP,aiProfileKeepBadge:SP,aiProfileMergeActions:wP,aiProfileDetailPane:bP,aiProfileDetailCard:_P,aiProfileDetailHero:CP,aiProfileDetailIcon:AP,aiProfileDetailAvatar:xP,aiProfileDetailHeading:IP,aiProfileDetailTitleRow:TP,aiProfileDetailTitle:RP,aiProfileDetailMetaRow:NP,aiProfileDetailHandle:jP,aiProfileDetailRole:PP,aiProfileDetailLinkedCount:MP,aiProfileDetailDescription:EP,aiProfileSignatureColor:DP,aiProfileSignatureSwatch:LP,aiProfileDetailDataList:BP,aiProfileDetailDataGroup:WP,aiProfileDetailDateGroup:FP,aiProfileDetailDataRow:OP,aiProfileDetailDataLabel:$P,aiProfileDetailDataValue:UP,aiProfileStatusSelect:zP,aiProfileInstanceSection:HP,aiProfileInstanceSectionHeader:GP,aiProfileInstanceList:VP,aiProfileInstanceCard:qP,aiProfileIdFooter:KP,aiProfileIdFooterValue:ZP,aiProfileDangerTextButton:YP,aiProfileInstanceTopRow:JP,aiProfileInstanceName:QP,aiProfileInstanceMeta:XP,aiProfileInlineError:e0},t0="_standaloneWrapper_1r0om_1",n0="_standalonePage_1r0om_11",a0="_standaloneHeader_1r0om_21",r0="_standaloneTitle_1r0om_27",s0="_standaloneContent_1r0om_31",o0="_workspaceToolRail_1r0om_37",i0="_workspaceToolRailMain_1r0om_54",c0="_workspaceToolRailBottom_1r0om_62",l0="_workspaceToolRailDivider_1r0om_72",d0="_workspaceToolButton_1r0om_79",u0="_workspaceToolButtonActive_1r0om_99",m0="_workspaceToolButtonDisabled_1r0om_106",p0="_headerTitleWidget_1r0om_137",tn={standaloneWrapper:t0,standalonePage:n0,standaloneHeader:a0,standaloneTitle:r0,standaloneContent:s0,workspaceToolRail:o0,workspaceToolRailMain:i0,workspaceToolRailBottom:c0,workspaceToolRailDivider:l0,workspaceToolButton:d0,workspaceToolButtonActive:u0,workspaceToolButtonDisabled:m0,headerTitleWidget:p0},f0="_overlay_11v7l_1",h0="_browser_11v7l_16",g0="_header_11v7l_27",y0="_pathInfo_11v7l_36",k0="_actions_11v7l_52",v0="_list_11v7l_57",S0="_item_11v7l_63",w0="_itemCurrent_11v7l_80",b0="_itemFile_11v7l_86",_0="_empty_11v7l_90",jn={overlay:f0,browser:h0,header:g0,pathInfo:y0,actions:k0,list:v0,item:S0,itemCurrent:w0,itemFile:b0,empty:_0},C0="_overlay_1hk7m_2",A0="_overlayHighZ_1hk7m_15",x0="_modal_1hk7m_20",I0="_draggableModal_1hk7m_46",T0="_draggableHeader_1hk7m_53",R0="_headerActions_1hk7m_61",N0="_modalContent_1hk7m_69",j0="_form_1hk7m_80",P0="_formActions_1hk7m_91",M0="_modalFooter_1hk7m_98",E0="_modalSizeSm_1hk7m_104",D0="_modalSizeMd_1hk7m_108",L0="_modalSizeMdWide_1hk7m_112",B0="_modalSizeLg_1hk7m_116",W0="_modalSizeXl_1hk7m_120",F0="_modalSizeFull_1hk7m_124",O0="_settingsViewModal_1hk7m_129",$0="_unsavedOverlay_1hk7m_148",U0="_unsavedModal_1hk7m_153",z0="_unsavedHeader_1hk7m_159",H0="_unsavedTitle_1hk7m_164",G0="_unsavedContent_1hk7m_168",V0="_unsavedText_1hk7m_172",q0="_unsavedActions_1hk7m_177",It={overlay:C0,overlayHighZ:A0,modal:x0,draggableModal:I0,draggableHeader:T0,headerActions:R0,modalContent:N0,form:j0,formActions:P0,modalFooter:M0,modalSizeSm:E0,modalSizeMd:D0,modalSizeMdWide:L0,modalSizeLg:B0,modalSizeXl:W0,modalSizeFull:F0,settingsViewModal:O0,unsavedOverlay:$0,unsavedModal:U0,unsavedHeader:z0,unsavedTitle:H0,unsavedContent:G0,unsavedText:V0,unsavedActions:q0};function K0(e){const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),a={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return a[t]?a[t]:`${e}s`}function Yi({label:e,options:t,selected:a,onChange:s,variant:o="label",containerStyle:c}){const[i,d]=r.useState(!1),m=r.useRef(null);r.useEffect(()=>{const I=A=>{m.current&&!m.current.contains(A.target)&&d(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[]);const y=I=>{a.includes(I)?s(a.filter(A=>A!==I)):s([...a,I])},k=t.length>0&&t.every(I=>{const A=o==="label"?I.label:I.value;return a.includes(A)}),S=!t.some(I=>{const A=o==="label"?I.label:I.value;return a.includes(A)}),h=()=>{s(k?[]:t.map(I=>o==="label"?I.label:I.value))},g=t.filter(I=>{const A=o==="label"?I.label:I.value;return a.includes(A)}).length,v=K0(e),_=k?`All ${v}`:S?`No ${v}`:g===1?`1 ${e}`:`${g} ${v}`;return n.jsxs("div",{className:f.filterContainer,ref:m,style:c,children:[n.jsxs("button",{className:`${f.filterButton} ${k?"":f.filterActive}`,onClick:()=>d(!i),title:`Filter by ${e}`,children:[n.jsx("span",{children:_}),n.jsx(sl,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&n.jsxs("div",{className:`${f.filterDropdown} ${f.appScrollbar} tf-scrollbar`,children:[n.jsxs("div",{className:f.filterOption,onClick:h,children:[n.jsx("input",{type:"checkbox",checked:k,onChange:()=>{}}),n.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),n.jsx("div",{className:f.filterDivider}),t.map(I=>{const A=o==="label"?I.label:I.value,D=a.includes(A);return n.jsxs("div",{className:f.filterOption,onClick:()=>y(A),children:[n.jsx("input",{type:"checkbox",checked:D,onChange:()=>{}}),n.jsx("span",{children:I.label})]},I.value)})]})]})}const Z0="_taskItem_zvr7q_1",Y0="_compressed_zvr7q_20",J0="_taskHeader_zvr7q_25",Q0="_taskReferenceCluster_zvr7q_30",X0="_taskMeta_zvr7q_34",eM="_taskTitle_zvr7q_40",tM="_taskItemRecentlyChanged_zvr7q_67",nM="_assigneeAvatarImage_zvr7q_107",aM="_assigneeAvatarIndicator_zvr7q_115",rM="_assigneeAvatarEmpty_zvr7q_137",sM="_inProgress_zvr7q_164",oM="_onHold_zvr7q_175",iM="_readyForReview_zvr7q_186",cM="_completed_zvr7q_197",lM="_cancelled_zvr7q_208",dM="_archived_zvr7q_219",uM="_taskContent_zvr7q_229",mM="_kanbanCardOverlay_zvr7q_238",pM="_taskReferenceText_zvr7q_277",fM="_taskReferenceDivider_zvr7q_286",hM="_taskActions_zvr7q_293",gM="_taskMetaCompact_zvr7q_318",yM="_taskMetaRow_zvr7q_325",kM="_taskMetaBadgeGroup_zvr7q_333",vM="_taskDescription_zvr7q_339",SM="_taskLatestComment_zvr7q_398",wM="_taskCancellationReason_zvr7q_419",bM="_archiveBadge_zvr7q_573",_M="_attachmentThumbnails_zvr7q_578",CM="_attachmentImageRow_zvr7q_585",AM="_attachmentDocumentList_zvr7q_592",xM="_attachmentThumbnail_zvr7q_578",IM="_contextDocThumb_zvr7q_625",TM="_contextDocMain_zvr7q_651",RM="_contextDocText_zvr7q_658",NM="_contextDocIcon_zvr7q_666",jM="_contextDocName_zvr7q_677",PM="_contextDocType_zvr7q_687",MM="_taskSpecialists_zvr7q_699",EM="_taxonomiesList_zvr7q_708",Qt={taskItem:Z0,compressed:Y0,taskHeader:J0,taskReferenceCluster:Q0,taskMeta:X0,taskTitle:eM,taskItemRecentlyChanged:tM,assigneeAvatarImage:nM,assigneeAvatarIndicator:aM,assigneeAvatarEmpty:rM,inProgress:sM,onHold:oM,readyForReview:iM,completed:cM,cancelled:lM,archived:dM,taskContent:uM,kanbanCardOverlay:mM,taskReferenceText:pM,taskReferenceDivider:fM,taskActions:hM,taskMetaCompact:gM,taskMetaRow:yM,taskMetaBadgeGroup:kM,taskDescription:vM,taskLatestComment:SM,taskCancellationReason:wM,archiveBadge:bM,attachmentThumbnails:_M,attachmentImageRow:CM,attachmentDocumentList:AM,attachmentThumbnail:xM,contextDocThumb:IM,contextDocMain:TM,contextDocText:RM,contextDocIcon:NM,contextDocName:jM,contextDocType:PM,taskSpecialists:MM,taxonomiesList:EM},fy=({children:e,className:t,onTaskIdClick:a})=>{if(!e)return null;const s=i=>ze.Children.toArray(i).some(m=>ze.isValidElement(m)?String(m.props?.className||"").includes("task-list-item"):!1),o=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,c=i=>{if(!a)return i;if(typeof i=="string"){const y=Array.from(i.matchAll(o));if(!y.length)return i;const k=[];let S=0;for(let h=0;h<y.length;h+=1){const g=y[h],v=g[1],_=g.index??-1;_<S||(_>S&&k.push(i.slice(S,_)),k.push(n.jsx("button",{type:"button",className:f.taskIdInlineLink,onClick:I=>{I.preventDefault(),I.stopPropagation(),a(v)},children:v},`${v}-${_}-${h}`)),S=_+v.length)}return S<i.length&&k.push(i.slice(S)),k}if(Array.isArray(i))return i.map(c);if(!ze.isValidElement(i))return i;const d=typeof i.type=="string"?i.type:"";if(d==="code"||d==="pre"||d==="a")return i;const m=i.props?.children;return m===void 0?i:ze.cloneElement(i,{},ze.Children.map(m,c))};return n.jsx("div",{className:t,children:n.jsx(sv,{remarkPlugins:[ov,iv],components:{p:({children:i})=>n.jsx("p",{children:c(i)}),ul:({children:i})=>n.jsx("ul",{style:s(i)?{paddingLeft:0}:void 0,children:i}),li:({children:i,className:d})=>{const m=String(d||"").includes("task-list-item");return n.jsx("li",{className:d,style:m?{listStyle:"none"}:void 0,children:c(i)})},input:({type:i,checked:d})=>i!=="checkbox"?n.jsx("input",{type:i,checked:d,readOnly:!0}):n.jsx("input",{type:"checkbox",checked:!!d,readOnly:!0,style:{cursor:"default",marginRight:8}}),code:({children:i,className:d,...m})=>{const y=String(i||"").replace(/\n$/,"");return/language-(\w+)/.test(d||"")||y.includes(`
|
|
3
|
+
`)?n.jsx("pre",{className:f.codeBlock,children:n.jsx("code",{className:d,...m,children:y})}):n.jsx("code",{className:f.inlineCode,...m,children:y})}},children:e})})};function hy({label:e,title:t,ariaLabel:a,copied:s=!1,disabled:o=!1,className:c="",onClick:i,children:d}){return n.jsxs("button",{type:"button",className:`${f.taskIdBadge} ${s?f.copiedId:""} ${c}`.trim(),onClick:i,disabled:o,title:t,"aria-label":a,children:[s?n.jsx(eo,{size:13}):n.jsx(of,{size:13}),n.jsx("span",{className:f.taskIdBadgeLabel,children:d??e})]})}function tm({copied:e,disabled:t=!1,label:a,onClick:s,title:o="Copy task reference",ariaLabel:c,className:i=""}){return n.jsx(hy,{copied:e,disabled:t,label:"",onClick:s,title:o,ariaLabel:c,className:i,children:a})}const DM=(e,t=10)=>{const a=hm[e?.toLowerCase()]||{icon:"FileCode"},s=hs[a.icon]||Pk;return n.jsx(s,{size:t})},Gu=(e,t)=>{if(!e)return null;const a=t.trim();if(!a)return e;const o=jm(a)?.match(/^(lt|t)-(\d+)$/),c=o?`${o[1]==="lt"?"l\\s*t":"t"}\\s*(?:-|\\s)?\\s*${o[2]}`:a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^${c}$`,"i"),d=e.split(new RegExp(`(${c})`,"gi"));return n.jsx(n.Fragment,{children:d.map((m,y)=>i.test(m)?n.jsx("mark",{className:f.highlight,children:m},y):m)})};function Ad(e){return e.trim().replace(/\\/g,"/")}function gy(e){return e.split("?")[0].split("#")[0]}function Mm(e){return typeof e=="string"?e:String(e.path||"").trim()}function yy(e){const a=gy(Ad(e)).match(/\/api\/taskforce\/documents\/([^/]+)\/content$/i);if(!a?.[1])return null;try{return decodeURIComponent(a[1]).trim()||null}catch{return a[1].trim()||null}}function ky(e){if(!e.includes("/api/taskforce/context-link?path="))return null;try{const a=new URL(e,window.location.origin).searchParams.get("path");return a?Ad(a):null}catch{return null}}function LM(e,t){const a=(t||(typeof e=="string"?"":e.fsPath||"")).trim();if(a)return Ad(a);const s=Mm(e),o=ky(s);return o?Ad(o):null}function BM(e,t){const a=String(typeof e=="string"?"":e.assetId||"").trim();if(a)return a;const s=Mm(e);return yy(s)}function WM(e,t){const a=Mm(e);return yy(a)?!0:[(t||(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(),ky(a)||"",a].some(o=>{if(!o)return!1;const c=gy(Ad(o)).toLowerCase();return c.endsWith(".md")||c.endsWith(".markdown")})}function FM(e,t){const a=Mm(e),s=LM(e,t);if(!s||!WM(e,s))return!1;const o=BM(e),c=new CustomEvent("taskforce:open-markdown-document",{detail:{path:a,fsPath:s,...o?{assetId:o}:{},...typeof e!="string"&&e.taskId?{taskId:e.taskId}:{}},cancelable:!0});return!window.dispatchEvent(c)}const OM="I-";function vy(e){return Tm(OM,e)}function $M(e){return e.trim().replace(/\\/g,"/")}function Sy(e){return typeof e=="string"?e:String(e.path||"").trim()}function UM(e){return/\.(png|jpe?g|webp)(\?|#|$)/i.test(e)}function zM(e){return typeof e=="string"?$M(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function HM(e,t){if(typeof e=="string")return!1;const a=String(e.assetId||"").trim(),s=Sy(e);return!!(a&&s&&UM(s))}function GM(e,t){if(!HM(e))return!1;const a=e,s=String(t?.taskId||a.taskId||"").trim(),o=String(t?.taskReferenceLabel||"").trim(),c=String(a.assetId||"").trim(),i=vy(a),d=Sy(e),m=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...s?{taskId:s}:{},...o?{taskReferenceLabel:o}:{},assetId:c,...i?{imageReferenceLabel:i}:{},path:d,displayName:zM(e)},cancelable:!0});return!window.dispatchEvent(m)}function Eh(e,t){if(!e)return null;const a=String(e.taskId||"").trim(),s=String(e.assetId||"").trim(),o=String(e.path||"").trim(),c=String(e.displayName||"").trim()||"Image attachment";if(!s||!o)return null;const i=String(e.taskReferenceLabel||"").trim(),d=a?t.find(y=>y.id===a):void 0,m=a?i||nc(d)||a:void 0;return{...a?{taskId:a}:{},...m?{taskReferenceLabel:m}:{},assetId:s,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,path:o,displayName:c}}function km(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t)return"";const a=t.split("/").filter(Boolean);return a[a.length-1]||""}function Tf(e){const t=String(e||"").trim(),a=t.lastIndexOf(".");return a<=0?{stem:t,ext:""}:{stem:t.slice(0,a),ext:t.slice(a)}}function wy(e,t){const a=String(e||"").trim(),s=String(t||"").trim();return a?s&&a.startsWith(`${s}-`)?a.slice(s.length+1):a.replace(/^asset-[a-z0-9-]+-/i,""):""}function VM(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function Dh(e,t){const{stem:a,ext:s}=Tf(km(e)),o=wy(a,t),c=VM(o||a);return c?`${c}${s}`:km(e)||"Untitled document"}function Ip(e,t){const a=String(e||"").trim();if(!a)return!0;const s=km(a),{stem:o}=Tf(s),c=String(t||"").trim();if(c&&o.toLowerCase()===c.toLowerCase())return!0;const i=wy(o,t);return i?i!==o:!0}function qM(e){const t=String(e.logicalName||"").trim();if(t&&!Ip(t,e.assetId))return t;const a=String(e.displayName||"").trim();if(a&&!Ip(a,e.assetId))return a;const s=String(e.title||"").trim();if(s&&!Ip(s,e.assetId))return s;const o=String(e.originalFilename||"").trim();if(o)return Dh(o,e.assetId);const c=String(e.fsPath||"").trim();return c?Dh(c,e.assetId):"Untitled document"}function KM(e){return qM(e)}function ZM(e){const t=KM(e),a=String(e.originalFilename||e.fsPath||"").trim(),s=Tf(km(a)).ext;return s?t.toLowerCase().endsWith(s.toLowerCase())?t:`${t}${s}`:t}const YM="_taxonomyDropdown_tt12a_1",JM="_taxonomyDropdownActive_tt12a_6",QM="_taxonomyDropdownButton_tt12a_11",XM="_taxonomyDropdownOpen_tt12a_50",eE="_taxonomyDropdownButtonContent_tt12a_56",tE="_taxonomyDropdownIcon_tt12a_64",nE="_taxonomyDropdownLabel_tt12a_72",aE="_taxonomyDropdownChevron_tt12a_81",rE="_taxonomyDropdownChevronOpen_tt12a_87",sE="_taxonomyDropdownPanel_tt12a_91",oE="_taxonomyDropdownPanelPortal_tt12a_110",iE="_taxonomyDropdownOption_tt12a_129",cE="_taxonomyDropdownOptionHighlighted_tt12a_157",lE="_taxonomyDropdownOptionSelected_tt12a_163",wr={taxonomyDropdown:YM,taxonomyDropdownActive:JM,taxonomyDropdownButton:QM,taxonomyDropdownOpen:XM,taxonomyDropdownButtonContent:eE,taxonomyDropdownIcon:tE,taxonomyDropdownLabel:nE,taxonomyDropdownChevron:aE,taxonomyDropdownChevronOpen:rE,taxonomyDropdownPanel:sE,taxonomyDropdownPanelPortal:oE,taxonomyDropdownOption:iE,taxonomyDropdownOptionHighlighted:cE,taxonomyDropdownOptionSelected:lE};function ud({value:e,options:t,onChange:a,placeholder:s="Select...",required:o=!1,disabled:c=!1,className:i="",ariaLabelledBy:d,ariaLabel:m,hideSelectedLabel:y=!1,hideChevron:k=!1,panelClassName:S="",portalPanel:h=!1,panelMinWidth:g}){const[v,_]=r.useState(!1),[I,A]=r.useState(-1),[D,U]=r.useState({}),W=r.useRef(null),Q=r.useRef(null),le=r.useRef(null),ie=t.find(K=>String(K.value)===String(e));r.useEffect(()=>{if(!v)return;const K=j=>{const H=j.target,ue=!!W.current?.contains(H),ye=!!le.current?.contains(H);!ue&&!ye&&(_(!1),A(-1))};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[v]),r.useEffect(()=>{if(!v)A(-1);else{const K=t.findIndex(j=>String(j.value)===String(e));A(K>=0?K:0)}},[v,t,e]),r.useEffect(()=>{if(!v||!h)return;const K=()=>{const j=Q.current;if(!j)return;const H=j.getBoundingClientRect(),ue=Math.max(g||0,H.width),ye=Math.max(8,H.right-ue),G=H.bottom;U({position:"fixed",top:G,left:ye,minWidth:ue,zIndex:2e3})};return K(),window.addEventListener("resize",K),window.addEventListener("scroll",K,!0),()=>{window.removeEventListener("resize",K),window.removeEventListener("scroll",K,!0)}},[v,h,g]);const se=()=>{c||_(!v)},$=K=>{a(K.value),_(!1),Q.current?.focus()},C=K=>{if(!c)switch(K.key){case"Enter":case" ":K.preventDefault(),v?I>=0&&$(t[I]):_(!0);break;case"Escape":K.preventDefault(),_(!1),Q.current?.focus();break;case"ArrowDown":K.preventDefault(),v?A(j=>j<t.length-1?j+1:0):_(!0);break;case"ArrowUp":K.preventDefault(),v?A(j=>j>0?j-1:t.length-1):_(!0);break;case"Home":K.preventDefault(),v&&A(0);break;case"End":K.preventDefault(),v&&A(t.length-1);break;case"Tab":_(!1);break}},de=(K,j)=>{const H=K.icon&&hs[K.icon]?hs[K.icon]:ec,ue=K.color?Ma(K.color):"var(--text-secondary)",ye=j?.hideLabel===!0;return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:`taxonomyDropdownIcon ${wr.taxonomyDropdownIcon}`,style:{color:ue},children:n.jsx(H,{size:16})}),!ye&&n.jsx("span",{className:`taxonomyDropdownLabel ${wr.taxonomyDropdownLabel}`,children:K.label})]})},ke=v?n.jsx("div",{ref:le,id:`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,className:`taxonomyDropdownPanel ${wr.taxonomyDropdownPanel} ${h?wr.taxonomyDropdownPanelPortal:""} ${S}`,role:"listbox","aria-labelledby":d,"aria-label":m,style:h?D:void 0,children:t.map((K,j)=>{const H=String(K.value)===String(e),ue=j===I;return n.jsx("div",{className:`taxonomyDropdownOption ${wr.taxonomyDropdownOption} ${H?`taxonomyDropdownOptionSelected ${wr.taxonomyDropdownOptionSelected}`:""} ${ue?`taxonomyDropdownOptionHighlighted ${wr.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":H,onClick:()=>$(K),onMouseEnter:()=>A(j),style:(()=>{const ye=K.color,G=Ma(ye),je=!G||G.startsWith("var("),be=je?"#8b5cf6":G,ce=je?"20":"30",me=je?"05":"10";return{"--option-color":G||"var(--text-primary)","--option-border":`${be}${ce}`,"--option-bg":`${be}${me}`}})(),children:de(K)},String(K.value))})}):null;return n.jsxs("div",{ref:W,className:`taxonomyDropdown ${wr.taxonomyDropdown} ${v?`taxonomyDropdownActive ${wr.taxonomyDropdownActive}`:""} ${i}`,children:[n.jsxs("button",{ref:Q,type:"button",className:`taxonomyDropdownButton ${wr.taxonomyDropdownButton} ${v?`taxonomyDropdownOpen ${wr.taxonomyDropdownOpen}`:""}`,onClick:se,onKeyDown:C,disabled:c,role:"combobox","aria-haspopup":"listbox","aria-expanded":v,"aria-controls":`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,"aria-labelledby":d,"aria-label":m,style:(()=>{if(!ie)return{};const K=ie.color,j=Ma(K),H=!j||j.startsWith("var("),ue=H?"#8b5cf6":j,ye=H?"30":"50",G=H?"05":"10";return{"--field-color":j||"var(--text-primary)","--field-border":`${ue}${ye}`,"--field-bg":`${ue}${G}`}})(),children:[n.jsx("span",{className:`taxonomyDropdownButtonContent ${wr.taxonomyDropdownButtonContent}`,children:ie?de(ie,{hideLabel:y}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:`taxonomyDropdownIcon ${wr.taxonomyDropdownIcon}`,children:n.jsx(ec,{size:16})}),n.jsx("span",{className:`taxonomyDropdownLabel ${wr.taxonomyDropdownLabel}`,children:s})]})}),!k&&n.jsx(sl,{size:16,className:`taxonomyDropdownChevron ${wr.taxonomyDropdownChevron} ${v?`taxonomyDropdownChevronOpen ${wr.taxonomyDropdownChevronOpen}`:""}`})]}),h?ke?Xi.createPortal(ke,document.body):null:ke]})}function by({task:e,disabled:t=!1,actionDisabled:a,statusDisabled:s,compressed:o=!1,shortLabels:c=!1,showLabel:i=!0,onSetStatus:d,onArchiveTask:m,onUnarchiveTask:y,archiveActionMode:k="auto"}){const S=e?.status||"task",g=k==="auto"?!!e&&(S==="done"||S==="cancelled")?"archive":"none":k,v=a??t,_=s??t,I=Qc.map(A=>({...A,label:(o||c)&&A.shortLabel||A.label}));return n.jsxs("div",{className:`${f.statusActionsGroup} ${o?f.statusActionsGroupCompact:""}`,children:[g==="archive"&&n.jsx("button",{type:"button",className:`${f.actionBtn} ${f.archiveTaskBtn}`,onClick:()=>e&&!v&&m?.(e),disabled:v,title:"Archive Now","aria-label":"Archive task",children:n.jsx(Mk,{size:o?12:16})}),g==="unarchive"&&n.jsx("button",{type:"button",className:`${f.actionBtn} ${f.archiveTaskBtn}`,onClick:()=>e&&!v&&y?.(e),disabled:v,title:"Unarchive task","aria-label":"Unarchive task",children:n.jsx(Sd,{size:o?12:16})}),n.jsx("div",{className:`${f.statusSelectWrap} ${f.statusTaxonomyDropdownWrap}`,children:n.jsx(ud,{value:S,options:I,disabled:_||!e,ariaLabel:"Status",hideSelectedLabel:!i,hideChevron:!i,className:`${f.statusTaxonomyDropdown} ${o?f.statusTaxonomyDropdownCompact:""} ${i?"":f.statusTaxonomyDropdownIconOnly}`,panelClassName:i?"":f.statusTaxonomyDropdownIconOnlyPanel,portalPanel:!i,panelMinWidth:i?void 0:144,onChange:A=>{e&&d?.(e,A)}})})]})}function dE(e,t,a){const s=typeof e=="string"?e.trim():"";if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;const o=Number(t),c=Number.isFinite(o)&&o>0?String(Math.floor(o)):typeof a=="string"&&a.trim().length>0?a.trim():"";if(!c)return s;const[i,d=""]=s.split("#"),m=i.includes("?")?"&":"?";return`${i}${m}v=${encodeURIComponent(c)}${d?`#${d}`:""}`}function uE(e){return e==="taskId"?"Task":e==="title"?"Title":e==="description"?"Description":e==="assignee"?"Assigned to":e==="ownerId"?"Owner":e==="status"?"Status":e==="scheduledDate"?"Scheduled date":e==="dueDate"?"Due date":e==="workstreamId"?"Workstream":e==="initiativeId"?"Initiative":e}function mE(e){return e==="task"?"Task":e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function or(e,t,a){const s=a?.(t,e);if(typeof s=="string")return s;if(e==null||e==="")return"none";if(Array.isArray(e)){const o=e.map(c=>or(c,t,a)).filter(Boolean);return o.length>0?o.join(", "):"none"}return typeof e=="object"?"updated":t==="status"?mE(String(e)):String(e)}function Lh(e){return Array.isArray(e)?e.map((t,a)=>{const s=t&&typeof t=="object"?t:{},o=Number(s.order);return{id:String(s.id||"").trim(),title:String(s.title||"").trim(),isCompleted:!!s.isCompleted,order:Number.isFinite(o)?o:a}}):[]}function pE(e){const t=Lh(e?.from),a=Lh(e?.to),s=new Map(t.map(i=>[i.id||i.title,i])),o=new Map(a.map(i=>[i.id||i.title,i]));for(const[i,d]of o.entries()){const m=s.get(i);if(!m)return d.title?`Checklist item added: ${d.title}`:"Checklist item added";if(m.isCompleted!==d.isCompleted)return d.title?d.isCompleted?`Checklist item completed: ${d.title}`:`Checklist item reopened: ${d.title}`:d.isCompleted?"Checklist item completed":"Checklist item reopened"}for(const[i,d]of s.entries())if(!o.has(i))return d.title?`Checklist item removed: ${d.title}`:"Checklist item removed";return t.length===a.length&&t.every(i=>o.has(i.id||i.title))&&t.some((d,m)=>{const y=a[m];return(d.id||d.title)!==(y?.id||y?.title)})?"Checklist reordered":"Checklist updated"}function Rf(e){return e.split(/[?#]/,1)[0]||e}function Bh(e){const t=Rf(e).replace(/\\/g,"/"),a=t.split("/").filter(Boolean);return a[a.length-1]||t}function fE(e){return/\.(png|jpe?g|webp|gif)$/i.test(Rf(e))}function hE(e){return e.includes("/api/taskforce/documents/")?!0:/\.(pdf|txt|md|markdown|csv|json|docx?|html?|js|jsx|ts|tsx|css|py|java|go|rs|sh)$/i.test(Rf(e))}function Wh(e){return Array.isArray(e)?e.flatMap((t,a)=>{const s=t&&typeof t=="object"?t:null,o=typeof t=="string"?t:String(s?.path||"").trim(),c=String(s?.fsPath||"").trim(),i=String(s?.assetId||"").trim(),d=String(s?.referenceLabel||"").trim(),m=[s?.displayName,s?.originalFilename,s?.caption,d,c?Bh(c):"",o?Bh(o):""].map(h=>String(h||"").trim()).find(Boolean)||`Attachment ${a+1}`,y=i||c||o||`${m}:${a}`,k=[o,c,String(s?.originalFilename||"").trim(),String(s?.displayName||"").trim(),d].filter(Boolean),S=k.some(h=>fE(h))?"image":d.startsWith("D-")||k.some(h=>hE(h))?"document":"attachment";return[{key:y,label:m,kind:S}]}):[]}function gE(e,t){return t===1?e:e==="image"?"images":e==="document"?"documents":"attachments"}function Vu(e){if(e.length===0)return"attachments";const t=e.reduce((s,o)=>(s[o.kind]+=1,s),{image:0,document:0,attachment:0}),a=Object.entries(t).filter(([,s])=>s>0).map(([s,o])=>o===1?s:`${o} ${gE(s,o)}`);return a.length===1?a[0]:e.length<=3&&a.length<=2?a.join(" and "):`${e.length} attachments`}function Ki(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function yE(e){const t=Wh(e?.from),a=Wh(e?.to),s=new Map(t.map(m=>[m.key,m])),o=new Map(a.map(m=>[m.key,m])),c=a.filter(m=>!s.has(m.key)),i=t.filter(m=>!o.has(m.key));if(c.length===1&&i.length===0)return`${Ki(c[0].kind)} attached: ${c[0].label}`;if(i.length===1&&c.length===0)return`${Ki(i[0].kind)} removed: ${i[0].label}`;if(c.length>0&&i.length===0)return`${Ki(Vu(c))} attached`;if(i.length>0&&c.length===0)return`${Ki(Vu(i))} removed`;if(c.length===1&&i.length===1)return`${Ki(c[0].kind)} replaced: ${i[0].label} -> ${c[0].label}`;if(c.length>0||i.length>0)return`${Ki(Vu(c))} attached, ${Vu(i)} removed`;const d=a.filter(m=>{const y=s.get(m.key);return y&&y.label!==m.label});if(d.length===1&&t.length===1&&a.length===1){const m=s.get(d[0].key);return`${Ki(d[0].kind)} renamed: ${m?.label||"Attachment"} -> ${d[0].label}`}return"Attachment details updated"}function vm(e,t,a){if(e==="checklistItems")return pE(t);if(e==="attachments")return yE(t);const s=uE(e);if(e==="title")return`${s}: updated`;if(e==="description"){const o=or(t?.from,e,a)!=="none",c=or(t?.to,e,a)!=="none";return!o&&c?`${s}: added`:o&&!c?`${s}: cleared`:`${s}: updated`}return`${s}: ${or(t?.from,e,a)} -> ${or(t?.to,e,a)}`}function _y(e,t){const a=e.details?.changes||{},s=Object.keys(a);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"&&a.status)return`Status changed: ${or(a.status.from,"status",t)} -> ${or(a.status.to,"status",t)}`;if(e.action==="task-schedule-changed")return a.scheduledDate?`Scheduled date changed: ${or(a.scheduledDate.from,"scheduledDate",t)} -> ${or(a.scheduledDate.to,"scheduledDate",t)}`:a.dueDate?`Due date changed: ${or(a.dueDate.from,"dueDate",t)} -> ${or(a.dueDate.to,"dueDate",t)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&a.workstreamId)return`Workstream changed: ${or(a.workstreamId.from,"workstreamId",t)} -> ${or(a.workstreamId.to,"workstreamId",t)}`;if(e.action==="task-relationship-changed"&&a.initiativeId)return`Initiative changed: ${or(a.initiativeId.from,"initiativeId",t)} -> ${or(a.initiativeId.to,"initiativeId",t)}`;if(e.action==="task-attachments-changed")return a.attachments?vm("attachments",a.attachments,t):"Attachments updated";if(s.length===1){const o=s[0],c=a[o];return vm(o,c,t)}return s.length>1?`${s.length} fields updated`:"Task updated"}function i$(e,t){if(e.taskId||e.entityType==="task")return _y(e,t);const a=e.details?.changes||{},s=Object.keys(a),o=e.entityType==="initiative"?"Initiative":"Workstream",c=typeof e.details?.taskTitle=="string"&&e.details.taskTitle.trim().length>0?e.details.taskTitle.trim():null;return e.action==="initiative-created"?"Initiative created":e.action==="initiative-archived"?"Initiative archived":e.action==="initiative-unarchived"?"Initiative restored":e.action==="workstream-created"?"Workstream created":e.action==="workstream-archived"?"Workstream archived":e.action==="workstream-unarchived"?"Workstream restored":e.action==="workstream-task-added"?c?`Task added: ${c}`:"Task added":e.action==="workstream-task-removed"?c?`Task removed: ${c}`:"Task removed":e.action==="workstream-relationship-changed"&&a.initiativeId?`Initiative changed: ${or(a.initiativeId.from,"initiativeId",t)} -> ${or(a.initiativeId.to,"initiativeId",t)}`:(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&a.attachments?vm("attachments",a.attachments,t):s.length===1?vm(s[0],a[s[0]],t):s.length>1?`${s.length} fields updated`:e.action==="initiative-updated"||e.action==="workstream-updated"?`${o} updated`:`${o} activity updated`}function Sm(e){const t=Date.parse(String(e.timestamp||""));return Number.isFinite(t)?t:null}function kE(e){const t=e.details?.changes||{},a=Object.keys(t);if(e.action==="task-status-changed"&&t.status)return"status";if(e.action==="task-schedule-changed"){if(t.scheduledDate)return"scheduledDate";if(t.dueDate)return"dueDate"}if(e.action==="task-relationship-changed"){if(t.workstreamId)return"workstreamId";if(t.initiativeId)return"initiativeId"}return e.action==="task-attachments-changed"&&t.attachments?"attachments":a.length===1?a[0]:null}function c$(e){if(e.taskId||e.entityType==="task")return kE(e);const t=e.details?.changes||{},a=Object.keys(t);return(e.action==="workstream-task-added"||e.action==="workstream-task-removed")&&e.details?.taskId?"taskId":e.action==="workstream-relationship-changed"&&t.initiativeId?"initiativeId":(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&t.attachments?"attachments":a.length===1?a[0]:null}function Cy(e){const t=new Map,a=new Set,s=o=>{if(o.type==="event"&&o.event.action==="task-comment-added")return;const c=o.type==="comment"?`comment:${String(o.comment.id||o.id).replace(/^comment:/,"")}`:`event:${String(o.event.id||o.id).replace(/^event:/,"")}`;t.set(c,{...o,id:c}),o.type==="comment"&&a.add(String(o.comment.id||o.id).replace(/^comment:/,""))};return Array.isArray(e.activity)&&e.activity.forEach(s),Array.isArray(e.comments)&&e.comments.forEach(o=>{const c=String(o.id||"").trim();!c||a.has(c)||s({id:`comment:${c}`,type:"comment",timestamp:o.timestamp,comment:o})}),[...t.values()].sort((o,c)=>{const i=Sm(o),d=Sm(c);return i!==null&&d!==null&&i!==d?i-d:i!==null&&d===null?-1:i===null&&d!==null?1:String(o.id||"").localeCompare(String(c.id||""))})}function Nf(e){return Cy(e)}function vE(e){const t=Nf(e);return t.length===0?null:[...t].sort((a,s)=>{const o=Sm(a),c=Sm(s);return o!==null&&c!==null&&o!==c?c-o:o!==null&&c===null?-1:o===null&&c!==null?1:String(s.id||"").localeCompare(String(a.id||""))})[0]||null}function SE(e,t){return e?e.type==="comment"?e.comment.text:_y(e.event,t):""}const{MessageSquare:wE,User:bE,Bot:_E,Gauge:CE,ClipboardList:AE,HelpCircle:xE,File:IE}=hs,TE=({task:e,searchQuery:t="",copiedId:a=null,taxonomies:s=[],types:o=[],priorities:c=[],categories:i=[],assigneeOptions:d=[],taskWorkstream:m=null,taskInitiative:y=null,isOverlay:k=!1,isArchived:S=!1,readOnlyMode:h=null,isRecentlyChanged:g=!1,onClick:v,onCopyId:_,onToggleInProgress:I,onToggleReview:A,onToggleComplete:D,onToggleCancel:U,onSetStatus:W,onArchiveTask:Q,onUnarchive:le,onDelete:ie,deleteActionTitle:se,onOpenTaskById:$,compressed:C=!1,showStatusLabel:de=!0})=>{const ke=Bg(e),K=ke.label||(ke.isProvisional?"Pending":""),j=ke.isProvisional,H=!!ke.label,ue=fm(m)||m?.id||"",ye=dy(y)||y?.id||"",G=c.find(ae=>String(ae.value)===String(e.priority)),je=G?G.label.toLowerCase().replace(/\s+/g,"-"):String(e.priority),be=i.find(ae=>ae.value===e.category||ae.label===e.category),ce=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),me=Number.isFinite(ce)?Math.max(1,Math.min(5,Math.round(ce))):3,Te={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},Me={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},Pe=Te[me],Ee=`var(--complexity-${Me[me]})`,Z=Wv(e.priority,je),x=!!f[`priorityItem_${Z}`],b=um(e.assignee),R=hd(e.assignee,d),B=ze.useMemo(()=>{const ae=String(e.assignee||"").trim();return d.find(Ge=>String(Ge.value||"").trim()===ae)||null},[d,e.assignee]),Y=b!=="unassigned"&&typeof B?.avatarUrl=="string"?dE(B.avatarUrl,B.avatarRevision,B.avatarUpdatedAt):"",fe=b==="agent"?"var(--color-violet-500, #8b5cf6)":b==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",te=ze.useMemo(()=>vE(e),[e]),Le=h||(e.isDeleted?"deleted":S?"archived":null),oe=Le!==null,L=ze.useCallback((ae,Ge)=>{const ft=String(Ge||"").trim();if(ft){if(ae==="assignee")return hd(ft,d);if(ae==="workstreamId"&&ft===m?.id)return ue||m.id;if(ae==="initiativeId"&&ft===y?.id)return ye||y.id}},[d,ye,y,m,ue]),X=ze.useMemo(()=>SE(te,L),[L,te]),M=ze.useMemo(()=>Nf(e).length,[e]),V=[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:"",f[`priorityItem_${Z}`]||"",k?Qt.kanbanCardOverlay:"",S?Qt.archived:"",C?Qt.compressed:""].filter(Boolean).join(" "),ne=Ma(G?.color),Ce=o.find(ae=>ae.value===e.type),Ae=Ma(Ce?.color)||kb(e.type),Re=ae=>{const Ge=typeof ae=="string"?ae:ae.path,ft=typeof ae=="string"?"":(ae.fsPath||"").trim(),it=typeof ae=="string"?"":(ae.displayName||"").trim(),Mt=typeof ae=="string"?"":(ae.originalFilename||"").trim(),ht=typeof ae=="string"?"":(ae.caption||"").trim();return[ft,Mt,it,ht,Ge].some(Et=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(Et))},$e=ae=>{const Ge=typeof ae=="string"?ae:ae.path,ft=Ge.includes("/api/taskforce/documents/"),it=typeof ae=="string"?"":(ae.displayName||"").trim();if(ft&&typeof ae!="string")return ZM({displayName:ae.displayName,originalFilename:ae.originalFilename,fsPath:ae.fsPath,assetId:ae.assetId||null});const Mt=typeof ae=="string"?"":(ae.caption||"").trim();if(Mt)return Mt;if(it)return it;const ht=typeof ae=="string"?"":(ae.originalFilename||"").trim();return ht||Ge.split("?")[0].split("#")[0].split("/").pop()||"Context file"},vt=ae=>{const Ge=typeof ae=="string"?ae:ae.path,ft=typeof ae=="string"?"":(ae.fsPath||"").trim(),it=typeof ae=="string"?"":(ae.caption||"").trim(),Mt=typeof ae=="string"?"":(ae.originalFilename||"").trim(),ht=[];if(ft&&ht.push(ft),Mt&&ht.push(Mt),it&&ht.push(it),Ge.includes("/api/taskforce/context-link?path="))try{const Et=new URL(Ge,"http://localhost").searchParams.get("path");Et&&ht.push(Et)}catch{}ht.push(Ge);for(const Ft of ht){const We=Ft.split("?")[0].split("#")[0].split("/").pop()||"",tt=We.lastIndexOf(".");if(tt<=0||tt===We.length-1)continue;const Oe=We.slice(tt+1);if(Oe)return Oe.slice(0,5).toUpperCase()}return"FILE"},st={"--task-change-glow-color":ne||`var(--priority-${Z})`,...ne?{borderLeftColor:ne,[`--priority-${Z}`]:ne}:{},...!x&&ne?{borderLeft:`4px solid ${ne}`}:{}},kt=ae=>ae.replace(/\b\w/g,Ge=>Ge.toUpperCase()),Ye=Td(s,[e]),Ct=e.checklistItems||[],dt=Ct.length,Qe=dt>0?Ct.filter(ae=>ae.isCompleted).length:0,Tt=(ae,Ge)=>{ae.stopPropagation(),_?.(ae,Ge)};return n.jsxs("div",{className:V,onClick:()=>v?.(e),style:st,"data-task-card":"true",children:[n.jsxs("div",{className:Qt.taskHeader,children:[n.jsxs("div",{className:Qt.taskReferenceCluster,children:[y?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:Qt.taskReferenceText,children:ye}),n.jsx("span",{className:Qt.taskReferenceDivider,children:"/"})]}):null,m?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:Qt.taskReferenceText,children:ue}),n.jsx("span",{className:Qt.taskReferenceDivider,children:"/"})]}):null,K?n.jsx(tm,{copied:H&&a===ke.label,onClick:ae=>Tt(ae,ke.label),disabled:!H,title:H?"Copy task reference":"Task reference pending sync",className:S?Qt.archiveBadge:"",label:Gu(K,t)}):null,j?n.jsx("span",{className:f.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),n.jsx("div",{className:Qt.taskActions,onClick:ae=>ae.stopPropagation(),children:oe?le||ie?n.jsxs(n.Fragment,{children:[le&&n.jsx("button",{type:"button",className:f.actionBtn,onClick:()=>le(e.id),title:Le==="deleted"?"Restore deleted task":"Restore archived task",children:n.jsx(Sd,{size:16})}),ie&&n.jsx("button",{type:"button",className:`${f.actionBtn} ${f.deleteBtn}`,onClick:()=>ie(e.id),title:se||(Le==="deleted"?"Delete Permanently":"Move to Trash"),children:n.jsx(xm,{size:16})})]}):null:n.jsx(by,{task:e,compressed:C,shortLabels:!0,showLabel:de,onSetStatus:(ae,Ge)=>{if(W){W(ae,Ge);return}if(Ge==="in-progress"){I?.(ae);return}if(Ge==="review"){A?.(ae);return}if(Ge==="done"){D?.(ae);return}Ge==="cancelled"&&U?.(ae)},onArchiveTask:Q})})]}),n.jsxs("div",{className:Qt.taskContent,children:[oe&&n.jsx("div",{className:`${Qt.taskMeta} ${Qt.taskMetaCompact}`}),n.jsxs("div",{children:[n.jsxs("div",{className:Qt.taskTitle,style:C?{fontSize:"13px",lineHeight:"1.4"}:{},children:[Le==="archived"&&"✓ ",Le==="deleted"&&"Deleted: ",Gu(e.title,t)]}),e.description&&!oe&&!C&&n.jsx("div",{className:Qt.taskDescription,children:n.jsx(fy,{onTaskIdClick:$,children:e.description})})]}),e.attachments&&e.attachments.length>0&&!oe&&!C&&n.jsxs("div",{className:Qt.attachmentThumbnails,children:[n.jsx("div",{className:Qt.attachmentImageRow,children:(e.attachments||[]).map((ae,Ge)=>{const ft=typeof ae=="string"?ae:ae.path;return Re(ae)?n.jsx("div",{className:Qt.attachmentThumbnail,onClick:it=>{it.stopPropagation(),!GM(typeof ae=="string"?{path:ft}:ae,{taskId:e.id,taskReferenceLabel:K})&&window.open(ft,"_blank")},children:n.jsx("img",{src:ft,alt:`Attachment ${Ge}`})},Ge):null})}),n.jsx("div",{className:Qt.attachmentDocumentList,children:(e.attachments||[]).map((ae,Ge)=>{const ft=typeof ae=="string"?ae:ae.path,it=typeof ae=="string"?void 0:ae.fsPath,Mt=$e(ae);if(Re(ae))return null;const ht=vt(ae);return n.jsxs("button",{type:"button",className:Qt.contextDocThumb,onClick:Ft=>{Ft.stopPropagation();const Et=typeof ae=="string"?{path:ae,taskId:e.id}:{...ae,taskId:e.id};FM(Et,it)||window.open(ft,"_blank")},title:Mt,style:{"--context-doc-accent":vb(ht)},children:[n.jsxs("span",{className:Qt.contextDocMain,children:[n.jsx("span",{className:Qt.contextDocIcon,"aria-hidden":"true",children:n.jsx(IE,{size:13})}),n.jsx("span",{className:Qt.contextDocText,children:n.jsx("span",{className:Qt.contextDocName,children:Mt})})]}),n.jsx("span",{className:Qt.contextDocType,children:ht})]},Ge)})})]}),e.status==="cancelled"&&e.canceledReason&&!C&&n.jsxs("div",{className:Qt.taskCancellationReason,children:[n.jsx("strong",{children:"Cancellation Reason:"})," ",Gu(e.canceledReason,t)]}),X&&!oe&&!C&&n.jsxs("div",{className:Qt.taskLatestComment,children:[n.jsx("strong",{children:"Latest Activity:"})," ",Gu(X.length>120?X.substring(0,120)+"...":X,t)]}),!oe&&Ye.length>0&&!C&&n.jsx("div",{className:`${Qt.taskSpecialists} ${Qt.taxonomiesList}`,children:Ye.map(ae=>{const Ge=e.taxonomies?.[ae.id];return Ge?(Array.isArray(Ge)?Ge:[Ge]).map(it=>{const Mt=ae.options.find(tt=>tt.value===it);if(!Mt)return null;const ht=hs[Mt.icon||"Layers"]||Fp,Ft=Ma(Mt.color)||"var(--text-primary)",Et=ae.status==="retired"?`${ae.label} (Retired)`:ae.label,We=Mt.status==="retired"?`${Mt.label} (Retired)`:Mt.label;return n.jsx("span",{className:f.specialistBadge,style:{borderColor:`${Ft}50`,backgroundColor:`${Ft}15`,color:Ft},title:`${Et}: ${kt(We)}`,children:n.jsx(ht,{size:10})},`${ae.id}-${it}`)}):null})}),n.jsx("div",{className:Qt.taskMeta,children:oe?n.jsx("span",{children:e.category}):n.jsx(n.Fragment,{children:n.jsxs("div",{className:Qt.taskMetaRow,style:C?{marginBottom:0}:void 0,children:[n.jsxs("div",{className:Qt.taskMetaBadgeGroup,children:[(()=>{const ae=Ma(be?.color),Ge=be?.icon||"Folder",ft=hs[Ge]||Io;return n.jsx("span",{className:f.metaBadge,title:kt(e.category),style:{color:ae||"var(--text-secondary)",backgroundColor:ae?`${ae}15`:"var(--bg-tertiary)",borderColor:ae?`${ae}40`:"transparent"},children:n.jsx(ft,{size:14})})})(),n.jsx("span",{className:`${f.metaBadge} ${f[`type_${e.type}`]||""}`,title:kt(e.type||Gr),style:{color:`var(--type-color, ${Ae})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${Ae}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${Ae}), transparent 75%)`},children:Ce?.icon?(()=>{const ae=hs[Ce.icon]||xE;return n.jsx(ae,{size:14})})():DM(e.type,14)}),G&&n.jsx("span",{className:f.metaBadge,style:{color:ne||"var(--text-secondary)",backgroundColor:ne?`${ne}15`:"var(--bg-tertiary)",borderColor:ne?`${ne}40`:"var(--border-color)"},title:`${G.label}`,children:(()=>{const ae=G.icon||"AlertCircle",Ge=hs[ae]||Ek;return n.jsx(Ge,{size:14})})()}),M>0&&n.jsxs("span",{className:f.metaBadge,title:`${M} activity items`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[n.jsx(wE,{size:14}),n.jsx("span",{children:M})]}),dt>0&&n.jsxs("span",{className:f.metaBadge,title:`${Qe}/${dt} checklist items complete`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[n.jsx(AE,{size:14}),n.jsx("span",{children:`${Qe}/${dt}`})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("span",{className:f.metaBadge,title:`AI-estimated complexity: ${Pe} (${me}/5)`,style:{color:Ee,backgroundColor:`color-mix(in srgb, ${Ee}, transparent 88%)`,borderColor:`color-mix(in srgb, ${Ee}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[n.jsx(CE,{size:14}),!C&&n.jsx("span",{children:Pe})]}),n.jsx("span",{className:`${Qt.assigneeAvatarIndicator} ${b==="unassigned"?Qt.assigneeAvatarEmpty:""}`,title:`Assigned to: ${R}`,"aria-label":b==="unassigned"?"Unassigned":`Assigned to ${R}`,style:{"--assignee-avatar-color":fe},children:Y?n.jsx("img",{src:Y,alt:"",className:Qt.assigneeAvatarImage}):b==="agent"?n.jsx(_E,{size:C?18:20}):b==="member"?n.jsx(bE,{size:C?18:20}):null})]})]})})})]})]})},xd=ze.memo(TE),wm="168px";function Ay(){return n.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:qe("standalone.filtersCaps")})}function Ji({label:e,options:t,selected:a,onChange:s,variant:o="label"}){return n.jsx(Yi,{label:e,options:t,selected:a,onChange:s,variant:o,containerStyle:{flex:`0 0 ${wm}`,maxWidth:wm}})}function xy({onClick:e}){return n.jsxs("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[n.jsx(oc,{size:12})," ",qe("standalone.clearFilters")]})}function Fh({label:e,options:t,selected:a,onChange:s,allLabel:o,title:c}){const[i,d]=ze.useState(!1),m=ze.useRef(null),y=t.find(h=>h.value===a),k=y?.selectedLabel||y?.label||o;ze.useEffect(()=>{const h=g=>{m.current&&!m.current.contains(g.target)&&d(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const S=h=>{s(h),d(!1)};return n.jsxs("div",{className:f.filterContainer,ref:m,style:{flex:`0 0 ${wm}`,maxWidth:wm},children:[n.jsxs("button",{type:"button",className:`${f.filterButton} ${a?f.filterActive:""}`,onClick:()=>d(h=>!h),title:c||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":i,children:[n.jsx("span",{children:k}),n.jsx(sl,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&n.jsxs("div",{className:`${f.filterDropdown} ${f.appScrollbar} tf-scrollbar`,role:"listbox","aria-label":e,children:[n.jsxs("button",{type:"button",className:f.filterOption,onClick:()=>S(""),"aria-selected":!a,children:[n.jsx(eo,{size:14,style:{opacity:a?0:1}}),n.jsx("span",{style:{fontWeight:a?500:600},children:o})]}),n.jsx("div",{className:f.filterDivider}),t.map(h=>{const g=h.value===a;return n.jsxs("button",{type:"button",className:f.filterOption,onClick:()=>S(h.value),"aria-selected":g,children:[n.jsx(eo,{size:14,style:{opacity:g?1:0}}),n.jsx("span",{style:{fontWeight:g?600:500},children:h.label})]},h.value)})]})]})}function Iy({scope:e,onScopeChange:t,className:a,labelClassName:s}){return n.jsxs("div",{className:a,children:[n.jsx("span",{className:s,children:"Scope"}),n.jsx("div",{className:f.taskScopeTabs,role:"tablist","aria-label":"Task scope",children:[{value:"open",label:"Open"},{value:"archived",label:"Archived"},{value:"deleted",label:"Deleted"}].map(o=>{const c=e===o.value;return n.jsx("button",{type:"button",className:`${f.taskScopeTab} ${c?f.taskScopeTabActive:""}`,onClick:()=>t(o.value),role:"tab","aria-selected":c,"aria-pressed":c,title:`Show ${o.label.toLowerCase()} tasks`,children:o.label},o.value)})})]})}function Ty({onClick:e,disabled:t=!1,className:a,title:s="Permanently delete all deleted tasks",children:o="Delete All Permanently"}){return n.jsxs("button",{type:"button",className:a,onClick:e,disabled:t,title:s,children:[n.jsx(xm,{size:14}),o]})}const{Search:Oh,ClipboardList:RE,ChevronRight:NE,ChevronDown:jE,Folder:PE,Archive:ME,RotateCcw:EE,X:DE,Plus:LE,ArrowUpDown:BE,Trash2:WE}=hs,Ry=r.forwardRef((e,t)=>{const{tasks:a,archivedTasks:s,categories:o,types:c,priorities:i,taxonomyDisplayLabels:d,assigneeOptions:m=[],workstreams:y=[],initiatives:k=[],searchQuery:S,filterCategories:h,filterTypes:g,filterPriorities:v,filterStatus:_,filterAssignees:I=[],filterTaxonomies:A,sortBy:D,sortOrder:U,showArchive:W,taskScope:Q,collapsedCategories:le,loadingTasks:ie,filteredTasks:se,filteredArchive:$,groupedTasks:C,filteredDeletedTasks:de=[],groupedDeletedTasks:ke={},copiedId:K,recentlyChangedTaskIds:j=[],showTaskCardStatusLabel:H=!0,onSearchChange:ue,onFilterCategoriesChange:ye,onFilterTypesChange:G,onFilterPrioritiesChange:je,onFilterStatusChange:be,onFilterAssigneesChange:ce,onTaxonomyFilterChange:me,onSortByChange:Te,onSortOrderChange:Me,onShowArchiveChange:Pe,onTaskScopeChange:Ee,onClearFilters:Z,onToggleCategory:x,onEditTask:b,onOpenTaskById:R,onCopyId:B,onToggleInProgress:Y,onToggleReview:fe,onToggleComplete:te,onToggleCancel:Le,onSetStatus:oe,onArchiveTask:L,onBulkArchive:X,onUnarchive:M,onDelete:V,onDeleteAllDeleted:ne,onFetchArchive:Ce,onAddTaskToCategory:Ae,supplementalTasks:Re=[],taxonomies:$e}=e,vt=new Set(j),st=ze.useMemo(()=>new Map(y.map(re=>[re.id,re])),[y]),kt=ze.useMemo(()=>new Map(k.map(re=>[re.id,re])),[k]),Ye=ze.useCallback(re=>{const Be=re.workstreamId&&st.get(re.workstreamId)||null,At=Be?.initiativeId&&kt.get(Be.initiativeId)||null;return{taskWorkstream:Be,taskInitiative:At}},[kt,st]),Ct=[...a,...s,...Re],dt=!!Ee,Qe=Ee,Tt=Q??(W?"archived":"open"),ae=dt?Tt==="archived"?$:Tt==="deleted"?de:se:se,Ge=dt?Tt==="archived"?{Archived:$}:Tt==="deleted"?ke:C:C,ft=dt?Tt==="deleted"?"deleted":Tt==="archived"?"archived":null:null,it=jm(S),Mt=S?it?`No task found for ${it.toUpperCase()}`:qe("taskList.noMatchingTasks"):Tt==="archived"?"No archived tasks found.":Tt==="deleted"?"No deleted tasks found.":qe("taskList.noActiveTasks"),ht=o.filter(re=>!re.disabled),Ft=o.filter(re=>re.disabled&&Ct.some(Be=>Be.category===re.value)),Et=[...ht,...Ft.filter(re=>!ht.some(Be=>Be.value===re.value))].map(re=>({value:re.value,label:re.disabled?`${re.label} (Legacy)`:re.label})),We=c.filter(re=>re.status!=="retired"),tt=c.filter(re=>re.status==="retired"&&Ct.some(Be=>Be.type===re.value)),Oe=[...We,...tt.filter(re=>!We.some(Be=>Be.value===re.value))].map(re=>({value:re.value,label:re.status==="retired"?`${re.label} (Retired)`:re.label})),St=Td($e,Ct).filter(re=>re.filterEnabled!==!1).map(re=>({...re,options:If(re,Ct)})),ot=ze.useMemo(()=>[{value:"created",label:qe("taskList.sortCreated")},{value:"updated",label:qe("taskList.sortUpdated")},{value:"priority",label:qe("taskList.sortPriority")},...py($e,Ct)],[Ct,qe,$e]);return n.jsxs("div",{className:f.viewTab,ref:t,children:[n.jsxs("div",{className:f.filterBar,children:[n.jsxs("div",{className:f.searchContainer,children:[n.jsx(Oh,{size:16,className:f.searchIcon}),n.jsx("input",{type:"text",className:f.searchInput,placeholder:qe("taskList.searchPlaceholder"),value:S,onChange:re=>ue(re.target.value)}),S&&n.jsx("button",{className:f.clearSearchBtn,onClick:()=>ue(""),title:qe("taskList.clearSearchTitle"),children:n.jsx(DE,{size:14})})]}),n.jsxs("div",{className:f.filterRow,children:[n.jsx(Yi,{label:d?.category||qe("taskList.categoryLabel"),options:Et,selected:h,onChange:ye,variant:"value"}),n.jsx(Yi,{label:d?.type||qe("taskList.typeLabel"),options:Oe,selected:g,onChange:G,variant:"value"})]}),n.jsxs("div",{className:f.filterRow,children:[n.jsx(Yi,{label:d?.priority||qe("taskList.priorityLabel"),options:i,selected:v,onChange:je,variant:"value"}),n.jsx(Yi,{label:qe("taskList.statusLabel"),options:Xs,selected:_,onChange:be,variant:"value"}),n.jsx(Yi,{label:qe("taskList.assigneeLabel"),options:m,selected:I,onChange:re=>ce?.(re),variant:"value"})]}),St.map(re=>n.jsx(Yi,{label:re.status==="retired"?`${re.label} (Retired)`:re.label,options:re.options.map(Be=>({...Be,label:Be.status==="retired"?`${Be.label} (Retired)`:Be.label})),selected:A[re.id]||[],onChange:Be=>me(re.id,Be),variant:"value"},re.id)),n.jsxs("div",{className:f.filterRow,children:[n.jsxs("div",{className:f.sortLabel,children:[n.jsx(BE,{size:14,style:{marginRight:"4px"}})," ",qe("taskList.sortByLabel")]}),n.jsx("select",{value:D,onChange:re=>Te(re.target.value),className:`${f.filterSelect} ${f.filterSelectSort} `,children:ot.map(re=>n.jsx("option",{value:re.value,children:re.label},re.value))}),n.jsx("button",{className:`${f.resetFiltersBtn} ${f.sortDirectionBtnWidget}`,onClick:Me,title:qe(U==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:U==="desc"?n.jsx(fg,{size:14}):n.jsx(hg,{size:14})}),n.jsx("button",{className:f.resetFiltersBtn,onClick:Z,title:qe("taskList.resetFiltersTitle"),children:n.jsx(EE,{size:14})})]}),n.jsxs("div",{className:`${f.filterRow} ${f.archiveRow} `,children:[Tt==="open"?n.jsxs("button",{className:`${f.bulkArchiveBtn} ${a.some(re=>re.status==="done"||re.status==="cancelled")?"":f.disabledBtn} `,onClick:()=>a.some(re=>re.status==="done"||re.status==="cancelled")&&X(),disabled:!a.some(re=>re.status==="done"||re.status==="cancelled"),title:a.some(re=>re.status==="done"||re.status==="cancelled")?qe("taskList.archiveAllTitle"):qe("taskList.noTasksToArchiveTitle"),children:[n.jsx(ME,{size:12}),n.jsx("span",{children:qe("taskList.archiveFinished")})]}):Tt==="deleted"&&ne?n.jsx(Ty,{className:`${f.bulkArchiveBtn} ${f.taskToolbarAction} ${f.bulkDeleteBtn} ${de.length===0?f.disabledBtn:""}`,onClick:()=>de.length>0&&ne(),disabled:de.length===0,title:de.length>0?"Empty trash":"Trash is already empty",children:"Empty Trash"}):n.jsx("div",{}),dt?n.jsx(Iy,{scope:Tt,onScopeChange:re=>{Qe?.(re),re==="archived"?(Pe(!0),Ce()):W&&Pe(!1)},className:`${f.archiveToggle} ${f.taskScopeToggle}`}):n.jsxs("label",{className:f.archiveToggle,children:[n.jsx("input",{type:"checkbox","aria-label":"Archived",checked:W,onChange:re=>{Pe(re.target.checked),re.target.checked&&Ce()}}),n.jsx("span",{children:"Include Archive"})]})]})]}),ie&&a.length===0?n.jsx("div",{className:f.loading,children:n.jsx(br,{size:24,className:f.spinner})}):ae.length===0&&!ie?n.jsxs("div",{className:f.emptyState,children:[S?n.jsx(Oh,{size:48}):Tt==="deleted"?n.jsx(WE,{size:48}):n.jsx(RE,{size:48}),n.jsx("p",{children:Mt})]}):n.jsx("div",{className:f.taskList,style:{opacity:ie?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(Ge).map(([re,Be])=>{if(Be.length===0)return null;const At=le[re];return n.jsxs("div",{className:f.categoryGroup,children:[n.jsx("div",{className:f.categoryHeader,onClick:()=>x(re),children:n.jsxs("div",{className:f.categoryTitle,children:[At?n.jsx(NE,{size:16}):n.jsx(jE,{size:16}),(()=>{const Rt=o.find(Ot=>Ot.label===re),Bt=Rt?.icon&&rc[Rt.icon]?rc[Rt.icon]:PE,Ve=Ma(Rt?.color)||"var(--color-purple, #8b5cf6)";return n.jsx(Bt,{size:16,className:f.categoryTitleIcon,style:{color:Ve}})})(),re,n.jsxs("span",{className:f.categoryCount,children:["(",Be.length,")"]}),Ae&&n.jsx("button",{className:f.kanbanQuickAdd,onClick:Rt=>{Rt.stopPropagation(),Ae(re)},title:qe("taskList.addTaskToCategoryTitle",{category:re}),style:{marginLeft:"auto"},disabled:ft!==null,children:n.jsx(LE,{size:14})})]})}),!At&&n.jsx("div",{className:f.categoryItems,children:Be.map(Rt=>(()=>{const{taskWorkstream:Bt,taskInitiative:Ve}=Ye(Rt);return n.jsx(xd,{task:Rt,taskWorkstream:Bt,taskInitiative:Ve,searchQuery:S,copiedId:K,taxonomies:$e,types:c,priorities:i,assigneeOptions:m,onClick:b,onOpenTaskById:R,onCopyId:B,onToggleInProgress:Y,onToggleReview:fe,onToggleComplete:te,onToggleCancel:Le,onSetStatus:oe,onArchiveTask:L,onUnarchive:ft?M:void 0,onDelete:ft?V:void 0,categories:o,isRecentlyChanged:vt.has(Rt.id),readOnlyMode:ft,showStatusLabel:H},Rt.id)})())})]},re)})}),!dt&&W&&$.length>0&&n.jsxs("div",{className:f.archiveList,children:[n.jsx("div",{className:f.archiveHeader,children:"Archived"}),$.map(re=>(()=>{const{taskWorkstream:Be,taskInitiative:At}=Ye(re);return n.jsx(xd,{task:re,taskWorkstream:Be,taskInitiative:At,searchQuery:S,copiedId:K,isArchived:!0,types:c,assigneeOptions:m,onClick:b,onCopyId:B,onSetStatus:oe,onUnarchive:M,onDelete:V,deleteActionTitle:"Delete Permanently",categories:o,showStatusLabel:H},re.id)})())]})]})});Ry.displayName="TaskList";const FE="_formNotice_inuex_1",OE="_assigneeIndicator_inuex_12",$E="_assigneeIndicatorAgent_inuex_20",UE="_assigneeIndicatorUser_inuex_24",zE="_assigneeIndicatorUnassigned_inuex_28",HE="_markdownPreview_inuex_32",GE="_error_inuex_83",VE="_keyboardHint_inuex_92",qE="_taskFormLifecycle_inuex_110",KE="_taskFormMetaDivider_inuex_115",ZE="_taskFormMetaGrid_inuex_122",YE="_compactMetaSection_inuex_128",JE="_createWorkstreamRow_inuex_134",QE="_createWorkstreamDropdown_inuex_140",XE="_compactMetaGrid_inuex_145",eD="_compactMetaField_inuex_151",tD="_compactMetaFieldHint_inuex_165",nD="_formFieldsetReset_inuex_169",aD="_formLayout_inuex_176",rD="_formLayoutWithSidebar_inuex_183",sD="_formMainColumn_inuex_191",oD="_activitySidebar_inuex_198",iD="_activitySidebarHeader_inuex_208",cD="_activitySidebarTitle_inuex_215",lD="_activitySidebarCount_inuex_224",dD="_taskFormDateRow_inuex_246",uD="_taskFormDateLabel_inuex_253",mD="_taskFormDateValue_inuex_261",pD="_taskFormMetaStack_inuex_269",fD="_taskFormMetaActor_inuex_275",hD="_taskFormDateWarning_inuex_287",gD="_taskFormDateError_inuex_293",yD="_helpHeader_inuex_299",kD="_helpClose_inuex_310",vD="_markdownHelp_inuex_324",SD="_helpGrid_inuex_333",wD="_helpGridItem_inuex_339",bD="_settingsHint_inuex_351",_D="_sectionBlock_inuex_357",CD="_softSectionSurface_inuex_367",AD="_stackedList_inuex_374",xD="_stackedListSpaced_inuex_379",ID="_checklistRow_inuex_383",TD="_checklistRowDragging_inuex_392",RD="_checklistHandleBtn_inuex_396",ND="_checklistCheckboxBtn_inuex_419",jD="_checklistCheckboxBtnChecked_inuex_439",PD="_checklistItemText_inuex_444",MD="_checklistItemTextCompleted_inuex_450",ED="_checklistRemoveBtn_inuex_455",DD="_specialistChip_inuex_522",LD="_specialistChipActive_inuex_545",BD="_commentPanel_inuex_626",WD="_activitySidebarPanel_inuex_635",FD="_commentThread_inuex_643",OD="_emptyComments_inuex_663",$D="_activityLoadingThread_inuex_673",UD="_activitySkeletonItem_inuex_677",zD="_activitySkeletonMeta_inuex_683",HD="_activitySkeletonBody_inuex_684",GD="_comment_inuex_626",VD="_commentAi_inuex_740",qD="_commentUser_inuex_744",KD="_commentHeader_inuex_748",ZD="_commentAuthor_inuex_772",YD="_commentTime_inuex_780",JD="_commentText_inuex_784",QD="_commentInputArea_inuex_844",XD="_commentInput_inuex_844",eL="_sendCommentBtn_inuex_876",tL="_taxonomyFieldsGrid_inuex_903",nL="_markdownPreviewContainer_inuex_910",aL="_descriptionSurface_inuex_915",Xe={formNotice:FE,assigneeIndicator:OE,assigneeIndicatorAgent:$E,assigneeIndicatorUser:UE,assigneeIndicatorUnassigned:zE,markdownPreview:HE,error:GE,keyboardHint:VE,taskFormLifecycle:qE,taskFormMetaDivider:KE,taskFormMetaGrid:ZE,compactMetaSection:YE,createWorkstreamRow:JE,createWorkstreamDropdown:QE,compactMetaGrid:XE,compactMetaField:eD,compactMetaFieldHint:tD,formFieldsetReset:nD,formLayout:aD,formLayoutWithSidebar:rD,formMainColumn:sD,activitySidebar:oD,activitySidebarHeader:iD,activitySidebarTitle:cD,activitySidebarCount:lD,taskFormDateRow:dD,taskFormDateLabel:uD,taskFormDateValue:mD,taskFormMetaStack:pD,taskFormMetaActor:fD,taskFormDateWarning:hD,taskFormDateError:gD,helpHeader:yD,helpClose:kD,markdownHelp:vD,helpGrid:SD,helpGridItem:wD,settingsHint:bD,sectionBlock:_D,softSectionSurface:CD,stackedList:AD,stackedListSpaced:xD,checklistRow:ID,checklistRowDragging:TD,checklistHandleBtn:RD,checklistCheckboxBtn:ND,checklistCheckboxBtnChecked:jD,checklistItemText:PD,checklistItemTextCompleted:MD,checklistRemoveBtn:ED,specialistChip:DD,specialistChipActive:LD,commentPanel:BD,activitySidebarPanel:WD,commentThread:FD,emptyComments:OD,activityLoadingThread:$D,activitySkeletonItem:UD,activitySkeletonMeta:zD,activitySkeletonBody:HD,comment:GD,commentAi:VD,commentUser:qD,commentHeader:KD,commentAuthor:ZD,commentTime:YD,commentText:JD,commentInputArea:QD,commentInput:XD,sendCommentBtn:eL,taxonomyFieldsGrid:tL,markdownPreviewContainer:nL,descriptionSurface:aL};function Tp({label:e,value:t,options:a,onChange:s,type:o="priority",hideLabel:c=!1,showSelectedLabel:i=!0}){const d=a.find(m=>String(m.value)===String(t));return n.jsxs("div",{className:f.field,children:[!c&&n.jsxs("div",{className:f.labelRow,children:[n.jsx("label",{className:f.label,children:e}),i&&d&&n.jsx("span",{className:f.levelLabel,style:{color:Ma(d.color)||(o==="priority"?`var(--priority-${t})`:o==="complexity"?`var(--complexity-${t})`:"var(--text-secondary)"),backgroundColor:(Ma(d.color)?`${Ma(d.color)}25`:void 0)||(o==="priority"?`color-mix(in srgb, var(--priority-${t}), transparent 85%)`:o==="complexity"?`color-mix(in srgb, var(--complexity-${t}), transparent 85%)`:"rgba(255,255,255,0.05)")},children:d.label})]}),n.jsx("div",{className:f.levelSelect,children:a.map((m,y)=>{const k=a.findIndex(g=>String(g.value)===String(t)),S=y<=k,h=String(m.value)===String(t);return n.jsx("button",{type:"button",className:`${f.levelOption} ${S?f.levelOptionFilled:""} ${S?f[`levelOption_${o}_${m.value}`]:""} ${h?f.levelOptionSelected:""}`,onClick:()=>s(m.value),title:m.label,style:{opacity:S?1:.15,backgroundColor:S?Ma(m.color)||(o==="priority"?`var(--priority-${m.value})`:o==="complexity"?`var(--complexity-${m.value})`:"var(--text-primary)"):void 0,color:S?o==="priority"&&String(m.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:S&&(o==="priority"&&(String(m.value).toLowerCase()==="critical"||m.value===4)||o==="complexity"&&(String(m.value).toLowerCase()==="epic"||m.value===5))?`0 0 12px ${o==="priority"?"rgba(239, 68, 68, 0.6)":"rgba(217, 70, 239, 0.6)"}`:void 0}},String(m.value))})})]})}const $h=new Map;function rL(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t}function sL(e,t){const a=Object.entries(t).sort(([s],[o])=>s.localeCompare(o));return JSON.stringify([e,a])}function bm(e,t,a){const s=rL(e);if(!s)return"";const o=a??$g(),c=sL(o,t);let i=$h.get(c);return i||(i=new Intl.DateTimeFormat(o,t),$h.set(c,i)),i.format(s)}const oL=ze.lazy(()=>gs(()=>import("./EntityActivityTimeline-B8nSe8l3.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),iL=ze.lazy(()=>gs(()=>import("./TaskContextUpload-DvDlNpHC.js"),__vite__mapDeps([7,1,8,9,2,3,4,5])).then(e=>({default:e.TaskContextUpload})));function cL({count:e}){const t=Math.max(2,Math.min(e||3,4));return n.jsx("div",{className:`${Xe.commentThread} ${Xe.activityLoadingThread}`.trim(),"aria-busy":"true","aria-live":"polite","aria-label":"Loading activity",children:Array.from({length:t},(a,s)=>n.jsxs("div",{className:Xe.activitySkeletonItem,children:[n.jsx("div",{className:Xe.activitySkeletonMeta}),n.jsx("div",{className:Xe.activitySkeletonBody})]},s))})}function lL({id:e,item:t,onToggle:a,onRemove:s}){const{attributes:o,listeners:c,setNodeRef:i,transform:d,transition:m,isDragging:y}=Ig({id:e}),k={transform:df.Transform.toString(d),transition:m,opacity:y?.88:1};return n.jsxs("div",{ref:i,style:k,className:`${Xe.checklistRow} ${y?Xe.checklistRowDragging:""}`.trim(),children:[n.jsx("button",{type:"button",className:Xe.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...o,...c,children:n.jsx(Lk,{size:14})}),n.jsx("button",{type:"button",className:`${Xe.checklistCheckboxBtn} ${t.isCompleted?Xe.checklistCheckboxBtnChecked:""}`.trim(),onClick:a,title:t.isCompleted?"Mark incomplete":"Mark complete","aria-label":t.isCompleted?"Mark checklist item incomplete":"Mark checklist item complete",children:t.isCompleted?n.jsx(eo,{size:14,strokeWidth:2.1}):null}),n.jsx("span",{className:`${Xe.checklistItemText} ${t.isCompleted?Xe.checklistItemTextCompleted:""}`.trim(),children:t.title}),n.jsx("button",{type:"button",className:Xe.checklistRemoveBtn,onClick:s,title:"Remove checklist item","aria-label":"Remove checklist item",children:n.jsx(oc,{size:15,strokeWidth:1.9})})]})}function Ny(e){const{editingTaskId:t,error:a,title:s,description:o,category:c,type:i,priority:d,complexity:m,manualComplexityEnabled:y=!1,assignee:k,scheduledDate:S,dueDate:h,workstreamInput:g="",checklistItems:v,comments:_,newCommentText:I,contextFiles:A,currentWorkspaceId:D,apiBaseUrl:U,descriptionFocused:W,showMarkdownHelp:Q,showChecklist:le=!1,checklistEnabled:ie=!0,formTaxonomies:se,onTaxonomyChange:$,onOpenSettings:C,categories:de,types:ke,priorities:K,taxonomyDisplayLabels:j,assigneeOptions:H,taxonomies:ue,workstreams:ye=[],initiatives:G=[],copiedId:je,onTitleChange:be,onDescriptionChange:ce,onCategoryChange:me,onTypeChange:Te,onPriorityChange:Me,onComplexityChange:Pe,onAssigneeChange:Ee,onScheduledDateChange:Z,onDueDateChange:x,onWorkstreamInputChange:b=()=>{},onChecklistItemsChange:R,onNewCommentTextChange:B,onDescriptionFocusedChange:Y,onShowMarkdownHelpChange:fe,onShowChecklistChange:te=()=>{},onSubmit:Le,onAddComment:oe,onAddContextFile:L,onRemoveContextFile:X,onUpdateContextCaption:M,onCopyId:V,onToggleInProgress:ne,onToggleReview:Ce,onToggleComplete:Ae,onToggleCancel:Re,onSetStatus:$e,onArchiveTask:vt,onUnarchive:st,onOpenTaskById:kt,currentTask:Ye,commentsEndRef:Ct}=e,dt=nc(Ye),Qe=ze.useMemo(()=>db(ue,se),[ue,se]),Tt=ze.useMemo(()=>{const ge=de.find(bt=>bt.value===el),at={value:el,label:ge?.label||Im,icon:ge?.icon||"HelpCircle",color:ge?.color||"var(--text-secondary)"},xe=de.find(bt=>bt.value===c),pt=de.filter(bt=>!bt.disabled||bt.value===xe?.value).filter(bt=>bt.value!==el).map(bt=>({value:bt.value,label:bt.disabled?`${bt.label} (Legacy)`:bt.label,icon:bt.icon,color:bt.color}));return[at,...pt]},[de,c]),ae=ze.useMemo(()=>{const ge=ke.find(xe=>xe.value===i);return ke.filter(xe=>xe.status!=="retired"||xe.value===ge?.value).map(xe=>({value:xe.value,label:xe.status==="retired"?`${xe.label} (Retired)`:xe.label,icon:xe.icon||"Box",color:xe.color||"violet-500"}))},[ke,i]),Ge=ge=>ge&&bm(ge,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,ft=Ge(Ye?.createdAt),it=Ge(Ye?.updatedAt||Ye?.createdAt),Mt=Ge(Ye?.completedAt),ht=ze.useMemo(()=>{const ge=new Date,at=ge.getFullYear(),xe=String(ge.getMonth()+1).padStart(2,"0"),jt=String(ge.getDate()).padStart(2,"0");return`${at}-${xe}-${jt}`},[]),Ft=!!(h&&S&&h<S),Et=!!(h&&h<ht&&(!Ye||Ye.status!=="done"&&Ye.status!=="cancelled")),We=v.filter(ge=>ge.isCompleted).length,[tt,Oe]=ze.useState(""),[Ze,St]=ze.useState(!1),ot=!!Ye?.isArchived,re=!!Ye?.isDeleted,Be=ze.useMemo(()=>ye.map(ge=>{const at=fm(ge);return{value:at||ge.id,label:at?`${at} · ${ge.title}`:ge.title,icon:"Folder",color:"var(--text-secondary)"}}),[ye]),At=ze.useMemo(()=>Be.some(ge=>String(ge.value)===String(g||"").trim()),[g,Be]);ze.useEffect(()=>{if(t){Ze&&St(!1);return}if(g.trim()){if(At&&Ze){St(!1);return}!At&&!Ze&&St(!0)}},[t,At,Ze,g]);const Rt=ot||re,Bt=ze.useRef(null),Ve=bg($p(xg,{activationConstraint:{distance:6}}));ze.useLayoutEffect(()=>{const ge=Bt.current;if(!ge)return;const at=()=>{ge.scrollTop=0;const jt=ge.parentElement;jt&&(typeof jt.scrollTo=="function"?jt.scrollTo({top:0,left:0,behavior:"auto"}):jt.scrollTop=0)};at();const xe=window.requestAnimationFrame(at);return()=>window.cancelAnimationFrame(xe)},[t,Ye?.id]);const Ot=()=>{const ge=tt.trim();if(!ge)return;const at=new Date().toISOString();R([...v,{id:`checklist-draft-${at}-${v.length}`,taskId:t||"",title:ge,isCompleted:!1,order:v.length,createdAt:at,updatedAt:at}]),Oe("")},yt=ze.useCallback(ge=>{const{active:at,over:xe}=ge;if(!xe||at.id===xe.id)return;const jt=v.findIndex(vn=>vn.id===at.id),pt=v.findIndex(vn=>vn.id===xe.id);if(jt<0||pt<0)return;const bt=new Date().toISOString(),An=cv(v,jt,pt).map((vn,dn)=>({...vn,order:dn,updatedAt:bt}));R(An)},[v,R]),E=ge=>{const at=String(ge||"").trim(),xe=ge.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!xe||xe==="ai"||at.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${xe.split(" ").map(pt=>pt.charAt(0).toUpperCase()+pt.slice(1)).join(" ")}`},l=mS(H,k),J=um(k),Se=hd(k,l),Ie=ze.useMemo(()=>new Map(l.map(ge=>[String(ge.value),ge])),[l]),Ke=Ie.get(String(k||"unassigned")),Je=Ye?.assigneeActor?.color||Ke?.color,Ne=ze.useMemo(()=>{const ge=[Ye?.assigneeActor,Ye?.createdByActor].filter(Boolean);return new Map(ge.map(at=>[String(at.id),at]))},[Ye?.assigneeActor,Ye?.createdByActor]),zt=ze.useMemo(()=>new Map(ye.map(ge=>[ge.id,fm(ge)||ge.id])),[ye]),Yt=ze.useMemo(()=>new Map(G.map(ge=>[ge.id,dy(ge)||ge.id])),[G]),Pt=ze.useMemo(()=>Nf({activity:Ye?.activity,comments:_}),[_,Ye?.activity]),Wt=(ge,at)=>{const xe=String(at||"").trim();if(xe){if(ge==="assignee")return hd(xe,l);if(ge==="workstreamId")return zt.get(xe);if(ge==="initiativeId")return Yt.get(xe)}},Dt=ze.useCallback((ge,at,xe)=>{if(xe&&xe.trim())return xe.trim();const jt=String(ge||"").trim();if(!jt)return at==="ai"?"AI Agent":qe("taskForm.you");const pt=Ne.get(jt);if(pt?.label)return pt.label;const bt=Ie.get(jt)||Ie.get(jt.toLowerCase());return bt?.label?bt.label:at==="ai"?E(jt):hd(jt,l)||jt},[Ne,Ie,E,l]),Ht=ze.useCallback(({actorId:ge,actorType:at,actorProfile:xe,fallbackKind:jt})=>{const pt=String(ge||"").trim(),bt=pt.toLowerCase(),An=Ne.get(pt),vn=Ie.get(pt)||Ie.get(bt),dn=xe||An||vn||null,un=at==="system"?"system":at==="ai"||dn?.kind==="ai"?"agent":at==="human"||dn?.kind==="human"?"member":vn?.kind==="agent"?"agent":vn?.kind==="member"?"member":jt||(bt===""||bt==="user"||bt==="human"?"member":"agent"),Bn=un==="system"?"System":Dt(pt,un==="agent"?"ai":"human",dn?.label||null),gt=dn?.color,cr=String(dn?.icon||(un==="agent"?"Bot":un==="member"?"User":"ClipboardList")),fn=rc[cr]||(un==="agent"?sm:un==="member"?fi:gg);return{kind:un,label:Bn,color:gt,ActorIcon:fn}},[Ne,Ie,Dt]),sn=ze.useMemo(()=>{const ge=Pt[Pt.length-1];if(!ge)return null;if(ge.type==="comment"){const xe=ge.comment;return Dt(xe.author,xe.actor?.kind==="ai"?"ai":xe.actor?.kind==="human"?"human":null,xe.actor?.label||null)}const at=ge.event;return Dt(at.actor,at.actorType,at.actorProfile?.label||null)},[Dt,Pt]),Vt=ze.useMemo(()=>{if(!Ye?.completedAt)return null;for(const at of Pt){if(at.type!=="event")continue;const xe=at.event,jt=xe.details?.changes?.status?.to;if(jt==="done"||jt==="cancelled")return Dt(xe.actor,xe.actorType,xe.actorProfile?.label||null)}return sn},[Ye?.completedAt,sn,Dt,Pt]),Vn=Ye?.createdByActor?.label||Dt(Ye?.createdBy||null,Ye?.createdByActor?.kind==="ai"?"ai":Ye?.createdByActor?.kind==="human"?"human":null,Ye?.createdByActor?.label||null),qn=sn,Kn=Pt.length;ze.useLayoutEffect(()=>{if(!t)return;const ge=Ct.current;if(!ge)return;const at=ge.parentElement,xe=()=>{if(typeof ge.scrollIntoView=="function"){ge.scrollIntoView({block:"end"});return}at&&(at.scrollTop=at.scrollHeight)};xe();const jt=window.requestAnimationFrame(xe);return()=>window.cancelAnimationFrame(jt)},[Kn,Ct,Ye?.id,t]);const ga=t?n.jsxs("aside",{className:Xe.activitySidebar,"aria-label":qe("taskForm.commentsSectionTitle"),children:[n.jsxs("div",{className:Xe.activitySidebarHeader,children:[n.jsx("h2",{className:Xe.activitySidebarTitle,children:qe("taskForm.commentsSectionTitle")}),n.jsx("span",{className:Xe.activitySidebarCount,children:Kn})]}),n.jsxs("div",{className:`${Xe.commentPanel} ${Xe.activitySidebarPanel}`.trim(),children:[n.jsx(ze.Suspense,{fallback:n.jsx(cL,{count:Kn}),children:n.jsx(oL,{activity:Ye?.activity,comments:_,formatFieldValue:Wt,resolveActorPresentation:Ht,onOpenTaskById:kt,emptyMessage:qe("taskForm.noComments"),listClassName:Xe.commentThread,emptyClassName:Xe.emptyComments,endRef:Ct})}),n.jsxs("div",{className:Xe.commentInputArea,children:[n.jsx("textarea",{className:Xe.commentInput,placeholder:qe("taskForm.commentPlaceholder"),value:I,onChange:ge=>B(ge.target.value),onKeyDown:ge=>{ge.key==="Enter"&&!ge.shiftKey&&(ge.preventDefault(),oe())},rows:4}),n.jsx("button",{type:"button",className:Xe.sendCommentBtn,onClick:oe,disabled:!I.trim(),"aria-label":"Send comment",title:"Send comment",children:n.jsx(Dk,{size:16})})]})]})]}):null;return n.jsxs("form",{ref:Bt,onSubmit:Le,className:`${f.form} ${f.appScrollbar} tf-scrollbar`,children:[a&&n.jsx("div",{className:Xe.error,children:a}),Rt&&n.jsx("div",{className:`${Xe.formNotice} tf-text-helper`,children:re?"Deleted tasks are read-only. Restore the task to make changes.":"Archived tasks are read-only. Unarchive the task to make changes."}),n.jsxs("fieldset",{disabled:Rt,className:`${Xe.formFieldsetReset} ${t?Xe.formLayoutWithSidebar:Xe.formLayout}`.trim(),children:[n.jsxs("div",{className:Xe.formMainColumn,children:[n.jsxs("div",{className:f.field,children:[n.jsxs("div",{className:f.labelRow,children:[n.jsx("label",{className:f.label,children:"Title"}),k&&n.jsx("span",{title:`Assigned to: ${Se}`,className:[Xe.assigneeIndicator,J==="agent"?Xe.assigneeIndicatorAgent:J==="member"?Xe.assigneeIndicatorUser:Xe.assigneeIndicatorUnassigned].join(" "),style:Je?{color:Je}:void 0,children:J==="agent"?n.jsx(sm,{size:20}):J==="member"?n.jsx(fi,{size:20}):n.jsx(ec,{size:20})})]}),n.jsx("input",{type:"text",value:s,onChange:ge=>be(ge.target.value),placeholder:"What needs to be done?",className:f.input,required:!0,maxLength:255,autoFocus:!0})]}),n.jsxs("div",{className:f.field,children:[n.jsxs("div",{className:f.labelRow,children:[n.jsx("label",{className:f.label,children:"Description"}),n.jsx("button",{type:"button",className:f.helpLink,onClick:()=>fe(!Q),title:"Markdown Help",tabIndex:-1,children:n.jsx(ec,{size:14})})]}),Q&&n.jsxs("div",{className:Xe.markdownHelp,children:[n.jsxs("div",{className:Xe.helpHeader,children:[n.jsx("span",{children:"Markdown Guide"}),n.jsx("button",{onClick:()=>fe(!1),className:Xe.helpClose,children:n.jsx(oc,{size:12})})]}),n.jsxs("div",{className:Xe.helpGrid,children:[n.jsx("div",{children:n.jsx("code",{children:"**bold**"})}),n.jsx("div",{children:n.jsx("code",{children:"_italic_"})}),n.jsx("div",{children:n.jsx("code",{children:"- list"})}),n.jsx("div",{children:n.jsx("code",{children:"1. list"})}),n.jsx("div",{className:Xe.helpGridItem,children:n.jsx("code",{children:"`inline code`"})}),n.jsxs("div",{className:Xe.helpGridItem,children:[n.jsx("code",{children:"```"}),n.jsx("br",{}),n.jsx("code",{children:"code block"}),n.jsx("br",{}),n.jsx("code",{children:"```"})]}),n.jsx("div",{children:n.jsx("code",{children:"[link](url)"})})]})]}),W||!o?n.jsx("textarea",{className:`${f.textarea} ${Xe.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",value:o,onChange:ge=>ce(ge.target.value),onFocus:()=>Y(!0),onBlur:()=>Y(!1),rows:9,autoFocus:W}):n.jsx("div",{className:`${f.textarea} ${Xe.descriptionSurface} ${Xe.markdownPreview} ${Xe.markdownPreviewContainer}`,onClick:()=>Y(!0),children:n.jsx(fy,{onTaskIdClick:kt,children:o})})]}),n.jsxs("div",{className:Xe.compactMetaSection,children:[n.jsxs("div",{className:Xe.compactMetaGrid,children:[n.jsxs("div",{className:`${f.field} ${Xe.compactMetaField}`,children:[n.jsx("label",{id:"category-label",className:f.label,children:j?.category||"Category"}),n.jsx(ud,{value:c,options:Tt,onChange:ge=>me(String(ge)),required:!0,ariaLabelledBy:"category-label"})]}),n.jsxs("div",{className:`${f.field} ${Xe.compactMetaField}`,children:[n.jsx("label",{id:"type-label",className:f.label,children:j?.type||"Type"}),n.jsx(ud,{value:i,options:ae,onChange:ge=>Te(String(ge)),ariaLabelledBy:"type-label"})]}),n.jsxs("div",{className:`${f.field} ${Xe.compactMetaField}`,children:[n.jsx("label",{htmlFor:"task-form-scheduled-date",className:f.label,children:qe("taskForm.scheduledLabel")}),n.jsx("input",{id:"task-form-scheduled-date",type:"date",value:S,onChange:ge=>Z(ge.target.value),className:`${f.input} ${f.taskFormDateInput}`})]}),n.jsxs("div",{className:`${f.field} ${Xe.compactMetaField}`,children:[n.jsx("label",{id:"assignee-label",className:f.label,children:"Assigned To"}),n.jsx(ud,{value:k||"unassigned",options:l,onChange:ge=>Ee(String(ge)),ariaLabelledBy:"assignee-label"})]}),n.jsx("div",{className:Xe.compactMetaField,children:n.jsx(Tp,{label:j?.priority||"Priority",options:K,value:d,onChange:Me,type:"priority",showSelectedLabel:!1})}),n.jsxs("div",{className:`${f.field} ${Xe.compactMetaField}`,children:[n.jsx("label",{htmlFor:"task-form-due-date",className:f.label,children:qe("taskForm.dueLabel")}),n.jsx("input",{id:"task-form-due-date",type:"date",value:h,onChange:ge=>x(ge.target.value),className:`${f.input} ${f.taskFormDateInput}`}),Ft&&n.jsx("span",{className:`${Xe.taskFormDateWarning} ${Xe.compactMetaFieldHint}`,children:qe("taskForm.dueBeforeScheduled")}),Et&&n.jsx("span",{className:`${Xe.taskFormDateError} ${Xe.compactMetaFieldHint}`,children:qe("taskForm.overdue")})]}),y&&n.jsx("div",{className:Xe.compactMetaField,children:n.jsx(Tp,{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:m,onChange:Pe,type:"general"})})]}),!t&&n.jsxs("div",{className:Xe.createWorkstreamRow,children:[n.jsx("label",{className:f.label,children:"Attach to workstream"}),n.jsxs("div",{className:f.pathInputGroup,children:[Ze?n.jsx("input",{type:"text",className:f.input,value:g,onChange:ge=>b(ge.target.value),placeholder:"Type a workstream name or reference","aria-label":"Attach to workstream"}):n.jsx(ud,{value:g,options:Be,onChange:ge=>b(String(ge)),placeholder:"Select workstream...",ariaLabel:"Attach to workstream",className:Xe.createWorkstreamDropdown}),n.jsx("button",{type:"button",className:f.secondaryHeaderBtn,onClick:()=>{if(Ze){St(!1),At||b("");return}St(!0)},"aria-label":Ze?"Use workstream dropdown":"Enter workstream by name",title:Ze?"Use workstream dropdown":"Enter workstream by name",children:n.jsx(to,{size:14})})]})]})]}),n.jsxs("div",{className:Xe.sectionBlock,children:[n.jsx("div",{className:Xe.taxonomyFieldsGrid,children:Qe.map(ge=>{if(ge.id==="approach"&&ge.isSystem)return null;const at=se[ge.id],xe=Array.isArray(at)?at.map(pt=>String(pt)):at!=null&&at!==""?[String(at)]:[],jt=ge.options.filter(pt=>pt.status!=="retired"||xe.includes(String(pt.value)));return n.jsxs("div",{className:f.field,children:[n.jsx("label",{className:f.label,children:ge.label}),ge.description&&n.jsx("div",{className:`${Xe.settingsHint} tf-text-helper`,children:ge.description}),ge.widgetType==="level"?n.jsx(Tp,{label:ge.label,options:jt.map(pt=>({...pt,label:pt.status==="retired"?`${pt.label} (Retired)`:pt.label})),value:se[ge.id]||"",onChange:pt=>$(ge.id,pt),type:"general",hideLabel:!0}):ge.multiSelect?n.jsx("div",{className:`${f.dropdownList} ${Xe.softSectionSurface}`,children:jt.map(pt=>{const bt=String(pt.value),An=xe.includes(bt);return n.jsxs("button",{type:"button",className:`${Xe.specialistChip} ${An?Xe.specialistChipActive:""}`,onClick:()=>{const vn=An?xe.filter(dn=>dn!==bt):[...xe,bt];$(ge.id,vn)},title:An?"Click to remove":"Click to add",children:[An&&n.jsx(eo,{size:12}),pt.status==="retired"?`${pt.label} (Retired)`:pt.label]},bt)})}):n.jsxs("div",{className:f.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 pt=ge.options.find(vn=>String(vn.value)===String(se[ge.id])),bt=pt?.icon&&hs[pt.icon]?hs[pt.icon]:ec,An=pt?.color||"var(--text-secondary)";return n.jsx("div",{className:f.fieldIcon,style:{color:Ma(An)},children:n.jsx(bt,{size:16})})})(),n.jsxs("select",{value:se[ge.id]||"",onChange:pt=>$(ge.id,pt.target.value),className:`${f.select} ${f.field_dynamic}`,required:ge.isRequired,children:[n.jsxs("option",{value:"",children:["Select ",ge.label,"..."]}),jt.map(pt=>n.jsx("option",{value:pt.value,children:pt.status==="retired"?`${pt.label} (Retired)`:pt.label},pt.value))]})]})]},ge.id)})}),ie&&n.jsxs("div",{className:f.specialistSection,children:[n.jsxs("div",{className:f.toggleHeading,onClick:()=>te(!le),title:le?"Hide checklist":"Show checklist",children:[n.jsxs("label",{className:f.label,children:["Checklist"," ",v.length>0&&`(${We}/${v.length})`]}),le?n.jsx(sl,{size:14}):n.jsx(tl,{size:14})]}),le&&n.jsxs("div",{className:`${f.dropdownList} ${Xe.stackedList} ${Xe.stackedListSpaced}`,children:[n.jsxs("div",{className:f.pathInputGroup,children:[n.jsx("input",{type:"text",className:f.input,placeholder:"Add checklist item",value:tt,onChange:ge=>Oe(ge.target.value),onKeyDown:ge=>{ge.key==="Enter"&&(ge.preventDefault(),Ot())}}),n.jsx("button",{type:"button",className:f.secondaryHeaderBtn,onClick:Ot,disabled:!tt.trim(),children:"Add"})]}),v.length>0?n.jsx(_g,{sensors:Ve,collisionDetection:lv,onDragEnd:yt,children:n.jsx(Cg,{items:v.map(ge=>ge.id),strategy:Ag,children:v.map((ge,at)=>n.jsx(lL,{id:ge.id||`checklist-${at}`,item:ge,onToggle:()=>{const xe=new Date().toISOString();R(v.map((jt,pt)=>pt===at?{...jt,isCompleted:!jt.isCompleted,updatedAt:xe}:jt))},onRemove:()=>R(v.filter((xe,jt)=>jt!==at).map((xe,jt)=>({...xe,order:jt})))},ge.id||`checklist-${at}`))})}):n.jsx("div",{className:`${Xe.settingsHint} tf-text-helper`,children:"No checklist items yet."})]})]})]}),n.jsxs("div",{children:[n.jsx(ze.Suspense,{fallback:null,children:n.jsx(iL,{taskId:t,taskReferenceLabel:dt,workspaceId:D,apiBaseUrl:U,contextFiles:A,onAddContextFile:L,onRemoveContextFile:X,onUpdateContextCaption:M})}),n.jsx("div",{className:`${Xe.taskFormLifecycle} ${Xe.taskFormMetaDivider}`,children:n.jsx("div",{className:Xe.taskFormMetaGrid,children:Ye&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:Xe.taskFormDateRow,children:[n.jsx("span",{className:Xe.taskFormDateLabel,children:qe("taskForm.createdLabel")}),n.jsxs("span",{className:Xe.taskFormMetaStack,children:[n.jsx("span",{className:Xe.taskFormDateValue,children:ft||qe("taskForm.emptyValue")}),n.jsx("span",{className:Xe.taskFormMetaActor,children:Vn?`by ${Vn}`:qe("taskForm.emptyValue")})]})]}),n.jsxs("div",{className:Xe.taskFormDateRow,children:[n.jsx("span",{className:Xe.taskFormDateLabel,children:qe("taskForm.updatedLabel")}),n.jsxs("span",{className:Xe.taskFormMetaStack,children:[n.jsx("span",{className:Xe.taskFormDateValue,children:it||qe("taskForm.emptyValue")}),n.jsx("span",{className:Xe.taskFormMetaActor,children:qn?`by ${qn}`:qe("taskForm.emptyValue")})]})]}),n.jsxs("div",{className:Xe.taskFormDateRow,children:[n.jsx("span",{className:Xe.taskFormDateLabel,children:qe("taskForm.completedLabel")}),n.jsxs("span",{className:Xe.taskFormMetaStack,children:[n.jsx("span",{className:Xe.taskFormDateValue,children:Mt||qe("taskForm.emptyValue")}),n.jsx("span",{className:Xe.taskFormMetaActor,children:Vt?`by ${Vt}`:qe("taskForm.emptyValue")})]})]})]})})})]})]}),ga,n.jsxs("div",{className:Xe.keyboardHint,children:["Press ",n.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function Qi({ariaLabel:e,children:t,disabled:a=!1,onClick:s,title:o}){return n.jsx("button",{type:"button",className:`${f.taskIdBadge} ${f.taskHierarchyActionBtn}`,onClick:s,disabled:a,title:o,"aria-label":e,children:t})}function jy({editingTaskId:e,loading:t,autoSaveState:a="idle",title:s,handleSubmit:o,resetForm:c,handleCopyId:i,copiedId:d,tasks:m,currentTask:y,currentTaskWorkstream:k,currentTaskInitiative:S,workstreamInput:h="",onWorkstreamInputChange:g,onSetWorkstreamForCurrentTask:v,handleToggleInProgress:_,handleToggleReview:I,handleToggleComplete:A,handleToggleCancel:D,handleSetStatus:U,handleArchiveTask:W,handleUnarchiveTask:Q,handleRestoreDeletedTask:le,handlePermanentlyDeleteDeletedTask:ie}){const[se,$]=ze.useState(!1),C=y??(e&&m.find(ce=>ce.id===e)||null),de=!!C?.isArchived,ke=!!C?.isDeleted,K=Bg(C),j=K.label||(K.isProvisional?"Pending":""),H=K.isProvisional,ue=!!K.label,ye=k?fm(k)||k.id:"",G=S?rs(S)||S.id:"";ze.useEffect(()=>{k&&$(!1)},[k?.id]);const je=ze.useCallback(()=>{h.trim()&&v?.()},[v,h]),be=ze.useCallback(()=>{$(!1),g?.(""),v?.(null)},[v,g]);return n.jsx("div",{className:f.stickyActionHeader,children:e?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:f.taskHierarchyHeader,children:[n.jsxs("div",{className:f.taskHierarchyBadgeRow,children:[k?n.jsx(n.Fragment,{children:n.jsx(Qi,{onClick:be,disabled:t||de||ke,title:"Remove from workstream",ariaLabel:"Remove from workstream",children:n.jsx(Qu,{size:13})})}):null,S?n.jsxs("span",{className:f.taskHierarchySegment,children:[n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),n.jsx(tm,{copied:d===G,onClick:ce=>i(ce,G),disabled:t,title:"Copy initiative reference",label:G})]}):null,k?n.jsxs("span",{className:f.taskHierarchySegment,children:[n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),n.jsx(tm,{copied:d===ye,onClick:ce=>i(ce,ye),disabled:t,title:"Copy workstream reference",label:ye})]}):n.jsx(n.Fragment,{children:n.jsx(Qi,{onClick:()=>{g?.(""),$(ce=>!ce)},disabled:t||de||ke,title:"Attach to workstream",ariaLabel:"Attach to workstream",children:n.jsx(om,{size:13})})}),j?n.jsxs("span",{className:f.taskHierarchySegment,children:[n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),n.jsx(tm,{copied:ue&&d===K.label,onClick:ce=>i(ce,K.label),disabled:t||!ue,title:ue?qe("actionHeader.copyTaskIdTitle"):"Task reference pending sync",label:j})]}):null,H?n.jsx("span",{className:f.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),se&&!k?n.jsxs("div",{className:f.taskHierarchyEditor,children:[n.jsx("input",{type:"text",className:`${f.input} ${f.taskHierarchyInput}`,value:h,onChange:ce=>g?.(ce.target.value),placeholder:"WS-123","aria-label":"Attach workstream reference",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),je()),ce.key==="Escape"&&(ce.preventDefault(),g?.(""),$(!1))}}),n.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:je,disabled:!h.trim()||t,title:"Attach workstream","aria-label":"Attach workstream",children:n.jsx(eo,{size:14})}),n.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>{g?.(""),$(!1)},disabled:t,title:"Cancel workstream attach","aria-label":"Cancel workstream attach",children:n.jsx(oc,{size:14})})]}):null]}),n.jsx("div",{className:f.taskSaveStatusCenter,children:n.jsx("div",{className:`${f.taskSaveStatus} ${a==="error"?f.taskSaveStatusError:""}`,"aria-live":"polite",children:a==="saving"?n.jsxs(n.Fragment,{children:[n.jsx(br,{size:14,className:f.spinner}),n.jsx("span",{children:"Saving…"})]}):a==="saved"?n.jsx("span",{children:"Saved"}):a==="error"?n.jsx("span",{children:"Save failed"}):null})}),n.jsx("div",{className:f.editActionsGroup,children:ke&&C?.deletedRecordId?n.jsxs(n.Fragment,{children:[le&&n.jsx("button",{type:"button",className:f.actionBtn,onClick:()=>le(C.deletedRecordId||""),disabled:t,title:"Restore deleted task",children:n.jsx(Sd,{size:16})}),ie&&n.jsx("button",{type:"button",className:`${f.actionBtn} ${f.deleteBtn}`,onClick:()=>ie(C.deletedRecordId||""),disabled:t,title:"Permanently delete deleted task",children:n.jsx(xm,{size:16})})]}):n.jsx(by,{task:C,disabled:t,statusDisabled:t||de,archiveActionMode:de?"unarchive":"auto",onSetStatus:(ce,me)=>{if(U){U(ce,me);return}if(me==="in-progress"){_(ce);return}if(me==="review"){I(ce);return}if(me==="done"){A(ce);return}me==="cancelled"&&D(ce)},onArchiveTask:W,onUnarchiveTask:ce=>Q?.(ce.id)})})]}):n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",onClick:c,disabled:t,className:f.secondaryHeaderBtn,title:qe("actionHeader.clearFormTitle"),children:[n.jsx(Sd,{size:16}),qe("actionHeader.clear")]}),n.jsxs("button",{type:"button",onClick:ce=>o(ce),disabled:t||!s.trim(),className:f.primaryUpdateBtn,title:qe("actionHeader.addTaskTitle"),children:[t?n.jsx(br,{size:16,className:f.spinner}):n.jsx(to,{size:16}),qe("actionHeader.addTask")]})]})})}const dL="_topNoticeLayer_1m6a1_1",uL="_topNotice_1m6a1_1",mL="_topNoticeMessage_1m6a1_32",pL="_topNoticeSuccess_1m6a1_38",fL="_topNoticeError_1m6a1_44",hL="_topNoticeInfo_1m6a1_50",gL="_topNoticeDismiss_1m6a1_56",Zi={topNoticeLayer:dL,topNotice:uL,topNoticeMessage:mL,topNoticeSuccess:pL,topNoticeError:fL,topNoticeInfo:hL,topNoticeDismiss:gL};function Py({notice:e,onDismiss:t}){if(!e)return null;const a=e.tone==="error"?Zi.topNoticeError:e.tone==="success"?Zi.topNoticeSuccess:Zi.topNoticeInfo,s=e.tone==="error"?"alert":"status";return n.jsx("div",{className:Zi.topNoticeLayer,children:n.jsxs("div",{className:`${Zi.topNotice} ${a}`,role:s,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?n.jsx(wd,{size:14}):e.tone==="success"?n.jsx(eo,{size:14}):n.jsx(Bk,{size:14}),n.jsx("span",{className:Zi.topNoticeMessage,children:e.message}),t&&n.jsx("button",{type:"button",className:Zi.topNoticeDismiss,onClick:t,"aria-label":"Dismiss notice",title:"Dismiss notice",children:n.jsx(oc,{size:14})})]})})}const yL=ze.lazy(()=>gs(()=>import("./TaskSettings-CUWbYYtP.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings})));function kL(e){const{activeTab:t,setActiveTab:a,isOpen:s,setIsOpen:o,currentTheme:c,setCurrentTheme:i,saveSettings:d,pathSaved:m,keyShortcut:y,setKeyShortcut:k,jsonBackupEnabled:S,setJsonBackupEnabled:h,mcpHostRoot:g,setMcpHostRoot:v,settingsSection:_,setSettingsSection:I,projectRoot:A,projectName:D,mcpScriptPath:U,serverHostRoot:W,showFolderBrowser:Q,setShowFolderBrowser:le,folders:ie,files:se,currentBrowsePath:$,fetchFolders:C,browserTarget:de,setBrowserTarget:ke,handleSelectPath:K,handleAddPath:j,handleRemovePath:H,tasks:ue,loadingTasks:ye,archivedTasks:G,deletedTasks:je,activeCategories:be,activeTypes:ce,priorities:me,taxonomyDisplayLabels:Te,approaches:Me,taxonomies:Pe,searchQuery:Ee,setSearchQuery:Z,filterCategories:x,setFilterCategories:b,filterTypes:R,setFilterTypes:B,filterPriorities:Y,setFilterPriorities:fe,filterStatus:te,setFilterStatus:Le,filterAssignees:oe,setFilterAssignees:L,assigneeOptions:X,filterTaxonomies:M,setFilterTaxonomies:V,sortBy:ne,setSortBy:Ce,sortOrder:Ae,toggleSortOrder:Re,showArchive:$e,setShowArchive:vt,taskScope:st,setTaskScope:kt,clearFilters:Ye,filteredTasks:Ct,filteredArchive:dt,groupedTasks:Qe,collapsedCategories:Tt,setCollapsedCategories:ae,handleEdit:Ge,handleDelete:ft,handleCopyId:it,handleToggleComplete:Mt,handleToggleCancel:ht,handleToggleInProgress:Ft,handleToggleReview:Et,handleArchiveTask:We,handleBulkArchive:tt,handleUnarchive:Oe,handleRestoreDeletedTask:Ze,handlePermanentlyDeleteDeletedTask:St,handleEmptyDeletedTasks:ot,fetchArchive:re,editingTaskId:Be,loading:At,error:Rt,title:Bt,setTitle:Ve,description:Ot,setDescription:yt,checklistItems:E,setChecklistItems:l,category:J,setCategory:Se,type:Ie,setType:Ke,priority:Je,setPriority:Ne,complexity:zt,setComplexity:Yt,manualComplexityEnabled:Pt,checklistDropdownEnabled:Wt,showTaskCardStatusLabel:Dt,approach:Ht,setApproach:sn,assignee:Vt,setAssignee:Vn,scheduledDate:qn,setScheduledDate:Kn,dueDate:ga,setDueDate:ge,workstreamInput:at,setWorkstreamInput:xe,formTaxonomies:jt,setFormTaxonomies:pt,comments:bt,newCommentText:An,setNewCommentText:vn,attachments:dn,setAttachments:un,setAttachmentsDirty:Bn,descriptionFocused:gt,setDescriptionFocused:cr,showMarkdownHelp:fn,setShowMarkdownHelp:nn,showChecklist:bn,setShowChecklist:Kt,showComments:_r,setShowComments:Pn,handleSubmit:aa,resetForm:Mn,handleAddComment:Zt,handleSetWorkstreamForCurrentTask:Zn,handleOpenTaskById:an,autoSaveState:ra,unsavedModalOpen:Ea,setUnsavedModalOpen:Da,pendingNavigation:hn,handleNavigation:Va,handleClose:os,scheduleWarningPrompt:qa,confirmScheduleWarning:Ca,cancelScheduleWarning:Wn,uiNotice:Vr,clearNotice:Aa,taskReturnTrail:sa,clearReturnToParentTask:la,returnToPreviousTask:Fn,copiedId:Nt,recentlyChangedTaskIds:ya,tasksScrollRef:On,setTasksScrollPos:lr,currentTask:$n,currentTaskWorkstream:La,currentTaskInitiative:xa,exportEnvironment:Sn,setExportEnvironment:Dn,exportWorkflowsPath:Ba,setExportWorkflowsPath:gn,exportResult:Jt,exportingResource:Ka,availableWorkflows:xn,onExportWorkflows:En,availableEnvironments:Za,handleUpdateCategory:In,handleRemoveCategory:Mr,handleSaveCategory:cn,handleUpdateCategoryIcon:mn,handleUpdateCategoryColor:ka,handleSaveType:Yn,handleRemoveType:Cr,handleUpdateTaxonomies:Er,handleUpdatePriorities:Xt,pathValidation:Ia,validatePaths:Wa,getCategoryPaths:dr,commentsEndRef:Ar,currentWorkspaceId:Ya,settingsModel:Ja,onHeaderMouseDown:xr,isDragging:Jn}=e,Ta=r.useRef(null),[ur,oa]=ze.useState(0);r.useLayoutEffect(()=>{if(t==="tasks"&&On.current&&ur>0){const et=setTimeout(()=>{On.current&&(On.current.scrollTop=ur)},50);return()=>clearTimeout(et)}},[t,ur,ue]);const qr=et=>{Ce(et)},ia=()=>{Va(()=>{if(t==="add"||t==="settings"){if(t==="add"&&Fn())return;t==="add"&&sa.length>0&&la(),t==="add"&&Mn(),a("tasks")}else e.onClose?e.onClose():os()})},Dr=()=>{Da(!1),hn?(t==="add"&&Mn(),hn()):a("tasks")},Kr=async()=>{await aa({preventDefault:()=>{}}),Da(!1),hn&&hn()},va=(et,$t)=>{pt(Tn=>({...Tn,[et]:$t})),et==="approach"&&typeof $t=="string"&&sn($t)},Ir=r.useCallback(et=>{Mn(),Se(et),Va(()=>{a("add")})},[Mn,Se,a,Va]),Ra=ze.useMemo(()=>je.map(et=>({...et.taskSnapshot,isDeleted:!0,deletedRecordId:et.id})),[je]),Sa=ze.useMemo(()=>new globalThis.Map(je.map(et=>[et.taskId,et])),[je]),Fa=ze.useMemo(()=>{const et=Pm(Ee),$t={categories:be,types:ce,priorities:me,assigneeOptions:X,taxonomies:Pe},Tn=be.every(Gt=>x.includes(Gt.value)),_n=ce.every(Gt=>R.includes(Gt.value)),wn=Array.from(new Set(Y.map(Gt=>Number(Gt)).filter(Gt=>Number.isFinite(Gt)))),Qa=me.map(Gt=>Number(Gt.value)).filter(Gt=>Number.isFinite(Gt)).every(Gt=>wn.includes(Gt)),wa=["task","in-progress","review","done","cancelled","on-hold"].every(Gt=>te.includes(Gt)),Oa=X.length>0&&X.every(Gt=>oe.includes(Gt.value)),mr=Td(Pe,Ra);return Ra.filter(Gt=>{const ja=gm(Gt,et,$t),da=Tn||x.includes(Gt.category),Un=Qa||wn.includes(cm(Gt.priority)),Lr=_n||R.includes(Gt.type||Gr),Br=wa||te.includes(Gt.status),pr=Oa||oe.includes(Gt.assignee||"unassigned"),fr=Object.entries(M).every(([ks,ba])=>{const ua=mr.find(F=>F.id===ks);if(!ua||If(ua,Ra).every(F=>ba.includes(F.value)))return!0;const hr=Gt.taxonomies?.[ks];return hr?Array.isArray(hr)?hr.some(F=>ba.includes(F)):ba.includes(hr):ba.includes("")});return ja&&da&&Un&&Lr&&Br&&pr&&fr}).sort((Gt,ja)=>ym(Gt,ja,ne,Ae,Pe))},[be,ce,G,X,Ra,oe,x,Y,te,M,R,me,Ee,ne,Ae,Pe,ue]),Zr=ze.useMemo(()=>{const et={};return Fa.forEach($t=>{const _n=be.find(wn=>wn.value===$t.category||wn.label===$t.category)?.label||$t.category||"General";et[_n]||(et[_n]=[]),et[_n].push($t)}),et},[be,Fa]),Ds=st==="archived"?dt.length:st==="deleted"?Fa.length:Ct.length;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:Ta,className:`${It.modal} ${f.coreModal} ${t==="settings"?It.settingsViewModal:""}`,"data-theme":c,children:[n.jsxs("div",{className:"tf-modal-header",onMouseDown:xr,style:{cursor:xr?Jn?"grabbing":"grab":"default"},children:[n.jsxs("div",{className:`tf-modal-title ${tn.headerTitleWidget}`,children:["Taskforce",D&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:f.projectSlash,children:"/"}),n.jsx("span",{className:f.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:D})]}),n.jsx("span",{className:f.taskCountBadge,title:`${st.charAt(0).toUpperCase()+st.slice(1)} tasks`,children:Ds})]}),n.jsxs("div",{className:It.headerActions,children:[t==="tasks"&&n.jsx(n.Fragment,{children:n.jsx("button",{className:"tf-control-icon",onClick:()=>{Va(()=>{Mn(),a("add")})},title:"Add New Task",children:n.jsx(to,{size:18})})}),n.jsx("button",{className:`tf-control-icon ${t==="settings"?"tf-control-icon-active":""}`,onClick:()=>{t!=="settings"&&Va(()=>{a("settings")})},title:"Settings",children:n.jsx(cf,{size:18})}),n.jsx("button",{className:"tf-control-icon",onClick:ia,title:t==="tasks"?"Close":"Back to Tasks",children:t==="tasks"?n.jsx(oc,{size:20}):n.jsx(Wk,{size:20})})]})]}),n.jsx(Py,{notice:Vr,onDismiss:Aa}),t==="add"&&n.jsx(jy,{editingTaskId:Be,loading:At,autoSaveState:ra,title:Bt,currentTask:$n,currentTaskWorkstream:La,currentTaskInitiative:xa,workstreamInput:at,onWorkstreamInputChange:xe,onSetWorkstreamForCurrentTask:Zn,handleSubmit:aa,resetForm:Mn,handleCopyId:it,copiedId:Nt,tasks:ue,handleToggleInProgress:Ft,handleToggleReview:Et,handleToggleComplete:Mt,handleToggleCancel:ht,handleArchiveTask:We,handleUnarchiveTask:et=>{if($n?.isDeleted){const $t=Sa.get(et);$t&&Ze($t.id);return}Oe(et)},handleRestoreDeletedTask:et=>{Ze(et)},handlePermanentlyDeleteDeletedTask:et=>{St(et)}}),t==="tasks"&&n.jsx(Ry,{ref:On,tasks:ue,archivedTasks:G,categories:be,types:ce,priorities:me,taxonomyDisplayLabels:Te,taxonomies:Pe,searchQuery:Ee,filterCategories:x,filterTypes:R,filterPriorities:Y,filterStatus:te,filterAssignees:oe,assigneeOptions:X,filterTaxonomies:M,sortBy:ne,sortOrder:Ae,showArchive:$e,taskScope:st,collapsedCategories:Tt,loadingTasks:ye,filteredTasks:Ct,filteredArchive:dt,groupedTasks:Qe,filteredDeletedTasks:Fa,groupedDeletedTasks:Zr,copiedId:Nt,recentlyChangedTaskIds:ya,showTaskCardStatusLabel:Dt,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:Z,onFilterCategoriesChange:et=>b(et),onFilterTypesChange:et=>B(et),onFilterPrioritiesChange:fe,onFilterStatusChange:Le,onFilterAssigneesChange:et=>L(et),onTaxonomyFilterChange:(et,$t)=>V(Tn=>({...Tn,[et]:$t})),onSortByChange:qr,onSortOrderChange:Re,onShowArchiveChange:vt,onTaskScopeChange:kt,onClearFilters:Ye,onToggleCategory:et=>ae($t=>({...$t,[et]:!$t[et]})),onEditTask:Ge,onOpenTaskById:an,onCopyId:it,onToggleInProgress:Ft,onToggleReview:Et,onToggleComplete:Mt,onToggleCancel:ht,onArchiveTask:We,onBulkArchive:tt,onUnarchive:et=>{const $t=Sa.get(et);if($t){Ze($t.id);return}Oe(et)},onDelete:et=>{const $t=Sa.get(et);if($t){St($t.id);return}ft(et)},onDeleteAllDeleted:()=>{ot()},onFetchArchive:re,onAddTaskToCategory:Ir,supplementalTasks:Ra}),t==="add"&&n.jsx(Ny,{editingTaskId:Be,error:Rt,title:Bt,description:Ot,checklistItems:E,category:J,type:Ie,priority:Je,complexity:zt,manualComplexityEnabled:Pt,approach:Ht,assignee:Vt,scheduledDate:qn,dueDate:ga,workstreamInput:at,formTaxonomies:jt,onTaxonomyChange:va,taxonomies:Pe,comments:bt,newCommentText:An,contextFiles:dn,currentWorkspaceId:Ya,apiBaseUrl:"",descriptionFocused:gt,showMarkdownHelp:fn,showChecklist:bn,checklistEnabled:Wt,showComments:_r,categories:be,types:ce,priorities:me,taxonomyDisplayLabels:Te,assigneeOptions:X,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:Nt,onTitleChange:Ve,onDescriptionChange:yt,onChecklistItemsChange:l,onCategoryChange:Se,onTypeChange:Ke,onPriorityChange:Ne,onComplexityChange:Yt,onApproachChange:et=>{sn(et),pt($t=>({...$t,approach:et}))},onAssigneeChange:Vn,onScheduledDateChange:Kn,onDueDateChange:ge,onWorkstreamInputChange:xe,onNewCommentTextChange:vn,onDescriptionFocusedChange:cr,onShowMarkdownHelpChange:nn,onShowChecklistChange:Kt,onShowCommentsChange:Pn,onOpenSettings:et=>{Va(()=>{I(et),a("settings")})},onSubmit:aa,commentsEndRef:Ar,onAddComment:()=>Zt(An),onOpenTaskById:an,onAddContextFile:et=>{Bn(!0),un($t=>[...$t,et])},onRemoveContextFile:async et=>{Bn(!0),un($t=>$t.filter((Tn,_n)=>_n!==et))},onUpdateContextCaption:(et,$t)=>{Bn(!0),un(Tn=>Tn.map((_n,wn)=>wn!==et?_n:typeof _n=="string"?{path:_n,caption:$t,timestamp:new Date().toISOString()}:{..._n,caption:$t}))},onCopyId:it,onToggleInProgress:Ft,onToggleReview:Et,onToggleComplete:Mt,onToggleCancel:ht,onArchiveTask:We,onUnarchive:et=>{if($n?.isDeleted){const $t=Sa.get(et);$t&&Ze($t.id);return}Oe(et)},currentTask:$n}),t==="settings"&&n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(yL,{settingsModel:Ja,onSectionChange:I})})]}),Q&&Xi.createPortal(n.jsx("div",{className:jn.overlay,children:n.jsxs("div",{className:jn.browser,children:[n.jsxs("div",{className:jn.header,children:[n.jsxs("div",{className:jn.pathInfo,children:[n.jsx(Io,{size:14}),n.jsx("span",{children:$||"Project Root"})]}),n.jsxs("div",{className:jn.actions,children:[$&&n.jsx("button",{className:f.helpLink,onClick:()=>{const et=$.split("/").filter(Boolean);et.pop(),C(et.length?et.join("/")+"/":"")},children:"Back"}),n.jsx("button",{className:f.helpLink,onClick:()=>le(!1),children:"Close"})]})]}),n.jsxs("div",{className:jn.list,children:[de&&typeof de=="object"&&n.jsxs("div",{className:`${jn.item} ${jn.itemCurrent}`,onClick:()=>K($),children:[n.jsx(eo,{size:14})," Select Current: ./",$||"(root)"]}),ie.map(et=>n.jsxs("div",{className:jn.item,onClick:()=>C($+et+"/"),children:[n.jsx(Io,{size:14})," ",et,"/"]},et)),se.map(et=>n.jsxs("div",{className:`${jn.item} ${jn.itemFile}`,onClick:()=>K($+et),children:[n.jsx(Op,{size:14})," ",et]},et)),ie.length===0&&se.length===0&&n.jsx("div",{className:`${jn.item} ${jn.empty}`,children:"No items found"})]})]})}),document.body),Ea&&n.jsx("div",{className:`${It.overlay} ${It.unsavedOverlay}`,children:n.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${It.modal} ${It.unsavedModal}`,"data-theme":c,children:[n.jsx("div",{className:`tf-modal-header ${It.unsavedHeader}`,children:n.jsxs("div",{className:`tf-modal-title ${It.unsavedTitle}`,children:[n.jsx(wd,{size:20}),"Unsaved Changes"]})}),n.jsx("div",{className:`${It.form} ${It.unsavedContent}`,children:n.jsx("p",{className:It.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),n.jsxs("div",{className:`${It.formActions} ${It.unsavedActions}`,children:[n.jsx("button",{className:f.cancelBtn,onClick:()=>Da(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),n.jsx("button",{className:f.destructiveBtn,onClick:Dr,title:"Discard unsaved changes and leave",children:"Discard"}),n.jsxs("button",{className:f.submitBtn,onClick:Kr,disabled:At,title:"Save changes and leave",children:[At?n.jsx(br,{size:16,className:f.spinner}):n.jsx(yg,{size:16}),"Save"]})]})]})}),qa&&n.jsx("div",{className:`${It.overlay} ${It.unsavedOverlay}`,children:n.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${It.modal} ${It.unsavedModal}`,"data-theme":c,children:[n.jsx("div",{className:`tf-modal-header ${It.unsavedHeader}`,children:n.jsxs("div",{className:`tf-modal-title ${It.unsavedTitle}`,children:[n.jsx(wd,{size:20}),"Date Warning"]})}),n.jsxs("div",{className:`${It.form} ${It.unsavedContent}`,children:[n.jsx("p",{className:It.unsavedText,children:"Due date is before scheduled date."}),n.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",qa.dueDate," · Scheduled: ",qa.scheduledDate]})]}),n.jsxs("div",{className:`${It.formActions} ${It.unsavedActions}`,children:[n.jsx("button",{className:f.cancelBtn,onClick:Wn,children:"Go Back"}),n.jsx("button",{className:f.submitBtn,onClick:Ca,children:"Save Anyway"})]})]})})]})}const vL="_accountMenuWrap_1mocf_1",SL="_avatarBtn_1mocf_5",wL="_avatarBadge_1mocf_9",bL="_avatarImage_1mocf_24",_L="_avatarIcon_1mocf_30",CL="_accountMenu_1mocf_1",AL="_accountMenuItem_1mocf_48",xL="_accountMenuItemActive_1mocf_68",IL="_accountMenuSection_1mocf_73",TL="_accountMenuSectionLabel_1mocf_79",RL="_accountMenuMeta_1mocf_88",NL="_accountMenuHint_1mocf_93",jL="_accountIdentityEmail_1mocf_99",PL="_accountIdentityBlock_1mocf_104",ML="_accountIdentityMetaLine_1mocf_109",EL="_accountIdentityMetaAction_1mocf_116",DL="_accountIdentityMetaValue_1mocf_125",LL="_accountIdentityMetaLabel_1mocf_130",BL="_accountMenuError_1mocf_159",WL="_accountHubCard_1mocf_165",FL="_profileAvatarEditor_1mocf_172",OL="_profileEditLayout_1mocf_178",$L="_profileFieldStack_1mocf_185",UL="_profileFieldLabel_1mocf_191",mt={accountMenuWrap:vL,avatarBtn:SL,avatarBadge:wL,avatarImage:bL,avatarIcon:_L,accountMenu:CL,accountMenuItem:AL,accountMenuItemActive:xL,accountMenuSection:IL,accountMenuSectionLabel:TL,accountMenuMeta:RL,accountMenuHint:NL,accountIdentityEmail:jL,accountIdentityBlock:PL,accountIdentityMetaLine:ML,accountIdentityMetaAction:EL,accountIdentityMetaValue:DL,accountIdentityMetaLabel:LL,accountMenuError:BL,accountHubCard:WL,profileAvatarEditor:FL,profileEditLayout:OL,profileFieldStack:$L,profileFieldLabel:UL},zL="_authBlockedBanner_1virb_1",HL="_loginView_1virb_10",GL="_loginCard_1virb_20",VL="_loginCloseBtn_1virb_34",qL="_loginLogo_1virb_56",KL="_authBrandRow_1virb_62",ZL="_setupHeaderRow_1virb_68",YL="_runtimeIconBadge_1virb_75",JL="_loginTitle_1virb_94",QL="_loginTitleAccent_1virb_105",XL="_loginSubtitle_1virb_109",eB="_loginError_1virb_115",tB="_loginField_1virb_121",nB="_loginFieldLabel_1virb_126",aB="_loginInput_1virb_133",rB="_loginPrimaryBtn_1virb_149",sB="_authPrimaryActions_1virb_154",oB="_registerConsent_1virb_159",iB="_registerConsentLink_1virb_167",cB="_authModeSwitch_1virb_177",lB="_authModeSwitchLink_1virb_184",dB="_authModeLinks_1virb_199",uB="_authSecondaryActions_1virb_207",mB="_authModeLink_1virb_199",pB="_optionGrid_1virb_236",fB="_optionGroup_1virb_242",hB="_optionRow_1virb_247",gB="_inlineHint_1virb_254",yB="_actionRowEnd_1virb_260",kB="_oauthProviders_1virb_267",vB="_oauthDivider_1virb_274",SB="_oauthButtons_1virb_290",wB="_oauthButton_1virb_290",he={authBlockedBanner:zL,loginView:HL,loginCard:GL,loginCloseBtn:VL,loginLogo:qL,authBrandRow:KL,setupHeaderRow:ZL,runtimeIconBadge:YL,loginTitle:JL,loginTitleAccent:QL,loginSubtitle:XL,loginError:eB,loginField:tB,loginFieldLabel:nB,loginInput:aB,loginPrimaryBtn:rB,authPrimaryActions:sB,registerConsent:oB,registerConsentLink:iB,authModeSwitch:cB,authModeSwitchLink:lB,authModeLinks:dB,authSecondaryActions:uB,authModeLink:mB,optionGrid:pB,optionGroup:fB,optionRow:hB,inlineHint:gB,actionRowEnd:yB,oauthProviders:kB,oauthDivider:vB,oauthButtons:SB,oauthButton:wB};function bB(e={x:0,y:0}){const[t,a]=r.useState(e),[s,o]=r.useState(!1),[c,i]=r.useState({x:0,y:0}),[d,m]=r.useState(0),y=r.useRef(null),k=r.useCallback(g=>{const v=g.target;if(!(v.closest("button")||v.closest("input")||v.closest("select")||v.closest("textarea")||v.closest('[role="button"]')||v.closest(".no-drag"))){if(y.current){const _=y.current.getBoundingClientRect();m(_.top-t.y)}o(!0),i({x:g.clientX-t.x,y:g.clientY-t.y})}},[t]),S=r.useCallback(g=>{if(s){let v=g.clientX-c.x,_=g.clientY-c.y;_<-d&&(_=-d),a({x:v,y:_})}},[s,c,d]),h=r.useCallback(()=>{o(!1)},[]);return r.useEffect(()=>(s?(window.addEventListener("mousemove",S),window.addEventListener("mouseup",h)):(window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",h)),()=>{window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",h)}),[s,S,h]),{position:t,isDragging:s,handleMouseDown:k,modalRef:y,setPosition:a}}function Es({isOpen:e,onClose:t,title:a,children:s,footer:o,size:c="md",theme:i=im,className:d,headerActions:m,draggable:y=!1,isSettings:k=!1,closeOnOverlayClick:S=!0}){const h=r.useRef(null),{position:g,isDragging:v,handleMouseDown:_,modalRef:I}=bB();if(r.useEffect(()=>{const D=U=>{U.key==="Escape"&&e&&t()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[e,t]),r.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const A={sm:It.modalSizeSm,md:It.modalSizeMd,mdWide:It.modalSizeMdWide,lg:It.modalSizeLg,xl:It.modalSizeXl,full:It.modalSizeFull};return Xi.createPortal(n.jsx("div",{className:`${It.overlay} ${d||""} ${It.overlayHighZ}`,ref:h,onClick:D=>{S&&D.target===h.current&&t()},children:n.jsxs("div",{ref:I,className:`tf-surface-modal tf-modal-shell ${It.modal} tf-scrollbar-scope ${A[c]} ${y?It.draggableModal:""} ${k?It.settingsViewModal:""}`,"data-theme":i,style:{transform:y?`translate(${g.x}px, ${g.y}px)`:void 0,transition:v?"none":"transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s ease-out"},children:[n.jsxs("div",{className:`tf-modal-header ${y?It.draggableHeader:""}`,onMouseDown:y?_:void 0,style:{cursor:y?v?"grabbing":"grab":"default"},children:[n.jsx("div",{className:"tf-modal-title",children:a}),n.jsxs("div",{className:It.headerActions,children:[m,n.jsx("button",{className:"tf-control-icon",onClick:t,title:"Close",children:n.jsx(oc,{size:20})})]})]}),n.jsx("div",{className:It.modalContent,children:s}),o&&n.jsx("div",{className:`${It.formActions} ${It.modalFooter}`,children:o})]})}),document.body)}const _B="_modalBody_1t87j_1",CB="_mutedText_1t87j_5",AB="_sectionText_1t87j_10",xB="_sectionTextSpaced_1t87j_15",IB="_sectionTextTop_1t87j_20",TB="_errorText_1t87j_25",RB="_inlineFieldLabel_1t87j_29",NB="_wrapRow_1t87j_35",jB="_actionRowEnd_1t87j_42",PB="_modalActionsEnd_1t87j_50",MB="_helpIntro_1t87j_56",EB="_supportEmailRow_1t87j_61",DB="_supportEmailAddress_1t87j_68",LB="_supportEmailBtn_1t87j_80",BB="_supportPanel_1t87j_86",WB="_supportPanelHeader_1t87j_92",FB="_supportRouteList_1t87j_104",OB="_supportRouteBtn_1t87j_110",$B="_memberRow_1t87j_114",UB="_memberTitle_1t87j_120",zB="_memberActions_1t87j_124",HB="_selectRole_1t87j_131",GB="_selectPermission_1t87j_135",VB="_inviteRow_1t87j_139",qB="_listHeading_1t87j_143",KB="_auditList_1t87j_148",ZB="_auditPager_1t87j_154",YB="_labelFixed_1t87j_161",lt={modalBody:_B,mutedText:CB,sectionText:AB,sectionTextSpaced:xB,sectionTextTop:IB,errorText:TB,inlineFieldLabel:RB,wrapRow:NB,actionRowEnd:jB,modalActionsEnd:PB,helpIntro:MB,supportEmailRow:EB,supportEmailAddress:DB,supportEmailBtn:LB,supportPanel:BB,supportPanelHeader:WB,supportRouteList:FB,supportRouteBtn:OB,memberRow:$B,memberTitle:UB,memberActions:zB,selectRole:HB,selectPermission:GB,inviteRow:VB,listHeading:qB,auditList:KB,auditPager:ZB,labelFixed:YB};function JB({isOpen:e,theme:t,onClose:a,onConfirm:s}){return n.jsx(Es,{isOpen:e,onClose:a,title:"New Workspace",size:"sm",theme:t,draggable:!0,footer:n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",className:f.cancelBtn,onClick:a,children:"Cancel"}),n.jsx("button",{type:"button",className:f.submitBtn,onClick:s,children:"Start Setup"})]}),children:n.jsx("div",{className:`${It.form} ${lt.modalBody}`,children:n.jsx("p",{className:lt.sectionText,children:"Create and configure a new workspace."})})})}const QB=new Set(["active","trialing","grace"]),Uh={CHECKOUT_SESSION_EXPIRED:"Your previous checkout expired. Choose a plan to continue.",CHECKOUT_SESSION_SUPERSEDED:"A newer checkout replaced your previous checkout. Choose a plan to continue."},qu={planSelectionRequired:"Choose a plan to continue.",checkoutPending:"Complete checkout to continue.",misconfigured:"Onboarding policy is misconfigured. Contact support or a system administrator.",missingEntitlement:"No entitlement is linked to this account."};function sc(e){return String(e||"").trim()}function My(e){return sc(e).toLowerCase()}function XB(e){return sc(e).toLowerCase()}function e2(e){return!!(sc(e?.stripeCustomerId)||sc(e?.stripeSubscriptionId))}function t2(e){const t=sc(e?.trialEnd||e?.effectiveUntil);if(t){const a=new Date(t);if(!Number.isNaN(a.getTime()))return a.getTime()<=Date.now()?"Your trial end date has passed. Billing status is updating.":`Your trial is active through ${a.toLocaleString()}.`}return"Your trial is active. Continue to Taskforce or manage billing anytime."}function n2(e){return QB.has(My(e))}function Xp(e,t){const a=My(e?.entitlementState),s=XB(e?.gate||t),o=sc(e?.billingConflictCode).toUpperCase(),c=sc(e?.message),i=n2(a),d=e2(e);return o==="CHECKOUT_SESSION_EXPIRED"?{entitlementState:a||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:Uh.CHECKOUT_SESSION_EXPIRED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:o==="CHECKOUT_SESSION_SUPERSEDED"?{entitlementState:a||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:Uh.CHECKOUT_SESSION_SUPERSEDED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:a==="trialing"?{entitlementState:a,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:t2(e),primaryAction:d?"manage_billing":"none",primaryLabel:d?"Manage Billing":null,showManageBilling:d,markCurrentPlan:!0}:i?{entitlementState:a||null,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:c||null,primaryAction:"none",primaryLabel:null,showManageBilling:d,markCurrentPlan:!0}:a==="suspended"?{entitlementState:a,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access is suspended because billing needs attention. Update billing to restore access.",primaryAction:d?"manage_billing":"open_plans",primaryLabel:d?"Manage Billing":"Open Plans",showManageBilling:d,markCurrentPlan:!1}:a==="canceled"?{entitlementState:a,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access has ended. Choose a plan to reactivate your workspace.",primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:a==="pending_plan_selection"||e?.planSelectionRequired===!0||s==="plan_selection_required"?{entitlementState:a||"pending_plan_selection",gate:s||"plan_selection_required",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:c||qu.planSelectionRequired,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:a==="checkout_pending"||s==="checkout_pending"?{entitlementState:a||"checkout_pending",gate:s||"checkout_pending",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:c||qu.checkoutPending,primaryAction:"open_plans",primaryLabel:"Open Plans",showManageBilling:d,markCurrentPlan:!1}:s==="misconfigured"?{entitlementState:a||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:qu.misconfigured,primaryAction:"none",primaryLabel:null,showManageBilling:!1,markCurrentPlan:!1}:s==="missing_entitlement"?{entitlementState:a||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:qu.missingEntitlement,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:{entitlementState:a||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:c?"error":"info",message:c||null,primaryAction:"none",primaryLabel:null,showManageBilling:d,markCurrentPlan:!1}}const ef=12,a2=new Set(["12345678","123456789","1234567890","admin123","changeme","letmein","letmein123","password","password1","password12","password123","password1234","qwerty","qwerty123","welcome","welcome123"]),r2=e=>String(e||"").trim().toLowerCase().replace(/[^a-z0-9]/g,"");function s2(e){const t=new Set,a=String(e?.email||"").trim().toLowerCase(),s=String(e?.displayName||"").trim().toLowerCase();if(a.includes("@")){const o=a.split("@")[0]||"",c=o.replace(/[^a-z0-9]/g,"");c.length>=4&&t.add(c);for(const i of o.split(/[^a-z0-9]+/))i.length>=4&&t.add(i)}for(const o of s.split(/[^a-z0-9]+/))o.length>=4&&t.add(o);return[...t]}function Ey(){return[`Use at least ${ef} characters.`,"Avoid common passwords or obvious patterns.","Do not include your email or display name."]}function Dy(e,t){const a=String(e||"");if(!a)return{ok:!1,code:"PASSWORD_REQUIRED",message:"Password is required."};if(a.length<ef)return{ok:!1,code:"PASSWORD_TOO_SHORT",message:`Password must be at least ${ef} characters.`};const s=r2(a);return a2.has(s)?{ok:!1,code:"PASSWORD_TOO_COMMON",message:"Choose a less common password."}:s2(t).some(c=>s.includes(c))?{ok:!1,code:"PASSWORD_CONTAINS_PERSONAL_INFO",message:"Password cannot contain your email or display name."}:{ok:!0}}function o2({isOpen:e,theme:t,runtimeMode:a,authRequiredForApi:s,isAuthenticated:o,hasAuthIdentity:c,authIdentityLabel:i,billingLoading:d,billingError:m,billingActionError:y,billingNotice:k,billingActionBusy:S,billingIntervalChoice:h,accountProfileSummary:g,currentWorkspaceId:v,canOpenTeamManagement:_,canManageWorkspaceSync:I,workspaceCloudSyncEnabled:A,syncStatusLabel:D,workspaceSyncError:U,syncControlBusy:W,cloudAuthEnabled:Q,availableAuthProviders:le,onFetchLoginMethods:ie,onUnlinkLoginMethod:se,onAddPassword:$,onLinkProvider:C,onClose:de,onOpenWorkspaceAudit:ke,onBillingIntervalChange:K,onRefreshBilling:j,onUpdateInterval:H,onManageBilling:ue,onStartCheckout:ye,onToggleWorkspaceSync:G,onOpenHelp:je}){const be=Xp(g),ce=Ey(),me=be.message,Te=be.primaryLabel||"Start Checkout",Me=String(g?.planName||g?.planId||"n/a").trim()||"n/a",Pe=()=>{if(be.primaryAction==="manage_billing"){ue();return}ye()},[Ee,Z]=r.useState([]),[x,b]=r.useState(!1),[R,B]=r.useState(null),[Y,fe]=r.useState(null),[te,Le]=r.useState(null),[oe,L]=r.useState(!1),[X,M]=r.useState(""),[V,ne]=r.useState(!1),[Ce,Ae]=r.useState(null),[Re,$e]=r.useState(!1);r.useEffect(()=>{!e||!o||!Q||(b(!0),B(null),ie().then(Qe=>{b(!1),Qe.success&&Qe.methods?Z(Qe.methods):B(Qe.error||"Failed to load login methods.")}))},[e,o,Q,ie]);const vt=async Qe=>{fe(Qe),Le(null);const Tt=await se(Qe);fe(null),Tt.success?Z(ae=>ae.filter(Ge=>Ge.provider!==Qe)):Le(Tt.error||"Unlink failed.")},st=async()=>{const Qe=Dy(X);if(!Qe.ok){Ae(Qe.message||"Password does not meet the password policy.");return}ne(!0),Ae(null);const Tt=await $(X);if(ne(!1),!Tt.success)Ae(Tt.error||"Failed to add password.");else{$e(!0),M(""),L(!1);const ae=await ie();ae.success&&ae.methods&&Z(ae.methods)}},kt={password:"Email & Password",google:"Google",github:"GitHub",apple:"Apple"},Ye=new Set(Ee.map(Qe=>Qe.provider)),Ct=Ye.has("password"),dt=le.filter(Qe=>Qe!=="password"&&!Ye.has(Qe));return n.jsx(Es,{isOpen:e,onClose:de,title:"Account Hub",size:"md",theme:t,draggable:!0,children:n.jsxs("div",{className:`${It.form} ${lt.modalBody}`,children:[n.jsx("p",{className:lt.mutedText,children:"Manage sign in, profile, and workspace controls from one place."}),n.jsxs("div",{className:mt.accountHubCard,children:[n.jsx("strong",{children:"Authentication"}),n.jsx("p",{className:lt.sectionText,children:a==="cloud"?s?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."}),n.jsx("p",{className:lt.sectionTextSpaced,children:o?c?n.jsxs(n.Fragment,{children:["Signed in as ",n.jsx("span",{className:mt.accountIdentityEmail,children:i})]}):"Signed in":"Signed in as: not signed in"}),a==="cloud"&&s&&!o&&n.jsx("p",{className:lt.sectionTextTop,children:"Use the `/login` screen to sign in."})]}),o&&Q&&n.jsxs("div",{className:mt.accountHubCard,children:[n.jsx("strong",{children:"Login Methods"}),x&&n.jsx("p",{className:lt.sectionText,children:"Loading..."}),R&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:R}),te&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:te}),Re&&n.jsx("p",{className:lt.sectionText,style:{color:"var(--color-success, #4ade80)"},children:"Password login added."}),!x&&Ee.length>0&&n.jsx("div",{style:{marginTop:8,display:"grid",gap:6},children:Ee.map(Qe=>n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[n.jsxs("span",{className:lt.sectionText,children:[n.jsx("strong",{children:kt[Qe.provider]||Qe.provider}),Qe.providerEmail?n.jsxs(n.Fragment,{children:[" · ",n.jsx("span",{className:mt.accountMenuMeta,children:Qe.providerEmail})]}):null]}),Ee.length>1&&n.jsx("button",{className:f.cancelBtn,style:{fontSize:11,padding:"2px 8px"},disabled:Y===Qe.provider,onClick:()=>vt(Qe.provider),children:Y===Qe.provider?"Removing…":"Remove"})]},Qe.provider))}),!x&&!Ct&&!oe&&n.jsx("div",{className:lt.actionRowEnd,children:n.jsx("button",{className:f.cancelBtn,onClick:()=>{L(!0),$e(!1),Ae(null)},children:"Add Password Login"})}),oe&&n.jsxs("div",{style:{marginTop:10,display:"grid",gap:6},children:[n.jsxs("label",{className:mt.accountMenuMeta,style:{display:"block"},children:["New password",n.jsx("input",{type:"password",className:f.input,placeholder:"Use 12+ characters",value:X,onChange:Qe=>M(Qe.target.value),disabled:V,style:{marginTop:4,display:"block",width:"100%"},autoComplete:"new-password"})]}),n.jsx("p",{className:mt.accountMenuMeta,style:{margin:0},children:ce.join(" ")}),Ce&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:Ce}),n.jsxs("div",{className:lt.actionRowEnd,children:[n.jsx("button",{className:f.cancelBtn,onClick:()=>{L(!1),M(""),Ae(null)},disabled:V,children:"Cancel"}),n.jsx("button",{className:f.submitBtn,onClick:st,disabled:V||!X,children:V?"Saving…":"Save Password"})]})]}),!x&&dt.length>0&&n.jsxs("div",{style:{marginTop:10},children:[n.jsx("p",{className:mt.accountMenuMeta,style:{marginBottom:6},children:"Link another account:"}),n.jsx("div",{className:he.oauthButtons,children:dt.map(Qe=>n.jsx("button",{className:he.oauthButton,onClick:()=>C(Qe),children:kt[Qe]||Qe},Qe))})]})]}),n.jsxs("div",{className:mt.accountHubCard,children:[n.jsx("strong",{children:"Profile & Account"}),n.jsx("p",{className:lt.sectionText,children:"Profile editing and account preferences will live here."})]}),n.jsxs("div",{className:mt.accountHubCard,children:[n.jsx("strong",{children:"Billing"}),o?a!=="cloud"?n.jsx("p",{className:lt.sectionText,children:"Billing remains cloud-backed in local runtime and uses your connected cloud account."}):n.jsxs(n.Fragment,{children:[d&&n.jsx("p",{className:lt.sectionTextSpaced,children:"Loading billing status..."}),m&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:m}),y&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:y}),k&&n.jsx("p",{className:lt.errorText,children:k}),me&&n.jsx("p",{className:lt.sectionText,children:me}),n.jsxs("p",{className:lt.sectionTextSpaced,children:["Plan: ",n.jsx("code",{children:Me})," · ","Entitlement: ",n.jsx("code",{children:String(g?.entitlementState||"n/a")})]}),n.jsxs("p",{className:lt.sectionText,children:["Stripe status: ",n.jsx("code",{children:String(g?.stripeStatus||"n/a")}),g?.effectiveUntil?` · Effective until ${new Date(g.effectiveUntil).toLocaleString()}`:""]}),n.jsx("div",{className:lt.wrapRow,children:n.jsxs("label",{className:`${mt.accountMenuMeta} ${lt.inlineFieldLabel}`,children:["Interval",n.jsxs("select",{className:f.input,value:h,onChange:Qe=>K(Qe.target.value==="year"?"year":"month"),disabled:S,children:[n.jsx("option",{value:"month",children:"Monthly"}),n.jsx("option",{value:"year",children:"Yearly"})]})]})}),n.jsxs("div",{className:lt.actionRowEnd,children:[n.jsx("button",{className:f.cancelBtn,onClick:j,disabled:S||d,children:"Refresh Billing"}),n.jsx("button",{className:f.cancelBtn,onClick:H,disabled:S||!g?.stripeSubscriptionId,children:"Update Interval"}),n.jsx("button",{className:f.cancelBtn,onClick:ue,disabled:S||!g?.stripeCustomerId,children:"Manage Billing"}),n.jsx("button",{className:f.submitBtn,onClick:Pe,disabled:S||be.primaryAction==="manage_billing"&&!g?.stripeCustomerId,children:S?"Working...":Te})]})]}):n.jsx("p",{className:lt.sectionText,children:"Sign in to manage subscription billing."})]}),n.jsxs("div",{className:mt.accountHubCard,children:[n.jsx("strong",{children:"Workspace Audit Log"}),n.jsx("p",{className:lt.sectionText,children:"Audit entries are workspace-scoped for the active workspace, not global account history."}),n.jsxs("p",{className:lt.sectionText,children:["Active workspace: ",n.jsx("code",{children:v})]}),n.jsx("div",{className:lt.actionRowEnd,children:n.jsx("button",{className:f.cancelBtn,onClick:ke,disabled:!_,children:"Open Workspace Audit"})})]}),n.jsxs("div",{className:mt.accountHubCard,children:[n.jsx("strong",{children:"Workspace Cloud Sync"}),n.jsx("p",{className:lt.sectionText,children:I?A?`Enabled · ${D}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),U&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:U}),n.jsx("div",{className:lt.actionRowEnd,children:n.jsx("button",{className:f.cancelBtn,disabled:!I||W,onClick:()=>G(!A),children:A?"Disable Sync":"Enable Sync"})})]}),n.jsxs("div",{className:`${It.formActions} ${lt.modalActionsEnd}`,children:[n.jsx("button",{className:f.cancelBtn,onClick:je,children:"Help & Support"}),n.jsx("button",{className:f.submitBtn,onClick:de,children:"Close"})]})]})})}var zh=(e,t,a,s,o,c)=>{if(c===0)e.rect(t,a,s,o);else{let i=s-c,d=o-c;e.translate(t,a),e.arc(c,c,c,Math.PI,Math.PI*1.5),e.lineTo(i,0),e.arc(i,c,c,Math.PI*1.5,Math.PI*2),e.lineTo(s,d),e.arc(i,d,c,Math.PI*2,Math.PI*.5),e.lineTo(c,o),e.arc(c,d,c,Math.PI*.5,Math.PI),e.closePath(),e.translate(-t,-a)}},i2=(e,t,a,s,o,c)=>{e.fillStyle=c;let i=s/3,d=o/3;e.fillRect(t,a,1,o),e.fillRect(i+t,a,1,o),e.fillRect(i*2+t,a,1,o),e.fillRect(i*3+t,a,1,o),e.fillRect(i*4+t,a,1,o),e.fillRect(t,a,s,1),e.fillRect(t,d+a,s,1),e.fillRect(t,d*2+a,s,1),e.fillRect(t,d*3+a,s,1),e.fillRect(t,d*4+a,s,1)},c2=e=>!!e.match(/^\s*data:([a-z]+\/[a-z]+(;[a-z-]+=[a-z-]+)?)?(;base64)?,[a-z0-9!$&',()*+;=\-._~:@/?%\s]*\s*$/i),Ly=(e,t)=>new Promise((a,s)=>{let o=new Image;o.addEventListener("load",()=>a(o)),o.addEventListener("error",s),!c2(e)&&t&&(o.crossOrigin=t),o.src=e}),l2=e=>new Promise((t,a)=>{let s=new FileReader;s.addEventListener("load",o=>{try{if(!o?.target?.result)throw Error("No image data");t(Ly(o.target.result))}catch(c){a(c)}}),s.readAsDataURL(e)}),d2=typeof File<"u",Hh=e=>Math.PI/180*e,Gh={x:.5,y:.5},u2=class{constructor(e){this.imageState=Gh,this.config={border:25,borderRadius:0,scale:1,rotate:0,color:[0,0,0,.5],backgroundColor:"",borderColor:void 0,showGrid:!1,gridColor:"#666",disableBoundaryChecks:!1,disableHiDPIScaling:!1,disableCanvasRotation:!0,crossOrigin:void 0,...e},this.pixelRatio=typeof window<"u"&&window.devicePixelRatio&&!this.config.disableHiDPIScaling?window.devicePixelRatio:1}getPixelRatio(){return this.pixelRatio}getImageState(){return this.imageState}setImageState(e){this.imageState=e}updateConfig(e){this.config={...this.config,...e}}isVertical(){return!this.config.disableCanvasRotation&&this.config.rotate%180!=0}getBorders(e){let t=e??this.config.border;return Array.isArray(t)?t:[t,t]}getDimensions(){let{width:e,height:t,rotate:a,border:s}=this.config,o={width:0,height:0},[c,i]=this.getBorders(s);return this.isVertical()?(o.width=t,o.height=e):(o.width=e,o.height=t),o.width+=c*2,o.height+=i*2,{canvas:o,rotate:a,width:e,height:t,border:s}}getXScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.width/this.config.height,t=this.imageState.width/this.imageState.height;return Math.min(1,e/t)}getYScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.height/this.config.width,t=this.imageState.height/this.imageState.width;return Math.min(1,e/t)}getCroppingRect(e){if(!this.imageState.width||!this.imageState.height)return{x:0,y:0,width:1,height:1};let t=e||{x:this.imageState.x,y:this.imageState.y},a=1/this.config.scale*this.getXScale(),s=1/this.config.scale*this.getYScale(),o={x:t.x-a/2,y:t.y-s/2,width:a,height:s},c=0,i=1-o.width,d=0,m=1-o.height;return(this.config.disableBoundaryChecks||a>1||s>1)&&(c=-o.width,i=1,d=-o.height,m=1),{...o,x:Math.max(c,Math.min(o.x,i)),y:Math.max(d,Math.min(o.y,m))}}getInitialSize(e,t){let a,s,o=this.getDimensions();return o.height/o.width>t/e?(a=o.height,s=a/t*e):(s=o.width,a=s/e*t),{height:a,width:s}}async loadImage(e){let t;if(d2&&e instanceof File)t=await l2(e);else if(typeof e=="string")t=await Ly(e,this.config.crossOrigin);else throw Error("Invalid image source");let a={...this.getInitialSize(t.width,t.height),resource:t,x:.5,y:.5};return this.imageState=a,a}clearImage(){this.imageState=Gh}calculatePosition(e=this.imageState,t){let[a,s]=this.getBorders(t);if(!e.width||!e.height)throw Error("Image dimension is unknown.");let o=this.getCroppingRect(),c=e.width*this.config.scale,i=e.height*this.config.scale,d=-o.x*c,m=-o.y*i;return this.isVertical()?(d+=s,m+=a):(d+=a,m+=s),{x:d,y:m,height:i,width:c}}paint(e){e.save(),e.scale(this.pixelRatio,this.pixelRatio),e.translate(0,0),e.fillStyle="rgba("+this.config.color.slice(0,4).join(",")+")";let t=this.config.borderRadius,a=this.getDimensions(),[s,o]=this.getBorders(a.border),c=a.canvas.height,i=a.canvas.width;t=Math.max(t,0),t=Math.min(t,i/2-s,c/2-o),e.beginPath(),zh(e,s,o,i-s*2,c-o*2,t),e.rect(i,0,-i,c),e.fill("evenodd"),this.config.borderColor&&(e.strokeStyle="rgba("+this.config.borderColor.slice(0,4).join(",")+")",e.lineWidth=1,e.beginPath(),zh(e,s+.5,o+.5,i-s*2-1,c-o*2-1,t),e.stroke()),this.config.showGrid&&i2(e,s,o,i-s*2,c-o*2,this.config.gridColor),e.restore()}paintImage(e,t,a,s=this.pixelRatio){if(!t.resource)return;let o=this.calculatePosition(t,a);e.save(),e.translate(e.canvas.width/2,e.canvas.height/2),e.rotate(this.config.rotate*Math.PI/180),e.translate(-(e.canvas.width/2),-(e.canvas.height/2)),this.isVertical()&&e.translate((e.canvas.width-e.canvas.height)/2,(e.canvas.height-e.canvas.width)/2),e.scale(s,s),e.globalCompositeOperation="destination-over",e.drawImage(t.resource,o.x,o.y,o.width,o.height),this.config.backgroundColor&&(e.fillStyle=this.config.backgroundColor,e.fillRect(0,0,e.canvas.width,e.canvas.height)),e.restore()}getImage(){let e=this.getCroppingRect(),t=this.imageState;if(!t.resource)throw Error("No image resource available, please report this to: https://github.com/mosch/react-avatar-editor/issues");e.x*=t.resource.width,e.y*=t.resource.height,e.width*=t.resource.width,e.height*=t.resource.height;let a=document.createElement("canvas");this.isVertical()?(a.width=Math.round(e.height),a.height=Math.round(e.width)):(a.width=Math.round(e.width),a.height=Math.round(e.height));let s=a.getContext("2d");if(!s)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return s.translate(a.width/2,a.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(a.width/2),-(a.height/2)),this.isVertical()&&s.translate((a.width-a.height)/2,(a.height-a.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,a.width,a.height)),s.drawImage(t.resource,-e.x,-e.y),a}getImageScaledToCanvas(){let e=this.getDimensions(),t=this.imageState,a=document.createElement("canvas");if(this.isVertical()?(a.width=e.height,a.height=e.width):(a.width=e.width,a.height=e.height),!t.resource)return a;let s=a.getContext("2d");if(!s)return a;let o=this.calculatePosition(t,0);return s.save(),s.translate(a.width/2,a.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(a.width/2),-(a.height/2)),this.isVertical()&&s.translate((a.width-a.height)/2,(a.height-a.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,a.width,a.height)),s.drawImage(t.resource,o.x,o.y,o.width,o.height),s.restore(),a}calculateDragPosition(e,t,a,s){let o=a-e,c=s-t;if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let i=this.imageState.width*this.config.scale,d=this.imageState.height*this.config.scale,{x:m,y}=this.getCroppingRect();m*=i,y*=d;let k=this.config.rotate;k%=360,k=k<0?k+360:k;let S=Math.cos(Hh(k)),h=Math.sin(Hh(k)),g=m+o*S+c*h,v=y+-o*h+c*S,_=1/this.config.scale*this.getXScale(),I=1/this.config.scale*this.getYScale();return{x:g/i+_/2,y:v/d+I/2}}},Vh=()=>{},m2=()=>{let e=!1;try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",Vh,t),window.removeEventListener("test",Vh,t)}catch{e=!1}return e},By=r.forwardRef((e,t)=>{let{scale:a=1,rotate:s=0,border:o=25,borderRadius:c=0,width:i=200,height:d=200,color:m=[0,0,0,.5],showGrid:y=!1,gridColor:k="#666",disableBoundaryChecks:S=!1,disableHiDPIScaling:h=!1,disableCanvasRotation:g=!0,image:v,position:_,backgroundColor:I,crossOrigin:A,onLoadStart:D,onLoadFailure:U,onLoadSuccess:W,onImageReady:Q,onImageChange:le,onMouseUp:ie,onMouseMove:se,onPositionChange:$,borderColor:C,style:de}=e,ke=r.useRef(null),K=r.useRef(new u2({width:i,height:d,border:o,borderRadius:c,scale:a,rotate:s,color:m,backgroundColor:I,borderColor:C,showGrid:y,gridColor:k,disableBoundaryChecks:S,disableHiDPIScaling:h,disableCanvasRotation:g,crossOrigin:A})),j=r.useRef(!1),H=r.useRef(void 0),ue=r.useRef(void 0),[ye,G]=r.useState(!1),[je,be]=r.useState(!1),[ce,me]=r.useState(K.current.getImageState()),Te=r.useRef(ie);Te.current=ie;let Me=r.useRef(se);Me.current=se;let Pe=r.useRef($);Pe.current=$,r.useEffect(()=>{K.current.updateConfig({width:i,height:d,border:o,borderRadius:c,scale:a,rotate:s,color:m,backgroundColor:I,borderColor:C,showGrid:y,gridColor:k,disableBoundaryChecks:S,disableHiDPIScaling:h,disableCanvasRotation:g,crossOrigin:A})},[i,d,o,c,a,s,m,I,C,y,k,S,h,g,A]);let Ee=r.useCallback(()=>{if(!ke.current)throw Error("No canvas found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return ke.current},[]),Z=r.useCallback(()=>{let L=Ee().getContext("2d");if(!L)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return L},[Ee]),x=r.useCallback(async L=>{be(!0),D?.();try{let X=await K.current.loadImage(L);j.current=!1,G(!1),me(X),Q?.(),W?.(X)}catch{U?.()}finally{be(!1)}},[D,Q,W,U]),b=r.useCallback(()=>{let L=Ee();Z().clearRect(0,0,L.width,L.height),K.current.clearImage(),me(K.current.getImageState())},[Ee,Z]),R=r.useCallback(()=>{let L=Z(),X=Ee();L.clearRect(0,0,X.width,X.height),K.current.paint(L),K.current.paintImage(L,ce,o)},[Z,Ee,ce,o,i,d,c,a,s,m,I,C,y,k,S,h,g,A]),B=r.useCallback(L=>{L.preventDefault(),j.current=!0,H.current=void 0,ue.current=void 0,G(!0)},[]),Y=r.useCallback(()=>{j.current=!0,H.current=void 0,ue.current=void 0,G(!0)},[]);r.useImperativeHandle(t,()=>({getImage:()=>K.current.getImage(),getImageScaledToCanvas:()=>K.current.getImageScaledToCanvas(),getCroppingRect:()=>K.current.getCroppingRect()}),[]),r.useEffect(()=>{let L=Z();v&&x(v),K.current.paint(L);let X=ne=>{if(!j.current)return;ne.cancelable&&ne.preventDefault();let Ce="targetTouches"in ne?ne.targetTouches[0].pageX:ne.clientX,Ae="targetTouches"in ne?ne.targetTouches[0].pageY:ne.clientY,Re=H.current,$e=ue.current;if(H.current=Ce,ue.current=Ae,Re!==void 0&&$e!==void 0){let vt=K.current.getImageState();if(vt.width&&vt.height){let st=K.current.calculateDragPosition(Ce,Ae,Re,$e);Pe.current?.(st);let kt={...vt,...st};K.current.setImageState(kt),me(kt)}}Me.current?.(ne)},M=()=>{j.current&&(j.current=!1,G(!1),Te.current?.())},V=m2()?{passive:!1}:!1;return document.addEventListener("mousemove",X,V),document.addEventListener("mouseup",M,V),document.addEventListener("touchmove",X,V),document.addEventListener("touchend",M,V),()=>{document.removeEventListener("mousemove",X,!1),document.removeEventListener("mouseup",M,!1),document.removeEventListener("touchmove",X,!1),document.removeEventListener("touchend",M,!1)}},[]),r.useEffect(()=>{v?x(v):!v&&ce.x!==.5&&ce.y!==.5&&b()},[v,i,d,I]),r.useEffect(()=>{R()},[R]),r.useEffect(()=>{if(!je)return;let L=ke.current;if(!L)return;let X=L.getContext("2d");if(!X)return;let M,V=performance.now(),ne=Ce=>{let Ae=(Ce-V)/1e3,Re=.03+Math.sin(Ae*2.5)*.02+.02;X.save(),X.clearRect(0,0,L.width,L.height),X.fillStyle=`rgba(255,255,255,${Re})`,X.fillRect(0,0,L.width,L.height),X.restore(),M=requestAnimationFrame(ne)};return M=requestAnimationFrame(ne),()=>cancelAnimationFrame(M)},[je]);let fe=r.useRef({image:v,width:i,height:d,position:_,scale:a,rotate:s,imageX:ce.x,imageY:ce.y});r.useEffect(()=>{let L=fe.current;(L.image!==v||L.width!==i||L.height!==d||L.position!==_||L.scale!==a||L.rotate!==s||L.imageX!==ce.x||L.imageY!==ce.y)&&(le?.(),fe.current={image:v,width:i,height:d,position:_,scale:a,rotate:s,imageX:ce.x,imageY:ce.y})},[v,i,d,_,a,s,ce.x,ce.y,le]);let te=K.current.getDimensions(),Le=K.current.getPixelRatio(),oe={width:te.canvas.width,height:te.canvas.height,cursor:ye?"grabbing":"grab",touchAction:"none",maxWidth:"none",maxHeight:"none"};return ze.createElement("canvas",{width:te.canvas.width*Le,height:te.canvas.height*Le,onMouseDown:B,onTouchStart:Y,style:{...oe,...de},ref:ke})});By.displayName="AvatarEditor";const p2="_avatarManagerBody_1bfwv_1",f2="_editorPanel_1bfwv_7",h2="_editorFrame_1bfwv_13",g2="_gifPreviewImage_1bfwv_21",y2="_emptyPreview_1bfwv_28",k2="_controlPanel_1bfwv_41",v2="_zoomField_1bfwv_47",S2="_zoomSlider_1bfwv_52",w2="_actionGrid_1bfwv_57",b2="_fileInput_1bfwv_63",_2="_messageStack_1bfwv_67",Ps={avatarManagerBody:p2,editorPanel:f2,editorFrame:h2,gifPreviewImage:g2,emptyPreview:y2,controlPanel:k2,zoomField:v2,zoomSlider:S2,actionGrid:w2,fileInput:b2,messageStack:_2},Rp=512,C2=48,Ku=512;function qh(e,t,a){return new Promise(s=>{e.toBlob(s,t,a)})}function A2(e,t){const a=String(e).trim()||"avatar",s=a.lastIndexOf(".");return s<=0?`${a}${t}`:`${a.slice(0,s)}${t}`}async function x2(e,t){const a=e.getImageScaledToCanvas(),s=document.createElement("canvas");s.width=Ku,s.height=Ku;const o=s.getContext("2d");if(!o)throw new Error("Image editing requires a 2D canvas context.");o.drawImage(a,0,0,Ku,Ku);const i=await qh(s,"image/webp",.9)||await qh(s,"image/jpeg",.9);if(!i)throw new Error("Unable to prepare profile photo.");const d=i.type||"image/jpeg",m=d==="image/webp"?".webp":".jpg";return new File([i],A2(t,m),{type:d,lastModified:Date.now()})}function I2({isOpen:e,theme:t,title:a="Edit Photo",currentImageUrl:s,editorImageUrl:o="",fallbackInitial:c,accept:i,busy:d,hasPendingImage:m,canRemove:y,error:k,notice:S,onClose:h,onApplyImage:g,onRemoveImage:v,onDiscardPendingImage:_}){const I=r.useRef(null),A=r.useRef(null),[D,U]=r.useState(null),[W,Q]=r.useState(""),[le,ie]=r.useState(1.1),[se,$]=r.useState(null),[C,de]=r.useState(null);r.useEffect(()=>{e||(U(null),Q(""),ie(1.1),$(null),de(null))},[e]),r.useEffect(()=>{if(!D){Q("");return}const ce=URL.createObjectURL(D);return Q(ce),()=>URL.revokeObjectURL(ce)},[D]);const ke=W||o||s,K=D?.name||"avatar",j=String(c||"").trim().charAt(0).toUpperCase(),H=se||k,ue=C||S,ye=r.useCallback(ce=>{if($(null),de(null),!!ce){if(!ce.type.startsWith("image/")){$("Profile photo must be an image file.");return}ce.type==="image/gif"&&de("Animated GIFs will upload without repositioning."),U(ce),ie(1.1)}},[]),G=r.useCallback(async()=>{$(null);const ce=I.current;if(D?.type==="image/gif"){await g(D)&&h();return}if(!ce||!ke){$("Choose a profile photo first.");return}try{const me=await x2(ce,K);await g(me,D)&&h()}catch(me){$(me instanceof Error?me.message:"Unable to prepare profile photo.")}},[ke,g,h,D,K]),je=D?.type==="image/gif"||!!ke,be=r.useMemo(()=>n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",className:f.secondaryButton,onClick:h,disabled:d,children:"Cancel"}),n.jsx("button",{type:"button",className:f.primaryUpdateBtn,onClick:()=>{G()},disabled:d||!je,children:d?"Applying...":"Apply Photo"})]}),[d,je,G,h]);return n.jsx(Es,{isOpen:e,onClose:h,title:a,size:"md",theme:t,draggable:!0,footer:be,children:n.jsxs("div",{className:Ps.avatarManagerBody,children:[n.jsxs("div",{className:Ps.editorPanel,children:[n.jsx("div",{className:`tf-surface-inset ${Ps.editorFrame}`,children:D?.type==="image/gif"&&W?n.jsx("img",{src:W,alt:"",className:Ps.gifPreviewImage}):ke?n.jsx(By,{ref:I,image:ke,width:Rp,height:Rp,border:C2,borderRadius:Rp/2,scale:le,color:[15,15,26,.72],backgroundColor:"transparent",style:{width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",display:"block",borderRadius:"var(--radius-lg)",boxShadow:"var(--box-shadow-sm)"},disableCanvasRotation:!0}):n.jsx("div",{className:Ps.emptyPreview,"aria-hidden":"true",children:j})}),n.jsxs("div",{className:Ps.controlPanel,children:[n.jsx("input",{ref:A,type:"file","aria-label":"Choose profile photo",accept:i,className:Ps.fileInput,onChange:ce=>ye(ce.target.files?.[0]||null),disabled:d}),n.jsxs("div",{className:Ps.actionGrid,children:[n.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>A.current?.click(),disabled:d,children:[n.jsx(Fk,{size:16}),"Choose"]}),m&&_&&n.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:_,disabled:d,children:[n.jsx(Sd,{size:16}),"Discard"]}),y&&v&&n.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",onClick:v,disabled:d,children:[n.jsx(xm,{size:16}),"Remove"]})]}),n.jsxs("label",{className:`tf-field-stack ${Ps.zoomField}`,children:[n.jsx("span",{className:"tf-field-label",children:"Zoom"}),n.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:le,onChange:ce=>ie(Number(ce.target.value)),className:Ps.zoomSlider,disabled:d||!ke||D?.type==="image/gif"})]})]})]}),(H||ue)&&n.jsxs("div",{className:Ps.messageStack,children:[H&&n.jsx("p",{className:"tf-text-error",children:H}),ue&&!H&&n.jsx("p",{className:"tf-text-helper",children:ue})]})]})})}const T2="_editableAvatarButton_1ga39_1",R2="_editableAvatarImage_1ga39_47",N2="_editableAvatarFallback_1ga39_54",j2="_editableAvatarBadge_1ga39_65",Zu={editableAvatarButton:T2,editableAvatarImage:R2,editableAvatarFallback:N2,editableAvatarBadge:j2};function P2({label:e,imageUrl:t,fallback:a,accentColor:s,size:o=52,width:c,height:i,radius:d,editBadgeSize:m,editIconSize:y=16,disabled:k=!1,className:S="",onClick:h}){const g=String(t||"").trim(),v=c??o,_=i??o,I=typeof d=="number"?`${d}px`:d,A=typeof m=="number"?`${m}px`:m;return n.jsxs("button",{type:"button",className:`${Zu.editableAvatarButton} ${S}`.trim(),"aria-label":e,title:e,onClick:h,disabled:k,style:{"--editable-avatar-size":`${o}px`,"--editable-avatar-width":`${v}px`,"--editable-avatar-height":`${_}px`,...I?{"--editable-avatar-radius":I}:{},...A?{"--editable-avatar-badge-size":A}:{},...s?{"--editable-avatar-accent":s}:{}},children:[g?n.jsx("img",{src:g,alt:"",className:Zu.editableAvatarImage}):n.jsx("span",{className:Zu.editableAvatarFallback,children:a}),n.jsx("span",{className:Zu.editableAvatarBadge,"aria-hidden":"true",children:n.jsx(Ok,{size:y})})]})}function M2({isOpen:e,theme:t,onClose:a,onSave:s,displayName:o,email:c,avatarDisplayUrl:i,accountBadgeInitial:d,saveBusy:m,avatarBusy:y,saveError:k,saveNotice:S,onDisplayNameChange:h,onOpenAvatarManager:g}){return n.jsx(Es,{isOpen:e,onClose:a,title:"Edit Profile",size:"sm",theme:t,draggable:!0,footer:n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",className:f.secondaryButton,onClick:a,disabled:m||y,children:"Cancel"}),n.jsx("button",{type:"button",className:f.primaryUpdateBtn,onClick:s,disabled:m||y||!o.trim(),children:m?"Saving...":"Save Profile"})]}),children:n.jsxs("div",{className:`${It.form} ${lt.modalBody}`,children:[n.jsxs("div",{className:mt.profileEditLayout,children:[n.jsx("div",{className:mt.profileAvatarEditor,children:n.jsx(P2,{label:"Edit profile photo",imageUrl:i,fallback:d,disabled:m||y,onClick:g})}),n.jsxs("div",{className:mt.profileFieldStack,children:[n.jsxs("label",{className:mt.profileFieldLabel,children:[n.jsx("span",{children:"Display name"}),n.jsx("input",{className:f.input,type:"text",value:o,onChange:v=>h(v.target.value),placeholder:"Display name",disabled:m})]}),n.jsxs("label",{className:mt.profileFieldLabel,children:[n.jsx("span",{children:"Email"}),n.jsx("input",{className:f.input,type:"email",value:c,readOnly:!0,disabled:!0})]})]})]}),k&&n.jsx("p",{className:`${he.loginError} ${lt.errorText}`,children:k}),S&&!k&&n.jsx("p",{className:lt.errorText,children:S})]})})}const tf="support@taskforcehq.ai";function Yu(e){return String(e||"").trim()}function E2(e={}){const t=Yu(e.workspaceName),a=Yu(e.workspaceId),s=Yu(e.accountLabel),o=Yu(e.runtimeMode),c=[t?`Workspace: ${t}`:"",a?`Workspace ID: ${a}`:"",s?`Account: ${s}`:"",o?`Runtime: ${o}`:""].filter(Boolean),i=["Hi Taskforce team,","","I need help with:","",c.length>0?"Context:":"",...c,(c.length>0,""),"What happened:",""].filter((m,y,k)=>m!==""||k[y-1]!==""),d=new URLSearchParams({subject:"Taskforce support request",body:i.join(`
|
|
4
|
+
`)});return`mailto:${tf}?${d.toString()}`}function D2({isOpen:e,theme:t,onClose:a,onOpenSettings:s,onOpenAccountHub:o,supportMailtoHref:c}){const[i,d]=r.useState("idle"),m=async()=>{try{await navigator.clipboard.writeText(tf),d("copied"),window.setTimeout(()=>d("idle"),1600)}catch{d("failed"),window.setTimeout(()=>d("idle"),2200)}};return n.jsx(Es,{isOpen:e,onClose:a,title:"Help & Support",size:"md",theme:t,draggable:!0,children:n.jsxs("div",{className:`${It.form} ${lt.modalBody}`,children:[n.jsxs("div",{className:lt.helpIntro,children:[n.jsx("p",{className:"tf-text-body",children:"Need a hand with Taskforce? Send us what you were trying to do, what happened, and any workspace context that would help us reproduce it."}),n.jsxs("div",{className:lt.supportEmailRow,children:[n.jsx("code",{className:lt.supportEmailAddress,children:tf}),n.jsxs("button",{className:`${f.submitBtn} ${lt.supportEmailBtn}`,onClick:()=>{m()},type:"button",children:[i==="copied"?n.jsx(eo,{size:16}):n.jsx(of,{size:16}),i==="copied"?"Copied":i==="failed"?"Copy Failed":"Copy Email"]})]}),n.jsxs("a",{className:`${f.cancelBtn} ${lt.supportEmailBtn}`,href:c,children:[n.jsx(kg,{size:16}),"Open Email App"]})]}),n.jsxs("div",{className:`${lt.supportPanel} tf-surface-panel`,children:[n.jsxs("div",{className:lt.supportPanelHeader,children:[n.jsx($k,{size:16}),n.jsxs("div",{children:[n.jsx("h3",{className:"tf-heading-card",children:"Before you email"}),n.jsx("p",{className:"tf-text-secondary",children:"These are the fastest places to check for common workspace, account, and setup issues."})]})]}),n.jsxs("div",{className:lt.supportRouteList,children:[n.jsxs("button",{className:`${f.cancelBtn} ${lt.supportRouteBtn}`,onClick:s,children:[n.jsx(cf,{size:15}),"Open Settings"]}),o&&n.jsxs("button",{className:`${f.cancelBtn} ${lt.supportRouteBtn}`,onClick:o,children:[n.jsx(Uk,{size:15}),"Open Account Hub"]})]})]}),n.jsx("div",{className:`${It.formActions} ${lt.modalActionsEnd}`,children:n.jsx("button",{className:f.cancelBtn,onClick:a,children:"Close"})})]})})}function L2({prompt:e,theme:t,onClose:a,onConfirm:s}){return n.jsx(Es,{isOpen:!!e,onClose:a,title:"Date Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:n.jsxs("div",{className:`${f.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[n.jsx("p",{className:"tf-text-body",children:"Due date is before scheduled date."}),e&&n.jsxs("p",{className:"tf-text-helper",children:["Due: ",e.dueDate," · Scheduled: ",e.scheduledDate]}),n.jsxs("div",{className:f.formActions,children:[n.jsx("button",{className:f.cancelBtn,onClick:a,children:"Go Back"}),n.jsx("button",{className:f.submitBtn,onClick:s,children:"Save Anyway"})]})]})})}function B2({isOpen:e,theme:t,onClose:a,onConfirm:s}){return n.jsx(Es,{isOpen:e,onClose:a,title:"Cloud Sync Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:n.jsxs("div",{className:`${f.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[n.jsx("p",{className:"tf-text-body",children:"Turning on cloud sync can renumber task, document, and image references to match the cloud workspace."}),n.jsxs("p",{className:"tf-text-helper",children:["Labels like ",n.jsx("code",{children:"T-12"}),", ",n.jsx("code",{children:"D-4"}),", and ",n.jsx("code",{children:"IMG-2"})," may change. Plain file attachments are not renumbered."]}),n.jsxs("div",{className:f.formActions,children:[n.jsx("button",{className:f.cancelBtn,onClick:a,children:"Go Back"}),n.jsx("button",{className:f.submitBtn,onClick:s,children:"Enable Sync Anyway"})]})]})})}const W2="_syncStatusModal_4pd1g_1",F2="_syncStatusTop_4pd1g_6",O2="_syncStatusMetaHeader_4pd1g_15",$2="_syncStatusHeaderInfo_4pd1g_22",U2="_syncToggle_4pd1g_43",z2="_syncStatusBadge_4pd1g_47",H2="_syncToggleControl_4pd1g_75",G2="_syncToggleControlEnabled_4pd1g_91",V2="_syncToggleControlDisabled_4pd1g_98",q2="_syncToggleControlBusy_4pd1g_102",K2="_syncToggleControlBlocked_4pd1g_107",Z2="_syncToggleInput_4pd1g_112",Y2="_syncToggleState_4pd1g_125",J2="_syncToggleStateOn_4pd1g_136",Q2="_syncToggleStateOff_4pd1g_141",X2="_syncToggleThumb_4pd1g_146",e1="_syncStatusSummaryValue_4pd1g_173",t1="_syncStatusSummaryCompact_4pd1g_180",n1="_syncStatusRepairBanner_4pd1g_190",a1="_syncStatusRepairHeader_4pd1g_200",r1="_syncStatusRepairBadge_4pd1g_207",s1="_syncStatusRepairMeta_4pd1g_216",o1="_syncStatusRepairText_4pd1g_223",i1="_syncStatusLabel_4pd1g_257",c1="_syncStatusSectionHeader_4pd1g_265",l1="_syncStatusCompactGrid_4pd1g_278",d1="_syncStatusCompactItem_4pd1g_284",u1="_syncStatusValue_4pd1g_295",m1="_syncStatusValueError_4pd1g_325",p1="_syncStatusActions_4pd1g_329",f1="_syncStatusPanel_4pd1g_336",h1="_syncStatusPanelHeader_4pd1g_346",g1="_syncStatusPanelMeta_4pd1g_353",y1="_syncStatusEventsList_4pd1g_375",k1="_syncStatusEventItem_4pd1g_384",v1="_syncStatusEventItemError_4pd1g_391",S1="_syncStatusEventItemMuted_4pd1g_396",w1="_syncStatusEventLine_4pd1g_401",b1="_syncStatusSecondaryActions_4pd1g_411",_1="_syncStatusPrimaryActions_4pd1g_425",C1="_syncStatusPrimaryActionSlot_4pd1g_432",A1="_syncStatusActionPlaceholder_4pd1g_440",nt={syncStatusModal:W2,syncStatusTop:F2,syncStatusMetaHeader:O2,syncStatusHeaderInfo:$2,syncToggle:U2,syncStatusBadge:z2,syncToggleControl:H2,syncToggleControlEnabled:G2,syncToggleControlDisabled:V2,syncToggleControlBusy:q2,syncToggleControlBlocked:K2,syncToggleInput:Z2,syncToggleState:Y2,syncToggleStateOn:J2,syncToggleStateOff:Q2,syncToggleThumb:X2,syncStatusSummaryValue:e1,syncStatusSummaryCompact:t1,syncStatusRepairBanner:n1,syncStatusRepairHeader:a1,syncStatusRepairBadge:r1,syncStatusRepairMeta:s1,syncStatusRepairText:o1,syncStatusLabel:i1,syncStatusSectionHeader:c1,syncStatusCompactGrid:l1,syncStatusCompactItem:d1,syncStatusValue:u1,syncStatusValueError:m1,syncStatusActions:p1,syncStatusPanel:f1,syncStatusPanelHeader:h1,syncStatusPanelMeta:g1,syncStatusEventsList:y1,syncStatusEventItem:k1,syncStatusEventItemError:v1,syncStatusEventItemMuted:S1,syncStatusEventLine:w1,syncStatusSecondaryActions:b1,syncStatusPrimaryActions:_1,syncStatusPrimaryActionSlot:C1,syncStatusActionPlaceholder:A1};function x1({isOpen:e,theme:t,currentWorkspaceLabel:a,syncStatusMeta:s,workspaceCloudSyncEnabled:o,syncControlBusy:c,canManageWorkspaceSync:i,workspaceSyncSummary:d,workspaceSyncRecommendedAction:m,workspaceSyncRepairBusy:y,referenceMismatchCount:k,syncStageLabel:S,workspaceSyncPendingChanges:h,formattedLastSyncTime:g,formattedLastPullTime:v,formattedLastPushTime:_,syncLastError:I,workspaceSyncDiagnostics:A,activeReferenceMismatchSummaries:D,syncDiagnosticsSummary:U,syncEventRows:W,syncEventsListRef:Q,workspaceSyncRepairQueued:le,workspaceSyncBusy:ie,workspaceSyncCopied:se,runtimeMode:$,isAuthenticated:C,onClose:de,onToggleWorkspaceSync:ke,onRepairSync:K,onCopyReport:j,onOpenLogin:H,onRetrySync:ue}){return n.jsx(Es,{isOpen:e,onClose:de,title:"Sync Manager",size:"mdWide",theme:t,draggable:!0,children:n.jsxs("div",{className:`${It.form} ${nt.syncStatusModal}`,style:{gap:"10px"},children:[n.jsxs("div",{className:nt.syncStatusTop,children:[n.jsx("div",{className:nt.syncStatusHeaderInfo,children:n.jsxs("div",{className:nt.syncStatusMetaHeader,children:[n.jsx("div",{className:nt.syncStatusBadge,style:{borderColor:s.border,background:s.background,color:s.color},children:s.label}),n.jsxs("span",{className:nt.syncStatusLabel,children:["Workspace: ",n.jsx("code",{children:a})]})]})}),n.jsx("label",{className:nt.syncToggle,children:n.jsxs("span",{className:[nt.syncToggleControl,o?nt.syncToggleControlEnabled:nt.syncToggleControlDisabled,c?nt.syncToggleControlBusy:"",i?"":nt.syncToggleControlBlocked].filter(Boolean).join(" "),children:[n.jsx("input",{className:nt.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:o,disabled:!i||c,onChange:ye=>ke(ye.target.checked)}),n.jsx("span",{className:`${nt.syncToggleState} ${nt.syncToggleStateOn}`,children:"On"}),n.jsx("span",{className:`${nt.syncToggleState} ${nt.syncToggleStateOff}`,children:"Off"}),n.jsx("span",{className:nt.syncToggleThumb})]})})]}),n.jsxs("div",{className:nt.syncStatusSummaryCompact,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Health"}),n.jsx("span",{className:nt.syncStatusSummaryValue,children:d})]}),n.jsxs("div",{className:nt.syncStatusSummaryCompact,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Next Step"}),n.jsx("span",{className:nt.syncStatusSummaryValue,children:m})]}),y&&n.jsxs("div",{className:nt.syncStatusRepairBanner,children:[n.jsxs("div",{className:nt.syncStatusRepairHeader,children:[n.jsxs("div",{className:nt.syncStatusRepairBadge,children:[n.jsx(br,{size:13,className:f.spinner}),n.jsx("span",{children:"Repair In Progress"})]}),n.jsx("span",{className:nt.syncStatusRepairMeta,children:"Advanced recovery mode"})]}),n.jsx("span",{className:nt.syncStatusRepairText,children:k>0?`Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again, including ${k} detected reference mismatch${k===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."})]}),n.jsx("div",{className:nt.syncStatusSectionHeader,children:n.jsx("span",{className:nt.syncStatusLabel,children:"Current Session"})}),n.jsxs("div",{className:nt.syncStatusCompactGrid,children:[n.jsxs("div",{className:nt.syncStatusCompactItem,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Stage"}),n.jsx("span",{className:nt.syncStatusValue,children:S})]}),n.jsxs("div",{className:nt.syncStatusCompactItem,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Local Changes"}),n.jsx("span",{className:nt.syncStatusValue,children:h})]}),n.jsxs("div",{className:nt.syncStatusCompactItem,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Last Successful"}),n.jsx("span",{className:nt.syncStatusValue,children:g})]})]}),n.jsx("div",{className:nt.syncStatusSectionHeader,children:n.jsx("span",{className:nt.syncStatusLabel,children:"Activity"})}),n.jsxs("div",{className:nt.syncStatusCompactGrid,children:[n.jsxs("div",{className:nt.syncStatusCompactItem,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Last Pull"}),n.jsx("span",{className:nt.syncStatusValue,children:v})]}),n.jsxs("div",{className:nt.syncStatusCompactItem,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Last Push"}),n.jsx("span",{className:nt.syncStatusValue,children:_})]})]}),I!=="None"&&n.jsxs("div",{className:nt.syncStatusPanel,style:{background:"rgba(239, 68, 68, 0.05)",borderColor:"rgba(239, 68, 68, 0.2)"},children:[n.jsxs("div",{className:nt.syncStatusSectionHeader,style:{marginTop:0},children:[n.jsx(wd,{size:12,color:"#fda4af"}),n.jsxs("span",{className:nt.syncStatusLabel,style:{color:"#fda4af"},children:["Last Error (",A.lastErrorAt?new Date(A.lastErrorAt).toLocaleTimeString():"Recent",")"]})]}),n.jsx("span",{className:`${nt.syncStatusValue} ${nt.syncStatusValueError}`,children:I})]}),k>0&&n.jsxs("div",{className:nt.syncStatusPanel,style:{background:"rgba(250, 204, 21, 0.08)",borderColor:"rgba(250, 204, 21, 0.22)"},children:[n.jsxs("div",{className:nt.syncStatusPanelHeader,children:[n.jsx("span",{className:nt.syncStatusLabel,style:{color:"#fde68a"},children:"Identifier Integrity"}),n.jsxs("span",{className:nt.syncStatusPanelMeta,children:[k," mismatch",k===1?"":"es"," detected"]})]}),n.jsx("span",{className:nt.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."}),D.length>0&&n.jsx("div",{style:{marginTop:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:D.map(ye=>n.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:[n.jsx("span",{className:nt.syncStatusValue,style:{fontSize:"12px",wordBreak:"break-all"},children:ye.pathLabel}),ye.refsLabel?n.jsx("span",{className:nt.syncStatusPanelMeta,children:ye.refsLabel}):null]},ye.key))})]}),n.jsxs("div",{className:nt.syncStatusPanel,children:[n.jsxs("div",{className:nt.syncStatusPanelHeader,children:[n.jsx("span",{className:nt.syncStatusLabel,children:"Local Sync Diagnostics"}),n.jsx("span",{className:nt.syncStatusPanelMeta,style:{fontSize:"10px"},children:"AI profiles & metadata"})]}),n.jsx("div",{className:nt.syncStatusCompactGrid,style:{gridTemplateColumns:"repeat(2, 1fr)"},children:U.map(ye=>n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"8px"},children:[n.jsx("span",{className:nt.syncStatusLabel,style:{fontSize:"9px",textTransform:"capitalize"},children:ye.label}),n.jsx("span",{className:nt.syncStatusValue,style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:ye.value})]},ye.label))})]}),n.jsxs("div",{className:nt.syncStatusPanel,children:[n.jsx("div",{className:nt.syncStatusPanelHeader,children:n.jsx("span",{className:nt.syncStatusLabel,children:"Recent Events"})}),n.jsx("div",{ref:Q,className:nt.syncStatusEventsList,style:{height:"120px"},children:W.map(ye=>n.jsx("div",{className:[nt.syncStatusEventItem,ye.tone==="error"?nt.syncStatusEventItemError:"",ye.tone==="muted"?nt.syncStatusEventItemMuted:""].filter(Boolean).join(" "),style:{padding:"6px 8px",borderRadius:"6px"},children:n.jsx("span",{className:nt.syncStatusEventLine,style:{fontSize:"11px"},children:ye.text})},ye.key))})]}),n.jsxs("div",{className:`${It.formActions} ${nt.syncStatusActions}`,children:[n.jsxs("div",{className:nt.syncStatusSecondaryActions,children:[n.jsx("button",{className:f.cancelBtn,onClick:K,disabled:y,title:y?"Repair is running now.":le?"Repair is queued and will start when the current sync finishes.":ie?"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:y?n.jsxs(n.Fragment,{children:[n.jsx(br,{size:14,className:f.spinner}),n.jsx("span",{style:{marginLeft:"6px"},children:"Repairing..."})]}):le?"Repair Queued":"Repair"}),n.jsxs("button",{className:f.cancelBtn,onClick:j,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[n.jsx(of,{size:14}),n.jsx("span",{style:{marginLeft:"6px"},children:se?"Copied":"Copy Report"})]})]}),n.jsxs("div",{className:nt.syncStatusPrimaryActions,children:[n.jsx("div",{className:nt.syncStatusPrimaryActionSlot,children:$==="local"&&!C?n.jsx("button",{className:f.submitBtn,onClick:H,children:"Sign In / Register"}):n.jsx("div",{className:nt.syncStatusActionPlaceholder,"aria-hidden":"true"})}),n.jsx("div",{className:nt.syncStatusPrimaryActionSlot,children:n.jsx("button",{className:f.submitBtn,onClick:ue,disabled:ie,children:ie?n.jsxs(n.Fragment,{children:[n.jsx(br,{size:14,className:f.spinner}),"Syncing..."]}):n.jsxs(n.Fragment,{children:[n.jsx(zk,{size:14}),"Sync"]})})})]})]})]})})}function I1({isOpen:e,theme:t,teamPlanMode:a,teamMgmtError:s,teamManagementTab:o,teamUsersLoading:c,teamUsers:i,teamActionBusyUserId:d,teamInviteFeedback:m,teamInviteEmail:y,teamInviteRole:k,teamInvitePermissionMode:S,teamInviteBusy:h,pendingInvites:g,teamAuditLoading:v,teamAuditEvents:_,teamAuditPage:I,teamAuditPages:A,teamAuditHasMore:D,onClose:U,onOpenMembersTab:W,onOpenInvitesTab:Q,onOpenAuditTab:le,onMemberRoleChange:ie,onMemberPermissionChange:se,onToggleMemberDisabled:$,onRevokeInvite:C,onRemoveMember:de,onInviteEmailChange:ke,onInviteRoleChange:K,onInvitePermissionModeChange:j,onSubmitInvite:H,onLoadAuditPrevious:ue,onLoadAuditNext:ye}){return n.jsx(Es,{isOpen:e,onClose:U,title:"Team Management",size:"md",theme:t,draggable:!0,children:n.jsxs("div",{className:`${It.form} ${lt.modalBody}`,children:[a==="personal"&&n.jsx("p",{className:he.loginError,children:"Team management is only available in TEAM accounts."}),s&&n.jsx("p",{className:he.loginError,children:s}),n.jsxs("div",{className:`${f.settingsTabs} tf-scrollbar tf-scrollbar--track-transparent tf-scrollbar--compact`,children:[n.jsx("button",{className:`${f.settingsTabBtn} ${o==="members"?f.settingsTabBtnActive:""}`,onClick:W,children:"Members"}),n.jsx("button",{className:`${f.settingsTabBtn} ${o==="invites"?f.settingsTabBtnActive:""}`,onClick:Q,children:"Invites"}),n.jsx("button",{className:`${f.settingsTabBtn} ${o==="audit"?f.settingsTabBtnActive:""}`,onClick:le,children:"Audit Log"})]}),o==="members"&&n.jsxs("div",{className:mt.accountHubCard,children:[c&&n.jsx("p",{className:lt.mutedText,children:"Loading members..."}),!c&&i.length===0&&n.jsx("p",{className:lt.mutedText,children:"No users found."}),!c&&i.map(G=>n.jsxs("div",{className:lt.memberRow,children:[n.jsx("div",{className:lt.memberTitle,children:G.displayName||G.email}),n.jsxs("div",{className:mt.accountMenuMeta,children:[G.email," · ",G.status,G.disabled?" · deactivated":""]}),n.jsxs("div",{className:lt.memberActions,children:[n.jsxs("select",{className:`${f.input} ${lt.selectRole}`,value:G.role,onChange:je=>ie(G.userId,je.target.value),disabled:d===G.userId,children:[n.jsx("option",{value:"owner",children:"Owner"}),n.jsx("option",{value:"admin",children:"Admin"}),n.jsx("option",{value:"member",children:"Member"})]}),G.role==="member"&&n.jsxs("select",{className:`${f.input} ${lt.selectPermission}`,value:G.permissionMode,onChange:je=>se(G.userId,je.target.value),disabled:d===G.userId,children:[n.jsx("option",{value:"read-write",children:"Read / Write"}),n.jsx("option",{value:"read-only",children:"Read Only"})]}),n.jsx("button",{className:f.cancelBtn,disabled:d===G.userId,onClick:()=>$(G.userId,!G.disabled),children:G.disabled?"Reactivate":"Deactivate"}),G.status==="invited"&&n.jsx("button",{className:f.cancelBtn,disabled:d===G.userId,onClick:()=>C(G.userId),children:"Revoke Invite"}),n.jsx("button",{className:f.cancelBtn,disabled:d===G.userId,onClick:()=>de(G.userId),children:"Remove"})]})]},G.userId))]}),o==="invites"&&n.jsxs("div",{className:mt.accountHubCard,children:[m&&n.jsx("p",{className:lt.sectionText,children:m}),n.jsxs("div",{className:f.pathInputGroup,children:[n.jsx("label",{className:`${f.label} ${lt.labelFixed}`,children:"Email"}),n.jsx("input",{className:f.input,value:y,onChange:G=>ke(G.target.value),placeholder:"name@company.com"})]}),n.jsxs("div",{className:f.pathInputGroup,children:[n.jsx("label",{className:`${f.label} ${lt.labelFixed}`,children:"Role"}),n.jsxs("select",{className:`${f.input} ${lt.selectRole}`,value:k,onChange:G=>K(G.target.value==="admin"?"admin":"member"),children:[n.jsx("option",{value:"member",children:"Member"}),n.jsx("option",{value:"admin",children:"Admin"})]}),k==="member"&&n.jsxs("select",{className:`${f.input} ${lt.selectPermission}`,value:S,onChange:G=>j(G.target.value==="read-only"?"read-only":"read-write"),children:[n.jsx("option",{value:"read-write",children:"Read / Write"}),n.jsx("option",{value:"read-only",children:"Read Only"})]}),n.jsx("button",{className:f.submitBtn,disabled:h||!y.trim()||a!=="team",onClick:H,children:h?"Sending...":"Send Invite"})]}),n.jsxs("div",{className:lt.inviteRow,children:[n.jsx("div",{className:lt.listHeading,children:"Pending Invites"}),g.length===0&&n.jsx("p",{className:lt.mutedText,children:"No pending invites."}),g.map(G=>n.jsxs("div",{className:lt.memberRow,children:[n.jsx("div",{className:lt.memberTitle,children:G.displayName||G.email}),n.jsxs("div",{className:mt.accountMenuMeta,children:[G.email," · ",G.role]})]},G.userId))]})]}),o==="audit"&&n.jsxs("div",{className:mt.accountHubCard,children:[v&&n.jsx("p",{className:lt.mutedText,children:"Loading audit entries..."}),!v&&_.length===0&&n.jsx("p",{className:lt.mutedText,children:"No audit events for this workspace."}),!v&&n.jsx("div",{className:lt.auditList,children:_.map(G=>n.jsxs("div",{className:lt.memberRow,children:[n.jsx("div",{className:mt.accountMenuMeta,children:new Date(G.createdAt).toLocaleString()}),n.jsx("div",{className:lt.memberTitle,children:G.action}),n.jsxs("div",{className:mt.accountMenuMeta,children:[G.actorUserId," (",G.actorRole,")"]})]},G.id))}),n.jsxs("div",{className:lt.auditPager,children:[n.jsx("button",{className:f.cancelBtn,disabled:v||I===0,onClick:ue,children:"Previous"}),n.jsxs("span",{className:mt.accountMenuMeta,children:["Page ",I+1," of ",A]}),n.jsx("button",{className:f.cancelBtn,disabled:v||!D||I+1>=A,onClick:ye,children:"Next"})]})]}),n.jsx("div",{className:`${It.formActions} ${lt.modalActionsEnd}`,children:n.jsx("button",{className:f.cancelBtn,onClick:U,children:"Close"})})]})})}const Wy=e=>{const t=e.status||"task";return t==="done"||t==="cancelled"?"completed":t},T1=(e,t,a)=>{if(Wy(e)===t)return null;const o={status:t};return t==="task"||t==="on-hold"?(o.inProgress=!1,o.readyForReview=!1,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):t==="in-progress"?(o.inProgress=!0,o.readyForReview=!1,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):t==="review"?(o.inProgress=!1,o.readyForReview=!0,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):t==="done"||t==="completed"?(o.status="done",o.inProgress=!1,o.readyForReview=!1,o.completed=!0,o.cancelled=!1,o.completedAt=a,o):(t==="cancelled"&&(o.status="cancelled"),o)},R1=({targetTasks:e,overTaskId:t,isBelowOverItem:a})=>{if(!t)return e.length;const s=e.findIndex(o=>o.id===t);return s<0?e.length:s+(a?1:0)},Fy=(e,t=new Map)=>{const a=new Map(t);return e.forEach((s,o)=>{a.set(s.id,{...a.get(s.id)||{},orderInDay:o})}),a},jf=e=>Array.from(e.entries()).map(([t,a])=>({taskId:t,updates:a})),Oy=({sourceColumnId:e,targetColumnId:t,sourceTasks:a,updates:s})=>!e||e===t?s:Fy(a,s),N1=({activeTask:e,sourceColumnId:t,targetTasks:a,sourceTasks:s,insertAt:o})=>{const c=[...a];c.splice(o,0,e);let i=new Map;return c.forEach((d,m)=>{if(d.id===e.id){i.set(d.id,{...i.get(d.id)||{},...e.scheduledDate?{scheduledDate:null,scheduledWeekKey:null}:{},orderInDay:m});return}i.set(d.id,{...i.get(d.id)||{},orderInDay:m})}),i=Oy({sourceColumnId:t,targetColumnId:"backlog",sourceTasks:s,updates:i}),jf(i)},j1=({activeTask:e,targetTasks:t,insertAt:a})=>{const s=[...t];return s.splice(a,0,e),jf(Fy(s))},P1=({activeTask:e,sourceColumnId:t,targetColumnId:a,targetTasks:s,sourceTasks:o,insertAt:c,scheduledDate:i,scheduledWeekKey:d})=>{const m=[...s];m.splice(c,0,e);let y=new Map;return m.forEach((k,S)=>{if(k.id===e.id){y.set(k.id,{...y.get(k.id)||{},scheduledDate:i,scheduledWeekKey:d,orderInDay:S});return}y.set(k.id,{...y.get(k.id)||{},orderInDay:S})}),y=Oy({sourceColumnId:t,targetColumnId:a,sourceTasks:o,updates:y}),jf(y)},M1=({activeTask:e,sourceColumnId:t,targetColumnId:a,targetTasks:s,sourceTasks:o,overTaskId:c,isBelowOverItem:i,scheduleDates:d,parseToIsoWeekKey:m,todayDate:y})=>{const k=["mon","tue","wed","thu","fri","sat","sun"];if(!(a==="backlog"||a==="expired"||k.includes(a)))return null;const h=R1({targetTasks:s,overTaskId:c,isBelowOverItem:i});if(a==="expired")return t!=="expired"?null:{kind:"updates",updates:j1({activeTask:e,targetTasks:s,insertAt:h})};if(a==="backlog")return{kind:"updates",updates:N1({activeTask:e,sourceColumnId:t,targetTasks:s,sourceTasks:o,insertAt:h})};if(!k.includes(a))return null;const g=d[a];return g?!(e.status==="done"||e.status==="cancelled")&&g<y?{kind:"blocked",reason:"Only completed work can be scheduled in the past."}:{kind:"updates",updates:P1({activeTask:e,sourceColumnId:t,targetColumnId:a,targetTasks:s,sourceTasks:o,insertAt:h,scheduledDate:g,scheduledWeekKey:m(g)}),selectedDate:g}:null},nm="expired::";function E1({tasks:e,columns:t,groupBy:a,searchQuery:s,copiedId:o,taxonomies:c,types:i,priorities:d,approaches:m,assigneeOptions:y=[],onUpdateTask:k,onTaskClick:S,onOpenTaskById:h,onCopyId:g,onToggleInProgress:v,onToggleReview:_,onToggleComplete:I,onToggleCancel:A,onSetStatus:D,onArchiveTask:U,onUnarchive:W,onDelete:Q,allTasks:le=[],onAddTaskToColumn:ie,emptyColumnMode:se="show",filterCategories:$=[],filterTypes:C=[],filterPriorities:de=[],filterStatus:ke=[],filterAssignees:K=[],filtersReady:j=!0,scheduleFilteredTaskIds:H,categories:ue=[],compressed:ye=!1,readOnlyMode:G=null,recentlyChangedTaskIds:je=[],scheduleDates:be,onScheduleDaySelected:ce,persistedScrollLeft:me,onScrollLeftChange:Te,sortBy:Me="created",sortOrder:Pe="desc",planningDropTargets:Ee=null,onAssignTaskToWorkstream:Z,onAssignWorkstreamToInitiative:x,showTaskCardStatusLabel:b=!0,workstreams:R=[],initiatives:B=[]}){const[Y,fe]=r.useState(null),[te,Le]=r.useState(!1),[oe,L]=r.useState(!1),X=r.useMemo(()=>new Set(je),[je]),M=r.useMemo(()=>new Map(R.map(E=>[E.id,E])),[R]),V=r.useMemo(()=>new Map(B.map(E=>[E.id,E])),[B]),ne=r.useCallback(E=>{const l=E.workstreamId&&M.get(E.workstreamId)||null,J=l?.initiativeId&&V.get(l.initiativeId)||null;return{taskWorkstream:l,taskInitiative:J}},[V,M]),Ce=r.useMemo(()=>new Set(e.map(E=>E.id)),[e]),Ae=r.useCallback(E=>E.startsWith(nm)?E.slice(nm.length):E,[]),Re=r.useCallback(E=>Ce.has(Ae(E)),[Ce,Ae]),$e=r.useMemo(()=>new Set(H||[]),[H]),vt=r.useRef(null),st=r.useCallback(E=>{const l=E?.data?.current||{},J=String(E?.id||"");let Se=String(l.taskId||""),Ie=String(l.workstreamId||"");!Se&&J&&Re(J)&&(Se=Ae(J)),!Ie&&J.startsWith("planning-workstream:")&&(Ie=J.slice(20));let Ke=String(l.type||"");return Ke||(Se?Ke="task-card":Ie&&(Ke="planning-workstream")),{activeId:J,type:Ke,taskId:Se,workstreamId:Ie}},[Ae,Re]),kt=bg($p(xg,{activationConstraint:{distance:10}}),$p(pv,{coordinateGetter:mv})),Ye=Wy,Ct=r.useMemo(()=>{const E=new Date,l=E.getFullYear(),J=String(E.getMonth()+1).padStart(2,"0"),Se=String(E.getDate()).padStart(2,"0");return`${l}-${J}-${Se}`},[]),dt=r.useMemo(()=>{const E=Se=>{const Ie=Se.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!Ie)return null;const Ke=new Date(Date.UTC(Number(Ie[1]),Number(Ie[2])-1,Number(Ie[3]))),Je=Ke.getUTCDay()||7;Ke.setUTCDate(Ke.getUTCDate()+4-Je);const Ne=new Date(Date.UTC(Ke.getUTCFullYear(),0,1)),zt=Math.ceil(((Ke.getTime()-Ne.getTime())/864e5+1)/7);return`${Ke.getUTCFullYear()}-W${String(zt).padStart(2,"0")}`};return{dates:{...(()=>{const Se=new Date,Ie=Se.getDay(),Ke=Ie===0?-6:1-Ie,Je=new Date(Se);Je.setDate(Se.getDate()+Ke);const Ne=Pt=>{const Wt=Pt.getFullYear(),Dt=String(Pt.getMonth()+1).padStart(2,"0"),Ht=String(Pt.getDate()).padStart(2,"0");return`${Wt}-${Dt}-${Ht}`},zt={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((Pt,Wt)=>{const Dt=new Date(Je);Dt.setDate(Je.getDate()+Wt),zt[Pt]=Ne(Dt)}),zt})(),...be||{}},parseToIsoWeekKey:E}},[be]),Qe=E=>{const l=E.scheduledDate||null;return l?new Map([[dt.dates.mon,"mon"],[dt.dates.tue,"tue"],[dt.dates.wed,"wed"],[dt.dates.thu,"thu"],[dt.dates.fri,"fri"],[dt.dates.sat,"sat"],[dt.dates.sun,"sun"]]).get(l)||"__offweek":"backlog"},Tt=r.useMemo(()=>{if(a==="schedule")return[];const E=new Set(t.map(Ie=>String(Ie.value))),l=new Set(t.map(Ie=>Ie.label)),J=[],Se=Ie=>{const Ke=a==="status"?Ye(Ie):Ie[a],Je=String(Ke??"");if(!Je||E.has(Je)||l.has(Je))return null;if(a==="category"){const Ne=ue.find(zt=>zt.value===Je||zt.label===Je);return{value:Je,label:Ne?.label||Je,icon:Ne?.icon||"Folder",color:Ne?.color}}if(a==="type"){const Ne=i?.find(zt=>zt.value===Je||zt.label===Je);return{value:Je,label:Ne?.label||Je,icon:Ne?.icon||"CheckSquare",color:Ne?.color}}if(a==="priority"){const Ne=d?.find(zt=>Number(zt.value)===Number(Je));return{value:Number.isFinite(Number(Je))?Number(Je):Je,label:Ne?.label||Je,icon:Ne?.icon||"Flag",color:Ne?.color}}if(a==="complexity")return{value:Number.isFinite(Number(Je))?Number(Je):Je,label:Je,icon:"Gauge"};if(a==="status")return{value:Je,label:Je,icon:"Circle"};if(a==="assignee"){const Ne=y.find(zt=>zt.value===Je);return{value:Je,label:Ne?.label||Je,icon:Ne?.icon==="HelpCircle"?"Circle":Ne?.icon,color:Ne?.color}}return{value:Je,label:Je}};for(const Ie of e){const Ke=Se(Ie);Ke&&(J.push(Ke),E.add(String(Ke.value)),l.add(Ke.label))}return J},[y,ue,a,t,d,e,i]),ae=r.useMemo(()=>[...t,...Tt],[Tt,t]),Ge=r.useMemo(()=>{const E=new Map;for(const l of ae)E.set(String(l.value),l),E.has(l.label)||E.set(l.label,l);return E},[ae]),ft=r.useMemo(()=>{const E={};return ae.forEach(J=>{E[String(J.value)]=0}),(le.length>0?le:e).forEach(J=>{let Se="";if(a==="status")Se=Ye(J);else if(a==="schedule")Se=Qe(J);else{const Ke=J[a];Se=String(Ke??"")}const Ie=Ge.get(Se);if(Ie&&E[String(Ie.value)]++,a==="schedule"){const Ke=J.status==="done"||J.status==="cancelled";J.scheduledDate&&!Ke&&J.scheduledDate<Ct&&Ge.has("expired")&&(E.expired=(E.expired||0)+1)}}),E},[le,e,ae,a,Ge,Ct]),it=r.useMemo(()=>{const E={};if(ae.forEach(l=>{E[String(l.value)]=[]}),e.forEach(l=>{let J="";if(a==="status")J=Ye(l);else if(a==="schedule")J=Qe(l);else{const Ie=l[a];J=String(Ie??"")}const Se=Ge.get(J);if(Se){if(a==="schedule"&&String(Se.value)==="backlog"&&!$e.has(l.id))return;E[String(Se.value)].push(l)}if(a==="schedule"){const Ie=l.status==="done"||l.status==="cancelled";l.scheduledDate&&!Ie&&l.scheduledDate<Ct&&E.expired&&E.expired.push(l)}}),a==="schedule"){const l=(Se,Ie)=>{const Ke=typeof Se.orderInDay=="number"?Se.orderInDay:Number.MAX_SAFE_INTEGER,Je=typeof Ie.orderInDay=="number"?Ie.orderInDay:Number.MAX_SAFE_INTEGER;return Ke!==Je?Ke-Je:String(Se.createdAt||"").localeCompare(String(Ie.createdAt||""))},J=(Se,Ie)=>ym(Se,Ie,Me,Pe,c);Object.keys(E).forEach(Se=>{if(Se==="backlog"||Se==="expired"){E[Se].sort(J);return}E[Se].sort(l)})}return E},[e,le,ae,a,Ge,$e,Ct,Me,Pe]),Mt=Y?Ae(Y):null,ht=Mt?e.find(E=>E.id===Mt):null,Ft=r.useRef(null),Et=r.useRef(null),We=r.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),tt=r.useRef(-1),Oe=(E,l)=>j?a==="category"?!$.includes(String(E)):a==="type"?!C.includes(String(E)):a==="priority"?!de.some(J=>Number(J)===Number(E)):a==="status"?String(E)==="completed"?!ke.includes("done")&&!ke.includes("cancelled"):!ke.includes(String(E)):a==="assignee"?!K.includes(String(E)):!1:!1,Ze=r.useMemo(()=>{let Se=0;return ae.forEach((Ie,Ke)=>{const Je=it[String(Ie.value)]||[],Ne=Oe(Ie.value,Ie.label),zt=a!=="schedule"&&se==="hide"&&Je.length===0;if(Ne||zt)return;const Yt=se==="collapse"&&Je.length===0;Se+=Yt?72:320,Se+=4}),Se},[ae,it,se,a,$,C,de,ke,K,j]),St=r.useCallback(E=>{if(!Te)return;const l=Math.max(0,Math.round(E));l!==tt.current&&(tt.current=l,Te(l))},[Te]);r.useEffect(()=>{const E=Ft.current,l=Et.current;if(!E||!l)return;let J=!1,Se=!1;const Ie=()=>{!E||Se||(J=!0,E.scrollLeft=l.scrollLeft,St(l.scrollLeft),setTimeout(()=>J=!1,0))},Ke=()=>{!l||J||(Se=!0,l.scrollLeft=E.scrollLeft,St(E.scrollLeft),setTimeout(()=>Se=!1,0))};return l.addEventListener("scroll",Ie),E.addEventListener("scroll",Ke),()=>{l.removeEventListener("scroll",Ie),E.removeEventListener("scroll",Ke)}},[St]);const ot=r.useRef(!1);r.useEffect(()=>{if(ot.current)return;if(typeof me!="number"||!Number.isFinite(me)){ot.current=!0;return}const E=Ft.current,l=Et.current;if(!E||!l)return;const J=Math.max(0,E.scrollWidth-E.clientWidth),Se=Math.min(Math.max(0,me),J);E.scrollLeft=Se,l.scrollLeft=Se,ot.current=!0},[me,Ze]),r.useEffect(()=>{const E=()=>{const l=Ft.current;if(!l){L(!1);return}L(l.scrollWidth>l.clientWidth+4)};return E(),window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E)}},[Ze,ae.length,it]),r.useEffect(()=>{const E=J=>{const Se=We.current;if(Se.pointerId===null||Se.pointerId!==J.pointerId)return;const Ie=J.clientX-Se.startX,Ke=J.clientY-Se.startY;if(!Se.didPan){if(Math.abs(Ie)<7||Math.abs(Ie)<Math.abs(Ke))return;Se.didPan=!0,Le(!0),document.body.style.userSelect="none"}const Je=Se.startScrollLeft-Ie;Ft.current&&(Ft.current.scrollLeft=Je),Et.current&&(Et.current.scrollLeft=Je),J.preventDefault()},l=()=>{const J=We.current;J.pointerId!==null&&(J.pointerId=null,J.didPan=!1,te&&(Le(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",E),window.addEventListener("pointerup",l),window.addEventListener("pointercancel",l),()=>{window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l),document.body.style.userSelect=""}},[te]);const re=E=>{!oe||E.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(We.current.pointerId=E.pointerId,We.current.startX=E.clientX,We.current.startY=E.clientY,We.current.startScrollLeft=Ft.current?.scrollLeft||0,We.current.didPan=!1)},Be=E=>{fe(E.active.id)},At=E=>{const l=st(E.active),J=String(E.over?.data?.current?.type||"");l.type==="task-card"&&J.startsWith("planning-")?vt.current=`${String(E.over?.id||"")}:${J}`:vt.current&&(vt.current=null)},Rt=E=>{const{active:l,over:J}=E;vt.current=null,fe(null);const Se=st(l),Ie=Se.type,Ke=String(J?.data?.current?.type||""),Je=Se.taskId,Ne=Se.workstreamId,zt=String(J?.data?.current?.workstreamId||""),Yt=String(J?.data?.current?.initiativeId||"");if(Ie==="task-card"&&Ke==="planning-workstream-target"&&Je&&zt){Z?.(Je,zt);return}if(Ie==="planning-workstream"){if(Ke==="planning-initiative-target"&&Ne&&Yt){x?.(Ne,Yt);return}return}const Pt=String(l.id),Wt=J?String(J.id):null,Dt=Ae(Pt);Wt&&Ae(Wt);const Ht=e.find(ge=>ge.id===Dt);if(!Ht||!Wt)return;const sn=Bt(Pt),Vn=String(l?.data?.current?.sortable?.containerId||"")||sn,Kn=String(J?.data?.current?.sortable?.containerId||"")||Bt(Wt);if(!Kn)return;const ga=Ge.get(Kn)||ae.find(ge=>String(ge.value)===Kn||ge.label===Kn);if(ga){if(a==="schedule"){const xe=String(ga.value),jt=Wt&&Re(Wt)?Ae(Wt):null,pt=J?.rect,An=l.rect.current.translated||l.rect.current.initial,vn=!!(pt&&An&&An.top+An.height/2>pt.top+pt.height/2),dn=(it[xe]||[]).filter(gt=>gt.id!==Dt),un=(it[String(Vn)]||[]).filter(gt=>gt.id!==Dt),Bn=M1({activeTask:Ht,sourceColumnId:Vn,targetColumnId:xe,targetTasks:dn,sourceTasks:un,overTaskId:jt,isBelowOverItem:vn,scheduleDates:dt.dates,parseToIsoWeekKey:dt.parseToIsoWeekKey,todayDate:Ct});if(!Bn)return;if(Bn.kind==="blocked"){window.alert(Bn.reason);return}Bn.updates.forEach(({taskId:gt,updates:cr})=>k(gt,cr)),Bn.selectedDate&&ce?.(Bn.selectedDate);return}let ge=ga.value;if(a==="status"){const xe=String(ge),jt=T1(Ht,xe,new Date().toISOString());jt&&k(Ht.id,jt);return}(a==="priority"||a==="complexity")&&(ge=Number(ge));const at=Ht[a];if(String(at??"")!==String(ge??"")){const xe={[a]:ge};k(Ht.id,xe)}}},Bt=E=>{if(Ge.has(E)){const Se=Ge.get(E);return Se?String(Se.value):E}if(a==="schedule"&&E.startsWith(nm))return"expired";const l=Ae(E),J=e.find(Se=>Se.id===l);if(J){let Se="";a==="status"?Se=Ye(J):a==="schedule"?Se=Qe(J):Se=String(J[a]??"");const Ie=Ge.get(Se);return Ie?String(Ie.value):null}return null},Ve={sideEffects:fv({styles:{active:{opacity:"0"}}})},Ot=E=>{try{const l=uv(E);if(l.length>0){const J=l.find(zt=>String(zt.id).startsWith("planning-"));if(J)return[J];const Se=E.pointerCoordinates;if(!Se)return[l[0]];const Ie=l.filter(zt=>{const Yt=String(zt.id);return Re(Yt)&&Yt!==Y});if(Ie.length===0){const Yt=l.filter(Dt=>{const Ht=String(Dt.id);return!Re(Ht)}).find(Dt=>!!Bt(String(Dt.id)))||null,Pt=Yt?Bt(String(Yt.id)):null,Wt=(E.droppableContainers||[]).filter(Dt=>{const Ht=String(Dt.id);return!Re(Ht)||Ht===Y?!1:Pt?Bt(Ht)===Pt:!0});if(Wt.length>0){const Dt=ah({...E,droppableContainers:Wt});if(Dt.length>0)return[Dt[0]]}return Yt?[Yt]:[l[0]]}const Ke=Ie;let Je=Ke[0],Ne=Number.POSITIVE_INFINITY;for(const zt of Ke){const Yt=E.droppableRects?.get(zt.id);if(!Yt)continue;const Pt=Yt.left+Yt.width/2,Wt=Yt.top+Yt.height/2,Dt=Se.x-Pt,Ht=Se.y-Wt,sn=Dt*Dt+Ht*Ht;sn<Ne&&(Ne=sn,Je=zt)}return[Je]}return ah(E)}catch(l){return console.error("[TaskKanban] collision detection error",l),[]}},yt={searchQuery:s,copiedId:o,taxonomies:c,types:i,priorities:d,approaches:m,assigneeOptions:y,onCopyId:g,onToggleInProgress:v,onToggleReview:_,onToggleComplete:I,onToggleCancel:A,onSetStatus:D,onArchiveTask:U,onUnarchive:W,onDelete:Q,onOpenTaskById:h,categories:ue,readOnlyMode:G,changedTaskIdSet:X,resolveTaskHierarchy:ne,groupBy:a,showStatusLabel:b};return n.jsxs(_g,{sensors:kt,collisionDetection:Ot,onDragStart:Be,onDragOver:At,onDragEnd:Rt,onDragCancel:E=>{vt.current=null,fe(null)},children:[Ee,n.jsxs("div",{className:f.kanbanWrapper,children:[n.jsx("div",{ref:Et,className:`${f.kanbanTopScroll} tf-scrollbar`,children:n.jsx("div",{className:f.kanbanTopScrollSpacer,style:{width:`${Ze}px`}})}),n.jsx("div",{className:f.kanbanContainer,ref:Ft,children:ae.map(E=>{const l=it[String(E.value)]||[],J=Oe(E.value,E.label),Se=a!=="schedule"&&se==="hide"&&l.length===0,Ie=a==="schedule",Ke=Ie&&ae.some(Ht=>String(Ht.value)==="backlog"),Je=Ie&&String(E.value)==="backlog",Ne=Ie&&String(E.value)==="expired",zt=it.backlog||[],Pt=se==="collapse"&&zt.length===0?72:320,Wt=Je?0:Ne?Ke?Pt+4:0:void 0,Dt=Je?6:Ne?5:void 0;return J||Se?null:n.jsx(D1,{id:String(E.value),title:E.label,color:E.color,icon:E.icon,tasks:l,activeId:Y,activeTaskId:Mt,totalCount:ft[String(E.value)],onAddTask:()=>ie?.(a,E.value),onTaskClick:S,commonCardProps:yt,collapseEmpty:se==="collapse",compressed:ye,onHeaderPointerDown:re,isHeaderPanning:te,headerPanEnabled:oe,stickyLeft:Wt,stickyZIndex:Dt,isPast:!!E.isPast,isSelected:!!E.isSelected,isWeekend:!!E.isWeekend,disableSorting:!1,scheduleDate:a==="schedule"?dt.dates[String(E.value)]:void 0,onScheduleDaySelected:ce},String(E.value))})})]}),Xi.createPortal(n.jsx(dv,{dropAnimation:Ve,children:ht?(()=>{const{taskWorkstream:E,taskInitiative:l}=ne(ht);return n.jsx(xd,{task:ht,taskWorkstream:E,taskInitiative:l,isOverlay:!0,...yt,isArchived:ht.isArchived,categories:ue,compressed:ye,isRecentlyChanged:X.has(ht.id)})})():null}),document.body)]})}function D1({id:e,title:t,color:a,icon:s,tasks:o,activeId:c=null,activeTaskId:i=null,totalCount:d,onAddTask:m,onTaskClick:y,commonCardProps:k,collapseEmpty:S,compressed:h,onHeaderPointerDown:g,isHeaderPanning:v=!1,headerPanEnabled:_=!1,stickyLeft:I,stickyZIndex:A,isPast:D=!1,isSelected:U=!1,isWeekend:W=!1,disableSorting:Q=!1,scheduleDate:le,onScheduleDaySelected:ie}){const{setNodeRef:se}=uf({id:e,data:{type:"Column"}}),$=S&&o.length===0,C=i?o.filter(H=>H.id!==i):o,de=typeof I=="number",ke=r.useRef(null),K=H=>e==="expired"?`${nm}${H}`:H,j=H=>{if(!le||!ie)return;const ue=H.target;ue&&(ue.closest('[data-task-card="true"]')||ue.closest(`.${f.kanbanCardWrapper}`)||ie(le))};return n.jsxs("div",{ref:se,className:`${f.kanbanColumn} ${$?f.kanbanColumnCollapsed:""} ${de?f.kanbanColumnSticky:""} ${D?f.kanbanColumnPast:""} ${U?f.kanbanColumnSelectedDay:""} ${W?f.kanbanColumnWeekend:""}`,style:de?{left:`${I}px`,zIndex:A??4}:void 0,onClick:j,children:[n.jsxs("div",{className:`${f.kanbanHeader} ${_?f.kanbanHeaderDraggable:""} ${v?f.kanbanHeaderPanning:""}`,style:{borderTopColor:Ma(a)||"var(--color-purple)"},onPointerDown:g,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const H=s&&rc[s]?rc[s]:Io,ue=Ma(a)||"var(--color-purple)";return n.jsx(H,{size:16,style:{color:ue}})})(),!$&&n.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!$||d>0)&&n.jsx("span",{className:f.kanbanCount,children:$?d:`${o.length} / ${d}`}),!k.readOnlyMode&&n.jsx("button",{className:"tf-control-icon tf-control-icon-compact",onClick:H=>{H.stopPropagation(),m()},title:`Add task to ${t}`,"aria-label":`Add task to ${t}`,"data-no-header-pan":"true",children:n.jsx(to,{size:14})})]})]}),n.jsx("div",{className:f.kanbanDroppable,children:n.jsx("div",{className:`${f.kanbanDroppableScroll} ${f.appScrollbar} tf-scrollbar`,ref:ke,children:Q?C.map(H=>n.jsx("div",{className:f.kanbanCardWrapper,children:(()=>{const{taskWorkstream:ue,taskInitiative:ye}=k.resolveTaskHierarchy?.(H)||{};return n.jsx(xd,{task:H,taskWorkstream:ue,taskInitiative:ye,onClick:y,...k,isArchived:H.isArchived,readOnlyMode:k.readOnlyMode||null,compressed:h,isRecentlyChanged:!1})})()},H.id)):n.jsx(Cg,{id:e,items:C.map(H=>K(H.id)),strategy:Ag,children:C.map(H=>n.jsx(L1,{sortableId:K(H.id),task:H,onClick:y,commonCardProps:k,compressed:h,isRecentlyChanged:k.changedTaskIdSet?.has(H.id)},K(H.id)))})})})]})}function L1({sortableId:e,task:t,onClick:a,commonCardProps:s,compressed:o,isRecentlyChanged:c=!1}){const i=!!s?.readOnlyMode,{attributes:d,listeners:m,setNodeRef:y,transform:k,transition:S,isDragging:h}=Ig({id:e,disabled:i,data:{type:"task-card",taskId:t.id}}),g={transform:df.Transform.toString(k),transition:S,opacity:h?0:1,pointerEvents:h?"none":"auto"},v=s?.groupBy==="schedule",_=!v&&c;return n.jsx("div",{ref:y,style:g,...i?{}:d,...i?{}:m,className:`${f.kanbanCardWrapper} ${_?f.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:I,taskInitiative:A}=s.resolveTaskHierarchy?.(t)||{};return n.jsx(xd,{task:t,taskWorkstream:I,taskInitiative:A,onClick:a,...s,isArchived:t.isArchived,readOnlyMode:s?.readOnlyMode||null,compressed:o,isRecentlyChanged:v?!1:c})})()})}function B1(e,t,a){const s=String(t);if(e==="category"){const o=a.categories.find(c=>String(c.value)===s||c.label===s);return o?{category:o.label}:{}}if(e==="type")return{type:s};if(e==="priority")return Number.isFinite(Number(t))?{priority:Number(t)}:{};if(e==="complexity")return Number.isFinite(Number(t))?{complexity:Number(t)}:{};if(e==="approach"){const o=a.approaches.find(c=>String(c.value)===s||c.label===s);return o?{approach:o.value,taxonomyApproach:o.value}:{}}return e==="assignee"?s.trim().length>0?{assignee:s}:{}:e==="status"?s==="completed"?{status:"done"}:s==="task"||s==="on-hold"||s==="in-progress"||s==="review"||s==="done"||s==="cancelled"?{status:s}:{}:e==="schedule"?s==="backlog"||s==="expired"?{}:{scheduledDate:s}:{}}function W1(e){switch(e){case"auth-required":return{summary:"Sync is paused until you sign in again.",recommendedAction:"Sign in, then press Sync to retry."};case"attach-cloud":return{summary:"This workspace still needs its first cloud pull before local pushes can run.",recommendedAction:"Keep this window open for the first cloud pull. If it seems stuck, press Repair."};case"provision-local":return{summary:"This workspace is still doing its first cloud upload before normal pulls can run.",recommendedAction:"Keep this window open until the first cloud upload finishes."};case"repair-active":return{summary:"Repair is already running for this workspace.",recommendedAction:"Wait for repair to finish before retrying sync."};case"retry-pending":return{summary:"Sync hit a temporary problem and is waiting for its scheduled retry.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."};case"push-in-flight":case"pull-in-flight":return{summary:"A sync request is already running for this workspace.",recommendedAction:"Wait for the current sync request to finish."};case"lease-held":return{summary:"Another local window is already syncing this workspace.",recommendedAction:"Use a single local window for sync, or close the other syncing window."};case"invalid-workspace":return{summary:"Workspace setup is required before sync can run.",recommendedAction:"Open or create a named workspace before retrying sync."};case"cloud-auth-unconfigured":return{summary:"Cloud sync is unavailable because cloud authentication is not configured.",recommendedAction:"Configure cloud authentication before turning on sync."};case"runtime-not-local":return{summary:"Workspace sync controls are only available in the local runtime.",recommendedAction:"Open this workspace in the local app to manage sync."};case"sync-disabled":return{summary:"Workspace sync is currently turned off.",recommendedAction:"Turn on sync when you are ready to connect this workspace to cloud."};default:return null}}function F1(e){const t=e.runtimeMode==="local"&&e.isAuthenticated;if(t){const a=W1(e.retryBlockedReason||e.pullBlockedReason||e.pushBlockedReason||null);return{actionable:t,status:e.workspaceSyncStatus,syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:a?.summary||e.workspaceSyncSummary,recommendedAction:a?.recommendedAction||e.workspaceSyncRecommendedAction,lastError:e.workspaceSyncError}}return{actionable:t,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."}}function _m(e,t){return e==="deleted"?!1:e==="archived"?t:!t}function Kh(e,t){return t===null?e:e.filter(a=>t.has(a.id))}function O1(e,t,a){const s=t.filter(d=>_m(a,!!d.isArchived)),o=a==="deleted"?[]:e.filter(d=>_m(a,!!d.isArchived)).map(d=>({...d,workstreams:s.filter(m=>m.initiativeId===d.id)})),c=s.filter(d=>!d.initiativeId),i=[...o.flatMap(d=>d.workstreams),...c];return{initiatives:o,standaloneWorkstreams:c,visibleWorkstreams:i,initiativeById:new Map(o.map(d=>[d.id,d])),workstreamById:new Map(i.map(d=>[d.id,d]))}}function $y(e){return typeof e.occurredAt=="string"&&e.occurredAt.trim().length>0?e.occurredAt:"unknown-time"}function $1(e){return typeof e.eventType=="string"&&e.eventType.trim().length>0?e.eventType.trim():"sync"}function U1(e){const t=Nm(e.details),a=t?t.source:null;return typeof a=="string"?a.trim():""}function Zh(e){const t=String(e||"").trim();switch(t){case"auth-required":return"sign in required";case"lease-held":return"another window is already syncing";case"sync-disabled":return"sync is turned off";case"attach-cloud":return"initial cloud pull required";case"provision-local":return"initial cloud upload required";default:return t.length>0?t.replace(/-/g," "):"blocked"}}function Yh(e){const t=String(e||"").trim();switch(t){case"attach-cloud":return"initial cloud pull";case"provision-local":return"initial cloud upload";case"active":return"active sync";case"error":return"error recovery";case"idle":return"idle sync";default:return t.length>0?t.replace(/-/g," "):"sync"}}function z1(e){const t=$y(e),a=Nm(e.details),s=U1(e);return s==="retry.blocked"?`${t} manual retry blocked: ${Zh(a?.reason)} during ${Yh(a?.phase)}`:s==="repair.started"?`${t} manual repair started: ${Yh(a?.repairPhase)} selected`:s==="repair.blocked"?`${t} manual repair blocked: ${Zh(a?.reason)}`:null}function rl(e,t=0){const a=String(e.id??"").trim();return a?`id:${a}`:[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(),Cw(e.details),String(t)].join("|")}function H1(e,t,a=15){const s=new Map;for(const[o,c]of e.entries())s.set(rl(c,o),c);for(const[o,c]of t.entries())s.set(rl(c,o),c);return Array.from(s.values()).sort((o,c)=>String(c.occurredAt||"").localeCompare(String(o.occurredAt||""))).slice(0,Math.max(1,a))}function G1(e,t){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a+=1)if(rl(e[a],a)!==rl(t[a],a))return!1;return!0}function Uy(e){const t=z1(e);if(t)return t;const a=$y(e),s=$1(e),o=e.status==="error"?"failed":"succeeded",c=Number(e.changeCount),i=Number.isFinite(c)?` (${Math.max(0,Math.floor(c))} change${Math.floor(c)===1?"":"s"})`:"",d=Number(e.requestMs),m=Number.isFinite(d)?` in ${Math.max(0,Math.floor(d))}ms`:"",y=Number(e.statusCode),k=Number.isFinite(y)?` [${Math.floor(y)}]`:"",S=typeof e.errorMessage=="string"&&e.errorMessage.trim().length>0?`: ${e.errorMessage.trim()}`:"";return`${a} ${s} ${o}${i}${m}${k}${S}`}function nf(e){if(!e)return"Never";const t=new Date(e);return Number.isNaN(t.getTime())?"Never":t.toLocaleString()}function V1(e){switch(e){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)"}}}function zy(e,t,a){if(t)return"Repairing";if(a&&e==="error")return"Recovering";switch(e){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"}}function q1(e){return[{label:"AI profile snapshot",value:`${e.aiProfileSnapshotCount} local profile${e.aiProfileSnapshotCount===1?"":"s"}`},{label:"AI profile raw response",value:`${e.aiProfileSnapshotRawCount} from route`},{label:"Last pushed AI profiles",value:`${e.lastPushedAiProfileCount} tracked`},{label:"AI watermark map",value:`${e.lastPushedAiProfileWatermarkCount} tracked`},{label:"Document snapshot",value:`${e.documentSnapshotCount} local doc${e.documentSnapshotCount===1?"":"s"}`},{label:"Asset snapshot",value:`${e.assetSnapshotCount} local asset${e.assetSnapshotCount===1?"":"s"}`},{label:"Queued full AI sync",value:e.forceFullAiProfilePushQueued?"Yes":"No"},{label:"AI snapshot last fetch",value:nf(e.aiProfileSnapshotLastFetchAt)},{label:"AI snapshot fetch error",value:e.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:e.aiProfileSnapshotLastSkipReason||"None"}]}function K1({syncRecentEvents:e,syncRecentEventsError:t,syncRecentEventsLoading:a}){return a&&e.length===0?[{key:"loading",text:"Loading recent sync events...",tone:"muted"}]:t?[{key:"error",text:t,tone:"error"}]:e.length===0?[{key:"empty",text:"No recent sync events recorded.",tone:"muted"}]:e.map((s,o)=>({key:rl(s,o),text:Uy(s),tone:s.status==="error"?"error":"default"}))}function Hy(e){const t=[];for(const a of e){if(String(a.errorMessage||"").toLowerCase().includes("reference number mismatch")){t.push(a);continue}if(String(a.status||"").toLowerCase()==="success")break}return t}function Z1(e){return Hy(e).length}function Y1(e){return Hy(e).map((t,a)=>{const s=t.details&&typeof t.details=="object"?t.details:null,o=String(s?.path||"").trim(),c=String(s?.referenceLabel||"").trim(),i=String(s?.taskTitle||s?.existingTaskTitle||"").trim(),d=Number(s?.existingReferenceNumber),m=Number(s?.incomingReferenceNumber),y=o||i||c||`Mismatch ${a+1}`,k=Number.isFinite(d)||Number.isFinite(m)?`Existing ${Number.isFinite(d)?d:"?"} vs incoming ${Number.isFinite(m)?m:"?"}`:c?`Both claimed ${c}`:null;return{key:rl(t,a),pathLabel:y,refsLabel:k}})}function J1({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:a,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:c,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:k,referenceMismatchCount:S,syncRecentEvents:h}){const g=["Taskforce Sync Manager",`Workspace ID: ${e}`,`Status: ${t}`,`Summary: ${a}`,`Recommended action: ${s}`,`Last successful sync: ${o}`,`Last pull from cloud: ${c}`,`Last push to cloud: ${i}`,`Last error at: ${nf(d.lastErrorAt)}`,`Pending local changes: ${m}`,`Last error: ${y}`,`Sync stage: ${k}`,`Push blocked reason: ${d.pushBlockedReason||"None"}`,`Pull blocked reason: ${d.pullBlockedReason||"None"}`,`Retry blocked reason: ${d.retryBlockedReason||"None"}`,`Repair active: ${d.repairActive?"Yes":"No"}`,`Push in flight: ${d.pushInFlight?"Yes":"No"}`,`Pull in flight: ${d.pullInFlight?"Yes":"No"}`,`Retry pending: ${d.retryPending?"Yes":"No"}`,`AI profile snapshot: ${d.aiProfileSnapshotCount}`,`AI profile raw response: ${d.aiProfileSnapshotRawCount}`,`Last pushed AI profiles tracked: ${d.lastPushedAiProfileCount}`,`AI profile watermarks tracked: ${d.lastPushedAiProfileWatermarkCount}`,`AI snapshot last fetch: ${nf(d.aiProfileSnapshotLastFetchAt)}`,`AI snapshot fetch error: ${d.aiProfileSnapshotLastFetchError||"None"}`,`AI snapshot skip reason: ${d.aiProfileSnapshotLastSkipReason||"None"}`,`Document snapshot: ${d.documentSnapshotCount}`,`Asset snapshot: ${d.assetSnapshotCount}`,`Reference mismatches detected: ${S}`,`Queued full AI sync: ${d.forceFullAiProfilePushQueued?"Yes":"No"}`],v=h.map(_=>Uy(_));return[...g,"","Recent sync events",...v.length>0?v:["No recent sync events recorded."]].join(`
|
|
5
|
+
`)}const Jh="/api/taskforce/account/profile-summary",Q1=9e4,Zc=new Map;function Ju(){return typeof performance<"u"?performance.now():Date.now()}function Gy(e,t){const a=String(e||"").trim();if(!a)return"";const s=String(t||"").trim();return s?`${a}::${s}`:a}function Qh(e,t){Zc.delete(Gy(e,t?.identityKey))}async function X1(e,t){const a=String(e||"").trim(),s=Gy(e,t?.identityKey);if(!s||!a)return null;const o=t?.force===!0,c=Date.now(),i=Zc.get(s);if(!o&&i?.payload!==void 0&&c-i.fetchedAt<Q1)return Ut("account_profile_summary_cache_hit",{url:a,cacheKey:s,ageMs:c-i.fetchedAt}),i.payload;if(!o&&i?.promise)return Ut("account_profile_summary_request_reused",{url:a,cacheKey:s}),i.promise;const d=Ju(),m=(async()=>{const y=await fetch(a,{method:"GET",credentials:"include"});if(!y.ok)throw new Error(String((await y.json().catch(()=>({})))?.error||"Failed to load account summary."));const S=await y.json().catch(()=>({}))||null;return Zc.set(s,{payload:S,fetchedAt:Date.now(),promise:null}),Ut("account_profile_summary_loaded",{url:a,cacheKey:s,durationMs:Math.round(Ju()-d),fromCache:!1}),S})().catch(y=>{const k=i?.payload??null;if(k)return Zc.set(s,{payload:k,fetchedAt:i?.fetchedAt??Date.now(),promise:null}),Ut("account_profile_summary_failed",{url:a,cacheKey:s,durationMs:Math.round(Ju()-d),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!0}),k;throw Zc.delete(s),Ut("account_profile_summary_failed",{url:a,cacheKey:s,durationMs:Math.round(Ju()-d),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!1}),y});return Zc.set(s,{payload:i?.payload??null,fetchedAt:i?.fetchedAt??0,promise:m}),m}const eW=1024,tW=5*1024*1024,nW=[.9,.82,.74,.66,.58],aW=[.9,.82,.74,.66,.58],rW=[1,.85,.7,.55,.4],sW=new Set(["image/png","image/jpeg","image/webp"]);function oW(e,t){const a=document.createElement("canvas");return a.width=Math.max(1,Math.round(e)),a.height=Math.max(1,Math.round(t)),a}async function iW(e){const t=URL.createObjectURL(e);try{const a=await new Promise((s,o)=>{const c=new Image;c.onload=()=>s(c),c.onerror=()=>o(new Error("Failed to load image.")),c.src=t});return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,source:a}}finally{URL.revokeObjectURL(t)}}async function cW(e){const t=oW(e.width,e.height),a=t.getContext("2d");if(!a)throw new Error("Image optimization requires a 2D canvas context.");return a.drawImage(e.image.source,0,0,t.width,t.height),await new Promise((s,o)=>{t.toBlob(c=>{if(c){s(c);return}o(new Error("Failed to encode resized image."))},e.type,e.quality)})}const lW={loadImage:iW,renderToBlob:cW};function Xh(e,t){return e==="image/png"?".png":e==="image/jpeg"?".jpg":e==="image/webp"?".webp":(t.includes(".")?t.slice(t.lastIndexOf(".")):"")||".img"}function eg(e,t){const a=String(e||"").trim();if(!a)return`avatar${t}`;const s=a.lastIndexOf(".");return s<=0?`${a}${t}`:`${a.slice(0,s)}${t}`}function dW(e){const t=e==="image/jpeg"?"image/jpeg":"image/webp";return Array.from(new Set([t,"image/webp","image/jpeg"]))}function uW(e){return e==="image/webp"?nW:e==="image/jpeg"?aW:[void 0]}async function mW(e,t,a=lW){const s=Number.isFinite(t?.maxBytes)&&(t?.maxBytes||0)>0?Math.floor(t?.maxBytes):tW,o=Number.isFinite(t?.maxDimension)&&(t?.maxDimension||0)>0?Math.floor(t?.maxDimension):eW;if(e.size<=s)return{file:e,optimized:!1,exceededLimit:!1};if(!sW.has(e.type))return{file:e,optimized:!1,exceededLimit:!0};const c=await a.loadImage(e),i=Math.max(c.width,c.height,1),d=Math.min(1,o/i);let m=null;for(const k of rW){const S=Math.min(1,d*k),h=Math.max(1,Math.round(c.width*S)),g=Math.max(1,Math.round(c.height*S));for(const v of dW(e.type))for(const _ of uW(v)){const I=await a.renderToBlob({image:c,width:h,height:g,type:v,quality:_});if((!m||I.size<m.size)&&(m=I),I.size<=s)return{file:new File([I],eg(e.name,Xh(I.type||v,e.name)),{type:I.type||v,lastModified:e.lastModified}),optimized:!0,exceededLimit:!1}}}if(!m)return{file:e,optimized:!1,exceededLimit:!0};const y=new File([m],eg(e.name,Xh(m.type||e.type,e.name)),{type:m.type||e.type,lastModified:e.lastModified});return{file:y,optimized:y.size<e.size,exceededLimit:y.size>s}}const af="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Vy="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",tg="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function pW({projectName:e,currentWorkspaceId:t,brandLabel:a="TaskForce",brandHomeLabel:s="Go to Kanban",onBrandClick:o,runtimeMode:c="local",theme:i=im,meta:d,actions:m}){const y=r.useRef(null),k=r.useRef(null),[S,h]=r.useState(!0),g=Eg(i)?Vy:af,v=String(e||"").trim(),_=String(t||"").trim(),I=_.toLowerCase(),A=!!(v&&(c!=="cloud"||I&&I!=="default")),D=r.useCallback(()=>{if(!A){h(!0);return}const ie=y.current,se=k.current;if(!ie||!se)return;const $=ie.getBoundingClientRect().width,C=se.getBoundingClientRect().width;if($<=0||C<=0)return;const de=window.getComputedStyle(ie),ke=Number.parseFloat(de.columnGap||de.gap||"0")||0,K=Array.from(ie.children).filter(ue=>{if(ue===se)return!1;const ye=ue.getBoundingClientRect();return ye.width>0&&ye.height>0}),H=K.reduce((ue,ye)=>ue+ye.getBoundingClientRect().width,0)+C+ke*K.length;h(H<=$)},[A]);r.useLayoutEffect(()=>{D();const ie=y.current,se=k.current;if(!ie||!se)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",D),()=>window.removeEventListener("resize",D);const $=new ResizeObserver(D);return $.observe(ie),$.observe(se),()=>$.disconnect()},[D,v,d]);const U=A&&S,W=()=>{if(!_||typeof navigator>"u")return;const ie=navigator.clipboard;ie?.writeText&&ie.writeText(_).catch(()=>{})},Q=ie=>{ie.key!=="Enter"&&ie.key!==" "||(ie.preventDefault(),W())},le=n.jsxs(n.Fragment,{children:[n.jsx("img",{src:g,alt:"Taskforce Logo",className:f.brandIcon,onError:ie=>{const se=ie.currentTarget;se.src!==tg?se.src=tg:se.style.display="none"}}),n.jsx("span",{children:a}),c==="cloud"&&n.jsx("span",{className:f.brandCloudSuffix,children:"HQ"})]});return n.jsxs("div",{className:`${f.header} ${tn.standaloneHeader}`,children:[n.jsxs("div",{ref:y,className:`${f.headerTitle} ${tn.standaloneTitle}`,children:[o?n.jsx("button",{type:"button",className:f.brandHomeButton,onClick:o,title:s,"aria-label":s,children:le}):n.jsx("span",{className:f.brandHomeStatic,children:le}),A&&n.jsxs("span",{ref:k,className:`${f.projectNameGroup} ${U?"":f.projectNameGroupHidden}`.trim(),"aria-hidden":U?void 0:!0,children:[n.jsx("span",{className:f.projectSlash,children:"/"}),n.jsx("span",{className:f.projectName,title:U&&_?`Workspace ID: ${_}`:void 0,role:U&&_?"button":void 0,tabIndex:U&&_?0:void 0,onClick:W,onMouseDown:ie=>ie.preventDefault(),onKeyDown:Q,children:v})]}),d]}),n.jsx("div",{className:f.headerActions,style:{gap:"16px"},children:m})]})}function fW({value:e,placeholder:t,active:a=!1,onChange:s,onClear:o,clearTitle:c}){return n.jsxs("div",{className:f.searchContainer,style:{width:"240px"},children:[n.jsx(Hk,{size:16,className:f.searchIcon}),n.jsx("input",{type:"text",className:`${f.searchInput} ${a?f.searchActive:""}`,placeholder:t,value:e,onChange:i=>s(i.target.value)}),e&&o&&n.jsx("button",{className:f.clearSearchBtn,onClick:o,title:c,children:n.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function ng({label:e,value:t,options:a,onChange:s,trailingAction:o,width:c}){return n.jsxs("div",{className:f.groupByContainer,style:c?{width:c}:void 0,children:[n.jsx("span",{className:f.groupByLabel,children:e}),n.jsx("select",{className:`${f.select} ${f.groupBySelect}`,value:t,onChange:i=>s(i.target.value),children:a.map(i=>n.jsx("option",{value:i.value,children:i.label},String(i.value)))}),o]})}function Np({actions:e}){return n.jsx(n.Fragment,{children:e.map(t=>n.jsx("button",{className:`tf-control-icon ${t.active?"tf-control-icon-active":""} ${t.className||""}`.trim(),onClick:t.onClick,title:t.title,disabled:t.disabled,"aria-disabled":t.ariaDisabled,children:t.icon},t.key))})}function ag(){return n.jsx("div",{className:f.headerDivider})}function hW({icon:e,label:t,onClick:a,disabled:s=!1}){return n.jsxs("button",{className:f.primaryUpdateBtn,onClick:a,disabled:s,children:[e," ",t]})}function Pf({children:e}){return n.jsx("div",{className:f.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 gW(){return n.jsx(Pf,{children:n.jsx("div",{"aria-hidden":"true",style:{minHeight:"32px",flex:1}})})}function yW({categoryFilterOptions:e,typeFilterOptions:t,priorities:a,taxonomyDisplayLabels:s,filterCategories:o,setFilterCategories:c,filterTypes:i,setFilterTypes:d,filterPriorities:m,setFilterPriorities:y,filterStatus:k,setFilterStatus:S,filterAssignees:h,setFilterAssignees:g,assigneeOptions:v,initiativeFilterOptions:_=[],selectedInitiativeId:I="",setSelectedInitiativeId:A=()=>{},workstreamFilterOptions:D=[],selectedWorkstreamId:U="",setSelectedWorkstreamId:W=()=>{},taskScope:Q,setTaskScope:le,showArchive:ie,setShowArchive:se,fetchArchive:$,onDeleteAllDeleted:C,clearFilters:de}){return n.jsxs(n.Fragment,{children:[n.jsx(Ay,{}),n.jsx(Ji,{label:s?.category||qe("standalone.categoryLabel"),options:e,selected:o,onChange:ke=>c(ke),variant:"value"}),n.jsx(Ji,{label:s?.type||qe("standalone.typeLabel"),options:t,selected:i,onChange:ke=>d(ke),variant:"value"}),n.jsx(Ji,{label:s?.priority||qe("standalone.priorityLabel"),options:a,selected:m,onChange:ke=>y(ke),variant:"value"}),n.jsx(Ji,{label:qe("standalone.statusLabel"),options:Xs,selected:k,onChange:ke=>S(ke),variant:"value"}),n.jsx(Ji,{label:qe("standalone.assigneeLabel"),options:v,selected:h,onChange:ke=>g(ke),variant:"value"}),n.jsx("div",{className:f.headerDivider,style:{height:"16px",margin:"0 8px"}}),n.jsx(Fh,{label:"Initiative",options:_,selected:I,onChange:A,allLabel:"All Initiatives",title:"Filter by initiative"}),n.jsx(Fh,{label:"Workstream",options:D,selected:U,onChange:W,allLabel:"All Workstreams",title:"Filter by workstream"}),n.jsx(Iy,{scope:Q,onScopeChange:ke=>{le(ke),ke==="archived"?(se(!0),$()):ie&&se(!1)},className:f.groupByContainer,labelClassName:f.groupByLabel}),n.jsx("div",{style:{flex:1}}),Q==="deleted"&&C&&n.jsx(Ty,{onClick:C,className:`${f.bulkArchiveBtn} ${f.taskToolbarAction} ${f.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),n.jsx(xy,{onClick:de})]})}function kW(e){return n.jsx(Pf,{children:n.jsx(yW,{...e})})}const am=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],rm=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function vW({typeFilters:e,setTypeFilters:t,attachmentFilters:a,setAttachmentFilters:s,clearFilters:o}){return n.jsxs(Pf,{children:[n.jsx(Ay,{}),n.jsx(Ji,{label:"Attachment",options:rm,selected:a,onChange:c=>s(c),variant:"value"}),n.jsx(Ji,{label:"Type",options:am,selected:e,onChange:c=>t(c),variant:"value"}),n.jsx("div",{style:{flex:1}}),n.jsx(xy,{onClick:o})]})}const SW="_drawerBody_pra12_1",wW="_paneShell_pra12_9",bW="_collapsedPaneShell_pra12_18",_W="_collapsedPaneHeader_pra12_27",CW="_collapsedPaneLabel_pra12_39",AW="_treePane_pra12_49",xW="_treePaneSplit_pra12_59",IW="_detailPane_pra12_63",TW="_paneHeader_pra12_73",RW="_paneHeaderLabel_pra12_87",NW="_paneContent_pra12_96",jW="_sectionTitle_pra12_105",PW="_sectionHeaderRow_pra12_113",MW="_headerActionGroup_pra12_120",EW="_toggleActive_pra12_127",DW="_sectionGroup_pra12_133",LW="_treeList_pra12_158",BW="_treeChildren_pra12_164",WW="_treeRow_pra12_172",FW="_treeRowDetailOpen_pra12_184",OW="_treeRowDropReady_pra12_190",$W="_treeRowDropActive_pra12_194",UW="_treeRowDropMode_pra12_200",zW="_treeChevron_pra12_200",HW="_rowButton_pra12_201",GW="_detailsButton_pra12_202",VW="_treeRowDragging_pra12_206",qW="_treeChevronPlaceholder_pra12_230",KW="_rowContent_pra12_252",ZW="_rowTopRow_pra12_262",YW="_referenceBadgeButton_pra12_271",JW="_referenceBadgeStatic_pra12_277",QW="_rowTitle_pra12_298",XW="_rowMeta_pra12_312",eF="_detailsButtonActive_pra12_340",tF="_emptyPanel_pra12_347",nF="_emptyPanelTitle_pra12_356",aF="_emptyPanelText_pra12_362",rF="_sectionNote_pra12_368",sF="_detailHero_pra12_375",oF="_detailReferenceRow_pra12_382",iF="_detailTitle_pra12_389",cF="_detailDescription_pra12_396",lF="_detailActionRow_pra12_407",dF="_metricGrid_pra12_414",uF="_metricCard_pra12_421",mF="_editorCard_pra12_426",pF="_editorField_pra12_433",fF="_editorLabel_pra12_439",hF="_editorHint_pra12_445",gF="_editorActions_pra12_450",yF="_metricValue_pra12_456",kF="_metricLabel_pra12_463",vF="_progressTrack_pra12_470",SF="_progressFill_pra12_478",wF="_listCard_pra12_484",bF="_activityTimelineList_pra12_493",_F="_activityTimelineEmpty_pra12_502",CF="_deferredPanelFallback_pra12_506",AF="_sectionDropReady_pra12_532",xF="_sectionDropActive_pra12_537",IF="_sectionDropMode_pra12_543",TF="_attachReferenceRow_pra12_547",RF="_attachReferenceInput_pra12_554",NF="_attachReferenceSubmit_pra12_559",jF="_listItem_pra12_585",PF="_listItemButton_pra12_594",MF="_detailCardButton_pra12_603",EF="_listItemText_pra12_608",DF="_listItemTitle_pra12_623",LF="_listItemMeta_pra12_637",BF="_detailChildCard_pra12_642",WF="_detailChildCardArchived_pra12_654",FF="_detailChildCardTopRow_pra12_659",OF="_detailChildReferenceRow_pra12_668",$F="_taskStatusIcon_pra12_675",_e={drawerBody:SW,paneShell:wW,collapsedPaneShell:bW,collapsedPaneHeader:_W,collapsedPaneLabel:CW,treePane:AW,treePaneSplit:xW,detailPane:IW,paneHeader:TW,paneHeaderLabel:RW,paneContent:NW,sectionTitle:jW,sectionHeaderRow:PW,headerActionGroup:MW,toggleActive:EW,sectionGroup:DW,treeList:LW,treeChildren:BW,treeRow:WW,treeRowDetailOpen:FW,treeRowDropReady:OW,treeRowDropActive:$W,treeRowDropMode:UW,treeChevron:zW,rowButton:HW,detailsButton:GW,treeRowDragging:VW,treeChevronPlaceholder:qW,rowContent:KW,rowTopRow:ZW,referenceBadgeButton:YW,referenceBadgeStatic:JW,rowTitle:QW,rowMeta:XW,detailsButtonActive:eF,emptyPanel:tF,emptyPanelTitle:nF,emptyPanelText:aF,sectionNote:rF,detailHero:sF,detailReferenceRow:oF,detailTitle:iF,detailDescription:cF,detailActionRow:lF,metricGrid:dF,metricCard:uF,editorCard:mF,editorField:pF,editorLabel:fF,editorHint:hF,editorActions:gF,metricValue:yF,metricLabel:kF,progressTrack:vF,progressFill:SF,listCard:wF,activityTimelineList:bF,activityTimelineEmpty:_F,deferredPanelFallback:CF,sectionDropReady:AF,sectionDropActive:xF,sectionDropMode:IF,attachReferenceRow:TF,attachReferenceInput:RF,attachReferenceSubmit:NF,listItem:jF,listItemButton:PF,detailCardButton:MF,listItemText:EF,listItemTitle:DF,listItemMeta:LF,detailChildCard:BF,detailChildCardArchived:WF,detailChildCardTopRow:FF,detailChildReferenceRow:OF,taskStatusIcon:$F},UF="_header_c26na_1",zF="_title_c26na_31",HF="_icon_c26na_40",jp={header:UF,title:zF,icon:HF};function GF({label:e,count:t,showZeroCount:a=!1,expanded:s,expandedTitle:o,collapsedTitle:c,onToggle:i,className:d=""}){const m=typeof t=="number"&&(a||t>0),y=s?sl:tl;return n.jsxs("button",{type:"button",className:`${jp.header} ${d}`.trim(),onClick:i,"aria-expanded":s,title:s?o:c,children:[n.jsxs("span",{className:jp.title,children:[e,m?` (${t})`:""]}),n.jsx(y,{className:jp.icon,size:14,"aria-hidden":"true"})]})}const VF=ze.lazy(()=>gs(()=>import("./EntityActivityTimeline-B8nSe8l3.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),qF=ze.lazy(()=>gs(()=>import("./ContextAttachmentManager-DsXPTvi-.js"),__vite__mapDeps([8,1,9,2,3,4,5])).then(e=>({default:e.ContextAttachmentManager}))),md=332,Qs=392,Pp=56;function qy(e,t,a,s,o){return(e?Pp:md)+(t?a?Pp:Qs:0)+(s?o?Pp:Qs:0)}function KF(e,t){const a=String(t||"").trim(),s=new Map;for(const o of e){const c=String(o?.value||"").trim();if(!c||c==="unassigned"||typeof o.archivedAt=="string"&&o.archivedAt.trim().length>0)continue;const i=String(o.label||c).trim()||c,d=String(o.kind||"").trim().toLowerCase(),m=String(o.username||"").trim().toLowerCase(),y=d==="agent"?`agent:${m||i.toLowerCase()}`:`value:${c}`;(!s.has(y)||c===a)&&s.set(y,{...o,value:c,label:i})}return Array.from(s.values()).sort((o,c)=>o.label.localeCompare(c.label,void 0,{sensitivity:"base"}))}function Mp(e){return e?e.split(/[-_\s]+/g).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):"No status"}function pd({label:e,entityType:t,interactive:a=!0}){const[s,o]=ze.useState(!1),c=ze.useCallback(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),window.setTimeout(()=>o(!1),1200)}catch{o(!1)}},[e]);return a?n.jsx(hy,{copied:s,label:e,onClick:c,title:`Copy ${t} reference`,ariaLabel:s?`Copied ${t} reference`:`Copy ${t} reference`,className:_e.referenceBadgeButton,children:e}):n.jsx("span",{className:`${f.taskIdBadge} ${_e.referenceBadgeStatic}`.trim(),children:n.jsx("span",{children:e})})}function Ep({rowId:e,rowType:t,referenceLabel:a,title:s,meta:o,active:c,detailOpen:i=!1,canExpand:d=!1,expanded:m=!1,onToggleExpand:y,onToggleScope:k,onToggleDetails:S}){const{active:h}=Tg(),g=String(h?.data?.current?.type||""),v=t==="workstream"&&g==="task-card",_=t==="initiative"&&g==="planning-workstream",I=t==="workstream"?"planning-workstream-target":"planning-initiative-target",{setNodeRef:A,isOver:D}=uf({id:`${I}:${e}`,data:t==="workstream"?{type:I,workstreamId:e}:{type:I,initiativeId:e}}),U=t==="workstream",{attributes:W,listeners:Q,setNodeRef:le,transform:ie,isDragging:se}=hv({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!U}),$=U&&ie?{transform:df.Translate.toString(ie)}:void 0,C=v||_;return n.jsxs("div",{ref:A,style:$,className:`${_e.treeRow} ${i?_e.treeRowDetailOpen:""} ${C?_e.treeRowDropReady:""} ${D?_e.treeRowDropActive:""} ${se?_e.treeRowDragging:""} ${C?_e.treeRowDropMode:""}`,children:[d?n.jsx("button",{type:"button",className:_e.treeChevron,onClick:y,title:m?"Collapse workstreams":"Expand workstreams",children:m?n.jsx(sl,{size:15}):n.jsx(tl,{size:15})}):n.jsx("span",{className:`${_e.treeChevron} ${_e.treeChevronPlaceholder}`,"aria-hidden":"true"}),n.jsxs("div",{className:_e.rowContent,children:[n.jsxs("div",{className:_e.rowTopRow,children:[a?n.jsx(pd,{label:a,entityType:t}):n.jsx("span",{"aria-hidden":"true"}),n.jsx("button",{type:"button",className:`${_e.detailsButton} ${c?_e.detailsButtonActive:""}`,onClick:k,title:c?"Clear board scope":"Scope board to this item",children:n.jsx(Sg,{size:14})})]}),n.jsxs("button",{type:"button",ref:U?le:void 0,className:_e.rowButton,onClick:S,...U?W:{},...U?Q:{},children:[n.jsx("span",{className:_e.rowTitle,children:s}),n.jsx("span",{className:_e.rowMeta,children:o})]})]})]})}function Dp({label:e,onExpand:t}){return n.jsx("div",{className:`${_e.paneShell} ${_e.collapsedPaneShell}`.trim(),children:n.jsxs("div",{className:_e.collapsedPaneHeader,children:[n.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:`Expand ${e}`,children:n.jsx(tl,{size:16})}),n.jsx("span",{className:_e.collapsedPaneLabel,children:e})]})})}function rg(){return n.jsxs("div",{className:_e.deferredPanelFallback,"aria-hidden":"true",children:[n.jsx("span",{}),n.jsx("span",{}),n.jsx("span",{})]})}function ZF({initiatives:e,standaloneWorkstreams:t,allStandaloneWorkstreams:a=t,activeInitiativeId:s,activeWorkstreamId:o,expandedInitiativeIds:c,detail:i,secondaryPane:d,onCreateInitiative:m,onCreateWorkstream:y,onToggleInitiative:k,onSelectInitiative:S,onSelectWorkstream:h,onOpenInitiativeDetails:g,onOpenWorkstreamDetails:v}){const[_,I]=ze.useState(!1),A=ze.useCallback(W=>{if(!_)return W.workstreams;const Q=new Set(W.workstreams.map(ie=>ie.id)),le=(W.allWorkstreams||[]).filter(ie=>!!ie.isArchived&&!Q.has(ie.id));return[...W.workstreams,...le]},[_]),D=ze.useMemo(()=>{if(!_)return t;const W=new Set(t.map(le=>le.id)),Q=a.filter(le=>!!le.isArchived&&!W.has(le.id));return[...t,...Q]},[a,_,t]),U=ze.useMemo(()=>{const W=e.reduce((le,ie)=>le+(ie.allWorkstreams||[]).filter(se=>!!se.isArchived).length,0),Q=a.filter(le=>!!le.isArchived).length;return W+Q},[a,e]);return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:_e.sectionGroup,children:[n.jsxs("div",{className:_e.sectionHeaderRow,children:[n.jsx("div",{className:_e.sectionTitle,children:"Initiatives"}),n.jsxs("div",{className:_e.headerActionGroup,children:[U>0?n.jsx("button",{type:"button",className:`tf-control-icon ${_?_e.toggleActive:""}`.trim(),title:_?"Hide archived workstreams in tray":"Show archived workstreams in tray","aria-label":_?"Hide archived workstreams in tray":"Show archived workstreams in tray","aria-pressed":_,onClick:()=>I(W=>!W),children:_?n.jsx(lf,{size:15}):n.jsx(vg,{size:15})}):null,n.jsx("button",{type:"button",className:"tf-control-icon",title:"Create initiative","aria-label":"Create initiative",onClick:m,children:n.jsx(to,{size:15})})]})]}),n.jsx("div",{className:_e.treeList,children:e.length===0?n.jsxs("div",{className:_e.emptyPanel,children:[n.jsx("div",{className:_e.emptyPanelTitle,children:"No initiatives yet"}),n.jsxs("div",{className:_e.emptyPanelText,children:["Initiatives give larger efforts a clear home without crowding the task board. Use the ",n.jsx("code",{children:"+"})," action above to create the first one."]})]}):e.map(W=>{const Q=c.has(W.id),le=A(W),ie=W.workstreamCount||0,se=le.filter(de=>!!de.isArchived).length,C=`${_&&se>0?`${ie} workstreams + ${se} archived`:`${ie} workstreams`} • ${W.taskCount} tasks${W.isArchived?" • archived":""}`;return n.jsxs("div",{children:[n.jsx(Ep,{rowId:W.id,rowType:"initiative",referenceLabel:rs(W),title:W.title,meta:C,active:s===W.id&&!o,detailOpen:i?.type==="initiative"&&i.item.id===W.id,canExpand:le.length>0,expanded:Q,onToggleExpand:()=>k(W.id),onToggleScope:()=>S(W.id),onToggleDetails:()=>{if(i?.type==="initiative"&&i.item.id===W.id){g("");return}g(W.id)}}),Q&&le.length>0&&n.jsx("div",{className:_e.treeChildren,children:le.map(de=>n.jsx(Ep,{rowId:de.id,rowType:"workstream",referenceLabel:Ro(de),title:de.title,meta:`${de.taskCount} tasks • ${de.progressPercent}% complete${de.isArchived?" • archived":""}`,active:o===de.id,detailOpen:i?.type==="workstream"&&i.item.id===de.id||d?.kind==="detail"&&d.detail.item.id===de.id,onToggleScope:()=>h(de.id,W.id),onToggleDetails:()=>{if(d?.kind==="detail"&&d.detail.item.id===de.id){v("");return}if(i?.type==="workstream"&&i.item.id===de.id){v("");return}v(de.id)}},de.id))})]},W.id)})})]}),n.jsxs("div",{className:_e.sectionGroup,children:[n.jsxs("div",{className:_e.sectionHeaderRow,children:[n.jsx("div",{className:_e.sectionTitle,children:"Workstreams"}),n.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:y,children:n.jsx(to,{size:15})})]}),n.jsx("div",{className:_e.treeList,children:D.length===0?n.jsxs("div",{className:_e.emptyPanel,children:[n.jsx("div",{className:_e.emptyPanelTitle,children:"No standalone workstreams yet"}),n.jsxs("div",{className:_e.emptyPanelText,children:["Smaller projects can still use workstreams without needing initiative-level structure. Use the ",n.jsx("code",{children:"+"})," action above to add one."]})]}):D.map(W=>n.jsx(Ep,{rowId:W.id,rowType:"workstream",referenceLabel:Ro(W),title:W.title,meta:`${W.taskCount} tasks • ${W.progressPercent}% complete${W.isArchived?" • archived":""}`,active:o===W.id,detailOpen:i?.type==="workstream"&&i.item.id===W.id||d?.kind==="detail"&&d.detail.item.id===W.id,onToggleScope:()=>h(W.id,null),onToggleDetails:()=>{if(i?.type==="workstream"&&i.item.id===W.id){v("");return}v(W.id)}},W.id))})]})]})}function sg({detail:e,currentWorkspaceId:t,onOpenNestedWorkstreamDetails:a,onEdit:s,onArchive:o,onUnarchive:c,onCreateTaskInWorkstream:i,onCreateWorkstreamInInitiative:d,onOpenTaskById:m,onRemoveTaskFromWorkstream:y,onAssignInitiativeToWorkstream:k,onAttachTaskToWorkstreamByReference:S,onAttachWorkstreamToInitiativeByReference:h,onAddPlanningContextFile:g,onRemovePlanningContextFile:v,onUpdatePlanningContextCaption:_,parentInitiative:I=null,assigneeOptions:A}){const[D,U]=ze.useState(""),[W,Q]=ze.useState(!1),[le,ie]=ze.useState(!1),[se,$]=ze.useState(!0),{active:C}=Tg(),de=String(C?.data?.current?.type||""),ke=e.type==="workstream"&&de==="task-card",K=e.type==="initiative"&&de==="planning-workstream",j=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:H,isOver:ue}=uf({id:`${j}:detail:${e.item.id}`,data:e.type==="initiative"?{type:j,initiativeId:e.item.id}:{type:j,workstreamId:e.item.id}}),ye=e.type==="initiative"?"Workstreams":"Tasks",G=ze.useMemo(()=>{if(e.type!=="initiative")return[];const L=new Set(e.item.workstreams.map(M=>M.id)),X=(e.item.allWorkstreams||[]).filter(M=>!!M.isArchived&&!L.has(M.id));return[...e.item.workstreams,...X]},[e.item,e.type]),je=ze.useMemo(()=>e.type!=="workstream"?[]:e.item.tasks||[],[e.item,e.type]),be=e.type==="initiative"?G.filter(L=>!!L.isArchived).length:je.filter(L=>!!L.isArchived).length,ce=le?G:G.filter(L=>!L.isArchived),me=le?je:je.filter(L=>!L.isArchived),Te=e.type==="initiative"?"Initiative":"Workstream",Me=e.type==="initiative"?rs(e.item):Ro(e.item);ze.useEffect(()=>{U(""),Q(!1),ie(!1),$(!0)},[e.item.id,e.type]);const Pe=e.type==="initiative"?!!h:!!S,Ee=!!D.trim()&&Pe&&!W,Z=ze.useCallback(async()=>{const L=D.trim();if(!L||W)return;const X=e.type==="initiative"?h:S;if(X){Q(!0);try{await X(e.item.id,L)!==!1&&U("")}finally{Q(!1)}}},[D,e.item.id,e.type,W,S,h]),x=e.type==="initiative"?"Attach workstream to initiative":"Attach task to workstream",b=e.type==="initiative"?"archived workstreams":"archived tasks",R=e.type==="workstream"&&I?rs(I):"",B=ze.useMemo(()=>{const L=new Map;for(const X of A){const M=String(X.value||"").trim();M&&(L.set(M,X),L.set(M.toLowerCase(),X))}return L},[A]),Y=ze.useCallback((L,X,M)=>{if(M&&M.trim())return M.trim();const V=String(L||"").trim();if(!V)return X==="ai"?"AI Agent":"You";const ne=B.get(V)||B.get(V.toLowerCase());return ne?.label?ne.label:V},[B]),fe=ze.useCallback(L=>{const X=String(L.actorId||"").trim(),M=B.get(X)||B.get(X.toLowerCase()),V=L.actorProfile||M||null,ne=L.actorType==="system"?"system":L.actorType==="ai"||V?.kind==="ai"||M?.kind==="agent"?"agent":L.actorType==="human"||V?.kind==="human"||M?.kind==="member"?"member":L.fallbackKind||"member",Ce=String(V&&"icon"in V&&V.icon?V.icon:ne==="agent"?"Bot":ne==="member"?"User":"ClipboardList"),Ae=rc[Ce]||(ne==="agent"?sm:ne==="member"?fi:gg);return{kind:ne,label:ne==="system"?"System":Y(X,ne==="agent"?"ai":"human",V&&"label"in V&&V.label||null),color:V&&"color"in V&&V.color||void 0,ActorIcon:Ae}},[B,Y]),te=ze.useCallback((L,X)=>{const M=String(X||"").trim();if(M){if(L==="ownerId")return B.get(M)?.label||B.get(M.toLowerCase())?.label||M;if(L==="initiativeId"&&I&&M===I.id)return rs(I)||I.title}},[B,I]),oe=ze.useMemo(()=>Cy({activity:e.item.activity,comments:e.item.comments}),[e.item.activity,e.item.comments]).length;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:_e.detailHero,children:[Me?n.jsxs("div",{className:_e.detailReferenceRow,children:[e.type==="workstream"?n.jsxs(n.Fragment,{children:[n.jsx(Qi,{onClick:L=>{if(L.stopPropagation(),R){k?.(e.item.id,null);return}s()},title:R?"Remove from initiative":"Attach to initiative",ariaLabel:R?"Remove from initiative":"Attach to initiative",children:R?n.jsx(Qu,{size:13}):n.jsx(om,{size:13})}),n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),R?n.jsxs(n.Fragment,{children:[n.jsx(pd,{label:R,entityType:"initiative"}),n.jsx("span",{className:f.taskHierarchyDivider,children:"/"})]}):null]}):null,n.jsx(pd,{label:Me,entityType:e.type})]}):null,n.jsx("h3",{className:_e.detailTitle,children:e.item.title}),n.jsx("p",{className:_e.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.")}),n.jsx("div",{className:_e.progressTrack,"aria-label":`${e.item.progressPercent}% complete`,children:n.jsx("div",{className:_e.progressFill,style:{width:`${e.item.progressPercent}%`}})}),n.jsxs("div",{className:_e.detailActionRow,children:[n.jsx("button",{type:"button",className:f.secondaryHeaderBtn,onClick:s,children:n.jsxs("span",{children:["Edit ",Te]})}),e.item.isArchived?n.jsx("button",{type:"button",className:f.secondaryHeaderBtn,onClick:c,children:n.jsx("span",{children:"Unarchive"})}):n.jsx("button",{type:"button",className:f.secondaryHeaderBtn,onClick:o,children:n.jsx("span",{children:"Archive"})})]})]}),n.jsxs("div",{className:_e.metricGrid,children:[n.jsxs("div",{className:_e.metricCard,children:[n.jsx("span",{className:_e.metricValue,children:e.item.taskCount}),n.jsx("span",{className:_e.metricLabel,children:"Tasks in scope"})]}),n.jsxs("div",{className:_e.metricCard,children:[n.jsx("span",{className:_e.metricValue,children:e.item.completedTaskCount}),n.jsx("span",{className:_e.metricLabel,children:"Done / terminal"})]}),n.jsxs("div",{className:_e.metricCard,children:[n.jsx("span",{className:_e.metricValue,children:e.item.ownerLabel||"Unassigned"}),n.jsx("span",{className:_e.metricLabel,children:"Owner"})]}),n.jsxs("div",{className:_e.metricCard,children:[n.jsx("span",{className:_e.metricValue,children:(e.item.commentCount||0)+(e.item.attachmentCount||0)}),n.jsx("span",{className:_e.metricLabel,children:"Context items"})]})]}),n.jsxs("div",{ref:H,className:`${_e.listCard} ${ke||K?_e.sectionDropReady:""} ${ue?_e.sectionDropActive:""} ${ke||K?_e.sectionDropMode:""}`.trim(),children:[n.jsxs("div",{className:_e.sectionHeaderRow,children:[n.jsx("div",{className:_e.sectionTitle,children:ye}),n.jsxs("div",{className:_e.headerActionGroup,children:[be>0?n.jsx("button",{type:"button",className:`tf-control-icon ${le?_e.toggleActive:""}`.trim(),title:le?`Hide ${b}`:`Show ${b}`,"aria-label":le?`Hide ${b}`:`Show ${b}`,"aria-pressed":le,onClick:()=>ie(L=>!L),children:le?n.jsx(lf,{size:15}):n.jsx(vg,{size:15})}):null,e.type==="initiative"?n.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream in this initiative","aria-label":"Create workstream in this initiative",onClick:()=>d?.(e.item.id),children:n.jsx(to,{size:15})}):n.jsx("button",{type:"button",className:"tf-control-icon",title:"Create task in this workstream","aria-label":"Create task in this workstream",onClick:()=>i?.(e.item.id),children:n.jsx(to,{size:15})})]})]}),n.jsxs("div",{className:_e.attachReferenceRow,children:[n.jsx(Qi,{onClick:L=>{L.stopPropagation(),Z()},disabled:!Ee,title:x,ariaLabel:x,children:n.jsx(om,{size:13})}),n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),n.jsx("input",{type:"text",className:`${f.input} ${_e.attachReferenceInput}`.trim(),placeholder:e.type==="initiative"?"Paste workstream reference (e.g. WS-123)":"Paste task reference (e.g. T-123)",disabled:W,value:D,onChange:L=>U(L.target.value),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),Z())}}),n.jsx("button",{type:"button",className:_e.attachReferenceSubmit,disabled:!Ee,onClick:()=>{Z()},children:W?"Attaching":"Attach"})]}),e.type==="initiative"?ce.length>0?ce.map(L=>{const X=Ro(L),M=()=>a?.(L.id);return n.jsx("div",{className:`${_e.listItemButton} ${_e.detailCardButton}`.trim(),children:n.jsxs("div",{className:`${_e.listItem} ${_e.detailChildCard} ${L.isArchived?_e.detailChildCardArchived:""}`.trim(),children:[n.jsx("div",{className:_e.detailChildCardTopRow,children:n.jsxs("div",{className:_e.detailChildReferenceRow,children:[n.jsx(Qi,{onClick:V=>{V.stopPropagation(),k?.(L.id,null)},title:"Remove from initiative",ariaLabel:"Remove from initiative",children:n.jsx(Qu,{size:13})}),n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),X?n.jsx(pd,{label:X,entityType:"workstream"}):n.jsx("span",{"aria-hidden":"true"})]})}),n.jsxs("div",{role:"button",tabIndex:0,className:_e.listItemText,onClick:M,onKeyDown:V=>{V.key!=="Enter"&&V.key!==" "||(V.preventDefault(),M())},children:[n.jsx("span",{className:_e.listItemTitle,children:L.title}),n.jsxs("span",{className:_e.listItemMeta,children:[L.taskCount," tasks • ",L.progressPercent,"% complete",L.isArchived?" • archived":""]})]})]})},L.id)}):n.jsxs("div",{className:_e.emptyPanel,children:[n.jsx("div",{className:_e.emptyPanelTitle,children:"No workstreams yet"}),n.jsx("div",{className:_e.emptyPanelText,children:"Add the first workstream to break the initiative into clearer lanes of execution."})]}):me.length>0?[...me].sort((L,X)=>{const M=yd(L.status).value==="done",V=yd(X.status).value==="done";return M===V?0:M?1:-1}).map(L=>{const X=L.referenceNumber?`T-${L.referenceNumber}`:"",M=yd(L.status),V=rc[M.icon||"Square"],ne=Ma(M.color)||"var(--text-secondary)",Ce=()=>m?.(L.id),Ae=`${Mp(L.status)}${L.isArchived?" • archived":""}`;return n.jsx("div",{className:`${_e.listItemButton} ${_e.detailCardButton}`.trim(),children:n.jsxs("div",{className:`${_e.listItem} ${_e.detailChildCard} ${L.isArchived?_e.detailChildCardArchived:""}`.trim(),children:[n.jsxs("div",{className:_e.detailChildCardTopRow,children:[n.jsxs("div",{className:_e.detailChildReferenceRow,children:[n.jsx(Qi,{onClick:Re=>{Re.stopPropagation(),y?.(L.id,e.item.id)},title:"Remove from workstream",ariaLabel:"Remove from workstream",children:n.jsx(Qu,{size:13})}),n.jsx("span",{className:f.taskHierarchyDivider,children:"/"}),X?n.jsx(pd,{label:X,entityType:"task"}):n.jsx("span",{"aria-hidden":"true"})]}),n.jsx("span",{className:_e.taskStatusIcon,style:{color:ne},"aria-label":M.shortLabel||Mp(L.status),title:M.shortLabel||Mp(L.status),children:V?n.jsx(V,{size:18,strokeWidth:2.4}):null})]}),n.jsxs("div",{role:"button",tabIndex:0,className:_e.listItemText,onClick:Ce,onKeyDown:Re=>{Re.key!=="Enter"&&Re.key!==" "||(Re.preventDefault(),Ce())},children:[n.jsx("span",{className:_e.listItemTitle,children:L.title}),n.jsx("span",{className:_e.listItemMeta,children:Ae})]})]})},L.id)}):n.jsxs("div",{className:_e.sectionNote,children:["No tasks are linked to this workstream yet. Use the ",n.jsx("code",{children:"+"})," action above to add the first one."]})]}),n.jsx("div",{className:_e.listCard,children:n.jsx(ze.Suspense,{fallback:n.jsx(rg,{}),children:n.jsx(qF,{ownerType:e.type,ownerId:e.item.id,ownerReferenceLabel:Me,workspaceId:t,attachments:e.item.attachments||[],onAddAttachment:L=>g?.(e.type,e.item.id,L),onRemoveAttachment:L=>v?.(e.type,e.item.id,L),onUpdateAttachmentCaption:(L,X)=>_?.(e.type,e.item.id,L,X)})})}),n.jsxs("div",{className:_e.listCard,children:[n.jsx(GF,{label:"Recent Activity",count:oe,showZeroCount:!0,expanded:se,expandedTitle:"Hide recent activity",collapsedTitle:"Show recent activity",onToggle:()=>$(L=>!L)}),se?n.jsx(ze.Suspense,{fallback:n.jsx(rg,{}),children:n.jsx(VF,{activity:e.item.activity,comments:e.item.comments,formatFieldValue:te,resolveActorPresentation:fe,onOpenTaskById:m,emptyMessage:`No ${e.type} activity yet.`,listClassName:_e.activityTimelineList,emptyClassName:_e.activityTimelineEmpty})}):null]})]})}function og({editor:e,draftTitle:t,draftDescription:a,draftOwner:s,draftInitiativeId:o,assigneeOptions:c,draftInitiativeSummary:i,onChangeDraftTitle:d,onChangeDraftDescription:m,onChangeDraftOwner:y,onChangeDraftInitiativeId:k,onCancel:S,onSubmit:h,isSubmitting:g,onAssignInitiativeToWorkstream:v}){const _=e.entityType==="initiative"?"Initiative":"Workstream",I=g?e.mode==="create"?`Creating ${_}...`:`Saving ${_}...`:e.mode==="create"?`Create ${_}`:`Save ${_}`,A=ze.useMemo(()=>KF(c,s),[c,s]),D=ze.useCallback(W=>{W.preventDefault(),h()},[h]),U=ze.useCallback(()=>{e.mode!=="edit"||e.entityType!=="workstream"||v?.(e.targetId)},[e,v]);return n.jsxs("form",{className:_e.editorCard,onSubmit:D,children:[n.jsxs("div",{className:_e.editorField,children:[n.jsx("label",{className:_e.editorLabel,children:"Title"}),n.jsx("input",{className:f.input,disabled:g,value:t,onChange:W=>d(W.target.value),placeholder:e.entityType==="initiative"?"Q3 Product Launch":"Content Production"})]}),n.jsxs("div",{className:_e.editorField,children:[n.jsx("label",{className:_e.editorLabel,children:"Description"}),n.jsx("textarea",{className:f.textarea,disabled:g,value:a,onChange:W=>m(W.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"&&n.jsxs("div",{className:_e.editorField,children:[n.jsx("label",{className:_e.editorLabel,children:"Initiative"}),i&&n.jsxs("div",{className:_e.editorHint,children:["Current: ",i.title]}),n.jsxs("div",{className:_e.attachReferenceRow,children:[e.mode==="edit"&&n.jsxs(n.Fragment,{children:[n.jsx(Qi,{onClick:W=>{W.stopPropagation(),U()},disabled:g||!o.trim(),title:"Attach workstream to initiative",ariaLabel:"Attach workstream to initiative",children:n.jsx(om,{size:13})}),n.jsx("span",{className:f.taskHierarchyDivider,children:"/"})]}),n.jsx("input",{type:"text",className:`${f.input} ${_e.attachReferenceInput}`.trim(),disabled:g,placeholder:"Paste initiative reference (e.g. IN-123)",value:o,onChange:W=>k(W.target.value),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),U())}})]})]}),n.jsxs("div",{className:_e.editorField,children:[n.jsx("label",{className:_e.editorLabel,children:"Owner"}),n.jsxs("select",{className:`${f.select} ${f.groupBySelect}`,disabled:g,value:s,onChange:W=>y(W.target.value),children:[n.jsx("option",{value:"",children:"Unassigned"}),A.map(W=>n.jsx("option",{value:W.value,children:W.label},W.value))]})]}),n.jsxs("div",{className:_e.editorActions,children:[n.jsx("button",{type:"button",className:f.secondaryHeaderBtn,onClick:S,disabled:g,children:"Cancel"}),n.jsx("button",{type:"submit",className:f.primaryUpdateBtn,disabled:g,children:I})]})]})}function YF({open:e,leftOffset:t=0,initiatives:a,standaloneWorkstreams:s,allStandaloneWorkstreams:o,activeInitiativeId:c,activeWorkstreamId:i,expandedInitiativeIds:d,detail:m,editor:y,secondaryPane:k,currentWorkspaceId:S,assigneeOptions:h,draftInitiativeSummary:g,draftTitle:v,draftDescription:_,draftOwner:I,draftInitiativeId:A,onChangeDraftTitle:D,onChangeDraftDescription:U,onChangeDraftOwner:W,onChangeDraftInitiativeId:Q,onCollapseTreePane:le,onExpandTreePane:ie,onCollapsePrimaryPane:se,onExpandPrimaryPane:$,onCollapseSecondaryPane:C,onExpandSecondaryPane:de,onBackFromSecondary:ke,treeCollapsed:K,primaryCollapsed:j,secondaryCollapsed:H,onCancelEditor:ue,onSubmitEditor:ye,isSubmittingEditor:G,onCreateInitiative:je,onCreateWorkstream:be,onToggleInitiative:ce,onSelectInitiative:me,onSelectWorkstream:Te,onOpenInitiativeDetails:Me,onOpenWorkstreamDetails:Pe,onOpenNestedWorkstreamDetails:Ee,onEditInitiative:Z,onEditWorkstream:x,onArchiveInitiative:b,onUnarchiveInitiative:R,onArchiveWorkstream:B,onUnarchiveWorkstream:Y,onCreateTaskInWorkstream:fe,onCreateWorkstreamInInitiative:te,onAssignInitiativeToWorkstream:Le,onOpenTaskById:oe,onRemoveTaskFromWorkstream:L,onAttachTaskToWorkstreamByReference:X,onAttachWorkstreamToInitiativeByReference:M,onAddPlanningContextFile:V,onRemovePlanningContextFile:ne,onUpdatePlanningContextCaption:Ce}){const Ae=!!(m||y),Re=!!k,$e=qy(K,Ae,j,Re,H),vt=y?y.entityType==="initiative"?y.mode==="create"?"New Initiative":"Edit Initiative":y.mode==="create"?"New Workstream":"Edit Workstream":m?.type==="initiative"?"Initiative":"Workstream",st=k?.kind==="editor"?k.editor.mode==="create"?"New Workstream":"Edit Workstream":"Workstream",kt=ze.useCallback(Ye=>{const Ct=String(Ye.initiativeId||"").trim();return Ct&&a.find(dt=>dt.id===Ct)||null},[a]);return n.jsx("aside",{style:{position:"absolute",top:0,left:e?`${t}px`:`${t-$e-24}px`,bottom:0,width:`${$e}px`,minWidth:`${$e}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:n.jsxs("div",{className:_e.drawerBody,children:[K?n.jsx(Dp,{label:"Planning",onExpand:ie}):n.jsxs("div",{className:`${_e.paneShell} ${f.appScrollbar} tf-scrollbar ${_e.treePane} ${Ae&&!j?_e.treePaneSplit:""}`.trim(),style:{flex:`0 0 ${md}px`,width:`${md}px`,minWidth:`${md}px`,maxWidth:`${md}px`},children:[n.jsxs("div",{className:_e.paneHeader,children:[n.jsx("span",{className:_e.paneHeaderLabel,children:"Planning"}),n.jsx("button",{type:"button",className:"tf-control-icon",onClick:le,children:n.jsx(To,{size:16})})]}),n.jsx("div",{className:_e.paneContent,children:n.jsx(ZF,{initiatives:a,standaloneWorkstreams:s,allStandaloneWorkstreams:o,activeInitiativeId:c,activeWorkstreamId:i,expandedInitiativeIds:d,detail:m,secondaryPane:k,onCreateInitiative:je,onCreateWorkstream:be,onToggleInitiative:ce,onSelectInitiative:me,onSelectWorkstream:Te,onOpenInitiativeDetails:Me,onOpenWorkstreamDetails:Pe})})]}),Ae&&(j?n.jsx(Dp,{label:vt,onExpand:$}):n.jsxs("div",{className:`${_e.paneShell} ${f.appScrollbar} tf-scrollbar ${_e.detailPane}`.trim(),style:{flex:`0 0 ${Qs}px`,width:`${Qs}px`,minWidth:`${Qs}px`,maxWidth:`${Qs}px`},children:[n.jsxs("div",{className:_e.paneHeader,children:[n.jsx("span",{className:_e.paneHeaderLabel,children:vt}),n.jsx("button",{type:"button",className:"tf-control-icon",onClick:se,children:n.jsx(To,{size:16})})]}),n.jsx("div",{className:_e.paneContent,children:y?n.jsx(og,{editor:y,draftTitle:v,draftDescription:_,draftOwner:I,draftInitiativeId:A,assigneeOptions:h,draftInitiativeSummary:g,onChangeDraftTitle:D,onChangeDraftDescription:U,onChangeDraftOwner:W,onChangeDraftInitiativeId:Q,onCancel:ue,onSubmit:ye,isSubmitting:G,onAssignInitiativeToWorkstream:Le}):m?n.jsx(sg,{detail:m,currentWorkspaceId:S,assigneeOptions:h,onOpenNestedWorkstreamDetails:m.type==="initiative"?Ee:void 0,onCreateTaskInWorkstream:m.type==="workstream"?fe:void 0,onCreateWorkstreamInInitiative:m.type==="initiative"?te:void 0,onOpenTaskById:m.type==="workstream"?oe:void 0,onRemoveTaskFromWorkstream:m.type==="workstream"?L:void 0,onAssignInitiativeToWorkstream:Le,onAttachTaskToWorkstreamByReference:m.type==="workstream"?X:void 0,onAttachWorkstreamToInitiativeByReference:m.type==="initiative"?M:void 0,parentInitiative:m.type==="workstream"?kt(m.item):null,onEdit:()=>m.type==="initiative"?Z(m.item.id):x(m.item.id),onArchive:()=>m.type==="initiative"?b(m.item.id):B(m.item.id),onUnarchive:()=>m.type==="initiative"?R(m.item.id):Y(m.item.id),onAddPlanningContextFile:V,onRemovePlanningContextFile:ne,onUpdatePlanningContextCaption:Ce}):null})]})),Re&&(H?n.jsx(Dp,{label:st,onExpand:de}):n.jsxs("div",{className:`${_e.paneShell} ${f.appScrollbar} tf-scrollbar ${_e.detailPane}`.trim(),style:{flex:`0 0 ${Qs}px`,width:`${Qs}px`,minWidth:`${Qs}px`,maxWidth:`${Qs}px`},children:[n.jsxs("div",{className:_e.paneHeader,children:[n.jsx("span",{className:_e.paneHeaderLabel,children:st}),n.jsx("button",{type:"button",className:"tf-control-icon",onClick:C,children:n.jsx(To,{size:16})})]}),n.jsx("div",{className:_e.paneContent,children:k?.kind==="editor"?n.jsx(og,{editor:k.editor,draftTitle:v,draftDescription:_,draftOwner:I,draftInitiativeId:A,assigneeOptions:h,draftInitiativeSummary:g,onChangeDraftTitle:D,onChangeDraftDescription:U,onChangeDraftOwner:W,onChangeDraftInitiativeId:Q,onCancel:ke,onSubmit:ye,isSubmitting:G,onAssignInitiativeToWorkstream:Le}):k?n.jsx(sg,{detail:k.detail,currentWorkspaceId:S,assigneeOptions:h,onCreateTaskInWorkstream:fe,onOpenTaskById:oe,onRemoveTaskFromWorkstream:L,onAssignInitiativeToWorkstream:Le,onAttachTaskToWorkstreamByReference:X,parentInitiative:kt(k.detail.item),onEdit:()=>x(k.detail.item.id),onArchive:()=>B(k.detail.item.id),onUnarchive:()=>Y(k.detail.item.id),onAddPlanningContextFile:V,onRemovePlanningContextFile:ne,onUpdatePlanningContextCaption:Ce}):null})]}))]})})}const JF={"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:!1,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"}},kd="annotated_attachments.workspace_access",vd="documents.workspace_access",Cm="workflows.workspace_access",Am="agents.workspace_access",ig="initiatives.workspace_access",QF=Object.entries(JF).reduce((e,[t,a])=>(e[t]={key:t,enabled:!!a.enabled,description:String(a.description||""),owner:String(a.owner||""),removalMilestone:String(a.removalMilestone||"")},e),{});function XF(e){const t=String(e||"").trim();return t&&QF[t]||null}function eO(e){const t=XF(e);return t?t.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 od(e){return eO(e.featureKey)}const tO=["tasks","docs","annotate","workflows","agents"];function nO(e){const t=e?.featureAccess||{},a={tasks:{id:"tasks",label:"Tasks",featureKey:null,enabled:!0,fallbackModuleId:"tasks"},docs:{id:"docs",label:"Documents",featureKey:vd,enabled:t[vd]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:"Image Notes",featureKey:kd,enabled:t[kd]?.allowed??!1,fallbackModuleId:"tasks"},workflows:{id:"workflows",label:"Workflows",featureKey:Cm,enabled:t[Cm]?.allowed??!1,fallbackModuleId:"tasks"},agents:{id:"agents",label:"Agents",featureKey:Am,enabled:t[Am]?.allowed??!1,fallbackModuleId:"tasks"}};return tO.map(s=>a[s])}function aO(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 cg(e,t){const a=t.find(s=>s.id===e);return a?a.enabled?a.id:a.fallbackModuleId:"tasks"}const rO="_weekLabel_vet2o_1",sO="_sectionTitle_vet2o_6",oO="_calendarHeader_vet2o_11",iO="_monthLabel_vet2o_18",cO="_weekdayGrid_vet2o_23",lO="_weekdayLabel_vet2o_30",dO="_calendarGrid_vet2o_36",uO="_calendarDay_vet2o_42",mO="_calendarDayDot_vet2o_55",pO="_jumpRow_vet2o_67",fO="_displaySection_vet2o_73",hO="_toggleLabel_vet2o_79",gO="_expiredSummary_vet2o_87",yO="_actionButton_vet2o_95",Ha={weekLabel:rO,sectionTitle:sO,calendarHeader:oO,monthLabel:iO,weekdayGrid:cO,weekdayLabel:lO,calendarGrid:dO,calendarDay:uO,calendarDayDot:mO,jumpRow:pO,displaySection:fO,toggleLabel:hO,expiredSummary:gO,actionButton:yO},lg=["mon","tue","wed","thu","fri","sat","sun"],kO={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function Xc(e){const t=e.getFullYear(),a=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${t}-${a}-${s}`}function fd(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const a=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(a.getTime())?null:a}function rf(e,t){const a=e.getDay(),s=t==="sunday"?-a:a===0?-6:1-a,o=new Date(e);return o.setHours(0,0,0,0),o.setDate(o.getDate()+s),o}function vO(e,t){return t==="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 Ky(e,t){const a=new Date(e);return a.setDate(e.getDate()+t),a}function SO(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const a=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))),s=a.getUTCDay()||7;a.setUTCDate(a.getUTCDate()+4-s);const o=new Date(Date.UTC(a.getUTCFullYear(),0,1)),c=Math.ceil(((a.getTime()-o.getTime())/864e5+1)/7);return`${a.getUTCFullYear()}-W${String(c).padStart(2,"0")}`}const sf=320;function wO({open:e,onClose:t,scheduleSelectedDate:a,setScheduleSelectedDate:s,scheduleCalendarMonth:o,setScheduleCalendarMonth:c,scheduleShowWeekends:i,setScheduleShowWeekends:d,scheduleShowBacklog:m,setScheduleShowBacklog:y,scheduleOnlyExpired:k,setScheduleOnlyExpired:S,expiredScheduledCount:h,overdueDueCount:g,expiredLeafCandidates:v,expiredRecoveryCandidates:_,onMoveExpiredToSelectedWeek:I,onMoveExpiredToBacklog:A,scheduleBulkBusy:D,globalWeekStartsOn:U,resolvedLocale:W,todayDateOnly:Q,scheduleBaseTasks:le,scheduleWeekStart:ie,scheduleWeekLabel:se}){const $=ze.useMemo(()=>{const[j,H]=o.split("-"),ue=Number(j),ye=Number(H);if(!Number.isInteger(ue)||!Number.isInteger(ye)||ye<1||ye>12){const G=fd(a)||new Date;return new Date(G.getFullYear(),G.getMonth(),1)}return new Date(ue,ye-1,1)},[o,a]),C=ze.useMemo(()=>bm($,{month:"long",year:"numeric"},W),[$,W]),de=ze.useMemo(()=>{const j=rf($,U);return Array.from({length:42},(H,ue)=>Ky(j,ue))},[$,U]),ke=ze.useMemo(()=>{const j=new Map;for(const H of le){const ue=H.scheduledDate||"";if(!ue)continue;const G=!(H.status==="done"||H.status==="cancelled")&&ue<Q,je=j.get(ue);je?(je.count+=1,G&&(je.hasExpired=!0)):j.set(ue,{count:1,hasExpired:G})}return j},[le,Q]),K=ze.useMemo(()=>U==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[U]);return n.jsxs("aside",{className:`${f.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:`${sf}px`,minWidth:`${sf}px`},children:[n.jsxs("div",{className:"tf-sidebar-header",children:[n.jsxs("div",{className:"tf-sidebar-title",children:[n.jsx(Gk,{size:16}),n.jsx("span",{children:"Schedule Controls"})]}),n.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:"Hide Schedule Sidebar",children:n.jsx(tl,{size:16})})]}),n.jsxs("div",{className:Ha.weekLabel,children:["Week of ",se]}),n.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[n.jsxs("div",{className:Ha.calendarHeader,children:[n.jsx("button",{className:"tf-control-icon",onClick:()=>{const j=new Date($);j.setMonth($.getMonth()-1),c(`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:n.jsx(To,{size:14})}),n.jsx("div",{className:Ha.monthLabel,children:C}),n.jsx("button",{className:"tf-control-icon",onClick:()=>{const j=new Date($);j.setMonth($.getMonth()+1),c(`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:n.jsx(tl,{size:14})})]}),n.jsx("div",{className:Ha.weekdayGrid,children:K.map(j=>n.jsx("div",{className:Ha.weekdayLabel,children:j},j))}),n.jsx("div",{className:Ha.calendarGrid,children:de.map(j=>{const H=Xc(j),ue=j.getMonth()!==$.getMonth(),ye=rf(j,U),G=Xc(ye)===Xc(ie),je=H===a,be=H===Q,ce=H<Q,me=ke.get(H),Te=!!me,Me=!!me?.hasExpired;return n.jsxs("button",{onClick:()=>{s(H),c(`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}`)},className:Ha.calendarDay,style:{"--calendar-day-border":je?"1px solid #2563eb":be?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":je?"rgba(59,130,246,0.22)":be?"rgba(245,158,11,0.16)":G?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":ue?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":je||be?700:500,"--calendar-day-opacity":ce?.42:1},title:`${be?`${H} (Today)`:H}`+(Te?` • ${me?.count} scheduled`:"")+(Me?" • includes expired":""),children:[j.getDate(),Te&&n.jsx("span",{className:Ha.calendarDayDot,style:{"--calendar-dot-background":Me?"#ef4444":"#3b82f6","--calendar-dot-opacity":ue?.6:.95}})]},H)})}),n.jsx("div",{className:Ha.jumpRow,children:n.jsx("button",{className:"tf-control-icon",onClick:()=>{const j=new Date;s(Xc(j)),c(`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),n.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${Ha.displaySection}`,children:[n.jsx("div",{className:Ha.sectionTitle,children:"Display"}),n.jsxs("label",{className:Ha.toggleLabel,children:[n.jsx("input",{type:"checkbox",checked:i,onChange:j=>d(j.target.checked)}),"Show weekends"]}),n.jsxs("label",{className:Ha.toggleLabel,children:[n.jsx("input",{type:"checkbox",checked:m,onChange:j=>y(j.target.checked)}),"Show backlog"]}),n.jsxs("label",{className:Ha.toggleLabel,children:[n.jsx("input",{type:"checkbox",checked:k,onChange:j=>S(j.target.checked)}),"Only expired/overdue"]})]}),h>0&&n.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[n.jsx("div",{className:Ha.sectionTitle,children:"Expired Tasks"}),n.jsxs("div",{className:Ha.expiredSummary,children:[n.jsxs("span",{children:[h," expired"]}),n.jsxs("span",{children:[g," overdue"]})]}),n.jsx("button",{className:`tf-control-icon ${Ha.actionButton}`,onClick:I,disabled:D||v.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",children:D?"Working...":"Schedule to selected week"}),n.jsx("button",{className:`tf-control-icon ${Ha.actionButton}`,onClick:A,disabled:D||_.length===0,title:"Unschedule expired/overdue tasks back to backlog",children:D?"Working...":"Unschedule to backlog"})]})]})}function Zy(e,t){return e&&(t==="owner"||t==="admin")}function bO(e,t,a){return Zy(e,t)&&a==="team"}function _O({isOpen:e,workspaceId:t,refreshKeys:a}){const[s,o]=r.useState([]),[c,i]=r.useState(!1),[d,m]=r.useState(null),y=r.useRef(null),k=r.useRef(null);r.useLayoutEffect(()=>{k.current=AO(y.current,k.current)},[s]);const S=r.useCallback(async()=>{const h=await fetch(`/api/taskforce/sync/events?workspace_id=${encodeURIComponent(t)}&limit=15`,{method:"GET",credentials:"include"});if(!h.ok)throw new Error(`Failed to load sync events (${h.status})`);const g=await h.json().catch(()=>({}));return Array.isArray(g?.events)?g.events.filter(v=>v&&typeof v=="object"):[]},[t]);return r.useEffect(()=>{if(!e)return;let h=!1;const g=s.length===0;return g&&i(!0),S().then(v=>{h||(k.current=CO(y.current),o(_=>{const I=_.length===0?v:H1(_,v,15);return G1(_,I)?_:I}),m(null))}).catch(v=>{if(h)return;const _=v instanceof Error&&v.message.trim().length>0?v.message.trim():"Unable to load recent sync events.";m(_),g&&o([])}).finally(()=>{h||g&&i(!1)}),()=>{h=!0}},[e,S,...a]),{syncRecentEvents:s,syncRecentEventsLoading:c,syncRecentEventsError:d,syncEventsListRef:y,loadRecentSyncEvents:S}}function CO(e){return e&&e.scrollTop>8?{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight}:null}function AO(e,t){if(!t||!e)return null;const a=e.scrollHeight-t.scrollHeight;return e.scrollTop=t.scrollTop+Math.max(0,a),null}function xO({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:a,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:c,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,workspaceSyncPhase:k,referenceMismatchCount:S,syncRecentEvents:h,loadRecentSyncEvents:g,pushNotice:v,resetWorkspaceSyncCursorAndPull:_,workspaceSyncBusy:I}){const[A,D]=r.useState(!1),[U,W]=r.useState(!1),[Q,le]=r.useState(!1),ie=r.useCallback(async()=>{try{const C=h.length>0?h:await g(),de=J1({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:a,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:c,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:zy(k,A,I),referenceMismatchCount:S,syncRecentEvents:C});await navigator.clipboard.writeText(de),le(!0),window.setTimeout(()=>{le(!1)},1800),v("Sync details copied to clipboard.","success")}catch{le(!1),v("Failed to copy sync details.","error")}},[e,c,i,o,g,v,S,y,h,t,d,k,m,s,a,I,A]),se=r.useCallback(async()=>{W(!1),D(!0);try{await _()}finally{D(!1)}},[_]),$=r.useCallback(()=>{if(!A){if(I){W(!0);return}se()}},[se,I,A]);return r.useEffect(()=>{U&&(I||A||se())},[se,I,A,U]),{workspaceSyncRepairBusy:A,workspaceSyncRepairQueued:U,workspaceSyncCopied:Q,handleCopySyncDetails:ie,handleQueueOrRunRepairSync:$}}function IO({canManageWorkspaceSync:e,workspaceCloudSyncEnabled:t,saveWorkspaceCloudSyncSettings:a}){const[s,o]=r.useState(!1),[c,i]=r.useState(!1),[d,m]=r.useState(!1),[y,k]=r.useState(null),S=r.useCallback(async A=>{if(e){k(null),m(!0);try{const D=await a({enabled:A});D.success||k(D.error||(A?"Failed to enable sync.":"Failed to disable sync."))}finally{m(!1)}}},[e,a]),h=r.useCallback(async A=>{if(A&&!t){i(!0);return}await S(A)},[S,t]),g=r.useCallback(()=>{i(!1)},[]),v=r.useCallback(()=>{i(!1),S(!0)},[S]),_=r.useCallback(()=>{o(!0)},[]),I=r.useCallback(()=>{o(!1)},[]);return{showSyncStatusModal:s,showSyncEnableWarning:c,workspaceSyncToggleBusy:d,workspaceSyncError:y,syncControlBusy:d,openSyncStatusModal:_,closeSyncStatusModal:I,handleWorkspaceSyncToggle:h,cancelSyncEnableWarning:g,confirmSyncEnableWarning:v}}const dg=ze.lazy(()=>gs(()=>import("./TaskSettings-CUWbYYtP.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings}))),TO=ze.lazy(()=>gs(()=>import("./AnnotatedAttachmentWorkspace-B-Dq22d2.js"),__vite__mapDeps([12,1,2,3,4,5,13])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),RO=ze.lazy(()=>gs(()=>import("./DocumentWorkspace-CxA1wO3U.js"),__vite__mapDeps([14,1,2,9,3,4,5,15])).then(e=>({default:e.DocumentWorkspaceShell}))),NO=ze.lazy(()=>gs(()=>import("./WorkflowsModule-CgM3Jako.js"),__vite__mapDeps([16,1,2,3,4,5])).then(e=>({default:e.WorkflowsModule}))),jO=ze.lazy(()=>gs(()=>import("./AgentsModule-C4LcqhcZ.js"),__vite__mapDeps([17,1,2,3,4,5])).then(e=>({default:e.AgentsModule})));ze.lazy(()=>gs(()=>import("./InitiativesModule-VY95v38E.js"),__vite__mapDeps([18,1,2,3,4,5])).then(e=>({default:e.InitiativesModule})));const PO=ze.lazy(()=>gs(()=>import("./PlansPage-CQbKDv1a.js"),__vite__mapDeps([19,1,2,5,3,4,20])).then(e=>({default:e.PlansPage}))),MO="image/png,image/jpeg,image/webp,image/gif",EO=5*1024*1024,DO=e=>e;function LO(e,t){const a=Rm(e);if(a)return oh(a).label.toUpperCase();for(const s of t){const o=String(s||"").trim();if(!o)continue;const c=gf(o);if(c)return oh(c).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 id(){return typeof performance<"u"?performance.now():Date.now()}function BO(e){const s=Rg(),o=Ng(),c=r.useMemo(()=>new URLSearchParams(o.search),[o.search]),i=String(c.get("screen")||"").trim().toLowerCase()==="plans",d=r.useCallback(u=>{const w=new URLSearchParams(o.search);w.set("screen","plans");for(const[P,pe]of Object.entries(u||{}))pe==null||String(pe).trim()===""?w.delete(P):w.set(P,String(pe));s(`/?${w.toString()}${o.hash||""}`)},[o.hash,o.search,s]),m=r.useCallback(()=>{const u=new URLSearchParams(o.search);u.delete("screen"),u.delete("gate"),u.delete("checkout"),u.delete("planId"),u.delete("planVersionId"),u.delete("interval");const w=u.toString();s(`${o.pathname==="/"?"/":o.pathname}${w?`?${w}`:""}${o.hash||""}`)},[o.hash,o.pathname,o.search,s]),{activeTab:y,setActiveTab:k,activeCategories:S,groupBy:h,setGroupBy:g,activeWorkspaceModule:v,setActiveWorkspaceModule:_,emptyColumnMode:I,setEmptyColumnMode:A,zenMode:D,setZenMode:U,filterStatus:W,setFilterStatus:Q,tasks:le,handleEdit:ie,handleSubmit:se,resetForm:$,handleUpdateTask:C,editingTaskId:de,loading:ke,error:K,title:j,setTitle:H,description:ue,setDescription:ye,checklistItems:G,setChecklistItems:je,category:be,setCategory:ce,type:me,setType:Te,priority:Me,setPriority:Pe,complexity:Ee,setComplexity:Z,setStatus:x,approach:b,setApproach:R,assignee:B,setAssignee:Y,scheduledDate:fe,setScheduledDate:te,dueDate:Le,setDueDate:oe,workstreamInput:L,setWorkstreamInput:X,manualComplexityEnabled:M,checklistDropdownEnabled:V,showTaskCardStatusLabel:ne,formTaxonomies:Ce,setFormTaxonomies:Ae,comments:Re,newCommentText:$e,setNewCommentText:vt,attachments:st,setAttachments:kt,setAttachmentsDirty:Ye,descriptionFocused:Ct,setDescriptionFocused:dt,showMarkdownHelp:Qe,setShowMarkdownHelp:Tt,showChecklist:ae,setShowChecklist:Ge,showComments:ft,setShowComments:it,handleAddComment:Mt,handleSetWorkstreamForCurrentTask:ht,handleOpenTaskById:Ft,taxonomies:Et,activeTypes:We,priorities:tt,taxonomyDisplayLabels:Oe,approaches:Ze,copiedId:St,handleCopyId:ot,handleToggleInProgress:re,handleToggleComplete:Be,handleToggleReview:At,handleToggleCancel:Rt,handleArchiveTask:Bt,handleDelete:Ve,handleUnarchive:Ot,handleRestoreDeletedTask:yt,handlePermanentlyDeleteDeletedTask:E,handleEmptyDeletedTasks:l,fetchTasks:J,searchQuery:Se,setSearchQuery:Ie,filterCategories:Ke,setFilterCategories:Je,filterTypes:Ne,setFilterTypes:zt,filterPriorities:Yt,setFilterPriorities:Pt,filterAssignees:Wt,setFilterAssignees:Dt,hasInitedFilters:Ht,assigneeOptions:sn,taskScope:Vt,setTaskScope:Vn,sortBy:qn,setSortBy:Kn,clearFilters:ga,settingsModel:ge,configLoaded:at,currentTheme:xe,setCurrentTheme:jt,pathSaved:pt,saveSettings:bt,keyShortcut:An,setKeyShortcut:vn,globalWeekStartsOn:dn,locale:un,jsonBackupEnabled:Bn,setJsonBackupEnabled:gt,mcpHostRoot:cr,setMcpHostRoot:fn,settingsSection:nn,setSettingsSection:bn,runtimeMode:Kt,workspaceSwitchingEnabled:_r,cloudAuthConfigured:Pn,authRequiredForApi:aa,authBlocked:Mn,isAuthenticated:Zt,authUserId:Zn,authWorkspaceId:an,authUserEmail:ra,authUserDisplayName:Ea,authUserAvatarUrl:Da,authSessionResolved:hn,realtimeSyncEnabled:Va,realtimeSyncFlagSource:os,workspaceCloudSyncEnabled:qa,workspaceSyncPhase:Ca,workspaceSyncStatus:Wn,workspaceSyncSummary:Vr,workspaceSyncRecommendedAction:Aa,workspaceSyncBusy:sa,workspaceSyncPendingChanges:la,saveWorkspaceCloudSyncSettings:Fn,pushNotice:Nt,userGlobalSyncStatus:ya,workspaceLastSuccessfulSyncAt:On,workspaceLastPullAt:lr,workspaceLastPushAt:$n,workspaceLastErrorAt:La,userGlobalSyncError:xa,workspaceLastErrorMessage:Sn,retryWorkspaceCloudSync:Dn,resetWorkspaceSyncCursorAndPull:Ba,getWorkspaceSyncDiagnostics:gn,currentWorkspaceId:Jt,currentWorkspaceRole:Ka,availableWorkspaces:xn,switchWorkspace:En,updateCurrentUserProfile:Za,resolveCloudAuthUrl:In=DO,logout:Mr,fetchLoginMethods:cn,unlinkLoginMethod:mn,addPasswordToAccount:ka,beginOAuthLogin:Yn,beginOAuthLink:Cr,availableAuthProviders:Er,projectRoot:Xt,projectName:Ia,mcpScriptPath:Wa,serverHostRoot:dr,showFolderBrowser:Ar,setShowFolderBrowser:Ya,folders:Ja,files:xr,currentBrowsePath:Jn,fetchFolders:Ta,browserTarget:ur,setBrowserTarget:oa,handleSelectPath:qr,handleAddPath:ia,handleRemovePath:Dr,handleUpdateCategory:Kr,handleRemoveCategory:va,handleSaveCategory:Ir,handleUpdateCategoryIcon:Ra,handleUpdateCategoryColor:Sa,handleSaveType:Fa,handleRemoveType:Zr,handleUpdateTaxonomies:Ds,handleUpdatePriorities:et,pathValidation:$t,exportEnvironment:Tn,setExportEnvironment:_n,exportWorkflowsPath:wn,setExportWorkflowsPath:Na,exportResult:Qa,exportingResource:ys,availableWorkflows:wa,onExportWorkflows:Oa,fetchWorkflows:mr,availableEnvironments:Gt,initiativeTemplates:ja,fetchInitiativeTemplates:da,createInitiativeFromTemplate:Un,uiNotice:Lr,clearNotice:Br,taskReturnTrail:pr,clearReturnToParentTask:fr,returnToPreviousTask:ks,tasksScrollRef:ba,setTasksScrollPos:ua,commentsEndRef:no,autoSaveState:vs,unsavedModalOpen:hr,setUnsavedModalOpen:F,pendingNavigation:He,handleNavigation:xt,currentTask:Lt,currentTaskWorkstream:Rn,currentTaskInitiative:Tr,scheduleWarningPrompt:Wr,confirmScheduleWarning:ao,cancelScheduleWarning:Qn}=e,ma=un||$g();r.useEffect(()=>{const u=String(Ia||"").trim();document.title=u?`Taskforce - ${u}`:"Taskforce"},[Ia]);const T=()=>{F(!1),He?(y==="add"&&$(),He()):(y==="add"&&$(),k("tasks"))},N=async()=>{await se({preventDefault:()=>{}}),F(!1),He&&He()},[rt,wt]=r.useState(!1),[we,ee]=r.useState(!1),[gr,Pa]=r.useState(!0),[$a,Rr]=r.useState(!1),[jo,Xa]=r.useState(!0),[er,ro]=r.useState(Xc(new Date)),[Po,Mo]=r.useState(()=>{const u=new Date;return`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}`}),[so,ic]=r.useState(0),[Xn,cc]=r.useState(!1),[oo,lc]=r.useState(!1),[Fr,Eo]=r.useState(!1),[Ss,Do]=r.useState(!0),[Ls,io]=r.useState(!0),[Yr,yi]=r.useState(!0),[ws,Lo]=r.useState(!1),[Nr,co]=r.useState(!1),[yn,Bs]=r.useState(!1),[pn,ea]=r.useState(""),[Jr,lo]=r.useState(""),[il,Qr]=r.useState(new Set),[is,yr]=r.useState(null),[bs,pa]=r.useState(null),[Bo,kr]=r.useState(null),[Wo,Ws]=r.useState(null),[Fo,Fs]=r.useState(""),[Oo,_s]=r.useState(""),[cs,ln]=r.useState(""),[zn,tr]=r.useState(""),[cl,Xr]=r.useState(!1),dc=r.useRef({taskId:null,attachments:[]}),ll=r.useRef(new Map),ki=r.useRef(new Map),[Hn,vi]=r.useState(()=>am.map(u=>u.value)),[Os,Si]=r.useState(()=>rm.map(u=>u.value)),[Rd,dl]=r.useState(null),[Em,ul]=r.useState(null),[nr,uo]=r.useState(null),[ls,wi]=r.useState(null),[Dm,Nd]=r.useState(0),[$o,Lm]=r.useState({}),[jd,Pd]=r.useState(!1),$s=r.useRef(!1),Md=r.useRef(""),ml=r.useRef(null),Ed=r.useRef(null),pl=r.useRef(new Set);r.useEffect(()=>{dc.current={taskId:de||null,attachments:st}},[de,st]);const uc=r.useCallback(u=>{const w=de||null,P=dc.current,pe=P.taskId===w?P.attachments:st,ve=u(pe);dc.current={taskId:w,attachments:ve},kt(ve),Ye(!0),w&&C(w,{attachments:ve})},[st,de,C,kt,Ye]),Uo=r.useMemo(()=>{const u={},w=String(Jt||"").trim();return Kt==="cloud"&&w&&w!=="default"&&(u["x-taskforce-workspace-id"]=w),u},[Kt,Jt]),mo=r.useMemo(()=>`${Kt}:${String(Jt||"default").trim()||"default"}`,[Kt,Jt]),mc=r.useMemo(()=>`taskforce:annotate-layout:${mo}`,[mo]),Us=r.useMemo(()=>`taskforce:task-origin-workspace-module:${mo}`,[mo]),bi=r.useMemo(()=>Kt==="cloud"?hn:at,[hn,at,Kt]),zo=r.useRef(!1),_i=r.useRef(!1),Ho=r.useCallback(u=>{const w=String(u||"").trim();if(!(!w||typeof window>"u")){zo.current=!0;try{window.sessionStorage.setItem(Us,w)}catch{}}},[Us]),Or=r.useCallback(()=>{if(zo.current=!1,!(typeof window>"u"))try{window.sessionStorage.removeItem(Us)}catch{}},[Us]);r.useEffect(()=>{ml.current=nr},[nr]),r.useEffect(()=>{Ed.current=ls},[ls]);const Cs=r.useMemo(()=>({[vd]:od({featureKey:vd}),[kd]:od({featureKey:kd}),[Cm]:od({featureKey:Cm}),[Am]:od({featureKey:Am}),[ig]:od({featureKey:ig})}),[Kt]),ds=r.useMemo(()=>nO({featureAccess:Cs}),[Cs]),on=r.useMemo(()=>cg(v,ds),[v,ds]),Go=Cs[vd]?.allowed??!1,pc=Cs[kd]?.allowed??!1,fl="Documents is not available in this build yet.",hl="Annotate is not available in this build yet.";r.useEffect(()=>{const u=w=>{const P=w,pe=P.detail?.fsPath,ve=String(P.detail?.assetId||"").trim()||null;if(!(!pe&&!ve)){if(P.preventDefault(),!Go){Nt(fl,"error");return}Ho(P.detail?.taskId),dl(pe||null),ul(ve),_("docs")}};return window.addEventListener("taskforce:open-markdown-document",u),()=>{window.removeEventListener("taskforce:open-markdown-document",u)}},[Go,fl,Nt,Ho,_]),r.useEffect(()=>{on!==v&&_(on)},[v,on,_]),r.useEffect(()=>{on==="docs"&&Go||(dl(null),ul(null))},[Go,on]),r.useEffect(()=>{if(!(typeof window>"u"))try{const u=window.sessionStorage.getItem(mc);if(!u)return;const w=JSON.parse(u);w?.annotatedTarget&&typeof w.annotatedTarget=="object"&&uo(w.annotatedTarget),typeof w?.annotatedSessionId=="string"&&wi(w.annotatedSessionId.trim()||null)}catch{}},[mc]),r.useEffect(()=>{if(!_i.current&&!(on!=="docs"&&on!=="annotate")&&(_i.current=!0,!(zo.current||typeof window>"u")))try{if(!String(window.sessionStorage.getItem(Us)||"").trim())return;window.sessionStorage.removeItem(Us),_("tasks")}catch{}},[on,_,Us]),r.useEffect(()=>{_i.current=!1,zo.current=!1},[Us]),r.useEffect(()=>{if(Md.current===mo)return;Md.current=mo,Pd(!1);let u=!1;return(async()=>{try{const P=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:Uo});if(!P.ok)return;const pe=await P.json().catch(()=>({})),ve=pe?.state&&typeof pe.state=="object"?pe.state:null;if(!ve||u)return;if(typeof ve.scheduleShowWeekends=="boolean"&&ee(ve.scheduleShowWeekends),typeof ve.scheduleShowBacklog=="boolean"&&Pa(ve.scheduleShowBacklog),typeof ve.scheduleOnlyExpired=="boolean"&&Rr(ve.scheduleOnlyExpired),typeof ve.scheduleSidebarOpen=="boolean"&&Xa(ve.scheduleSidebarOpen),typeof ve.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(ve.scheduleSelectedDate)&&ro(ve.scheduleSelectedDate),typeof ve.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(ve.scheduleCalendarMonth)&&Mo(ve.scheduleCalendarMonth),typeof ve.scheduleScrollLeft=="number"&&Number.isFinite(ve.scheduleScrollLeft)&&ve.scheduleScrollLeft>=0&&ic(ve.scheduleScrollLeft),typeof ve.showFilters=="boolean"&&cc(ve.showFilters),Array.isArray(ve.documentTypeFilters)&&vi(ve.documentTypeFilters),Array.isArray(ve.documentAttachmentFilters)&&Si(ve.documentAttachmentFilters),typeof ve.planningDrawerOpen=="boolean"&&Eo(ve.planningDrawerOpen),typeof ve.documentTrayOpen=="boolean"&&Do(ve.documentTrayOpen),typeof ve.imageTrayOpen=="boolean"&&io(ve.imageTrayOpen),typeof ve.agentTrayOpen=="boolean"&&yi(ve.agentTrayOpen),typeof ve.planningTreeCollapsed=="boolean"&&Lo(ve.planningTreeCollapsed),typeof ve.planningPrimaryCollapsed=="boolean"&&co(ve.planningPrimaryCollapsed),typeof ve.planningSecondaryCollapsed=="boolean"&&Bs(ve.planningSecondaryCollapsed),Array.isArray(ve.planningExpandedInitiativeIds)&&Qr(new Set(ve.planningExpandedInitiativeIds.map(qt=>String(qt||"").trim()).filter(Boolean))),ve.planningDrawerDetail&&typeof ve.planningDrawerDetail=="object"&&(ve.planningDrawerDetail.type==="initiative"||ve.planningDrawerDetail.type==="workstream")&&typeof ve.planningDrawerDetail.id=="string"){const qt=ve.planningDrawerDetail.id.trim();yr(qt?{type:ve.planningDrawerDetail.type,id:qt}:null)}else ve.planningDrawerDetail===null&&yr(null);typeof ve.planningNestedWorkstreamDetailId=="string"?pa(ve.planningNestedWorkstreamDetailId.trim()||null):ve.planningNestedWorkstreamDetailId===null&&pa(null);const ut=ve.annotatedTarget;ut&&typeof ut=="object"&&(ml.current||uo(ut)),typeof ve.annotatedSessionId=="string"&&(Ed.current||wi(ve.annotatedSessionId.trim()||null))}catch{}finally{u||Pd(!0)}})(),()=>{u=!0}},[mo,Uo]),r.useEffect(()=>{if(!jd)return;const u=window.setTimeout(async()=>{try{await kf({stateKey:"layout",workspaceId:Jt,headers:Uo,patch:{scheduleShowWeekends:we,scheduleShowBacklog:gr,scheduleOnlyExpired:$a,scheduleSidebarOpen:jo,scheduleSelectedDate:er,scheduleCalendarMonth:Po,scheduleScrollLeft:so,showFilters:Xn,documentTypeFilters:Hn,documentAttachmentFilters:Os,documentTrayOpen:Ss,imageTrayOpen:Ls,agentTrayOpen:Yr,planningDrawerOpen:Fr,planningTreeCollapsed:ws,planningPrimaryCollapsed:Nr,planningSecondaryCollapsed:yn,planningExpandedInitiativeIds:Array.from(il),planningDrawerDetail:is,planningNestedWorkstreamDetailId:bs,annotatedTarget:nr,annotatedSessionId:ls}})}catch{}},250);return()=>window.clearTimeout(u)},[jd,we,gr,$a,jo,er,Po,so,Xn,Hn,Os,Ss,Ls,Yr,Fr,ws,Nr,yn,il,is,bs,nr,ls,Uo]),r.useEffect(()=>{if(!(typeof window>"u"))try{window.sessionStorage.setItem(mc,JSON.stringify({annotatedTarget:nr,annotatedSessionId:ls}))}catch{}},[mc,ls,nr]),r.useEffect(()=>{h==="schedule"&&Xa(!0)},[h]);const{showArchive:po,setShowArchive:gl,fetchArchive:yl,filteredArchive:kl}=e,Ci=r.useMemo(()=>kl.map(u=>({...u,isArchived:!0})),[kl]),Ua=r.useMemo(()=>e.archivedTasks.map(u=>({...u,isArchived:!0})),[e.archivedTasks]),As=r.useMemo(()=>[...e.searchAgnosticTasks,...Ua],[Ua,e.searchAgnosticTasks]),Dd=r.useCallback(u=>{const w=String(u||"").trim();if(!w)return"";const P=As.find(pe=>pe.id===w);return nc(P)||""},[As]),Ld=r.useCallback(u=>{const w=String(u||"").trim();if(!w)return"";const P=String($o[w]||"").trim();if(P)return P;for(const pe of As)for(const ve of pe.attachments||[]){if(!ve||typeof ve!="object"||String(ve.assetId||"").trim()!==w)continue;const ut=vy({referenceNumber:typeof ve.referenceNumber=="number"?ve.referenceNumber:null,referenceLabel:String(ve.referenceLabel||"").trim()||null});if(ut)return ut}return""},[As,$o]);r.useEffect(()=>{const u=w=>{const P=w,pe=Eh(P.detail,As);if(pe){if(P.preventDefault(),!pc){Nt(hl,"error");return}uo(pe),wi(null),Nd(ve=>ve+1),Ho(pe.taskId),_("annotate")}};return window.addEventListener("taskforce:open-annotated-attachment",u),()=>{window.removeEventListener("taskforce:open-annotated-attachment",u)}},[As,pc,hl,Nt,Ho,_]),r.useEffect(()=>{if(!nr)return;const u=Eh(nr,As);u&&(u.taskReferenceLabel===nr.taskReferenceLabel&&u.imageReferenceLabel===nr.imageReferenceLabel||uo(u))},[As,nr]),r.useEffect(()=>{const u=ml.current,w=String(u?.assetId||"").trim();if(!w)return;const P=String($o[w]||"").trim();P&&P!==String(u?.imageReferenceLabel||"").trim()&&uo(pe=>!pe||String(pe.assetId||"").trim()!==w?pe:{...pe,imageReferenceLabel:P})},[$o,nr]),r.useEffect(()=>{if(!bi)return;const w=String(nr?.assetId||"").trim();if(!w||pl.current.has(w)||String($o[w]||"").trim())return;let P=!1;pl.current.add(w);const pe=String(Jt||"default").trim()||"default",ve=new URLSearchParams({workspaceId:pe});return(async()=>{try{const qt=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(w)}?${ve.toString()}`,{method:"GET",credentials:"include",headers:Uo});if(!qt.ok)return;const kn=await qt.json().catch(()=>({})),ps=String(kn?.target?.imageReferenceLabel||"").trim();if(!ps||P)return;Lm(Cn=>Cn[w]===ps?Cn:{...Cn,[w]:ps})}catch{}finally{pl.current.delete(w)}})(),()=>{P=!0}},[bi,$o,Jt,nr,Uo]);const ar=r.useMemo(()=>e.deletedTasks.map(u=>({...u.taskSnapshot,isDeleted:!0,deletedRecordId:u.id})),[e.deletedTasks]),Vo=r.useMemo(()=>{const u=new Map;return e.deletedTasks.forEach(w=>{u.set(w.taskSnapshot.id,w)}),u},[e.deletedTasks]),fc=r.useMemo(()=>{const u=ar,w=Pm(Se),P={categories:S,types:We,priorities:tt,assigneeOptions:e.assigneeOptions,taxonomies:Et},pe=S.every(Cn=>Ke.includes(Cn.value)),ve=We.every(Cn=>Ne.includes(Cn.value)),ut=new Set(Yt.map(Cn=>String(Cn))),qt=tt.every(Cn=>ut.has(String(Cn.value))),kn=new Set(W.map(Cn=>String(Cn))),ps=Xs.every(Cn=>kn.has(String(Cn.value)));return u.filter(Cn=>{const up=gm(Cn,w,P),Pu=pe||Ke.includes(Cn.category),mp=ve||Ne.includes(Cn.type||Gr),pp=qt||ut.has(String(Cn.priority)),Mu=ps||kn.has(String(Cn.status)),fp=Wt.length===0||Wt.includes(Cn.assignee||"unassigned");return up&&Pu&&mp&&pp&&Mu&&fp})},[S,We,ar,Wt,Ke,Yt,W,Ne,tt,Se]),qo=r.useMemo(()=>[...e.tasks,...Ua,...ar],[Ua,ar,e.tasks]),vl=r.useMemo(()=>{const u=S.filter(P=>!P.disabled).map(P=>({value:P.value,label:P.label})),w=S.filter(P=>P.disabled&&qo.some(pe=>pe.category===P.value)).map(P=>({value:P.value,label:`${P.label} (Legacy)`}));return[...u,...w]},[S,qo]),hc=r.useMemo(()=>{const u=We.filter(P=>P.status!=="retired").map(P=>({value:P.value,label:P.label})),w=We.filter(P=>P.status==="retired"&&qo.some(pe=>(pe.type||Gr)===P.value)).map(P=>({value:P.value,label:`${P.label} (Retired)`}));return[...u,...w]},[We,qo]),fo=r.useMemo(()=>Vt==="archived"?Ci:Vt==="deleted"?fc:po?[...e.filteredTasks,...Ci]:e.filteredTasks,[Ci,fc,e.filteredTasks,po,Vt]),Ai=r.useMemo(()=>Vt==="open"?e.tasks.filter(u=>!u.isArchived):fo,[fo,e.tasks,Vt]),Bd=r.useMemo(()=>new Set(fo.map(u=>u.id)),[fo]),gc=r.useMemo(()=>Vt==="archived"?Ua:Vt==="deleted"?ar:po?[...e.tasks,...Ua]:e.tasks,[Ua,ar,e.tasks,po,Vt]),Ko=r.useMemo(()=>{const u=new Map;for(const w of Ua)u.set(w.id,w);for(const w of ar)u.set(w.id,w);for(const w of e.tasks)u.set(w.id,w);return Array.from(u.values())},[Ua,ar,e.tasks]),Sl=r.useMemo(()=>{const u=new Map;return Ko.forEach(w=>u.set(w.id,w)),u},[Ko]),xi=r.useMemo(()=>{const u=new Map;sn.forEach(pe=>{u.set(String(pe.value),pe.label)});const w=String(Zn||"").trim(),P=String(Ea||ra||"").trim();return w&&P&&u.set(w,P),u},[sn,Ea,ra,Zn]),_t=r.useMemo(()=>{const u=Vt==="archived"?Ua:Vt==="deleted"?ar:e.tasks.filter(ct=>!ct.isArchived),w=Vt==="deleted"?ar:Array.from([...e.tasks,...Ua].reduce((ct,na)=>ct.set(na.id,na),new Map).values()),P=(ct,na)=>({progressPercent:ct>0?Math.round(na/ct*100):0,taskCount:ct,completedTaskCount:na}),pe=Vt==="open"&&e.planningBootstrapTaskSummaries.length>0&&(e.loadingTasks||e.tasks.length===0),ve=new Map,ut=new Map;pe?e.planningBootstrapTaskSummaries.forEach(ct=>{ve.set(ct.workstreamId,ct),ut.set(ct.workstreamId,ct.tasks||[])}):(u.forEach(ct=>{const na=String(ct.workstreamId||"").trim();if(!na)return;const Sr=ve.get(na)||{workstreamId:na,taskCount:0,completedTaskCount:0,tasks:[]};Sr.taskCount+=1,(ct.isArchived||ct.status==="done"||ct.status==="cancelled")&&(Sr.completedTaskCount+=1),ve.set(na,Sr)}),w.forEach(ct=>{const na=String(ct.workstreamId||"").trim();if(!na)return;const Sr=ut.get(na)||[];Sr.push({id:ct.id,referenceNumber:ct.referenceNumber??null,title:ct.title,status:ct.status||null,isArchived:!!ct.isArchived}),ut.set(na,Sr)}));const qt=new Map,kn=new Map,ps=new Map,Cn=new Map,up=ct=>{const na=ve.get(ct.id),Sr=ut.get(ct.id)||na?.tasks||[],Eu={id:ct.id,referenceNumber:ct.referenceNumber??null,title:ct.title,description:String(ct.description||"").trim()||void 0,ownerId:ct.ownerId?String(ct.ownerId):null,ownerLabel:ct.ownerId?xi.get(String(ct.ownerId))||String(ct.ownerId):null,...P(na?.taskCount||0,na?.completedTaskCount||0),initiativeId:ct.initiativeId||null,commentCount:Array.isArray(ct.comments)?ct.comments.length:0,attachmentCount:Array.isArray(ct.attachments)?ct.attachments.length:0,attachments:Array.isArray(ct.attachments)?ct.attachments:[],isArchived:!!ct.isArchived,tasks:Sr};if(qt.set(ct.id,Sr.map(Vc=>Vc.id)),ct.initiativeId){kn.set(ct.id,ct.initiativeId);const Vc=Cn.get(ct.initiativeId)||[];Vc.push(Eu),Cn.set(ct.initiativeId,Vc)}return Eu},Pu=e.workstreams.map(up),mp=Pu.filter(ct=>_m(Vt,!!ct.isArchived)),pp=e.initiatives.map(ct=>{const na=Cn.get(ct.id)||[],Sr=na.filter(nd=>_m(Vt,!!nd.isArchived)),Eu=Sr.reduce((nd,hp)=>nd+hp.taskCount,0),Vc=Sr.reduce((nd,hp)=>nd+hp.completedTaskCount,0);return{id:ct.id,referenceNumber:ct.referenceNumber??null,title:ct.title,description:String(ct.description||"").trim()||void 0,ownerId:ct.ownerId?String(ct.ownerId):null,ownerLabel:ct.ownerId?xi.get(String(ct.ownerId))||String(ct.ownerId):null,...P(Eu,Vc),workstreamCount:Sr.length,workstreams:Sr,allWorkstreams:na,commentCount:Array.isArray(ct.comments)?ct.comments.length:0,attachmentCount:Array.isArray(ct.attachments)?ct.attachments.length:0,attachments:Array.isArray(ct.attachments)?ct.attachments:[],isArchived:!!ct.isArchived}}),{initiatives:Mu,standaloneWorkstreams:fp,initiativeById:Tk,workstreamById:Rk}=O1(pp,mp,Vt),Nk=Pu.filter(ct=>!ct.initiativeId);return Mu.forEach(ct=>{ps.set(ct.id,ct.workstreams.flatMap(na=>(na.tasks||[]).map(Sr=>Sr.id)))}),{initiatives:Mu,standaloneWorkstreams:fp,allStandaloneWorkstreams:Nk,workstreamTaskIds:qt,workstreamInitiativeIds:kn,initiativeTaskIds:ps,workstreamById:Rk,initiativeById:Tk}},[Ua,xi,ar,e.initiatives,e.loadingTasks,e.planningBootstrapTaskSummaries,e.tasks,e.workstreams,Vt]),wl=r.useMemo(()=>_t.initiatives.map(u=>{const w=rs(u);return{value:u.id,label:w||u.title}}),[_t.initiatives]),Wd=r.useMemo(()=>{const w=(pn?_t.initiativeById.get(pn)?.workstreams||[]:_t.initiatives.flatMap(pe=>pe.workstreams)).map(pe=>{const ve=Ro(pe);return{value:pe.id,label:ve||pe.title}}),P=pn?[]:_t.standaloneWorkstreams.map(pe=>{const ve=Ro(pe);return{value:pe.id,label:ve||pe.title}});return[...w,...P]},[_t.initiativeById,_t.initiatives,_t.standaloneWorkstreams,pn]),Zo=r.useMemo(()=>Jr?new Set(_t.workstreamTaskIds.get(Jr)||[]):pn?new Set(_t.initiativeTaskIds.get(pn)||[]):null,[_t.initiativeTaskIds,_t.workstreamTaskIds,pn,Jr]),yc=r.useMemo(()=>{if(!is)return null;if(is.type==="initiative"){const w=_t.initiativeById.get(is.id);return w?{type:"initiative",item:w}:null}const u=_t.workstreamById.get(is.id)||_t.standaloneWorkstreams.find(w=>w.id===is.id);return u?{type:"workstream",item:u}:null},[is,_t.initiativeById,_t.standaloneWorkstreams,_t.workstreamById]),ho=r.useMemo(()=>{if(!bs)return null;const u=_t.workstreamById.get(bs)||_t.standaloneWorkstreams.find(w=>w.id===bs);return u?{type:"workstream",item:u}:null},[bs,_t.standaloneWorkstreams,_t.workstreamById]),bl=r.useMemo(()=>Wo?{kind:"editor",editor:Wo}:ho?{kind:"detail",detail:ho}:null,[ho,Wo]),_l=qy(ws,!!(yc||Bo),Nr,!!bl,yn),Fd=r.useMemo(()=>{if(!zn.trim())return null;const u=_t.initiativeById.get(zn);return u||Cp(_t.initiatives,zn)},[zn,_t.initiativeById,_t.initiatives]);r.useEffect(()=>{pn&&!_t.initiativeById.has(pn)&&ea(""),Jr&&!_t.workstreamById.has(Jr)&&lo("")},[_t.initiativeById,_t.workstreamById,pn,Jr]);const vr=r.useMemo(()=>h==="schedule"?Ai:fo,[h,fo,Ai]),Gn=r.useMemo(()=>{const u=new Date,w=u.getFullYear(),P=String(u.getMonth()+1).padStart(2,"0"),pe=String(u.getDate()).padStart(2,"0");return`${w}-${P}-${pe}`},[]),Ii=r.useMemo(()=>h!=="schedule"||!$a?vr:vr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const P=!!u.scheduledDate&&u.scheduledDate<Gn,pe=!!u.dueDate&&u.dueDate<Gn;return P||pe}),[h,$a,vr,Gn]),Cl=r.useMemo(()=>Kh(Ii,Zo),[Ii,Zo]),Al=r.useMemo(()=>Kh(gc,Zo),[gc,Zo]),go=r.useMemo(()=>h!=="schedule"?[]:vr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const P=!!u.scheduledDate&&u.scheduledDate<Gn,pe=!!u.dueDate&&u.dueDate<Gn;return P||pe}),[h,vr,Gn]),xl=r.useMemo(()=>h!=="schedule"?0:vr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<Gn).length,[h,vr,Gn]),Od=r.useMemo(()=>h!=="schedule"?0:vr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.dueDate&&u.dueDate<Gn).length,[h,vr,Gn]),$r=String(Zn||"").trim(),$d=r.useMemo(()=>!$r||$r==="anonymous"?0:le.filter(u=>u.status==="done"||u.status==="cancelled"?!1:String(u.assignee||"").trim()===$r).length,[$r,le]),Il=r.useMemo(()=>!$r||$r==="anonymous"?0:le.filter(u=>u.status==="done"||u.status==="cancelled"||String(u.assignee||"").trim()!==$r?!1:!!u.dueDate&&u.dueDate<Gn).length,[$r,le,Gn]),Ud=r.useMemo(()=>h!=="schedule"?[]:vr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<Gn),[h,vr,Gn]),Yo=go,[yo,Jo]=r.useState(!1),kc=()=>{xt(()=>{ks()||(y==="add"&&pr.length>0&&fr(),lc(!1),y==="add"&&$(),k("tasks"))})};r.useEffect(()=>{y!=="add"&&lc(!1)},[y]);const Ti=r.useCallback((u,w)=>{if(u.status!==w){if(w==="in-progress"){re(u);return}if(w==="review"){At(u);return}if(w==="done"){Be(u);return}if(w==="cancelled"){Rt(u);return}C(u.id,{status:w,completedAt:null})}},[re,At,Be,Rt,C]),zd=r.useCallback((u,w)=>{$();const P=B1(u,w,{categories:S,approaches:Ze});P.category&&ce(P.category),P.type&&Te(P.type),typeof P.priority=="number"&&Pe(P.priority),typeof P.complexity=="number"&&Z(P.complexity),P.approach&&R(P.approach);const pe=P.taxonomyApproach;typeof pe=="string"&&pe.length>0&&Ae(ve=>({...ve,approach:pe})),P.assignee&&Y(P.assignee),P.status&&x(P.status),P.scheduledDate&&te(P.scheduledDate),k("add")},[$,S,Ze,ce,Te,Pe,Z,x,R,Y,te,Ae,k]);ze.useEffect(()=>{W&&!W.includes("done")&&Q(u=>[...u,"done"])},[]);const[Tl,ko]=r.useState(!1),[zs,za]=r.useState(!1),[Qo,Hs]=r.useState(!1),[vc,Rl]=r.useState(!1),[Bm,Sc]=r.useState(!1),[wc,Hd]=r.useState(!1),[Gd,Nl]=r.useState(""),[Wm,Ri]=r.useState(!1),[jl,Vd]=r.useState(!1),[Fm,Ni]=r.useState("members"),[bc,_c]=r.useState(null),[qd,Xo]=r.useState("unknown"),[Kd,Cc]=r.useState(!1),[Pl,ji]=r.useState(null),[jr,ta]=r.useState(null),[Zd,Pi]=r.useState(!1),[Mi,Ac]=r.useState([]),[Ml,ei]=r.useState(null),[vo,xc]=r.useState(""),[ti,ni]=r.useState("member"),[So,El]=r.useState("read-write"),[Ic,Ei]=r.useState(!1),[Yd,Tc]=r.useState(null),[xs,Rc]=r.useState(0),[Om,Dl]=r.useState(!1),[$m,Um]=r.useState([]),[zm,Hm]=r.useState(!1),[Gm,Jd]=r.useState(1),[_a,Ll]=r.useState(null),[Qd,Xd]=r.useState(!1),[Is,wo]=r.useState(null),[Nc,jc]=r.useState(!1),[Vm,Ts]=r.useState(null),[rr,Gs]=r.useState(!1),[Bl,es]=r.useState(null),[ai,qm]=r.useState("month"),[ri,si]=r.useState(""),[Wl,oi]=r.useState(""),[ca,ii]=r.useState(null),[Fl,eu]=r.useState(!1),[tu,Ol]=r.useState(!1),[nu,ts]=r.useState(null),[au,ns]=r.useState(null),ru=25,su=r.useRef(null),Di=r.useRef(null),$l=r.useRef({billing:!1,teamManagement:!1}),Li=r.useRef(null);r.useEffect(()=>{Li.current=_a},[_a]),r.useEffect(()=>{if(!zs)return;const u=w=>{su.current?.contains(w.target)||za(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[zs]);const Km=Kt==="cloud"&&_r&&Zt,ci=Zt&&(Kt==="cloud"||Pn),Ul=Kt==="local"&&Zt,{showSyncStatusModal:ou,showSyncEnableWarning:Zm,workspaceSyncError:zl,syncControlBusy:iu,openSyncStatusModal:cu,closeSyncStatusModal:Hl,handleWorkspaceSyncToggle:lu,cancelSyncEnableWarning:Pc,confirmSyncEnableWarning:Ym}=IO({canManageWorkspaceSync:Ul,workspaceCloudSyncEnabled:qa,saveWorkspaceCloudSyncSettings:Fn}),Gl=r.useMemo(()=>{const u=xn.find(pe=>pe.id===Jt),w=String(u?.name||"").trim();if(w)return w;if(Kt==="local"){const pe=String(Ia||"").trim();if(pe)return pe}return String(Jt||"").trim()||"Workspace"},[xn,Jt,Ia,Kt]),Mc=Zy(ci,bc),li=bO(ci,bc,qd),Ec=String(Ea||"").trim(),Ur=String(Da||"").trim(),Vs=String(ra||"").trim(),qs=Ec||Vs,Vl=qs.length>0,Jm=Vs.length>0,ql=r.useMemo(()=>E2({workspaceName:Gl,workspaceId:Jt,accountLabel:qs||Vs,runtimeMode:Kt}),[Vs,qs,Jt,Gl,Kt]),Dc=(qs||Vs||"").trim(),Lc=Zt&&hn&&Dc.length>0?Dc.charAt(0).toUpperCase():"",du=Ur,Bc=Zt&&hn&&du.length>0,Kl=String(Wl||Ur).trim(),Wc=String(_a?.planName||_a?.planId||"").trim(),uu=Wc.length>0,Ks=String(_a?.workspaceId||an||Jt||"").trim(),mu=Kt==="cloud"?"CLOUD":"LOCAL",Zl=e.config?.apiBaseUrl||"",pu=r.useMemo(()=>LO(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]),Yl=Pn&&!hn;r.useEffect(()=>{vc&&(si(Ec),oi(Ur),ii(null),ts(null),ns(null))},[Ur,Ec,vc]);const Rs=r.useCallback(async u=>{const w=String(u||"").trim();if(!(!w||!Pn))try{await fetch(In("/api/taskforce/auth/profile/avatar/discard"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:w})})}catch{}},[Pn,In]),fu=r.useCallback(()=>{const u=ca;Rl(!1),Sc(!1),ts(null),ns(null),ii(null),oi(Ur),u&&Rs(u)},[Ur,Rs,ca]),Xm=r.useCallback(async u=>{if(!u||!Pn)return!1;if(!u.type.startsWith("image/"))return ts("Profile photo must be an image file."),ns(null),!1;eu(!0),ts(null),ns(null);try{const w=await mW(u,{maxBytes:EO});if(w.exceededLimit){const Cn=u.type==="image/gif"?"Animated GIF profile photos must be 5 MB or smaller.":"Profile photo must be 5 MB or smaller.";throw new Error(Cn)}const P=w.file,pe=await fetch(In("/api/taskforce/auth/profile/avatar/init"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:P.name,mimeType:P.type,size:P.size})}),ve=await pe.json().catch(()=>({}));if(!pe.ok||!ve?.success||typeof ve?.draftId!="string"||typeof ve?.relativePath!="string")throw new Error(ve?.error||"Failed to start avatar upload.");if(!(await fetch(In("/api/taskforce/auth/profile/avatar/upload"),{method:"POST",headers:{"Content-Type":P.type||"application/octet-stream","x-taskforce-avatar-draft-id":ve.draftId},credentials:"include",body:P})).ok)throw new Error("Failed to upload avatar.");const qt=await fetch(In("/api/taskforce/auth/profile/avatar/finalize"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:ve.draftId,relativePath:ve.relativePath})}),kn=await qt.json().catch(()=>({}));if(!qt.ok||!kn?.success||typeof kn?.draftId!="string")throw new Error(kn?.error||"Failed to finalize avatar upload.");const ps=ca;return ii(kn.draftId),oi(typeof kn?.avatarUrl=="string"?kn.avatarUrl:""),ns(null),ps&&ps!==kn.draftId&&Rs(ps),!0}catch(w){return ts(w instanceof Error?w.message:"Failed to upload profile photo."),!1}finally{eu(!1)}},[Pn,Rs,ca,In]),hu=r.useCallback(()=>{if(!ca)return;const u=ca;ii(null),oi(Ur),ns(null),ts(null),Rs(u)},[Ur,Rs,ca]),gu=r.useCallback(()=>{const u=ca;ii(null),oi(""),ns(Ur?"Profile photo will be removed when you save.":null),ts(null),u&&Rs(u)},[Ur,Rs,ca]),yu=r.useCallback(async()=>{const u=ri.trim();if(!u){ts("Display name is required."),ns(null);return}Ol(!0),ts(null),ns(null);const w=await Za({displayName:u,avatarDraftId:ca,clearAvatar:!ca&&!Wl&&!!Ur});if(!w.success){ts(w.error||"Failed to update profile."),Ol(!1);return}ns("Profile updated."),ii(null),oi(""),Ol(!1),Sc(!1),Rl(!1)},[Ur,ca,Wl,ri,Za]),zr=r.useCallback(()=>{const u={},w=String(Ks||"").trim();w&&(u["x-taskforce-workspace-id"]=w);const P=bc||Ka;return(P==="owner"||P==="admin"||P==="member"||P==="read-only")&&(u["x-taskforce-workspace-role"]=P),u},[Ka,Ks,bc]),Fc=r.useCallback(u=>{const w=Zt,P=ci;Di.current=id(),$l.current={billing:w,teamManagement:P},Ut("account_surface_opened",{surface:u,expectsBilling:w,expectsTeamManagement:P}),!w&&!P&&(Ut("account_surface_ready",{surface:u,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),Di.current=null)},[ci,Zt]),di=r.useCallback(u=>{const w=$l.current;if(w[u]=!1,w.billing||w.teamManagement)return;const P=Di.current;P!==null&&(Ut("account_surface_ready",{surface:Qo?"account_hub":zs?"account_menu":"closed",durationMs:Math.round(id()-P),teamManagementVisible:li,billingPlanId:String(_a?.planId||"").trim()||null}),Di.current=null)},[_a?.planId,li,Qo,zs]),Ns=r.useCallback(async u=>{const w=In(Jh);if(!Zt)return Ll(null),wo(null),_c(null),Xo("unknown"),Cc(!1),ji(null),Qh(w,{identityKey:Zn}),di("billing"),di("teamManagement"),null;const P=id();Xd(!0),wo(null),Cc(ci),ji(null);try{const pe=await X1(w,{identityKey:Zn,force:u?.force===!0}),ve=pe?.workspaceRole==="owner"||pe?.workspaceRole==="admin"||pe?.workspaceRole==="member"||pe?.workspaceRole==="read-only"?pe.workspaceRole:null,ut=pe?.teamPlanMode==="team"||pe?.teamPlanMode==="personal"?pe.teamPlanMode:"unknown";return Ll(pe),_c(ve),Xo(ut),ji(null),Ut("account_profile_summary_resolved",{durationMs:Math.round(id()-P),planId:String(pe?.planId||"").trim()||null,gate:String(pe?.gate||"").trim()||null,teamManagementAllowed:pe?.teamManagementAllowed===!0}),pe}catch(pe){const ve=pe instanceof Error?pe.message:"Failed to load account summary.",ut=!!Li.current;return wo(ve),ut?ji(null):(_c(null),Xo("unknown"),ji(ve)),Ut("account_profile_summary_failed",{durationMs:Math.round(id()-P),error:ve,preservedSummary:ut}),Li.current}finally{Xd(!1),Cc(!1),di("billing"),di("teamManagement")}},[Zn,ci,Zt,di,In]),ep=r.useCallback(u=>{Ll(u);const w=u?.workspaceRole==="owner"||u?.workspaceRole==="admin"||u?.workspaceRole==="member"||u?.workspaceRole==="read-only"?u.workspaceRole:null,P=u?.teamPlanMode==="team"||u?.teamPlanMode==="personal"?u.teamPlanMode:"unknown";_c(w),Xo(P)},[]),Oc=r.useMemo(()=>Xp(_a).allowReturnToApp,[_a]),Bi=r.useCallback(async()=>{const u=new URLSearchParams;u.set("screen","plans"),u.set("interval",ai);const w=String(_a?.planId||"").trim(),P=String(_a?.planVersionId||"").trim();w&&u.set("planId",w),P&&u.set("planVersionId",P),s(`/?${u.toString()}`)},[_a?.planId,_a?.planVersionId,ai,s]),Jl=r.useCallback(async()=>{Ts(null),es(null),jc(!0);try{const u=await fetch(In("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),w=await u.json().catch(()=>({}));if(!u.ok){Ts(String(w?.error||"Failed to create portal session."));return}const P=String(w?.url||"").trim();if(!P){Ts("Portal session did not return a redirect URL.");return}window.location.assign(P)}catch{Ts("Failed to open billing portal.")}finally{jc(!1)}},[In]),tp=r.useCallback(async()=>{Ts(null),es(null),jc(!0);try{const u=String(_a?.planVersionId||"").trim();if(!u){Ts("No active plan version is linked to this account.");return}const w=await fetch(In("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:u,interval:ai})}),P=await w.json().catch(()=>({}));if(!w.ok){Ts(String(P?.error||"Failed to update subscription interval."));return}es("Subscription updated."),Qh(In(Jh),{identityKey:Zn}),await Ns()}catch{Ts("Failed to update subscription interval.")}finally{jc(!1)}},[_a?.planVersionId,Zn,ai,Ns,In]);r.useEffect(()=>{!Zt||!hn||Ns()},[hn,Zt,Ns]),r.useEffect(()=>{!Qo&&!zs||Ns()},[Ns,Qo,zs]);const Wi=r.useCallback(async()=>{if(Mc){Pi(!0),ta(null);try{const u=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:zr()}),w=await u.json().catch(()=>({}));if(!u.ok){ta(w?.error||"Failed to load workspace users.");return}const P=Array.isArray(w?.users)?w.users:[],pe={owner:0,admin:1,member:2,"read-only":3},ve=P.map(ut=>({userId:String(ut?.userId||""),email:String(ut?.email||""),displayName:typeof ut?.displayName=="string"?ut.displayName:null,role:ut?.role==="owner"||ut?.role==="admin"||ut?.role==="member"||ut?.role==="read-only"?ut.role:"member",permissionMode:ut?.permissionMode==="read-only"?"read-only":"read-write",status:String(ut?.status||"active"),disabled:ut?.disabled===!0}));ve.sort((ut,qt)=>{const kn=(pe[ut.role]??99)-(pe[qt.role]??99);return kn!==0?kn:(ut.displayName||ut.email).localeCompare(qt.displayName||qt.email,void 0,{sensitivity:"base"})}),Ac(ve)}catch{ta("Failed to load workspace users.")}finally{Pi(!1)}}},[Mc,zr]),js=r.useCallback(async u=>{if(!Mc)return;const w=Math.max(0,Math.floor(u));Dl(!0),ta(null);try{const P=w*ru,pe=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${ru}&offset=${P}`,{method:"GET",credentials:"include",headers:zr()}),ve=await pe.json().catch(()=>({}));if(!pe.ok){ta(ve?.error||"Failed to load workspace audit log.");return}const ut=Array.isArray(ve?.events)?ve.events:[];Um(ut.map(kn=>({id:String(kn?.id||""),action:String(kn?.action||""),actorUserId:String(kn?.actorUserId||""),actorRole:String(kn?.actorRole||""),createdAt:String(kn?.createdAt||kn?.ts||"")}))),Rc(w);const qt=Math.max(1,Number(ve?.pages||1));Jd(qt),Hm(w+1<qt)}catch{ta("Failed to load workspace audit log.")}finally{Dl(!1)}},[Mc,zr]),Fi=r.useCallback(async()=>{await Promise.all([Wi(),js(xs)])},[Wi,js,xs]),Oi=r.useCallback((u="login")=>{const w=`${o.pathname}${o.search}${o.hash}`,P=!w||w==="/login"||!w.startsWith("/")?"/":w;za(!1),Hs(!1),Hl(),s(`/login?mode=${u}&next=${encodeURIComponent(P)}`)},[Hl,o.hash,o.pathname,o.search,s]),$i=r.useCallback(u=>{za(!1),Ri(!1);const w=new URLSearchParams({step:"workspace"});u?.intent==="create-workspace"&&w.set("intent","create-workspace"),s(`/setup?${w.toString()}`,{replace:!0})},[s]),$c=r.useCallback(async()=>{if(rr)return;if(Gs(!0),!Zt){try{m()}finally{Gs(!1)}return}const u=Li.current;if(u&&!Xp(u).allowReturnToApp){Gs(!1);return}m(),(async()=>{try{const w=await e.continueAfterCommercialOnboarding();if(!w.success){Nt(w.error||"Unable to finish onboarding.","error"),w.destination==="login"&&s("/login",{replace:!0});return}w.destination==="setup"&&$i()}finally{Gs(!1)}})()},[Li,m,Zt,s,$i,rr,e,Nt]),np=r.useCallback(()=>{if(i){$c();return}xt(()=>{Or(),_("tasks"),Eo(!1),yr(null),pa(null),kr(null),lc(!1),y==="add"&&$(),k("tasks"),(o.pathname!=="/"||o.search)&&s("/")})},[y,Or,xt,$c,i,o.pathname,o.search,s,$,k,_]),ap=r.useCallback(async u=>{if(!(!u||wc)){Nl(""),Hd(!0);try{const w=await En(u);if(!w.success){if(w.code==="WORKSPACE_NOT_FOUND"||w.code==="WORKSPACE_ID_REQUIRED"){$i();return}Nl(w.error||"Failed to switch workspace.");return}await J(!0),za(!1)}finally{Hd(!1)}}},[En,wc,J,$i]),Uc=r.useCallback(async()=>{za(!1),Vd(!0),Ni("members"),((await Ns())?.teamManagementAllowed??li)&&(await Wi(),await js(0))},[li,Ns,js,Wi]),bo=r.useCallback(async(u,w)=>{ta(null),ei(u);try{const P=await w(),pe=await P.json().catch(()=>({}));if(!P.ok){ta(pe?.error||"Team management action failed.");return}await Fi()}catch{ta("Team management action failed.")}finally{ei(null)}},[Fi]),Ql=r.useCallback(async()=>{const u=vo.trim();if(u){Ei(!0),ta(null),Tc(null);try{const w=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...zr()},credentials:"include",body:JSON.stringify({workspaceId:Ks,email:u,role:ti,permissionMode:ti==="member"?So:"read-write"})}),P=await w.json().catch(()=>({}));if(!w.ok){ta(P?.error||"Failed to send invite.");return}xc(""),P?.inviteEmailSent===!1?Tc(`Invite created, but email delivery failed${P?.inviteEmailError?`: ${String(P.inviteEmailError)}`:"."}`):Tc("Invite sent."),await Fi()}catch{ta("Failed to send invite.")}finally{Ei(!1)}}},[Jt,Fi,zr,vo,So,ti]),Ui=r.useMemo(()=>Se.trim().length>0,[Se]),Xl=r.useMemo(()=>Mi.filter(u=>u.status==="invited"),[Mi]),zi=r.useMemo(()=>{const u=Ke.length!==S.length,w=Ne.length!==We.length,P=Yt.length!==tt.length,pe=W.length!==Xs.length,ve=Wt.length!==sn.length,ut=pn.length>0,qt=Jr.length>0;return u||w||P||pe||ve||ut||qt},[S.length,We.length,sn.length,Wt.length,Ke.length,Yt.length,W.length,Ne.length,tt.length,pn,Jr]),zc=r.useMemo(()=>Hn.length!==am.length||Os.length!==rm.length,[Os.length,Hn.length]),ku=on,Zs=r.useMemo(()=>aO(ku),[ku]),vu=r.useMemo(()=>{switch(Zs.filterBar.kind){case"task-filters":return zi;case"document-filters":return zc;default:return!1}},[zc,zi,Zs.filterBar.kind]),Su=Ui||zi,wu=Vt==="archived"?Ua.length:Vt==="deleted"?ar.length:le.length,rp=Vt==="archived"?Ci.length:Vt==="deleted"?fc.length:e.filteredTasks.length,bu=Su?`${rp}/${wu}`:`${wu}`,sp=Su?`${Vt.charAt(0).toUpperCase()+Vt.slice(1)} tasks matching current filters`:`${Vt.charAt(0).toUpperCase()+Vt.slice(1)} tasks`,_u=Kt==="local"&&Zt,ui=r.useCallback(u=>{if(!u)return"Never";const w=new Date(u);return Number.isNaN(w.getTime())?"Never":w.toLocaleString()},[]),Hi=r.useMemo(()=>ui(On),[ui,On]),Cu=r.useMemo(()=>ui(lr),[ui,lr]),Au=r.useMemo(()=>ui($n),[ui,$n]),xu=zl||Sn||xa||"None",us=gn(),ms=r.useMemo(()=>F1({runtimeMode:Kt,isAuthenticated:Zt,workspaceSyncStatus:Wn,workspaceCloudSyncEnabled:qa,workspaceSyncSummary:Vr,workspaceSyncRecommendedAction:Aa,workspaceSyncError:xu,pushBlockedReason:us.pushBlockedReason||null,pullBlockedReason:us.pullBlockedReason||null,retryBlockedReason:us.retryBlockedReason||null}),[Kt,Zt,Wn,qa,Vr,Aa,xu,us.pushBlockedReason,us.pullBlockedReason,us.retryBlockedReason]),Iu=ms.lastError,[Tu,Ru]=r.useState(ms.status),op=r.useMemo(()=>q1(us),[us]),{syncRecentEvents:_o,syncRecentEventsLoading:ip,syncRecentEventsError:p,syncEventsListRef:O,loadRecentSyncEvents:z}=_O({isOpen:ou,workspaceId:Jt,refreshKeys:[$n,lr,La,Wn]}),q=ms.actionable&&Wn==="syncing"&&Ca==="active"&&la===0;r.useEffect(()=>{if(!q){Ru(ms.status);return}const u=window.setTimeout(()=>{Ru(ms.status)},1200);return()=>window.clearTimeout(u)},[ms.status,q]);const Fe=r.useMemo(()=>K1({syncRecentEvents:_o,syncRecentEventsError:p,syncRecentEventsLoading:ip}),[_o,p,ip]),De=r.useMemo(()=>Z1(_o),[_o]),Ue=r.useMemo(()=>Y1(_o),[_o]),en=r.useMemo(()=>V1(Tu),[Tu]),{workspaceSyncRepairBusy:rn,workspaceSyncRepairQueued:Ln,workspaceSyncCopied:fa,handleCopySyncDetails:sr,handleQueueOrRunRepairSync:Pr}=xO({currentWorkspaceId:Jt,syncStatusLabel:en.label,workspaceSyncSummary:ms.summary,workspaceSyncRecommendedAction:ms.recommendedAction,formattedLastSyncTime:Hi,formattedLastPullTime:Cu,formattedLastPushTime:Au,workspaceSyncDiagnostics:us,workspaceSyncPendingChanges:la,syncLastError:Iu,workspaceSyncPhase:Ca,referenceMismatchCount:De,syncRecentEvents:_o,loadRecentSyncEvents:z,pushNotice:Nt,resetWorkspaceSyncCursorAndPull:Ba,workspaceSyncBusy:sa}),ed=r.useMemo(()=>zy(Ca,rn,sa),[sa,Ca,rn]),Mf=r.useMemo(()=>fd(er)||new Date,[er]),Gi=r.useMemo(()=>rf(Mf,dn),[Mf,dn]),Co=r.useMemo(()=>{const u={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return lg.forEach(w=>{const P=vO(w,dn);u[w]=Xc(Ky(Gi,P))}),u},[Gi,dn]),Ef=r.useCallback(u=>{const w=fd(u);if(!w)return Co.mon;const P=w.getDay();return Co[P===1?"mon":P===2?"tue":P===3?"wed":P===4?"thu":P===5?"fri":P===6?we?"sat":"fri":we?"sun":"fri"]||Co.mon},[Co,we]),Jy=r.useCallback(async()=>{if(!(yo||Yo.length===0)){Jo(!0);try{for(const u of Yo){const w=u.scheduledDate||u.dueDate||Gn,P=Ef(w);await C(u.id,{scheduledDate:P,scheduledWeekKey:SO(P),orderInDay:null})}await J(!0)}finally{Jo(!1)}}},[yo,Yo,Gn,Ef,C,J]),Qy=r.useCallback(async()=>{if(!(yo||go.length===0)){Jo(!0);try{for(const u of go)await C(u.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await J(!0)}finally{Jo(!1)}}},[yo,go,C,J]),Xy=r.useMemo(()=>bm(Gi,{month:"short",day:"numeric",year:"numeric"},ma),[Gi,ma]),Df=r.useMemo(()=>{const P=(we?dn==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:lg:["mon","tue","wed","thu","fri"]).map(ve=>{const ut=fd(Co[ve])||Gi,qt=Co[ve],kn=ve==="sat"||ve==="sun";return{value:ve,label:`${kO[ve]} ${bm(ut,{month:"short",day:"numeric"},ma)}`,color:kn?"#1e3a8a":"#3b82f6",icon:"Calendar",date:qt,isPast:qt<Gn,isSelected:qt===er,isWeekend:kn}}),pe=Ud.length>0;return[...gr?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...pe?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...P]},[we,gr,Co,Gi,Ud.length,Gn,er,dn,ma]),Lf=r.useMemo(()=>{switch(h){case"category":return S;case"type":return(We||[]).map(u=>({...u,icon:u.icon||hm[u.value]?.icon,color:u.color||hm[u.value]?.color}));case"priority":return tt;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 Ze;case"assignee":return sn.map(u=>({value:u.value,label:u.label,icon:u.icon==="HelpCircle"?"Circle":u.icon,color:u.color}));case"status":return[...Xs.filter(u=>u.value!=="done"&&u.value!=="cancelled"),{value:"completed",label:"Completed",icon:yd("done").icon,color:yd("done").color}];case"schedule":return Df;default:return S}},[h,S,We,tt,Ze,sn,Df]),ek=n.jsxs("div",{className:mt.accountMenuWrap,ref:su,children:[n.jsx("button",{className:`tf-control-icon ${mt.avatarBtn}`,onClick:()=>{za(u=>{const w=!u;return w?Fc("account_menu"):(Di.current=null,$l.current={billing:!1,teamManagement:!1}),w})},title:Zt?"Account":"Account (Not signed in)","aria-label":Zt?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":zs,children:n.jsx("span",{className:mt.avatarBadge,"aria-hidden":"true",children:Bc?n.jsx("img",{src:du,alt:"",className:mt.avatarImage}):Lc||n.jsx(fi,{size:14,className:mt.avatarIcon})})}),zs&&n.jsxs("div",{className:mt.accountMenu,role:"menu","aria-label":"Account menu",children:[n.jsxs("div",{className:mt.accountMenuSection,children:[n.jsx("div",{className:mt.accountMenuSectionLabel,children:"Account"}),n.jsx("div",{className:mt.accountMenuHint,children:Yl?"Checking sign-in status...":Zt?n.jsx(n.Fragment,{children:Vl?n.jsx(n.Fragment,{children:n.jsxs("span",{className:mt.accountIdentityBlock,children:[n.jsx("span",{className:mt.accountIdentityEmail,children:qs}),Jm&&Ec&&n.jsxs("span",{className:mt.accountIdentityMetaLine,children:[n.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Email"}),n.jsx("span",{className:mt.accountIdentityMetaValue,children:Vs})]}),Qd?n.jsxs("span",{className:mt.accountIdentityMetaLine,children:[n.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),n.jsx("span",{className:mt.accountIdentityMetaValue,children:"Loading…"})]}):uu?n.jsxs("button",{"aria-label":`Subscription ${Wc}`,className:`${mt.accountIdentityMetaLine} ${mt.accountIdentityMetaAction}`,onClick:()=>{za(!1),d()},type:"button",children:[n.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),n.jsx("span",{className:mt.accountIdentityMetaValue,children:Wc})]}):Is?n.jsxs("span",{className:mt.accountIdentityMetaLine,children:[n.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),n.jsx("span",{className:mt.accountIdentityMetaValue,children:"Unavailable"})]}):null,n.jsxs("span",{className:mt.accountIdentityMetaLine,children:[n.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Runtime"}),n.jsx("span",{className:mt.accountIdentityMetaValue,children:mu})]}),n.jsxs("span",{className:mt.accountIdentityMetaLine,children:[n.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Environment"}),n.jsx("span",{className:mt.accountIdentityMetaValue,children:pu})]})]})}):"Signed in"}):"Not signed in"})]}),Km&&n.jsxs("div",{className:mt.accountMenuSection,children:[n.jsx("div",{className:mt.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),xn.length===0&&n.jsx("div",{className:mt.accountMenuHint,children:"No workspaces found for this account yet."}),xn.map(u=>n.jsxs("button",{className:`${mt.accountMenuItem} ${u.id===Jt?mt.accountMenuItemActive:""}`,onClick:()=>ap(u.id),role:"menuitem",disabled:wc||u.id===Jt,title:u.description||u.name,children:[n.jsx(Io,{size:15}),n.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[n.jsx("span",{children:u.name}),n.jsx("span",{className:mt.accountMenuMeta,children:u.role})]})]},u.id)),n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{Nl(""),Ri(!0),za(!1)},role:"menuitem",disabled:wc,children:[n.jsx(to,{size:15}),"Create Workspace"]}),Gd&&n.jsx("div",{className:mt.accountMenuError,children:Gd})]}),Kd?n.jsx("div",{className:mt.accountMenuHint,children:"Resolving team management access..."}):li?n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{Uc()},role:"menuitem",children:[n.jsx(Vk,{size:15}),"Team Management"]}):Pl?n.jsx("div",{className:mt.accountMenuHint,children:"Team Management unavailable right now."}):null,Zt&&n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{za(!1),Rl(!0)},role:"menuitem",children:[n.jsx(fi,{size:15}),"Edit Profile"]}),n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{za(!1),d()},role:"menuitem",children:[n.jsx(Fp,{size:15}),"Plans"]}),n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{za(!1),Fc("account_hub"),Hs(!0)},role:"menuitem",children:[n.jsx(fi,{size:15}),"Account Hub"]}),n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{za(!1),ko(!0)},role:"menuitem",children:[n.jsx(ec,{size:15}),"Help & Support"]}),n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{za(!1),ko(!0)},role:"menuitem",children:[n.jsx(kg,{size:15}),"Contact Support"]}),Kt==="local"&&!Zt&&!Yl&&n.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{Oi("login")},role:"menuitem",children:[n.jsx(fi,{size:15}),"Sign In / Register"]}),Zt&&n.jsxs("button",{className:mt.accountMenuItem,onClick:async()=>{za(!1),await Mr(),Kt==="cloud"&&s("/login",{replace:!0})},role:"menuitem",children:[n.jsx(qk,{size:15}),"Sign Out"]})]})]}),Bf=r.useCallback(()=>{A(u=>u==="show"?"collapse":u==="collapse"?"hide":"show")},[A]),Wf=r.useCallback(()=>{$(),_("tasks"),k("add")},[$,k,_]),tk=r.useCallback(u=>{const w=e.workstreams.find(P=>P.id===u);$(),X(Ro(w)||u),_("tasks"),k("add")},[e.workstreams,$,k,_,X]),Ff=r.useCallback(u=>{$s.current=!1,Xr(!1),kr(u),co(!1),Ws(null),Bs(!1),Fs(""),_s(""),ln("");const w=u.entityType==="workstream"&&pn&&_t.initiativeById.get(pn)||null;tr(w?rs(w):""),pa(null)},[_t.initiativeById,pn]),Of=r.useCallback((u,w)=>{$s.current=!1,Xr(!1),Ws(u),Bs(!1),Fs(""),_s(""),ln("");const P=u.entityType==="workstream"&&((w?_t.initiativeById.get(w):null)||pn&&_t.initiativeById.get(pn))||null;tr(P?rs(P):""),pa(null)},[_t.initiativeById,pn]),cp=r.useCallback(()=>{$s.current=!1,Xr(!1),kr(null),Fs(""),_s(""),ln(""),tr("")},[]),$f=r.useCallback(()=>{$s.current=!1,Xr(!1),Ws(null),Fs(""),_s(""),ln(""),tr("")},[]),nk=r.useCallback(async()=>{const u=Wo||Bo;if(!u||$s.current)return;$s.current=!0,Xr(!0);const w=!!Wo,P=cs.trim()||null;try{if(u.entityType==="initiative")if(u.mode==="edit")await e.updateInitiative(u.targetId,{title:Fo.trim()||"Untitled Initiative",description:Oo.trim()||null,ownerId:P}),yr({type:"initiative",id:u.targetId}),pa(null),Nt("Initiative updated","success");else{const pe=await e.createInitiative({title:Fo.trim()||"Untitled Initiative",description:Oo.trim()||null,ownerId:P});yr({type:"initiative",id:pe.id}),pa(null),Nt("Initiative created","success")}else{const pe=zn.trim(),ve=pe.length===0?null:Cp(_t.initiatives,pe);if(pe.length>0&&!ve){Nt("Initiative not found by that reference.","error");return}const ut={title:Fo.trim()||"Untitled Workstream",description:Oo.trim()||null,ownerId:P,initiativeId:ve?.id||null};if(u.mode==="edit")await e.updateWorkstream(u.targetId,ut),w?pa(u.targetId):(yr({type:"workstream",id:u.targetId}),pa(null)),Nt("Workstream updated","success");else{const qt=await e.createWorkstream(ut);w?pa(qt.id):(yr({type:"workstream",id:qt.id}),pa(null)),Nt("Workstream created","success")}}w?$f():cp()}catch(pe){Nt(pe instanceof Error?pe.message:"Failed to save planning item.","error")}finally{$s.current=!1,Xr(!1)}},[cp,$f,Oo,zn,cs,Fo,Bo,Wo,_t.initiatives,e,Nt]),ak=r.useCallback(u=>{Qr(w=>{const P=new Set(w);return P.has(u)?P.delete(u):P.add(u),P})},[]),rk=r.useCallback(u=>{ea(w=>w===u?"":u),lo("")},[]),sk=r.useCallback((u,w)=>{lo(P=>{const pe=P===u?"":u;return ea(pe&&w||""),pe})},[]),ok=r.useCallback(u=>{kr(null),Ws(null),co(!1),Bs(!1),yr(u?{type:"initiative",id:u}:null),pa(null)},[]),ik=r.useCallback(u=>{kr(null),Ws(null),co(!1),Bs(!1),yr(u?{type:"workstream",id:u}:null),pa(null)},[]),ck=r.useCallback(u=>{Ws(null),Bs(!1),pa(u)},[]),lp=r.useCallback((u,w)=>{if(u==="workstream"&&w){Of({mode:"create",entityType:"workstream"},w);return}if(Ff({mode:"create",entityType:u}),u==="workstream"){const P=(w?_t.initiativeById.get(w):null)||(pn?_t.initiativeById.get(pn):null)||null;tr(P?rs(P):"")}},[Ff,Of,_t.initiativeById,pn]),Uf=r.useCallback((u,w)=>{if(u==="initiative"){const P=_t.initiativeById.get(w);if(!P)return;kr({mode:"edit",entityType:"initiative",targetId:w}),Fs(P.title),_s(P.description||""),ln(P.ownerId?String(P.ownerId):""),tr("")}else{const P=_t.workstreamById.get(w)||_t.standaloneWorkstreams.find(ve=>ve.id===w);if(!P)return;kr({mode:"edit",entityType:"workstream",targetId:w}),Fs(P.title),_s(P.description||""),ln(P.ownerId?String(P.ownerId):"");const pe=P.initiativeId&&_t.initiativeById.get(P.initiativeId)||null;tr(pe?rs(pe):"")}pa(null)},[_t.initiativeById,_t.standaloneWorkstreams,_t.workstreamById]),Nu=r.useCallback(async(u,w)=>{const P=e.workstreams.find(qt=>qt.id===u);if(!P)return Nt("Workstream not found.","error"),!1;const pe=typeof w=="string"?w.trim():w===null?"":zn.trim(),ve=pe.length===0?null:Cp(_t.initiatives,pe);if(pe.length>0&&!ve)return Nt("Initiative not found by that reference.","error"),!1;const ut=ve?.id||null;if((P.initiativeId||null)===ut)return Nt(ut?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info"),!1;try{return await e.updateWorkstream(u,{initiativeId:ut}),tr(ve?rs(ve):""),Nt(ut?"Initiative set":"Initiative removed","success"),!0}catch{return Nt("Failed to set initiative.","error"),!1}},[zn,_t.initiatives,e,Nt]),ju=r.useCallback(async(u,w)=>{const P=Sl.get(u);if(!P)return Nt("Task not found.","error"),!1;const pe=w||null;if(_t.initiativeById.has(u)||_t.workstreamById.has(u))return Nt("Only execution tasks can be moved into workstreams.","error"),!1;if(pe&&!_t.workstreamById.has(pe))return Nt("Workstream not found.","error"),!1;if((P.workstreamId||null)===pe)return Nt(pe?"Task already belongs to that workstream.":"Task is already standalone.","info"),!1;try{const ve=await fetch(`/api/taskforce/task/${u}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:pe})});if(!ve.ok){const ut=await ve.json().catch(()=>({}));return Nt(ut?.error||"Failed to set workstream.","error"),!1}return await ve.json().catch(()=>null),await J(!0),Nt(pe?"Workstream set":"Workstream removed","success"),!0}catch{return Nt("Failed to set workstream.","error"),!1}},[J,Sl,_t.initiativeById,_t.workstreamById,Nt]),lk=r.useCallback(async(u,w)=>{const P=w.trim();if(!P)return Nt("Enter a task reference.","error"),!1;const pe=Lg(P),ve=Ko.find(ut=>ut.id===P||nc(ut)===P||pe!==null&&ut.referenceNumber===pe);return ve?ju(ve.id,u):(Nt("Task not found by that reference.","error"),!1)},[ju,Ko,Nt]),dk=r.useCallback(async(u,w)=>{const P=w.trim();if(!P)return Nt("Enter a workstream reference.","error"),!1;const pe=_t.initiativeById.get(u);if(!pe)return Nt("Initiative not found.","error"),!1;const ve=ly(P),ut=e.workstreams.find(qt=>qt.id===P||Ro(qt)===P||ve!==null&&qt.referenceNumber===ve);return ut?Nu(ut.id,rs(pe)):(Nt("Workstream not found by that reference.","error"),!1)},[Nu,_t.initiativeById,e.workstreams,Nt]),Hc=r.useCallback((u,w)=>{const P=`${u}:${w}`,pe=ll.current.get(P);if(pe)return pe;const ve=u==="initiative"?e.initiatives.find(ut=>ut.id===w):e.workstreams.find(ut=>ut.id===w);return Array.isArray(ve?.attachments)?ve.attachments:[]},[e.initiatives,e.workstreams]),Gc=r.useCallback((u,w,P)=>{const pe=`${u}:${w}`;ll.current.set(pe,P);const ut=(ki.current.get(pe)||Promise.resolve()).catch(()=>{}).then(()=>u==="initiative"?e.updateInitiative(w,{attachments:P}):e.updateWorkstream(w,{attachments:P}));ki.current.set(pe,ut),ut.catch(qt=>{Nt(qt instanceof Error?qt.message:"Failed to update planning context.","error")}).finally(()=>{ki.current.get(pe)===ut&&ki.current.delete(pe)})},[e,Nt]),uk=r.useCallback((u,w,P)=>{const pe=Hc(u,w);Gc(u,w,[...pe,P])},[Hc,Gc]),mk=r.useCallback((u,w,P)=>{const pe=Hc(u,w);Gc(u,w,pe.filter((ve,ut)=>ut!==P))},[Hc,Gc]),pk=r.useCallback((u,w,P,pe)=>{const ut=Hc(u,w).map((qt,kn)=>kn!==P?qt:typeof qt=="string"?{path:qt,caption:pe,timestamp:new Date().toISOString()}:{...qt,caption:pe});Gc(u,w,ut)},[Hc,Gc]),zf=r.useCallback(u=>{ea(u),lo("")},[]),Hf=r.useCallback(u=>{lo(u),ea(u&&_t.workstreamInitiativeIds.get(u)||"")},[_t.workstreamInitiativeIds]),dp=r.useCallback(u=>{const w=cg(u,ds);if(w!==u){const P=ds.find(pe=>pe.id===u)?.label||"That module";Nt(`${P} is not available in this build yet.`,"error");return}Or(),_(w)},[Or,Nt,_,ds]),Gf=r.useCallback(()=>{if(on==="tasks"&&Fr){Eo(!1),yr(null),pa(null),kr(null);return}if(on!=="tasks"){_("tasks"),Eo(!0);return}Eo(u=>!u)},[Fr,on,_]),Vf=r.useCallback(()=>{if(on!=="docs"){_("docs"),Do(!0);return}Do(u=>!u)},[on,_]),qf=r.useCallback(()=>{if(on!=="annotate"){_("annotate"),io(!0);return}io(u=>!u)},[on,_]),Kf=r.useCallback(()=>{if(on!=="agents"){_("agents"),yi(!0);return}yi(u=>!u)},[on,_]),fk=r.useCallback(u=>{Or(),_("tasks"),Ft(u)},[Or,Ft,_]),hk=r.useCallback(u=>{Or(),_("tasks"),Ft(u)},[Or,Ft,_]),gk=r.useCallback((u,w)=>{uo(u),wi(w?.sessionId??null),Nd(P=>P+1),_("annotate")},[_]),yk=r.useCallback(({target:u,sessionId:w})=>{uo(P=>!P&&!u||P&&u&&P.taskId===u.taskId&&P.taskReferenceLabel===u.taskReferenceLabel&&P.assetId===u.assetId&&P.imageReferenceLabel===u.imageReferenceLabel&&P.path===u.path&&P.displayName===u.displayName?P:u),wi(P=>P===w?P:w)},[]),Zf=r.useMemo(()=>[{value:"created",label:qe("standalone.sortCreated")},{value:"updated",label:qe("standalone.sortUpdated")},{value:"priority",label:qe("standalone.sortPriority")},{value:"complexity",label:qe("standalone.sortComplexity")},...py(Et,[...e.searchAgnosticTasks,...Ua])],[Ua,e.searchAgnosticTasks,Et]),Yf=r.useMemo(()=>[{value:"status",label:qe("standalone.groupStatus")},{value:"category",label:qe("standalone.groupCategory")},{value:"type",label:qe("standalone.groupType")},{value:"priority",label:qe("standalone.groupPriority")},{value:"complexity",label:qe("standalone.groupComplexity")},{value:"assignee",label:qe("standalone.groupAssignee")},{value:"schedule",label:qe("standalone.groupSchedule")}],[]),Jf=r.useMemo(()=>ds.filter(u=>u.enabled),[ds]),Qf=r.useMemo(()=>[{key:"empty-columns",icon:I==="show"?n.jsx(eh,{size:16}):I==="collapse"?n.jsx(th,{size:16}):n.jsx(lf,{size:16}),title:qe(I==="show"?"standalone.showEmptyColumns":I==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:Bf,active:I!=="show"},{key:"compressed-cards",icon:rt?n.jsx(Kk,{size:16}):n.jsx(Zk,{size:16}),title:qe(rt?"standalone.expandCards":"standalone.compressCards"),onClick:()=>wt(!rt),active:rt}],[rt,Bf,I]),kk=r.useMemo(()=>[{key:"filter-toggle",icon:n.jsx(Sg,{size:16}),title:qe("standalone.toggleFilters"),onClick:()=>cc(!Xn),active:Xn,className:vu?f.filterGlow:""}],[vu,cc,Xn]),vk=r.useMemo(()=>{switch(Zs.filterBar.kind){case"task-filters":return n.jsx(kW,{categoryFilterOptions:vl,typeFilterOptions:hc,priorities:tt,taxonomyDisplayLabels:Oe,filterCategories:Ke,setFilterCategories:Je,filterTypes:Ne,setFilterTypes:zt,filterPriorities:Yt,setFilterPriorities:Pt,filterStatus:W,setFilterStatus:Q,filterAssignees:Wt,setFilterAssignees:Dt,assigneeOptions:sn,initiativeFilterOptions:wl,selectedInitiativeId:pn,setSelectedInitiativeId:zf,workstreamFilterOptions:Wd,selectedWorkstreamId:Jr,setSelectedWorkstreamId:Hf,taskScope:Vt,setTaskScope:Vn,showArchive:po,setShowArchive:gl,fetchArchive:yl,onDeleteAllDeleted:()=>{const u=ar.length;u===0||!window.confirm(`Permanently delete ${u} deleted task${u===1?"":"s"}? This cannot be undone.`)||l()},clearFilters:()=>{ga(),ea(""),lo("")}});case"document-filters":return n.jsx(vW,{typeFilters:Hn,setTypeFilters:vi,attachmentFilters:Os,setAttachmentFilters:Si,clearFilters:()=>{vi(am.map(u=>u.value)),Si(rm.map(u=>u.value))}});default:return n.jsx(gW,{})}},[sn,vl,ga,ar.length,Os,Hn,Wt,Ke,Yt,W,Ne,zf,Hf,wl,tt,pn,Jr,Si,vi,Dt,Je,Pt,Q,zt,ea,lo,gl,Vn,po,Vt,Oe,hc,Wd,Zs.filterBar.kind,yl,l]),Sk=r.useMemo(()=>[{key:"zen-toggle",icon:n.jsx(Yk,{size:16,fill:D?"currentColor":"none"}),title:qe(D?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>U(),active:D}],[D,U]),wk=r.useMemo(()=>({search:n.jsx(fW,{value:Se,placeholder:qe("standalone.searchPlaceholder"),active:Ui,onChange:Ie,onClear:()=>Ie(""),clearTitle:qe("standalone.clearSearchTitle")}),sort:n.jsx(ng,{label:n.jsxs(n.Fragment,{children:[n.jsx(Jk,{size:12})," ",qe("standalone.sortLabel")]}),value:qn,options:Zf,onChange:u=>Kn(u),trailingAction:n.jsx("button",{className:`tf-control-icon ${f.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?qe("standalone.sortDirectionDescTitle"):qe("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?n.jsx(fg,{size:14}):n.jsx(hg,{size:14})})}),"divider-primary":n.jsx(ag,{}),grouping:n.jsx(ng,{label:n.jsxs(n.Fragment,{children:[n.jsx(Fp,{size:12})," ",qe("standalone.groupLabel")]}),value:h,options:Yf,onChange:u=>g(u)}),"divider-secondary":n.jsx(ag,{}),"task-display-actions":n.jsx(Np,{actions:Qf})}),[h,Yf,dp,Ui,e,Se,g,Ie,Kn,qn,Zf,Qf,Zs.moduleId]),bk=r.useMemo(()=>({"add-task":n.jsx(hW,{icon:n.jsx(to,{size:16}),label:qe("standalone.addTask"),onClick:Wf}),"add-document":null}),[Wf]),td=r.useMemo(()=>{const u={tasks:n.jsx(av,{size:18}),docs:n.jsx(Op,{size:18}),annotate:n.jsx(nv,{size:18}),workflows:n.jsx(nh,{size:18}),agents:n.jsx(sm,{size:18})},w=tn.workspaceToolButtonDisabled,P=on==="docs"?n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${Ss?tn.workspaceToolButtonActive:""}`.trim(),onClick:Vf,title:Ss?"Collapse document tray":"Document tray","aria-label":Ss?"Collapse document tray":"Document tray",children:Ss?n.jsx(To,{size:18}):n.jsx(Io,{size:18})}):on==="annotate"?n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${Ls?tn.workspaceToolButtonActive:""}`.trim(),onClick:qf,title:Ls?"Collapse image tray":"Image tray","aria-label":Ls?"Collapse image tray":"Image tray",children:Ls?n.jsx(To,{size:18}):n.jsx(Io,{size:18})}):on==="agents"?n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${Yr?tn.workspaceToolButtonActive:""}`.trim(),onClick:Kf,title:Yr?"Collapse agent tray":"MCP settings tray","aria-label":Yr?"Collapse agent tray":"MCP settings tray",children:Yr?n.jsx(To,{size:18}):n.jsx(ev,{size:18})}):on==="workflows"?n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${w}`.trim(),title:"Workflow tray coming soon","aria-label":"Workflow tray coming soon",disabled:!0,children:n.jsx(nh,{size:18})}):n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${on==="tasks"&&Fr?tn.workspaceToolButtonActive:""}`.trim(),onClick:Gf,title:on==="tasks"&&Fr?"Collapse planning trays":"Planning","aria-label":on==="tasks"&&Fr?"Collapse planning trays":"Planning",children:on==="tasks"&&Fr?n.jsx(To,{size:18}):n.jsx(tv,{size:18})});return n.jsxs("aside",{className:tn.workspaceToolRail,"aria-label":"Workspace tools",children:[n.jsxs("div",{className:tn.workspaceToolRailMain,children:[P,n.jsx("div",{className:tn.workspaceToolRailDivider}),Jf.map(pe=>n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${on===pe.id?tn.workspaceToolButtonActive:""}`.trim(),onClick:()=>dp(pe.id),title:pe.label,"aria-label":pe.label,children:u[pe.id]},pe.id))]}),n.jsxs("div",{className:tn.workspaceToolRailBottom,children:[n.jsx("div",{className:tn.workspaceToolRailDivider}),n.jsx("button",{type:"button",className:`${tn.workspaceToolButton} ${y==="settings"?tn.workspaceToolButtonActive:""}`.trim(),onClick:()=>{bn("general"),k("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:n.jsx(cf,{size:18})})]})]})},[y,Yr,Ss,Kf,Vf,qf,dp,Gf,Ls,Fr,on,bn,k,Jf]),[Xf,_k]=r.useState(null),Ck=r.useCallback(u=>{_k(u)},[]),Ak=n.jsx(YF,{open:Fr,leftOffset:56,initiatives:_t.initiatives,standaloneWorkstreams:_t.standaloneWorkstreams,allStandaloneWorkstreams:_t.allStandaloneWorkstreams,activeInitiativeId:pn,activeWorkstreamId:Jr,expandedInitiativeIds:il,detail:yc,editor:Bo,secondaryPane:bl,currentWorkspaceId:Jt,assigneeOptions:sn.map(u=>({value:String(u.value),label:u.label,kind:u.kind,username:u.username??null,archivedAt:u.archivedAt??null})),draftInitiativeSummary:Fd,draftTitle:Fo,draftDescription:Oo,draftOwner:cs,draftInitiativeId:zn,onChangeDraftTitle:Fs,onChangeDraftDescription:_s,onChangeDraftOwner:ln,onChangeDraftInitiativeId:tr,onCollapseTreePane:()=>Lo(!0),onExpandTreePane:()=>Lo(!1),onCollapsePrimaryPane:()=>co(!0),onExpandPrimaryPane:()=>co(!1),onCollapseSecondaryPane:()=>Bs(!0),onExpandSecondaryPane:()=>Bs(!1),onBackFromSecondary:()=>{$s.current=!1,Xr(!1),Ws(null),pa(null)},treeCollapsed:ws,primaryCollapsed:Nr,secondaryCollapsed:yn,onCancelEditor:cp,onSubmitEditor:nk,isSubmittingEditor:cl,onCreateInitiative:()=>lp("initiative"),onCreateWorkstream:()=>lp("workstream"),onCreateTaskInWorkstream:tk,onCreateWorkstreamInInitiative:u=>lp("workstream",u),onAssignInitiativeToWorkstream:Nu,onOpenTaskById:Ft,onRemoveTaskFromWorkstream:u=>{ju(u,null)},onAttachTaskToWorkstreamByReference:lk,onAttachWorkstreamToInitiativeByReference:dk,onAddPlanningContextFile:uk,onRemovePlanningContextFile:mk,onUpdatePlanningContextCaption:pk,onToggleInitiative:ak,onSelectInitiative:rk,onSelectWorkstream:sk,onOpenInitiativeDetails:ok,onOpenWorkstreamDetails:ik,onOpenNestedWorkstreamDetails:ck,onEditInitiative:u=>Uf("initiative",u),onEditWorkstream:u=>Uf("workstream",u),onArchiveInitiative:u=>{e.archiveInitiative(u).then(()=>{Nt("Initiative archived","success")}).catch(w=>{Nt(w instanceof Error?w.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:u=>{e.unarchiveInitiative(u).then(()=>{Nt("Initiative unarchived","success")}).catch(w=>{Nt(w instanceof Error?w.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:u=>{e.archiveWorkstream(u).then(()=>{Nt("Workstream archived","success")}).catch(w=>{Nt(w instanceof Error?w.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:u=>{e.unarchiveWorkstream(u).then(()=>{Nt("Workstream unarchived","success")}).catch(w=>{Nt(w instanceof Error?w.message:"Failed to unarchive workstream.","error")})}}),xk=Zs.headerSections.map(u=>{const w=wk[u];return w?n.jsx(ze.Fragment,{children:w},u):null}).filter(Boolean),Ik=Zs.primaryAction?bk[Zs.primaryAction]:null;return n.jsxs("div",{className:`${tn.standaloneWrapper} ${D?f.zenModeEnabled:""}`,"data-theme":xe,children:[n.jsx(pW,{projectName:Ia,currentWorkspaceId:Jt,runtimeMode:Kt,theme:xe,onBrandClick:np,meta:n.jsxs(n.Fragment,{children:[n.jsx("span",{className:f.taskCountBadge,title:sp,children:bu}),$r&&$r!=="anonymous"&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:f.taskCountBadge,title:"Tasks assigned to me",children:[n.jsx(fi,{size:13,className:f.taskCountBadgeIcon,"aria-hidden":"true"}),$d]}),n.jsxs("span",{className:`${f.taskCountBadge} ${Il>0?f.taskCountBadgeAlert:""}`.trim(),title:"Tasks overdue",children:[n.jsx(Qk,{size:13,className:f.taskCountBadgeIcon,"aria-hidden":"true"}),Il]})]}),_u&&n.jsx("button",{className:"tf-control-icon",onClick:cu,title:`Sync manager: ${en.label} | Last success: ${Hi}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${en.border}`,background:en.background,color:en.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:en.icon==="off"?n.jsx(Xk,{size:16}):n.jsx(wg,{size:16})})]}),actions:n.jsxs(n.Fragment,{children:[i&&n.jsxs(n.Fragment,{children:[Zt&&_a?.stripeCustomerId&&n.jsx("button",{className:"tf-control-icon",onClick:()=>{Jl()},title:"Manage billing",disabled:Nc,children:"Manage billing"}),n.jsx("button",{className:"tf-control-icon",onClick:()=>{if(Oc){$c();return}m()},title:Oc?"Continue to Taskforce":"Back",disabled:rr,children:Oc?"Take Me to Taskforce":"Back"})]}),!i&&n.jsxs(n.Fragment,{children:[xk,Ik]}),n.jsx(Np,{actions:Sk}),!i&&n.jsx(Np,{actions:kk}),ek]})}),n.jsx(Py,{notice:Lr,onDismiss:Br}),Mn&&n.jsx("div",{className:he.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),!i&&Xn&&vk,i?n.jsx("div",{className:`${tn.standalonePage} ${tn.standaloneContent} ${f.appScrollbar} tf-scrollbar`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",scrollbarGutter:"stable",background:"var(--surface-page)"},children:n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(PO,{...e,currentTheme:xe,projectName:Ia,currentWorkspaceId:Jt,authUserId:Zn,apiBaseUrl:Zl,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",resolveCloudAuthUrl:In,embedded:!0,shellOwnsScroll:!0,onAccountProfileSummaryChange:ep,onContinueToTaskforce:$c,continueBusy:rr})})}):on==="docs"&&Go?n.jsxs("div",{className:`${tn.standalonePage} ${tn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(RO,{tasks:le,runtimeMode:Kt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:Hn,attachmentFilters:Os,onTypeFiltersChange:vi,onAttachmentFiltersChange:Si,documentTrayOpen:Ss,onCloseDocumentTray:()=>Do(!1),requestedDocPath:Rd,requestedDocAssetId:Em,onRequestedDocHandled:()=>{dl(null),ul(null)},onBackToTask:hk,enableTaskGeneration:!0})})]}):on==="annotate"&&pc?n.jsxs("div",{className:`${tn.standalonePage} ${tn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(TO,{runtimeMode:Kt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:Jt,sessionLoadReady:bi,requestedTarget:nr,requestedSessionId:ls,requestedOpenVersion:Dm,imageTrayOpen:Ls,onCloseImageTray:()=>io(!1),resolveTaskReferenceLabel:Dd,resolveImageReferenceLabel:Ld,onOpenTarget:gk,onContextChange:yk,onBackToTask:fk})})]}):on==="workflows"?n.jsxs("div",{className:`${tn.standalonePage} ${tn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(NO,{availableWorkflows:wa,availableEnvironments:Gt,exportEnvironment:Tn,exportWorkflowsPath:e.exportWorkflowsPath,exportingResource:ys,exportResult:Qa,onExportEnvironmentChange:e.setExportEnvironment,onExportWorkflows:Oa,onRefreshWorkflows:mr,onFetchWorkflowTemplate:e.fetchWorkflowTemplate,onFetchWorkflowOverrideNames:e.fetchWorkflowOverrideNames,onSaveWorkflowTemplateDraft:e.saveWorkflowTemplateDraft,onResetWorkflowTemplateDraft:e.resetWorkflowTemplateDraft})})]}):on==="agents"?n.jsxs("div",{className:`${tn.standalonePage} ${tn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(jO,{workspaceId:Jt,cloudAuthConfigured:Pn,authSessionResolved:hn,isAuthenticated:Zt,cloudAiProfileSeatUsage:_a?.aiProfileSeatUsage??null,agentTrayOpen:Yr,onCloseAgentTray:()=>yi(!1),mcpSettingsNode:n.jsx(dg,{settingsModel:{...ge,initialSection:"mcp",onOpenCloudAuth:Oi},renderMode:"mcp-only"})})})]}):n.jsxs("div",{className:`${tn.standalonePage} ${tn.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:Fr?`${56+_l+6}px`:"62px",paddingRight:h==="schedule"&&jo?`${sf}px`:0},children:[td,n.jsx("div",{ref:Ck,style:{position:"absolute",inset:0,zIndex:35,pointerEvents:"none"}}),n.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.loadingTasks&&Ii.length>0&&n.jsx("div",{className:f.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:n.jsx(br,{size:14,className:f.spinner})}),n.jsx(E1,{tasks:Cl,allTasks:Al,columns:Lf,groupBy:h,scheduleDates:Co,searchQuery:Se,filterCategories:Ke,filterTypes:Ne,filterPriorities:Yt,filterStatus:W,filterAssignees:Wt,filtersReady:Ht,assigneeOptions:sn,scheduleFilteredTaskIds:Array.from(Bd),copiedId:St,taxonomies:Et,types:We,priorities:tt,onUpdateTask:C,onTaskClick:u=>ie(u),onOpenTaskById:Ft,onCopyId:ot,onToggleInProgress:re,onToggleReview:At,onToggleComplete:Be,onToggleCancel:Rt,onSetStatus:Ti,onArchiveTask:Bt,onAddTaskToColumn:zd,showTaskCardStatusLabel:ne,onScheduleDaySelected:u=>{ro(u);const w=fd(u);w&&Mo(`${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:h==="schedule"?so:void 0,onScrollLeftChange:u=>{h==="schedule"&&ic(u)},emptyColumnMode:I,categories:S,compressed:rt,readOnlyMode:Vt==="deleted"?"deleted":Vt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:qn,sortOrder:e.sortOrder,planningDropTargets:Xf?Xi.createPortal(Ak,Xf):null,onAssignTaskToWorkstream:ju,onAssignWorkstreamToInitiative:Nu,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:u=>{if(Vt==="deleted"){const w=Vo.get(u);if(!w)return;yt(w.id);return}Ot(u)},onDelete:u=>{if(Vt==="deleted"){const w=Vo.get(u);if(!w||!window.confirm("Permanently delete this task? This cannot be undone."))return;E(w.id);return}Ve(u)}},`${h}-${Lf.map(u=>String(u.value)).join("|")}-${Co.mon}`),h==="schedule"&&!jo&&n.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{yr(null),Xa(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:n.jsx(To,{size:16})})]}),h==="schedule"&&n.jsx(wO,{open:jo,onClose:()=>Xa(!1),scheduleSelectedDate:er,setScheduleSelectedDate:ro,scheduleCalendarMonth:Po,setScheduleCalendarMonth:Mo,scheduleShowWeekends:we,setScheduleShowWeekends:ee,scheduleShowBacklog:gr,setScheduleShowBacklog:Pa,scheduleOnlyExpired:$a,setScheduleOnlyExpired:Rr,expiredScheduledCount:xl,overdueDueCount:Od,expiredLeafCandidates:Yo,expiredRecoveryCandidates:go,onMoveExpiredToSelectedWeek:Jy,onMoveExpiredToBacklog:Qy,scheduleBulkBusy:yo,globalWeekStartsOn:dn,resolvedLocale:ma,todayDateOnly:Gn,scheduleBaseTasks:Ai,scheduleWeekStart:Gi,scheduleWeekLabel:Xy})]}),n.jsxs(Es,{isOpen:y==="add",onClose:kc,title:de?Lt?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:oo?"full":"xl",theme:xe,headerActions:n.jsx("button",{className:"tf-control-icon",onClick:()=>lc(u=>!u),title:oo?"Exit full screen":"Enter full screen","aria-label":oo?"Exit full screen":"Enter full screen",children:oo?n.jsx(th,{size:18}):n.jsx(eh,{size:18})}),draggable:!oo,closeOnOverlayClick:!1,children:[n.jsx(jy,{editingTaskId:de,loading:ke,autoSaveState:vs,title:j,currentTask:Lt,currentTaskWorkstream:Rn,currentTaskInitiative:Tr,workstreamInput:L,onWorkstreamInputChange:X,onSetWorkstreamForCurrentTask:ht,handleSubmit:se,resetForm:$,handleCopyId:ot,copiedId:St,tasks:le,handleToggleInProgress:re,handleToggleReview:At,handleToggleComplete:Be,handleToggleCancel:Rt,handleSetStatus:Ti,handleArchiveTask:Bt,handleUnarchiveTask:u=>{if(Lt?.isDeleted){const w=Vo.get(u);if(!w)return;yt(w.id);return}Ot(u)},handleRestoreDeletedTask:Lt?.deletedRecordId?u=>{yt(u)}:void 0,handlePermanentlyDeleteDeletedTask:Lt?.deletedRecordId?u=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(E(u),$(),k("tasks"))}:void 0}),n.jsx(Ny,{editingTaskId:de,error:K,title:j,description:ue,checklistItems:G,category:be,type:me,priority:Me,complexity:Ee,manualComplexityEnabled:M,approach:b,assignee:B,scheduledDate:fe,dueDate:Le,workstreamInput:L,formTaxonomies:Ce,onTaxonomyChange:(u,w)=>Ae(P=>({...P,[u]:w})),taxonomies:Et,comments:Re,newCommentText:$e,contextFiles:st,currentWorkspaceId:Jt,apiBaseUrl:Zl,descriptionFocused:Ct,showMarkdownHelp:Qe,showChecklist:ae,checklistEnabled:V,showComments:ft,categories:S,types:We,priorities:tt,taxonomyDisplayLabels:Oe,assigneeOptions:sn,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:St,onTitleChange:H,onDescriptionChange:ye,onChecklistItemsChange:je,onCategoryChange:ce,onTypeChange:Te,onPriorityChange:Pe,onComplexityChange:Z,onApproachChange:u=>{R(u),Ae(w=>({...w,approach:u}))},onAssigneeChange:Y,onScheduledDateChange:te,onDueDateChange:oe,onWorkstreamInputChange:X,onNewCommentTextChange:vt,onDescriptionFocusedChange:dt,onShowMarkdownHelpChange:Tt,onShowChecklistChange:Ge,onShowCommentsChange:it,onOpenSettings:u=>{bn(u),k("settings")},onSubmit:se,commentsEndRef:no,onAddComment:()=>Mt($e),onOpenTaskById:Ft,onAddContextFile:u=>{uc(w=>[...w,u])},onRemoveContextFile:async u=>{uc(w=>w.filter((P,pe)=>pe!==u))},onUpdateContextCaption:(u,w)=>{uc(P=>P.map((pe,ve)=>ve!==u?pe:typeof pe=="string"?{path:pe,caption:w,timestamp:new Date().toISOString()}:{...pe,caption:w}))},onCopyId:ot,onToggleInProgress:re,onToggleReview:At,onToggleComplete:Be,onToggleCancel:Rt,onSetStatus:Ti,onArchiveTask:Bt,onUnarchive:u=>{if(Lt?.isDeleted){const w=Vo.get(u);if(!w)return;yt(w.id);return}Ot(u)},currentTask:Lt})]}),n.jsx(Es,{isOpen:y==="settings",onClose:kc,title:"Settings",size:"xl",theme:xe,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:n.jsx(r.Suspense,{fallback:n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:n.jsx(br,{size:20,className:f.spinner})}),children:n.jsx(dg,{settingsModel:{...ge,onOpenCloudAuth:Oi},onSectionChange:bn})})}),n.jsx(L2,{prompt:Wr,theme:xe,onClose:Qn,onConfirm:ao}),n.jsx(B2,{isOpen:Zm,theme:xe,onClose:Pc,onConfirm:Ym}),n.jsx(D2,{isOpen:Tl,theme:xe,onClose:()=>ko(!1),supportMailtoHref:ql,onOpenSettings:()=>{ko(!1),k("settings"),bn("general")},onOpenAccountHub:()=>{ko(!1),Fc("account_hub"),Hs(!0)}}),n.jsx(M2,{isOpen:vc,theme:xe,onClose:fu,onSave:()=>{yu()},displayName:ri,email:Vs,avatarDisplayUrl:Kl,accountBadgeInitial:Lc,saveBusy:tu,avatarBusy:Fl,saveError:nu,saveNotice:au,onDisplayNameChange:si,onOpenAvatarManager:()=>{ts(null),ns(null),Sc(!0)}}),n.jsx(I2,{isOpen:Bm,theme:xe,title:"Edit Profile Photo",currentImageUrl:Kl,fallbackInitial:Lc,accept:MO,busy:Fl,hasPendingImage:!!ca,canRemove:!!Kl,error:nu,notice:au,onClose:()=>Sc(!1),onApplyImage:Xm,onRemoveImage:gu,onDiscardPendingImage:hu}),n.jsx(o2,{isOpen:Qo,theme:xe,runtimeMode:Kt,authRequiredForApi:aa,isAuthenticated:Zt,hasAuthIdentity:Vl,authIdentityLabel:qs,billingLoading:Qd,billingError:Is,billingActionError:Vm,billingNotice:Bl,billingActionBusy:Nc,billingIntervalChoice:ai,accountProfileSummary:_a,currentWorkspaceId:Jt,canOpenTeamManagement:li,canManageWorkspaceSync:Ul,workspaceCloudSyncEnabled:qa,syncStatusLabel:en.label,workspaceSyncError:zl,syncControlBusy:iu,cloudAuthEnabled:Pn,availableAuthProviders:Er,onFetchLoginMethods:cn,onUnlinkLoginMethod:mn,onAddPassword:ka,onLinkProvider:u=>Cr(u),onClose:()=>Hs(!1),onOpenWorkspaceAudit:()=>{Hs(!1),Uc(),Ni("audit")},onBillingIntervalChange:qm,onRefreshBilling:()=>{Ns()},onUpdateInterval:()=>{tp()},onManageBilling:()=>{Jl()},onStartCheckout:()=>{Bi()},onToggleWorkspaceSync:u=>{lu(u)},onOpenHelp:()=>{Hs(!1),ko(!0)}}),n.jsx(I1,{isOpen:jl,theme:xe,teamPlanMode:qd,teamMgmtError:jr,teamManagementTab:Fm,teamUsersLoading:Zd,teamUsers:Mi,teamActionBusyUserId:Ml,teamInviteFeedback:Yd,teamInviteEmail:vo,teamInviteRole:ti,teamInvitePermissionMode:So,teamInviteBusy:Ic,pendingInvites:Xl,teamAuditLoading:Om,teamAuditEvents:$m,teamAuditPage:xs,teamAuditPages:Gm,teamAuditHasMore:zm,onClose:()=>Vd(!1),onOpenMembersTab:()=>{Ni("members"),Wi()},onOpenInvitesTab:()=>Ni("invites"),onOpenAuditTab:()=>{Ni("audit"),js(xs)},onMemberRoleChange:(u,w)=>{bo(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...zr()},credentials:"include",body:JSON.stringify({workspaceId:Ks,role:w})}))},onMemberPermissionChange:(u,w)=>{bo(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...zr()},credentials:"include",body:JSON.stringify({workspaceId:Ks,mode:w})}))},onToggleMemberDisabled:(u,w)=>{bo(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...zr()},credentials:"include",body:JSON.stringify({workspaceId:Ks,disabled:w})}))},onRevokeInvite:u=>{bo(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...zr()},credentials:"include",body:JSON.stringify({workspaceId:Ks})}))},onRemoveMember:u=>{bo(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}?workspaceId=${encodeURIComponent(Ks)}`,{method:"DELETE",headers:zr(),credentials:"include"}))},onInviteEmailChange:xc,onInviteRoleChange:ni,onInvitePermissionModeChange:El,onSubmitInvite:()=>{Ql()},onLoadAuditPrevious:()=>{js(xs-1)},onLoadAuditNext:()=>{js(xs+1)}}),n.jsx(JB,{isOpen:Wm,theme:xe,onClose:()=>Ri(!1),onConfirm:()=>$i({intent:"create-workspace"})}),n.jsx(x1,{isOpen:ou,theme:xe,currentWorkspaceLabel:Gl,syncStatusMeta:en,workspaceCloudSyncEnabled:qa,syncControlBusy:iu,canManageWorkspaceSync:Ul,workspaceSyncSummary:ms.summary,workspaceSyncRecommendedAction:ms.recommendedAction,workspaceSyncRepairBusy:rn,referenceMismatchCount:De,syncStageLabel:ed,workspaceSyncPendingChanges:la,formattedLastSyncTime:Hi,formattedLastPullTime:Cu,formattedLastPushTime:Au,syncLastError:Iu,workspaceSyncDiagnostics:us,activeReferenceMismatchSummaries:Ue,syncDiagnosticsSummary:op,syncEventRows:Fe,syncEventsListRef:O,workspaceSyncRepairQueued:Ln,workspaceSyncBusy:sa,workspaceSyncCopied:fa,runtimeMode:Kt,isAuthenticated:Zt,onClose:Hl,onToggleWorkspaceSync:u=>{lu(u)},onRepairSync:Pr,onCopyReport:()=>{sr()},onOpenLogin:()=>{Oi("login")},onRetrySync:()=>{Dn()}}),hr&&Xi.createPortal(n.jsx("div",{className:`${It.overlay} ${It.unsavedOverlay}`,style:{zIndex:2e3},children:n.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${It.modal} ${It.unsavedModal}`,"data-theme":xe,children:[n.jsx("div",{className:`tf-modal-header ${It.unsavedHeader}`,children:n.jsxs("div",{className:`tf-modal-title ${It.unsavedTitle}`,children:[n.jsx(wd,{size:20}),"Unsaved Changes"]})}),n.jsx("div",{className:`${It.form} ${It.unsavedContent}`,children:n.jsx("p",{className:It.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),n.jsxs("div",{className:`${It.formActions} ${It.unsavedActions}`,children:[n.jsx("button",{className:f.cancelBtn,onClick:()=>F(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),n.jsx("button",{className:f.destructiveBtn,onClick:T,title:"Discard unsaved changes and leave",children:"Discard"}),n.jsxs("button",{className:f.submitBtn,onClick:N,disabled:ke,title:"Save changes and leave",children:[ke?n.jsx(br,{size:16,className:f.spinner}):n.jsx(yg,{size:16}),"Save"]})]})]})}),document.body),Ar&&Xi.createPortal(n.jsx("div",{className:jn.overlay,children:n.jsxs("div",{className:jn.browser,children:[n.jsxs("div",{className:jn.header,children:[n.jsxs("div",{className:jn.pathInfo,children:[n.jsx(Io,{size:14}),n.jsx("span",{children:Jn||"Project Root"})]}),n.jsxs("div",{className:jn.actions,children:[Jn&&n.jsx("button",{className:f.helpLink,onClick:()=>{const u=Jn.split("/").filter(Boolean);u.pop(),Ta(u.length?u.join("/")+"/":"")},children:"Back"}),n.jsx("button",{className:f.helpLink,onClick:()=>Ya(!1),children:"Close"})]})]}),n.jsxs("div",{className:jn.list,children:[ur&&typeof ur=="object"&&n.jsxs("div",{className:`${jn.item} ${jn.itemFile} ${jn.itemCurrent}`,onClick:()=>qr(Jn),children:[n.jsx(eo,{size:14})," Select Current: ./",Jn||"(root)"]}),Ja.map(u=>n.jsxs("div",{className:jn.item,onClick:()=>Ta(Jn+u+"/"),children:[n.jsx(Io,{size:14})," ",u,"/"]},u)),xr.map(u=>n.jsxs("div",{className:`${jn.item} ${jn.itemFile}`,onClick:()=>qr(Jn+u),children:[n.jsx(Op,{size:14})," ",u]},u)),Ja.length===0&&xr.length===0&&n.jsx("div",{className:`${jn.item} ${jn.empty}`,children:"No items found"})]})]})}),document.body)]})}function WO(e){const t=e.setupState,a=e.runtimeMode,s=e.isAuthenticated,o=!!(t&&a==="cloud"&&s&&t.globalSetupState==="missing"),c=!!(t&&a==="local"&&t.globalSetupState==="missing"),i=!!(t&&a==="cloud"&&s&&t.workspaceSetupState==="missing"),d=!!(t&&a==="local"&&t.workspaceSetupState==="missing"),m=!!(t&&(t.forceSetup||t.forceGlobalSetup||t.forceWorkspaceSetup||o||i||c||d));if(!m)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const y=!!(t&&(t.forceSetup||t.forceGlobalSetup||o||c)),k=!!(t&&(t.forceSetup||t.forceWorkspaceSetup||i||d)),S=!!(y&&t?.globalSetupState==="missing"),h=!!(k&&t?.workspaceSetupState==="missing"),g=!!(y&&t?.globalSetupState==="unreadable"),v=!!(k&&t?.workspaceSetupState==="unreadable"),_=g||v;return{setupGateActive:m,needsGlobalSetup:S,needsWorkspaceSetup:h,hasSetupReadError:_,phase:_?"setup-read-error":S?"needs-global-setup":h?"needs-workspace-setup":"ready"}}const Lp="/taskforce/assets/taskforce-BxLPokNB.png";function ug(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function Bp(e){return(Array.isArray(e)?e:[]).map(t=>String(t.label||t.value||"").trim()).filter(Boolean).join(", ")}function Wp(e={}){const t=new URLSearchParams;t.set("screen","plans");for(const[a,s]of Object.entries(e)){const o=String(s||"").trim();o&&t.set(a,o)}return`/?${t.toString()}`}function mg({config:e={},initialTaskId:t,onTaskCountChange:a,onHeaderMouseDown:s,isDragging:o,onClose:c,mode:i="standalone"}){const d=Ng(),m=r.useMemo(()=>new URLSearchParams(d.search),[d.search]),y=String(m.get("planId")||"").trim(),k=String(m.get("planVersionId")||"").trim(),S=String(m.get("interval")||"").trim(),h=d.pathname==="/pricing",g=d.pathname==="/plans",v=d.pathname==="/"&&String(m.get("screen")||"").trim().toLowerCase()==="plans",_=Wp(),I=Wp({gate:"plan_selection_required"}),A=Rg(),[D,U]=r.useState(""),[W,Q]=r.useState(""),[le,ie]=r.useState(""),[se,$]=r.useState(""),[C,de]=r.useState("login"),[ke,K]=r.useState(""),[j,H]=r.useState(!1),[ue,ye]=r.useState(null),[G,je]=r.useState(null),[be,ce]=r.useState(null),[me,Te]=r.useState(!1),[Me,Pe]=r.useState(""),[Ee,Z]=r.useState(""),[x,b]=r.useState(null),[R,B]=r.useState(null),[Y,fe]=r.useState("unknown"),[te,Le]=r.useState(!1),[oe,L]=r.useState([]),[X,M]=r.useState(null),[V,ne]=r.useState(null),[Ce,Ae]=r.useState(null),[Re,$e]=r.useState(!1),[vt,st]=r.useState(0),[kt,Ye]=r.useState(0),[Ct,dt]=r.useState(()=>Date.now()),[Qe,Tt]=r.useState("core"),[ae,Ge]=r.useState(!1),[ft,it]=r.useState(null),[Mt,ht]=r.useState(null),[Ft,Et]=r.useState(""),[We,tt]=r.useState(""),[Oe,Ze]=r.useState("local"),[St,ot]=r.useState("details"),[re,Be]=r.useState([]),[At,Rt]=r.useState(""),[Bt,Ve]=r.useState(!1),[Ot,yt]=r.useState(null),[E,l]=r.useState(!1),[J,Se]=r.useState(null),[Ie,Ke]=r.useState(!1),Je=r.useRef(!1),Ne=r.useMemo(()=>uy(),[]),[zt,Yt]=r.useState(Ne),[Pt,Wt]=r.useState(()=>Ne.find(F=>F.isDefaultStarter)?.id||Ne[0]?.id||""),[Dt,Ht]=r.useState(()=>ug(Ne.find(F=>F.isDefaultStarter)||Ne[0]||null)),[sn,Vt]=r.useState(!1),[Vn,qn]=r.useState(null),[Kn,ga]=r.useState(!1),[ge,at]=r.useState(null),[xe,jt]=r.useState(!1),pt=Hb({config:e,initialTaskId:t,onTaskCountChange:a,onClose:c}),{runtimeMode:bt,workspaceSwitchingEnabled:An,currentWorkspaceId:vn,cloudAuthConfigured:dn,authRequiredForApi:un,authBlocked:Bn,isAuthenticated:gt,hasBetaAccess:cr,authSessionResolved:fn,setupState:nn,runtimeCapabilities:bn,refreshSetupContext:Kt,retryBootstrapChecks:_r,createWorkspace:Pn,saveWorkspaceProfile:aa,fetchWorkspaces:Mn,applyWorkspaceSyncStateSnapshot:Zt,workspaceCloudSyncEnabled:Zn,workspaceSyncPhase:an,workspaceSyncSetupIntent:ra,workspaceSyncSummary:Ea,workspaceSyncRecommendedAction:Da,workspaceSyncBusy:hn,workspaceLastErrorMessage:Va,retryWorkspaceCloudSync:os,settingsModel:qa,fetchTasks:Ca,bootstrapState:Wn,loginWithCredentials:Vr,beginOAuthLogin:Aa,availableAuthProviders:sa,registerWithCredentials:la,requestEmailVerification:Fn,confirmEmailVerification:Nt,requestPasswordReset:ya,confirmPasswordReset:On,inspectInviteAcceptance:lr,acceptInviteWithToken:$n,joinInviteWithToken:La,authUserEmail:xa,currentTheme:Sn,logout:Dn}=pt,Ba=r.useCallback(async(F,He)=>{const xt=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:F,stateKey:"workspace-sync",patch:He})}),Lt=await xt.json().catch(()=>({}));if(!xt.ok||Lt?.success===!1)throw new Error(Lt?.error||`Failed to configure workspace sync (${xt.status})`);return Lt},[]),gn=r.useMemo(()=>zt.find(F=>F.id===Pt)||zt.find(F=>F.isDefaultStarter)||zt[0]||null,[Pt,zt]);Eg(Sn);const Jt=af,Ka=r.useMemo(()=>{const F=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return F?F.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),xn=bt==="cloud"||bn?.runtimeMode==="cloud",En=!xn&&dn&&!!Ka,Za=typeof window<"u"&&/^app\./i.test(window.location.hostname),In=bt==="cloud"&&un,Mr=bt==="cloud"&&Bn,cn=d.pathname==="/login",mn=d.pathname==="/setup",ka=d.pathname==="/coming-soon",Yn="/setup?step=workspace&source=cloud&postAuth=select-cloud-workspace",Cr=!xn&&Oe==="cloud",Er=Cr&&En,Xt=r.useMemo(()=>{if(J)return J;if(ra!=="attach-cloud-import")return null;const F=String(vn||"").trim();if(!F||F.toLowerCase()==="default")return null;const He=re.find(xt=>xt.id===F);return{workspaceId:F,name:He?.name||F}},[re,vn,J,ra]),Ia=!!(Xt&&vn===Xt.workspaceId),Wa=!!(Xt&&Ia&&an==="error"),dr=!!(Xt&&Ia&&Zn&&an==="active"&&!hn),Ar=r.useMemo(()=>{if(!Xt)return[];const F=ae?"In progress":"Complete",He=Wa?"Needs attention":hn||an==="attach-cloud"?"In progress":an==="active"?"Complete":"Waiting",xt=Ie?"In progress":dr?"Ready":"Waiting";return[`Connect workspace: ${F}`,`Import cloud data: ${He}`,`Open local workspace: ${xt}`]},[Xt,ae,Wa,hn,an,Ie,dr]),Ya=Za?(!gt||Bn)&&!h&&!g&&!v:(In&&!gt||Mr)&&!h&&!g&&!v,Ja=bt==="cloud"&>&&!cr&&!h&&!g&&!v,xr=bt==="cloud"&>&&fn&&ge?.canAccessApp===!1&&ge?.canAccessPlans!==!1&&!h&&!g&&!v,Jn=bt==="cloud"&>&&(!fn||!xe),Ta=dn,ur=r.useMemo(()=>{switch(C){case"register":return"Create Account | Taskforce";case"verify":return"Verify Email | Taskforce";case"forgot":return"Reset Password | Taskforce";case"reset":return"Set New Password | Taskforce";case"invite":return"Accept Invite | Taskforce";default:return"Sign In | Taskforce"}},[C]),oa=r.useMemo(()=>String(new URLSearchParams(d.search).get("step")||"").trim().toLowerCase(),[d.search]),qr=r.useMemo(()=>String(new URLSearchParams(d.search).get("intent")||"").trim().toLowerCase(),[d.search]),ia=mn&&oa==="workspace"&&qr==="create-workspace",Dr=i!=="widget"&&Wn.authPending&&!cn&&!mn&&!h&&!g&&!v&&(bt==="cloud"||Za),Kr=r.useMemo(()=>WO({setupState:nn?{globalSetupState:nn.globalSetupState,workspaceSetupState:nn.workspaceSetupState,runtimeMode:nn.runtimeMode,workspaceId:nn.workspaceId,mode:nn.mode,forceSetup:nn.forceSetup,forceGlobalSetup:nn.forceGlobalSetup,forceWorkspaceSetup:nn.forceWorkspaceSetup}:null,runtimeMode:bt,isAuthenticated:gt}),[nn,bt,gt]),va=Kr.setupGateActive,Ir=Kr.needsGlobalSetup,Ra=Kr.needsWorkspaceSetup,Sa=Kr.hasSetupReadError,Fa=i!=="widget"&&Wn.auth.resolved&&!Ya&&!Ja&&!h&&!g&&!v&&!cn&&Wn.appPending&&(mn||bt==="cloud"||Za),Zr=bt==="cloud"&&me&&!v,Ds=Wn.subtitle,et=ia||mn&&!!Xt||mn&&va&&(Sa||Ir||Ra),$t=r.useMemo(()=>Dr?"auth-bootstrap":Zr||Fa?"app-bootstrap":cn?"login":Ya&&!cn?"login-redirect":ka&&Ja?"coming-soon":et?"guided-setup":"app",[ka,cn,Ja,Ya,Zr,Dr,Fa,et]),Tn=r.useCallback((F,He,xt)=>{const Lt=String(F||"").trim().toLowerCase(),Rn=String(He||"").trim().toLowerCase();return!!(!Lt||Lt==="system default workspace"||Rn&&Lt===Rn)},[]);r.useEffect(()=>{const F=nn?.mode==="operations"?"operations":"core";Tt(F)},[nn?.mode]),r.useEffect(()=>{if(bt!=="cloud"||!gt){at(null),jt(!1);return}if(!fn){at(null),jt(!1);return}at(null),jt(!1);let F=!1;return(async()=>{try{const He=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),xt=await He.json().catch(()=>({}));if(F)return;if(!He.ok){at(null),jt(!0);return}const Lt=String(xt?.gate||"").trim().toLowerCase();if(Lt!=="ok"&&Lt!=="plan_selection_required"&&Lt!=="checkout_pending"&&Lt!=="misconfigured"&&Lt!=="missing_entitlement"){at(null),jt(!0);return}at({gate:Lt,canAccessApp:xt?.canAccessApp===!0,canAccessPlans:xt?.canAccessPlans!==!1,message:typeof xt?.message=="string"?xt.message:null}),jt(!0)}catch{F||(at(null),jt(!0))}})(),()=>{F=!0}},[fn,gt,bt,d.pathname,d.search]),r.useEffect(()=>{if(ia){Et(""),tt("");return}if(!nn)return;const F=String(nn.workspace?.name||"").trim(),He=String(nn.suggestedWorkspaceName||"").trim(),xt=Tn(F,nn.workspaceId,nn.workspace?.description)?He:F;Et(xt||He||F),tt(String(nn.workspace?.description||""))},[nn?.workspace?.name,nn?.workspace?.description,nn?.suggestedWorkspaceName,nn?.workspaceId,ia,Tn]),r.useEffect(()=>{if(!mn||oa!=="workspace")return;if(ot("details"),Xt&&En){Ze("cloud"),l(!1);return}if(String(new URLSearchParams(d.search).get("source")||"").trim().toLowerCase()==="cloud"&&En){Ze("cloud"),l(!1);return}Ze("local")},[Xt,En,mn,d.search,oa]);const _n=r.useCallback(async()=>{if(!En||!gt){Be([]),Rt("");return}Ve(!0),yt(null);try{const F=await fetch(`${Ka}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),He=await F.json().catch(()=>({}));if(!F.ok||He?.success===!1){Be([]),Rt(""),yt(He?.error||`Failed to load cloud projects (${F.status})`);return}const xt=Array.isArray(He?.workspaces)?He.workspaces.map(Lt=>({id:String(Lt?.id||"").trim(),name:String(Lt?.name||Lt?.id||"").trim(),description:typeof Lt?.description=="string"?Lt.description:null})).filter(Lt=>Lt.id.length>0):[];Be(xt),Rt(Lt=>Lt&&xt.some(Rn=>Rn.id===Lt)?Lt:xt[0]?.id||"")}catch{Be([]),Rt(""),yt("Failed to load cloud projects.")}finally{Ve(!1)}},[En,gt,Ka]);r.useEffect(()=>{Oe==="cloud"&&_n()},[_n,Oe]),r.useEffect(()=>{if(!mn||oa!=="workspace"||Oe==="cloud")return;let F=!1;return Vt(!0),qn(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async He=>{if(!He.ok)throw new Error(`Failed to load setup libraries (${He.status})`);const xt=await He.json().catch(()=>({})),Lt=Array.isArray(xt?.packs)?xt.packs:[];F||Lt.length===0||(Yt(Lt),Wt(Rn=>Lt.some(Tr=>Tr.id===Rn)?Rn:Lt.find(Tr=>Tr.isDefaultStarter)?.id||Lt[0]?.id||""))}).catch(He=>{F||(Yt(Ne),qn(He instanceof Error?He.message:"Failed to load setup libraries."))}).finally(()=>{F||Vt(!1)}),()=>{F=!0}},[Ne,mn,oa,Oe]),r.useEffect(()=>{Ht(ug(gn))},[Pt,gn]),r.useEffect(()=>{Oe==="cloud"&&ot("details")},[Oe]),r.useEffect(()=>{Er||(Se(null),Ke(!1),Je.current=!1)},[Er]),r.useEffect(()=>{!Wa||!Xt||(ht(null),it(Va||`Failed to import "${Xt.name}" from cloud. Retry import to continue.`))},[Xt,Wa,Va]),r.useEffect(()=>{if(!dr||!Xt||Je.current)return;let F=!1;return Je.current=!0,Ke(!0),it(null),ht(`Workspace import complete. Opening ${Xt.name}...`),(async()=>{try{if(await Kt(),await Promise.all([Mn(),Ca(!0)]),F)return;await Ba(Xt.workspaceId,{setupIntent:null}),Zt({enabled:Zn,phase:an,setupIntent:null}),Se(null),A("/",{replace:!0})}catch{if(F)return;ht(null),it(`Imported "${Xt.name}" but failed to finish opening it.`),Ke(!1),Je.current=!1}})(),()=>{F=!0}},[Xt,Zt,Ca,Mn,dr,A,Ba,Kt]);const wn=r.useMemo(()=>{const F=new URLSearchParams(d.search).get("next")||"/";if(F.startsWith("/"))return F==="/login"?"/":F;try{const He=new URL(F),xt=He.hostname.toLowerCase(),Lt=xt==="localhost"||xt==="127.0.0.1"||xt==="::1",Rn=xt==="taskforcehq.ai"||xt.endsWith(".taskforcehq.ai");if((He.protocol==="http:"||He.protocol==="https:")&&(Lt||Rn))return He.toString()}catch{return"/"}return"/"},[d.search]),Na=r.useMemo(()=>wn.startsWith("/")?wn:"/",[wn]),Qa=r.useCallback((F,He)=>{if(F){if(F.startsWith("/")){A(F,{replace:He?.replace===!0});return}typeof window<"u"&&(He?.replace===!0?window.location.replace(F):window.location.assign(F))}},[A]),ys=r.useMemo(()=>{try{const F=new URL(Na,"https://taskforce.local");return F.pathname==="/setup"&&F.searchParams.get("step")==="workspace"&&F.searchParams.get("source")==="cloud"&&F.searchParams.get("postAuth")==="select-cloud-workspace"}catch{return!1}},[Na]),wa=r.useCallback(()=>ys?Yn:"/setup?step=workspace",[ys]),Oa=S==="year"?"year":"month",mr=r.useCallback(F=>!!(F?.planSelectionRequired||F?.checkoutPending||F?.commercialState==="pending_plan_selection"||F?.commercialState==="checkout_pending"),[]),Gt=r.useCallback(F=>F?.planSelectionRequired||F?.commercialState==="pending_plan_selection"?I:F?.checkoutPending||F?.commercialState==="checkout_pending"?Wp({gate:"checkout_pending",checkout:k?"start":null,planId:y||null,planVersionId:k||null,interval:k?Oa:null}):wn,[wn,I,Oa,y,k]),ja=r.useMemo(()=>{const F=String(new URLSearchParams(d.search).get("mode")||"").trim().toLowerCase();return F==="register"?Ta?"register":"login":F==="verify"||F==="forgot"||F==="reset"||F==="invite"?F:"login"},[Ta,d.search]),da=r.useMemo(()=>String(new URLSearchParams(d.search).get("token")||"").trim(),[d.search]),Un=r.useCallback(F=>{const He=new URLSearchParams(d.search),xt=F==="register"&&!Ta?"login":F;xt==="login"?He.delete("mode"):He.set("mode",xt);const Lt=He.toString();A(`/login${Lt?`?${Lt}`:""}`,{replace:!0})},[Ta,d.search,A]);r.useEffect(()=>{cn&&(de(ja),ja==="verify"&&da&&K(da),ja==="reset"&&da&&Pe(da),ja==="invite"&&da&&Z(da))},[cn,ja,da]),r.useEffect(()=>{C!=="verify"&&(cn&&ja==="verify"||(H(!1),ye(null),je(null)))},[C,cn,ja]),r.useEffect(()=>{C!=="register"&&$("")},[C]),r.useEffect(()=>{if(!be||!gt||!be.commercialOnboardingGate&&(!fn||Jn))return;const F=!be.commercialOnboardingGate&&be.workspaceSetupRequired?wa():be.path,He=`${d.pathname}${d.search}${d.hash||""}`;if(F.startsWith("/")){He!==F&&A(F,{replace:!0});return}Qa(F,{replace:!0})},[fn,Jn,gt,d.hash,d.pathname,d.search,A,Qa,be,wa]),r.useEffect(()=>{if(!me||!fn)return;if(!gt){Te(!1),ce(null);return}if(xe&&ge?.canAccessApp===!0){U(""),Q(""),ie(""),$(""),ce(null),Te(!1);return}const F=be?.commercialOnboardingGate?be.path:I,He=`${d.pathname}${d.search}${d.hash||""}`;if(F.startsWith("/")){He!==F&&A(F,{replace:!0});return}Qa(F,{replace:!0})},[ge?.canAccessApp,xe,fn,me,gt,d.hash,d.pathname,d.search,A,Qa,be,I]),r.useEffect(()=>{if(!be||!gt)return;const F=!be.commercialOnboardingGate&&be.workspaceSetupRequired?wa():be.path;`${d.pathname}${d.search}${d.hash||""}`===F&&(be.commercialOnboardingGate||(U(""),Q(""),ie(""),$(""),ce(null)))},[d.hash,d.pathname,d.search,gt,be,wa,bt]),r.useEffect(()=>{cn&&(document.title=ur)},[ur,cn]),r.useEffect(()=>{if(!cn||C!=="invite"||!Ee.trim())return;let F=!0;return(async()=>{const He=await lr(Ee);if(F)if(He.success){b(He.email||null),B(He.workspaceId||null),Le(He.passwordRequired===!0);const xt=(He.availableMethods||[]).filter(Tr=>Tr==="google"||Tr==="github"||Tr==="apple");L(He.inviteeState==="pending_setup"?xt:[]);const Lt=!!(gt&&xa&&He.email&&xa.trim().toLowerCase()===He.email.trim().toLowerCase()),Rn=He.passwordRequired===!0?"new_user":Lt?"existing_user_ready":"existing_user_signed_out";fe(Rn),M(Rn==="new_user"?"Create your account password to join this workspace.":Rn==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),ne(null),Ae(null)}else b(null),B(null),fe("invalid"),Le(!1),L([]),ne(ba(He)),Ae(He.code||He.state||null)})(),()=>{F=!1}},[cn,C,Ee,lr,gt,xa]),r.useEffect(()=>{C==="invite"&&Y==="existing_user_signed_out"&&x&&U(F=>F.trim()?F:x)},[C,Y,x]),r.useEffect(()=>{if(!(vt>Date.now()||kt>Date.now()))return;const He=window.setInterval(()=>dt(Date.now()),1e3);return()=>window.clearInterval(He)},[vt,kt]);const Lr=Math.max(0,Math.ceil((vt-Ct)/1e3)),Br=Math.max(0,Math.ceil((kt-Ct)/1e3)),pr=Lr>0,fr=Br>0,ks=r.useMemo(()=>Ey(),[]),ba=F=>{const He=F.error||"Request failed.",xt=F.code||F.state;return xt?`[${xt}] ${He}`:He},ua=F=>F?.deliveryAttempted===!1?F?.intro||"If that account exists and still needs verification, we sent an email.":F?.emailSent===!1?`Verification email failed to send. ${F?.emailError||"Try Resend Verification again."}`:"Verification email resent.",no=F=>F?.deliveryAttempted===!1?"If that account exists, we sent password reset instructions.":F?.emailSent===!1?`Password reset email failed to send. ${F?.emailError||"Try again in a minute."}`:"Password reset instructions sent.";r.useEffect(()=>{if(i==="widget"||cn&&Re)return;const F=bt==="cloud"&>&&xe&&ge?.canAccessApp===!1&&ge?.canAccessPlans!==!1;if(Wn.workspace.pending&&!F)return;if(Ja){ka||A("/coming-soon",{replace:!0});return}if(ka&&!Ja){A("/",{replace:!0});return}if(Ya){if(!cn){const xt=`${d.pathname}${d.search}${d.hash}`;A(`/login?next=${encodeURIComponent(xt||"/")}`,{replace:!0});return}return}else{const xt=cn&&C==="invite"&&Ee.trim().length>0;if(cn&>&&!xt&&(!!be||Wn.workspace.pending||C==="register"||C==="verify"||!Wn.config.loaded||Jn))return;cn&>&&!xt&&Qa(wn,{replace:!0})}if(!(cn&&!gt||be&>||cn&>&&(C==="register"||C==="verify"||C==="invite"&&Ee.trim().length>0))&&!me&&!v){if(xr){if(!v){const xt=encodeURIComponent(String(ge?.gate||"plan_selection_required"));A(`/?screen=plans&gate=${xt}`,{replace:!0})}return}if(Xt){mn&&oa==="workspace"&&new URLSearchParams(d.search).get("source")==="cloud"||A(Yn,{replace:!0});return}if(!(v&&Jn)&&!(v&&bt==="cloud"&&xe&&ge?.canAccessApp===!1&&ge?.canAccessPlans!==!1)){if(va){if(Sa){(!mn||oa!=="error")&&A("/setup?step=error",{replace:!0});return}if(Ir){(!mn||oa!=="global")&&A("/setup?step=global",{replace:!0});return}if(Ra){(!mn||oa!=="workspace")&&A(wa(),{replace:!0});return}mn&&A("/",{replace:!0});return}mn&&nn&&!ia&&A("/",{replace:!0})}}},[i,Ya,Ja,xr,cn,mn,ka,g,v,ge,ge?.gate,xe,C,me,Jn,va,nn,Sa,ia,Xt,Ir,Ra,oa,Wn,bt,Re,gt,xe,Ee,d.pathname,d.search,d.hash,A,Na,be,Yn]),r.useEffect(()=>{if(i==="widget"||bt!=="local"||!Wn.config.loaded||cn||mn)return;const F=String(vn||"").trim().toLowerCase();(!F||F==="default")&&A("/setup?step=workspace",{replace:!0})},[i,bt,Wn.config.loaded,cn,mn,vn,A]);const vs=r.useCallback(async()=>{ga(!0);try{await _r()}finally{ga(!1)}},[_r]),hr=r.useCallback(async()=>{await Dn(),A("/login",{replace:!0})},[Dn,A]);if(i==="widget")return n.jsx(kL,{...pt,onHeaderMouseDown:s,isDragging:o,onClose:c});if(h){const F=new URLSearchParams(d.search);return F.set("screen","plans"),n.jsx(rh,{to:`/?${F.toString()}${d.hash||""}`,replace:!0})}if(g){const F=new URLSearchParams(d.search);return F.set("screen","plans"),n.jsx(rh,{to:`/?${F.toString()}${d.hash||""}`,replace:!0})}if($t==="auth-bootstrap")return n.jsx("div",{className:tn.standaloneWrapper,"data-theme":Sn,children:n.jsx("div",{className:he.loginView,children:n.jsxs("div",{className:he.loginCard,children:[n.jsxs("div",{className:he.authBrandRow,children:[n.jsx("img",{src:Jt,alt:"Taskforce",className:he.loginLogo}),n.jsx("h1",{className:he.loginTitle,children:"Loading Taskforce"})]}),n.jsx("p",{className:he.loginSubtitle,children:"Checking your session..."})]})})});if($t==="app-bootstrap")return n.jsx("div",{className:tn.standaloneWrapper,"data-theme":Sn,children:n.jsx("div",{className:he.loginView,children:n.jsxs("div",{className:he.loginCard,children:[n.jsxs("div",{className:he.authBrandRow,children:[n.jsx("img",{src:Jt,alt:"Taskforce",className:he.loginLogo}),n.jsx("h1",{className:he.loginTitle,children:"Loading Taskforce"})]}),n.jsx("p",{className:he.loginSubtitle,children:Ds}),Wn.stalled&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:he.loginError,children:Wn.error||"Startup checks timed out."}),n.jsx("button",{className:f.submitBtn,disabled:Kn,onClick:vs,children:Kn?"Retrying...":"Retry checks"}),xn&&n.jsx("button",{className:f.cancelBtn,disabled:Kn,onClick:hr,children:"Go to sign-in"})]})]})})});if($t==="login")return n.jsx("div",{className:tn.standaloneWrapper,"data-theme":Sn,children:n.jsx("div",{className:he.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Lp})`},children:n.jsxs("div",{className:he.loginCard,children:[!xn&&!Ya&&n.jsx("button",{className:he.loginCloseBtn,"aria-label":"Close sign in","data-testid":"auth-close-button",onClick:()=>A(Na,{replace:!0}),children:"×"}),n.jsxs("div",{className:he.authBrandRow,children:[n.jsx("img",{src:Jt,alt:"Taskforce",className:he.loginLogo}),n.jsxs("h1",{className:he.loginTitle,children:["TASKFORCE ",n.jsx("span",{className:he.loginTitleAccent,children:"HQ"})]})]}),n.jsxs("p",{className:he.loginSubtitle,children:[C==="login"&&"Sign in with your account credentials.",C==="register"&&"Create your Taskforce account.",C==="verify"&&"Enter your verification token.",C==="forgot"&&"Request a password reset link.",C==="reset"&&"Set a new password using your reset token.",C==="invite"&&(Y==="existing_user_ready"?`You've been invited to join ${R||"this workspace"}.`:Y==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(C==="login"||C==="register"||C==="verify"||C==="forgot"||C==="invite"&&Y==="existing_user_signed_out")&&n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:"Email"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"email",value:D,placeholder:"Email",autoComplete:"email","data-testid":"auth-email-input",onChange:F=>U(F.target.value)})]}),C==="register"&&n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:"Display name"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"text",value:W,placeholder:"Display name",autoComplete:"nickname","data-testid":"auth-display-name-input",onChange:F=>Q(F.target.value)})]}),(C==="login"||C==="register"||C==="reset"||C==="invite"&&(te||Y==="existing_user_signed_out"))&&n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:C==="reset"?"New password":C==="invite"&&te?"Create password":"Password"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"password",value:le,placeholder:C==="reset"?"New password":C==="invite"&&te?"Create password":"Password",autoComplete:C==="register"||C==="reset"||C==="invite"&&te?"new-password":"current-password","data-testid":"auth-password-input",onChange:F=>ie(F.target.value)})]}),(C==="register"||C==="invite"&&te)&&n.jsx(n.Fragment,{children:n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:"Confirm password"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"password",value:se,placeholder:"Confirm password",autoComplete:"new-password","data-testid":"auth-confirm-password-input",onChange:F=>$(F.target.value)})]})}),(C==="register"||C==="invite"&&te)&&n.jsx("p",{className:he.loginSubtitle,children:ks.join(" ")}),C==="verify"&&n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:"Verification token"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"text",value:ke,placeholder:"Verification token",autoComplete:"one-time-code","data-testid":"auth-verification-token-input",onChange:F=>K(F.target.value)})]}),C==="reset"&&n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:"Reset token"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"text",value:Me,placeholder:"Reset token",autoComplete:"one-time-code","data-testid":"auth-reset-token-input",onChange:F=>Pe(F.target.value)})]}),C==="invite"&&n.jsxs(n.Fragment,{children:[n.jsxs("label",{className:he.loginField,children:[n.jsx("span",{className:he.loginFieldLabel,children:"Invite token"}),n.jsx("input",{className:`${f.input} ${he.loginInput}`,type:"text",value:Ee,placeholder:"Invite token","data-testid":"auth-invite-token-input",onChange:F=>Z(F.target.value)})]}),x&&n.jsxs("p",{className:he.loginSubtitle,children:["Invite for: ",n.jsx("strong",{children:x}),R?` · Workspace: ${R}`:""]})]}),X&&n.jsx("p",{className:he.loginSubtitle,children:X}),V&&n.jsx("p",{className:he.loginError,children:V}),C==="login"&&Ce==="EMAIL_NOT_VERIFIED"&&D.trim()&&n.jsx("button",{className:he.authModeLink,disabled:Re||pr,onClick:async()=>{$e(!0),M(null);const F=await Fn(D);F.success?(st(Date.now()+3e4),Un("verify"),F.verificationToken&&K(F.verificationToken),M(ua(F)),ne(null),Ae(null)):ne(ba(F)),$e(!1)},children:pr?`Resend in ${Lr}s`:"Resend Verification Email"}),n.jsx("div",{className:he.authPrimaryActions,role:"group","aria-label":"Primary authentication action",children:n.jsx("button",{className:`${f.submitBtn} ${he.loginPrimaryBtn}`,disabled:Re||C==="forgot"&&fr,"data-testid":"auth-submit-button",onClick:async()=>{if($e(!0),M(null),ne(null),Ae(null),C==="register"&&!W.trim()){ne("Display name is required."),$e(!1);return}if(C==="register"){const He=Dy(le,{email:D,displayName:W});if(!He.ok){ne(He.message||"Password does not meet the password policy."),Ae(He.code||null),$e(!1);return}if(le!==se){ne("Passwords do not match."),Ae("PASSWORD_CONFIRMATION_MISMATCH"),$e(!1);return}}let F={success:!1};if(C==="login"?F=await Vr(D,le):C==="register"?F=await la(D,le,{displayName:W,planId:y||void 0,planVersionId:k||void 0,interval:S||void 0}):C==="verify"?F=await Nt(ke):C==="forgot"?F=await ya(D):C==="reset"?F=await On(Me,le):C==="invite"&&(Y==="existing_user_signed_out"?F=await Vr(D,le):F=te?await $n(Ee,le):await La(Ee)),F.success)if(C==="register"){const He=Gt(F),xt=mr(F);F.verificationRequired?(H(!!F.workspaceSetupRequired),ye(xt?String(F.commercialState||"").trim()||(F.planSelectionRequired?"pending_plan_selection":"checkout_pending"):null),je(He),F.verificationToken&&K(F.verificationToken),st(Date.now()+3e4),Un("verify"),M(F.emailSent===!1?`Account created, but verification email failed to send. ${F.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")):(Te(xt),ce({path:He,workspaceSetupRequired:!!F.workspaceSetupRequired,commercialOnboardingGate:xt}))}else if(C==="verify"){await _r();const He=ue==="pending_plan_selection"||ue==="checkout_pending";Te(He),ce({path:G||wn,workspaceSetupRequired:j,commercialOnboardingGate:He})}else if(C==="forgot"){const He=F.deliveryAttempted===!0&&F.emailSent===!1;F.resetToken&&Pe(F.resetToken),M(no(F)),He||(Ye(Date.now()+3e4),Un("reset"))}else if(C==="reset")Un("login"),M("Password updated. Sign in with your new password.");else if(C==="invite"){if(Y==="existing_user_signed_out"){const He=String(x||"").trim().toLowerCase(),xt=D.trim().toLowerCase();if(He&&xt===He){de("invite"),fe("existing_user_ready"),ie(""),$(""),M("Signed in. Review the invite details to continue."),ne(null),Ae(null),$e(!1);return}He&&U(x||""),fe("existing_user_signed_out"),ie(""),$(""),M(He?`Signed in, but this invite is for ${x}. Sign in with that account to continue.`:"Signed in, but this invite requires the invited account. Sign in with that account to continue."),ne("Sign in with the invited account to join this workspace."),Ae("INVITE_ACCOUNT_MISMATCH"),$e(!1);return}if(F.workspaceSetupRequired){A(wa(),{replace:!0}),$e(!1);return}Qa(wn,{replace:!0})}else if(C==="login"){if(Ee.trim()){de("invite"),ie(""),$(""),M("Signed in. Review the invite details to continue."),$e(!1);return}if(F.workspaceSetupRequired){A(wa(),{replace:!0}),$e(!1);return}U(""),Q(""),ie(""),$(""),Qa(wn,{replace:!0})}else U(""),Q(""),ie(""),$(""),Qa(wn,{replace:!0});else{if(C==="register"&&(F.code==="SIGNUP_PLAN_NOT_ENABLED"||F.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||F.code==="SIGNUP_PLAN_VERSION_REQUIRED")){A(I,{replace:!0}),$e(!1);return}if(ne(ba(F)),Ae(F.code||null),C==="login"&&(F.code==="WORKSPACE_NOT_FOUND"||F.code==="WORKSPACE_ID_REQUIRED")){A("/setup?step=workspace",{replace:!0}),$e(!1);return}if(C==="login"&&F.code==="EMAIL_NOT_VERIFIED"&&D.trim()){const He=await Fn(D);He.success&&(st(Date.now()+3e4),Un("verify"),He.verificationToken&&K(He.verificationToken),M(ua({...He,intro:"If that account exists and still needs verification, we sent an email."})),ne(null),Ae(null))}C==="register"&&F.code==="EMAIL_ALREADY_EXISTS_UNVERIFIED"&&D.trim()&&(st(Date.now()+3e4),Un("verify"),F.verificationToken&&K(F.verificationToken),M(F.emailSent===!1?`This email already has an unverified account, but verification email delivery failed. ${F.emailError||"Try Resend Verification again."}`:"This email already has an unverified account. Check your email for verification instructions."),ne(null),Ae(null))}$e(!1)},children:Re?"Working...":C==="login"?"Sign In":C==="register"?"Create Account":C==="verify"?"Verify Email":C==="forgot"?fr?`Retry in ${Br}s`:"Send Reset Link":C==="reset"?"Reset Password":Y==="existing_user_signed_out"?"Sign In to Continue":te?"Create Account and Join":"Join Workspace"})}),(C==="login"||C==="register")&&sa.length>0&&n.jsxs("div",{className:he.oauthProviders,children:[n.jsx("div",{className:he.oauthDivider,children:n.jsx("span",{children:"or continue with"})}),n.jsxs("div",{className:he.oauthButtons,children:[sa.includes("google")&&n.jsx("button",{type:"button",className:he.oauthButton,disabled:Re,onClick:()=>Aa("google",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with Google",children:"Google"}),sa.includes("github")&&n.jsx("button",{type:"button",className:he.oauthButton,disabled:Re,onClick:()=>Aa("github",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with GitHub",children:"GitHub"}),sa.includes("apple")&&n.jsx("button",{type:"button",className:he.oauthButton,disabled:Re,onClick:()=>Aa("apple",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with Apple",children:"Apple"})]})]}),C==="invite"&&Y==="new_user"&&oe.length>0&&n.jsxs("div",{className:he.oauthProviders,children:[n.jsx("div",{className:he.oauthDivider,children:n.jsx("span",{children:"or join with"})}),n.jsxs("div",{className:he.oauthButtons,children:[oe.includes("google")&&n.jsx("button",{type:"button",className:he.oauthButton,disabled:Re,onClick:()=>Aa("google","/",Ee),"aria-label":"Join with Google",children:"Google"}),oe.includes("github")&&n.jsx("button",{type:"button",className:he.oauthButton,disabled:Re,onClick:()=>Aa("github","/",Ee),"aria-label":"Join with GitHub",children:"GitHub"}),oe.includes("apple")&&n.jsx("button",{type:"button",className:he.oauthButton,disabled:Re,onClick:()=>Aa("apple","/",Ee),"aria-label":"Join with Apple",children:"Apple"})]})]}),C==="register"&&n.jsxs("p",{className:he.registerConsent,children:["By creating an account, you agree to the"," ",n.jsx("a",{className:he.registerConsentLink,href:"https://taskforcehq.ai/legal/terms/",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," ","and acknowledge the"," ",n.jsx("a",{className:he.registerConsentLink,href:"https://taskforcehq.ai/legal/privacy/",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]}),n.jsxs("div",{className:he.authSecondaryActions,role:"group","aria-label":"Authentication navigation",children:[Ta&&(C==="login"||C==="register")&&n.jsxs("p",{className:he.authModeSwitch,children:[C==="login"?"Need an account?":"Already have an account?"," ",n.jsx("button",{className:he.authModeSwitchLink,disabled:Re,"data-testid":"auth-switch-mode-button",onClick:()=>{ne(null),Ae(null),M(null),Un(C==="login"?"register":"login")},children:C==="login"?"Register":"Sign In"})]}),n.jsxs("div",{className:he.authModeLinks,children:[(C==="login"||C==="register")&&n.jsxs(n.Fragment,{children:[n.jsx("button",{className:he.authModeLink,disabled:Re||fr,"data-testid":"auth-forgot-password-button",onClick:()=>{ne(null),Ae(null),M(null),Un("forgot")},children:fr?`Forgot Password (${Br}s)`:"Forgot Password"}),n.jsx("button",{className:he.authModeLink,disabled:Re||pr,"data-testid":"auth-resend-verification-button",onClick:()=>{ne(null),Ae(null),M(null),Un("verify")},children:pr?`Resend Verification (${Lr}s)`:"Resend Verification"}),n.jsx("button",{className:he.authModeLink,disabled:Re,"data-testid":"auth-accept-invite-button",onClick:()=>{ne(null),Ae(null),M(null),Un("invite")},children:"Accept Invite"})]}),C!=="login"&&C!=="register"&&n.jsxs(n.Fragment,{children:[C==="verify"&&n.jsx("button",{className:he.authModeLink,disabled:Re||pr||!D.trim(),"data-testid":"auth-resend-verification-button",onClick:async()=>{$e(!0),M(null),ne(null),Ae(null);const F=await Fn(D);F.success?(st(Date.now()+3e4),F.verificationToken&&K(F.verificationToken),M(ua(F))):ne(ba(F)),$e(!1)},children:pr?`Resend Verification (${Lr}s)`:"Resend Verification"}),n.jsx("button",{className:he.authModeLink,disabled:Re,"data-testid":"auth-return-sign-in-button",onClick:()=>{ne(null),Ae(null),M(null),Un("login")},children:C==="verify"?"Back to Sign In":"Sign In"}),Ta&&C!=="verify"&&n.jsx("button",{className:he.authModeLink,disabled:Re,"data-testid":"auth-return-register-button",onClick:()=>{ne(null),Ae(null),M(null),Un("register")},children:"Register"}),C==="reset"&&n.jsx("button",{className:he.authModeLink,disabled:Re||fr,"data-testid":"auth-return-forgot-password-button",onClick:()=>{ne(null),Ae(null),M(null),Un("forgot")},children:fr?`Forgot Password (${Br}s)`:"Forgot Password"})]})]})]})]})})});if($t==="login-redirect")return n.jsx("div",{className:tn.standaloneWrapper,"data-theme":Sn,children:n.jsx("div",{className:he.loginView,children:n.jsxs("div",{className:he.loginCard,children:[n.jsxs("div",{className:he.authBrandRow,children:[n.jsx("img",{src:Jt,alt:"Taskforce",className:he.loginLogo}),n.jsx("h1",{className:he.loginTitle,children:"Loading Taskforce"})]}),n.jsx("p",{className:he.loginSubtitle,children:"Redirecting to sign in..."})]})})});if($t==="coming-soon")return n.jsx("div",{className:tn.standaloneWrapper,"data-theme":Sn,children:n.jsx("div",{className:he.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Lp})`},children:n.jsxs("div",{className:he.loginCard,children:[n.jsxs("div",{className:he.authBrandRow,children:[n.jsx("img",{src:Jt,alt:"Taskforce",className:he.loginLogo}),n.jsx("h1",{className:he.loginTitle,children:"Beta Access"})]}),n.jsx("p",{className:he.loginSubtitle,children:"You are signed in, but your account does not have beta access yet."}),n.jsx("p",{className:he.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),n.jsx("button",{className:f.cancelBtn,onClick:async()=>{await pt.logout(),A("/login",{replace:!0})},children:"Sign Out"})]})})});if($t==="guided-setup"){const F=!ia&&(Sa||oa==="error"),He=!ia&&!F&&(Ir||oa==="global"),xt=qe(F?"setup.headingCheckFailed":He?"setup.headingGlobalRequired":"setup.headingWorkspaceRequired"),Lt=F?qe("setup.subtitleUnreadable"):He?qe("setup.subtitleGlobalRequired"):null,Rn="Workspace",Tr=xn||Oe!=="cloud",Wr=Tr&&St==="details",ao=Tr&&St==="library",Qn=!xn&&En&&Wr&&!Xt,ma=bn?.runtimeMode==="cloud"?wg:rv,T=gn?Bp(gn.categories):"",N=gn?Bp(gn.types):"",rt=gn?Bp(gn.priorities):"",wt=ae?qe("setup.saving"):Cr?Xt?Wa?"Retry Import":"Importing Workspace...":"Connect Workspace":Wr?"Continue":ao?"Create Workspace":"Connect Workspace";return n.jsx("div",{className:tn.standaloneWrapper,"data-theme":Sn,children:n.jsx("div",{className:he.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Lp})`},children:n.jsxs("div",{className:he.loginCard,children:[n.jsxs("div",{className:he.setupHeaderRow,children:[n.jsxs("div",{className:he.authBrandRow,children:[n.jsx("img",{src:Jt,alt:"Taskforce",className:he.loginLogo}),n.jsxs("h1",{className:he.loginTitle,children:["TASKFORCE ",n.jsx("span",{className:he.loginTitleAccent,children:"HQ"})]})]}),bn&&n.jsx("span",{className:he.runtimeIconBadge,title:bn.runtimeMode==="cloud"?"Cloud runtime":"Local runtime","aria-label":bn.runtimeMode==="cloud"?"Cloud runtime":"Local runtime",children:ze.createElement(ma,{size:16,"aria-hidden":!0})})]}),n.jsx("p",{className:he.loginSubtitle,children:n.jsx("strong",{children:xt})}),Lt?n.jsx("p",{className:he.loginSubtitle,children:Lt}):null,Mt&&n.jsx("p",{className:he.loginSubtitle,children:Mt}),ft&&n.jsx("p",{className:he.loginError,children:ft}),He&&n.jsxs("div",{className:he.optionGrid,children:[n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:Qe==="core",onChange:()=>Tt("core"),disabled:ae}),n.jsx("span",{children:qe("setup.coreModeOption",{workspaceLabel:Rn})})]}),n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:Qe==="operations",onChange:()=>Tt("operations"),disabled:ae}),n.jsx("span",{children:qe("setup.operationsModeOption")})]})]}),!F&&!He&&n.jsxs("div",{className:he.optionGrid,children:[Qn&&n.jsxs("div",{className:he.optionGroup,children:[n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:Oe==="local",onChange:()=>Ze("local"),disabled:ae}),n.jsxs("span",{children:["Create new local ",Rn.toLowerCase()]})]}),n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:Oe==="cloud",onChange:()=>Ze("cloud"),disabled:ae}),n.jsxs("span",{children:["Sync existing cloud ",Rn.toLowerCase()]})]})]}),Cr?n.jsxs("div",{className:he.optionGroup,children:[!Xt&&!En&&n.jsx("p",{className:he.loginError,children:"Cloud workspace sync is unavailable right now. Switch back to local setup or refresh runtime configuration."}),!Xt&&En&&!gt&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:he.inlineHint,children:"Sign in to choose one of your cloud projects."}),n.jsxs("div",{className:he.actionRowEnd,children:[n.jsx("button",{className:f.cancelBtn,disabled:ae,onClick:()=>{A(`/login?mode=login&next=${encodeURIComponent(Yn)}`,{replace:!0})},children:"Sign In"}),Ta&&n.jsx("button",{className:f.submitBtn,disabled:ae,onClick:()=>{A(`/login?mode=register&next=${encodeURIComponent(Yn)}`,{replace:!0})},children:"Register"})]})]}),!Xt&&En&>&&n.jsxs(n.Fragment,{children:[n.jsxs("select",{className:f.input,value:At,onChange:we=>Rt(we.target.value),disabled:ae||Bt||re.length===0,children:[re.length===0&&n.jsx("option",{value:"",children:Bt?"Loading cloud projects...":"No cloud projects found"}),re.map(we=>n.jsxs("option",{value:we.id,children:[we.name," (",we.id,")"]},we.id))]}),n.jsx("div",{className:he.actionRowEnd,children:n.jsx("button",{className:f.cancelBtn,disabled:ae||Bt,onClick:()=>{_n()},children:"Refresh Cloud Projects"})}),Ot&&n.jsx("p",{className:he.loginError,children:Ot})]}),Xt&&n.jsxs(n.Fragment,{children:[n.jsxs("p",{className:he.inlineHint,children:['Importing "',Xt.name,'" from cloud into local.']}),n.jsx("div",{className:he.optionGroup,children:Ar.map(we=>n.jsx("p",{className:he.inlineHint,children:we},we))}),n.jsx("p",{className:he.inlineHint,children:Ie?"Finishing setup and opening your workspace.":Ea||"Pulling tasks, taxonomies, and settings into local."}),!Ie&&Da&&n.jsx("p",{className:he.inlineHint,children:Da})]})]}):n.jsxs(n.Fragment,{children:[Wr&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:he.loginSubtitle,children:"Workspace name"}),n.jsx("input",{className:f.input,type:"text",value:Ft,placeholder:"Workspace name",onChange:we=>Et(we.target.value),disabled:ae}),n.jsx("p",{className:he.loginSubtitle,children:"Workspace description"}),n.jsx("textarea",{className:f.textarea,value:We,placeholder:"Workspace description (optional)",onChange:we=>tt(we.target.value),disabled:ae,rows:4})]}),ao&&n.jsxs("div",{className:he.optionGroup,children:[n.jsx("p",{className:he.loginSubtitle,children:"What are you working on?"}),n.jsxs("select",{className:f.input,value:Pt,onChange:we=>Wt(we.target.value),disabled:ae||sn||zt.length===0,children:[zt.length===0&&n.jsx("option",{value:"",children:sn?"Loading setup options...":"No setup options available"}),zt.map(we=>n.jsx("option",{value:we.id,children:we.label},we.id))]}),gn?n.jsx(n.Fragment,{children:gn.description?n.jsx("p",{className:he.inlineHint,children:gn.description}):null}):null,n.jsxs("div",{className:he.optionGroup,children:[n.jsx("p",{className:he.loginSubtitle,children:"Apply Setup Sections"}),n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"checkbox",checked:Dt.categories,onChange:()=>Ht(we=>({...we,categories:!we.categories})),disabled:ae||!gn?.categories.length}),n.jsx("span",{children:"Categories"})]}),T?n.jsx("p",{className:he.inlineHint,children:T}):null,n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"checkbox",checked:Dt.types,onChange:()=>Ht(we=>({...we,types:!we.types})),disabled:ae||!gn?.types.length}),n.jsx("span",{children:"Task Types"})]}),N?n.jsx("p",{className:he.inlineHint,children:N}):null,n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"checkbox",checked:Dt.priorities,onChange:()=>Ht(we=>({...we,priorities:!we.priorities})),disabled:ae||!gn?.priorities.length}),n.jsx("span",{children:"Priorities"})]}),rt?n.jsx("p",{className:he.inlineHint,children:rt}):null]}),sn?n.jsx("p",{className:he.inlineHint,children:"Loading setup options…"}):null,Vn?n.jsx("p",{className:he.loginError,children:Vn}):null]}),!xn&&En&>&&Wr&&n.jsxs("div",{className:he.optionGroup,children:[n.jsxs("label",{className:`${he.authModeLink} ${he.optionRow}`,children:[n.jsx("input",{type:"checkbox",checked:E,onChange:we=>l(we.target.checked),disabled:ae}),n.jsx("span",{children:"Sync to cloud after setup"})]}),n.jsx("p",{className:he.inlineHint,children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),n.jsxs("div",{className:he.authModeLinks,children:[ao?n.jsx("button",{className:f.cancelBtn,onClick:()=>{it(null),ht(null),ot("details")},children:"Back"}):ia?n.jsx("button",{className:f.cancelBtn,onClick:()=>{it(null),ht(null),A("/",{replace:!0})},children:"Cancel"}):bt==="cloud"?n.jsx("button",{className:f.cancelBtn,onClick:async()=>{await pt.logout(),A("/login",{replace:!0})},children:qe("setup.signOut")}):null,He?n.jsx("button",{className:f.submitBtn,disabled:ae||Er&&!!Xt&&!Wa,onClick:async()=>{Ge(!0),ht(null),it(null);try{const we=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:Qe}})}),ee=await we.json().catch(()=>({}));!we.ok||ee?.success===!1?it(ee?.error||qe("setup.saveFailedWithStatus",{status:we.status})):(ht(qe("setup.globalSetupSaved")),await Kt())}catch{it(qe("setup.saveFailed"))}finally{Ge(!1)}},children:qe(ae?"setup.saving":"setup.saveGlobalSetup")}):F?n.jsx("button",{className:f.submitBtn,disabled:ae,onClick:Kt,children:qe("setup.retrySetupCheck")}):n.jsx("button",{className:f.submitBtn,disabled:ae||Er&&!Xt&&!gt,onClick:async()=>{if(Er&&Xt){if(!Wa)return;Ge(!0),ht(`Retrying import for ${Xt.name}...`),it(null);try{await os()}catch{ht(null),it(`Failed to retry import for "${Xt.name}".`)}finally{Ge(!1)}return}if(Cr){if(!En){it("Cloud workspace sync is unavailable right now."),Ge(!1);return}if(!gt){it("Sign in is required before syncing a cloud project."),Ge(!1);return}const we=re.find(Pa=>Pa.id===At);if(!we){it("Select a cloud project to sync."),Ge(!1);return}const ee=await aa({workspaceId:we.id,name:we.name||we.id,description:we.description||void 0});if(!ee.success){it(ee.error||qe("setup.saveWorkspaceFailed")),Ge(!1);return}const gr=String(ee.workspaceId||we.id||"").trim();if(!gr){it("Failed to resolve workspace id for sync setup."),Ge(!1);return}try{await Ba(gr,{version:2,enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null})}catch(Pa){it(Pa instanceof Error?Pa.message:"Failed to configure workspace sync."),Ge(!1);return}Zt({enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null}),await Kt(),Se({workspaceId:gr,name:we.name||we.id}),Ke(!1),ht(`Importing ${we.name||we.id} from cloud...`),Ge(!1);return}if(Wr){if(!Ft.trim()){it("Workspace name is required before continuing.");return}it(null),ht(null),ot("library");return}Ge(!0),ht(null),it(null);{const we=ia||nn?.workspaceSetupState==="missing",ee=ia||An&&we,gr=ee?await Pn(Ft,We||void 0):null,Pa=ee?null:await aa({workspaceId:we?void 0:nn?.workspaceId,name:Ft,description:We}),$a=gr||Pa;if($a?.success){const Rr=String(gr?.workspace?.id||Pa?.workspaceId||nn?.workspaceId||"").trim();if(!Rr){it("Failed to resolve workspace id for setup."),Ge(!1);return}if(!!gn&&(Dt.categories||Dt.types||Dt.priorities)&&gn){const Mo=await qa.onApplySystemTaxonomyPack({pack:gn,sections:Dt,remapExistingValuesToDefault:!0,workspaceIdOverride:Rr});if(!Mo?.success){it(Mo?.error||"Failed to apply setup library."),Ge(!1);return}}const Xa=!!(!xn&&E&&En&>),ro=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Rr,stateKey:"workspace-sync",patch:{version:2,enabled:Xa,phase:Xa?"provision-local":"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),Po=await ro.json().catch(()=>({}));if(!ro.ok||Po?.success===!1){it(Po?.error||`Failed to configure workspace sync (${ro.status})`),Ge(!1);return}Zt({enabled:Xa,phase:Xa?"provision-local":"idle",setupIntent:null,pullCursor:null}),ht(Xa?`${Rn} setup saved. Cloud sync enabled.`:qe("setup.workspaceSetupSaved",{workspaceLabel:Rn})),ia&&(await Kt(),await Ca(!0),A("/",{replace:!0}))}else{if($a?.code==="WORKSPACE_LIMIT_REACHED"){Ge(!1),A(_,{replace:!0});return}it($a?.error||qe("setup.saveWorkspaceFailed"))}}Ge(!1)},children:wt})]})]})})})}return n.jsx(BO,{...pt,onHeaderMouseDown:s,isDragging:o,onClose:c})}function FO(e){return gv()?n.jsx(mg,{...e}):n.jsx(yv,{children:n.jsx(mg,{...e})})}const Yy={},pg="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=pg,console.info(`[Taskforce] Build marker: ${pg}`));function OO(){if(typeof window<"u"){const t=window.location.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1")return}return yf(Yy).apiBaseUrl||void 0}function $O(e){const t=yf(Yy),a=t.cloudAuthBaseUrl;if(a)if(typeof window<"u"){const s=window.location.hostname.toLowerCase(),o=s==="localhost"||s==="127.0.0.1"||s==="::1",c="".trim().toLowerCase()==="true";if(!o&&!c)try{const i=new URL(a,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 a}catch{}else return a}else return a;if(t.baseUrl)return t.baseUrl;if(e)return e}function UO(){const e=OO(),t=$O(e);return n.jsx(kv,{children:n.jsx(FO,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:t}})})}jk.createRoot(document.getElementById("root")).render(n.jsx(ze.StrictMode,{children:n.jsx(UO,{})}));export{GM as $,r$ as A,I2 as B,dE as C,el as D,P2 as E,a$ as F,mW as G,n2 as H,rc as I,gf as J,Xp as K,Jh as L,Es as M,Qh as N,X1 as O,s$ as P,pW as Q,hy as R,Cy as S,ud as T,bm as U,fy as V,c$ as W,i$ as X,vm as Y,GF as Z,HM as _,Im as a,FM as a0,n$ as a1,Tm as a2,Gr as b,aS as c,Rv as d,Ut as e,YO as f,tm as g,KM as h,kb as i,o$ as j,ZM as k,uy as l,Xe as m,CS as n,am as o,ey as p,rm as q,Ma as r,ty as s,f as t,XO as u,JO as v,e$ as w,QO as x,t$ as y,OS as z};
|