@taskforcehq/taskforce 0.3.320 → 0.3.322

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/dist/TaskforceCore.js +8 -3
  2. package/dist/hooks/workspace/useTaskforceWorkspaceBootstrap.js +29 -5
  3. package/dist/mcp/runtime.js +72 -10
  4. package/dist/mcp/taskPlanningRegistrar.js +1 -0
  5. package/dist/server/routes/admin.d.ts +1 -0
  6. package/dist/server/routes/admin.js +17 -0
  7. package/dist/ui/assets/{AgentsModule-BZG0WHDN.js → AgentsModule-7jpDeuVR.js} +1 -1
  8. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-EQEzsETm.js → AnnotatedAttachmentWorkspace-BJLe8DFj.js} +1 -1
  9. package/dist/ui/assets/{ContextAttachmentManager-B3hESx6y.js → ContextAttachmentManager-AmEny3eI.js} +1 -1
  10. package/dist/ui/assets/{DocumentWorkspace-Z7bykYtA.js → DocumentWorkspace-Cqdq31Ha.js} +1 -1
  11. package/dist/ui/assets/{EntityActivityTimeline-B2aXkxiE.js → EntityActivityTimeline-BlS7DhA4.js} +1 -1
  12. package/dist/ui/assets/{InitiativesModule-CSzXelzW.js → InitiativesModule-C1qfO1uZ.js} +1 -1
  13. package/dist/ui/assets/{PlansPage-2vebpTBs.js → PlansPage-DFt5w-0Y.js} +1 -1
  14. package/dist/ui/assets/{TaskContextUpload-Bz06La5A.js → TaskContextUpload-zuro5gDT.js} +1 -1
  15. package/dist/ui/assets/{TaskSettings-4PbrcOqD.js → TaskSettings-CJPC2Bft.js} +1 -1
  16. package/dist/ui/assets/{WorkflowsModule-AyOzrP3y.js → WorkflowsModule-CEEGuxsf.js} +1 -1
  17. package/dist/ui/assets/documentReferences-Ca2P--i5.js +1 -0
  18. package/dist/ui/assets/index-CGDQY0nN.js +5 -0
  19. package/dist/ui/index.html +1 -1
  20. package/package.json +1 -1
  21. package/dist/ui/assets/documentReferences-CKk8ylqA.js +0 -1
  22. package/dist/ui/assets/index-rB9GGUCz.js +0 -5
@@ -0,0 +1,5 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EntityActivityTimeline-BlS7DhA4.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-zuro5gDT.js","assets/ContextAttachmentManager-AmEny3eI.js","assets/documentReferences-Ca2P--i5.js","assets/TaskSettings-CJPC2Bft.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-BJLe8DFj.js","assets/AnnotatedAttachmentWorkspace-BVKew-mH.css","assets/DocumentWorkspace-Cqdq31Ha.js","assets/DocumentWorkspace-D4rJKXzd.css","assets/WorkflowsModule-CEEGuxsf.js","assets/AgentsModule-7jpDeuVR.js","assets/InitiativesModule-C1qfO1uZ.js","assets/PlansPage-DFt5w-0Y.js","assets/PlansPage-DeAzWYTb.css"])))=>i.map(i=>d[i]);
2
+ import{r,j as a,R as Ue,a as Yi,b as Tk}from"./vendor-react-CKJs5o3c.js";import{I as As,C as Ji,a as nl,b as no,c as tf,F as Rk,A as jk,R as gd,T as _m,L as Ep,d as Po,e as Nk,X as nc,f as cg,g as lg,h as kr,B as am,U as ii,i as dg,S as Pk,P as ro,j as Xc,G as Mk,k as Zu,l as nm,m as yd,n as Ek,o as af,p as Dk,q as Dp,r as ug,s as Lk,t as Bk,M as mg,W as Wk,u as Fk,v as Ok,w as $k,x as Mo,E as nf,y as pg,z as fg,D as Uk,H as zk,J as Hk,K as Zf,N as Yf,O as Gk,Q as Vk,Z as qk,V as Kk,Y as Zk,_ as Yk,$ as hg,a0 as Jk,a1 as Jf,a2 as Qk,a3 as Xk,a4 as ev,a5 as tv}from"./vendor-icons-CLnehDTw.js";import{M as av,r as nv,a as rv}from"./vendor-markdown-BUxTU7dS.js";import{u as gg,a as Lp,b as sv,D as yg,c as ov,S as kg,v as vg,P as Sg,d as wg,C as rf,e as iv,p as cv,f as Qf,s as lv,K as dv,g as sf,h as uv,i as bg,j as mv}from"./vendor-dnd-DRzYolkg.js";import{u as _g,a as Cg,b as pv,M as fv,N as Xf,B as hv}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 l of o)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();const Qc="default",Cm="General",Vr="task",gv=2,yv=[{value:Qc,label:Cm,icon:"Inbox"}],Ag=[{value:Vr,label:"Task",icon:"CheckSquare",color:"blue-500"}],kv=[{value:gv,label:"Medium",color:"blue-500",icon:"Minus"}];function vv(){return yv.map(e=>({...e}))}function Sv(){return Ag.map(e=>({...e}))}function wv(e){const t=String(e||"").trim().toLowerCase();return Ag.find(n=>n.value===t)}function xg(){return kv.map(e=>({...e}))}const bv="default",_v=[{value:bv,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 Ig(){return _v.map(e=>({...e}))}const Cv={categories:vv(),types:Sv(),priorities:xg(),approaches:Ig(),taxonomies:[],apiEndpoint:"/api/taskforce/task",apiBaseUrl:void 0,cloudAuthBaseUrl:void 0,cloudMcpBaseUrl:void 0,wsBaseUrl:void 0,position:"bottom-right",offsetY:70,theme:"dark",shortcut:"Alt+T",manualComplexityEnabled:!1,checklistDropdownEnabled:!0,showTaskCardStatusLabel:!0},Av=["light","dawn","dark","midnight"],rm="dark",xv=[{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"}],Iv=new Set(Av),Tv=new Set(xv.filter(e=>e.family==="light").map(e=>e.id));function Rv(e){return typeof e=="string"&&Iv.has(e)}function Kc(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return Rv(t)?t:null}function Tg(e){const t=Kc(e);return t!==null&&Tv.has(t)}function Bp(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return null;const n=Math.floor(t);return n>0?n:null}function el(e,t){const n=Bp(typeof t=="object"&&t!==null?t.referenceNumber:t);return n?`${e}${n}`:""}function of(e,t){const n=String(e||"").trim(),s=String(t||"").trim();if(!n||!s)return null;const o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=s.match(new RegExp(`^${o}(\\d+)$`,"i"));return l?Bp(l[1]):null}function Am(e,t){return t?typeof t.referenceLabel=="string"&&t.referenceLabel.trim().length>0?t.referenceLabel.trim():el(e,t.referenceNumber):""}const cf="T-",eh="LT-";function jv(e){return el(cf,e)}function Rg(e){return typeof e=="number"||e===null||e===void 0?el(eh,e):el(eh,{referenceNumber:e.localReferenceNumber??null})}function jg(e){return of(cf,e)}function Xi(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const t=Am(cf,e);return t||Rg(e.localReferenceNumber)}function Nv(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function Ng(e){return{label:Xi(e),isProvisional:Nv(e)}}xg();const Pv={low:1,medium:2,high:3,critical:4,"on-hold":1},Mv={1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function Ev(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 sm(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)):Pv[String(e||"").trim().toLowerCase()]??2}function Dv(e,t){return Mv[String(e)]||t}function Do(e){const t=typeof e.referenceNumber=="number"?e.referenceNumber:Number.isFinite(Number(e.referenceNumber))?Number(e.referenceNumber):null,n=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:n&&n>0?Math.floor(n):null,referenceLabel:typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0?e.referenceLabel.trim():t?jv(t):Rg(n),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:sm(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:Ev(e.status)}}function Lv(e,t,n){if(!e||typeof e!="object")return{tasks:t,archivedTasks:n};const s=Do(e),o=String(s.id||"").trim();if(!o)return{tasks:t,archivedTasks:n};const l=!!s.isArchived,i=l?{...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=n.filter(k=>k.id!==o);return l?y.push(i):m.push(i),{tasks:d(m),archivedTasks:d(y)}}function Bv(e,t){if(!t.length||!e.length)return[];const n=new Set(t.map(o=>Number(o.value))),s=Array.from(new Set(e.map(o=>Number(o)).filter(o=>Number.isFinite(o)&&n.has(o))));return s.length>0?s:t.map(o=>Number(o.value))}function up(e,t){return t.some(n=>String(n)===String(e))}function Wv(e,t){if(!e.length||!t.length)return e;const n=new Set(t.map(o=>o.value)),s=Array.from(new Set(e.filter(o=>n.has(o))));return s.length>0?s:t.map(o=>o.value)}const Fv={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"}},Ov={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"}},$v={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"}},Pg=["en-US","es-419","pt-BR"],om="en-US",mp={"en-US":Fv,"es-419":Ov,"pt-BR":$v},Mg={en:"en-US",es:"es-419",pt:"pt-BR"};let Qi=om;function Uv(e){return e.split(".").filter(Boolean)}function pp(e,t){let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return typeof n=="string"?n:void 0}function Eg(e){if(!e)return om;const t=Pg.find(s=>s.toLowerCase()===e.toLowerCase());if(t)return t;const n=e.split("-")[0]?.toLowerCase()||"";return Mg[n]||om}function fp(e,t){return t?e.replace(/\{([^}]+)\}/g,(n,s)=>{const o=t[s];return o==null?"":String(o)}):e}function Dg(){return Qi}function zv(){return[...Pg]}function Lg(e){const t=Eg(e);return Qi=t,t}function Hv(e){const t=typeof navigator<"u"?navigator.language:null;return Qi=Eg(t),Qi}function qe(e,t){const n=Uv(e),s=pp(mp[Qi],n);if(s)return fp(s,t);const o=Qi.split("-")[0]?.toLowerCase()||"",l=Mg[o];if(l&&l!==Qi){const d=pp(mp[l],n);if(d)return fp(d,t)}const i=pp(mp[om],n);return i?fp(i,t):e}const Gv="default",ec="bootstrap";function Vv(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function lf(e){const t=String(e||"").trim().toLowerCase();return t?`${(t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${Vv(t)}`:ec}function Bg(e){const t=String(e||"").trim().toLowerCase();if(!t)return ec;const n=t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return n?n.slice(0,96):ec}function Wg(e){const t=String(e||"").trim();return t?lf(t):ec}function qv(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?ec:Wg(e.projectRoot)}function Kv(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const n=String(e.workspaceId||"").trim();return n&&!df(n)?lf(`cloud-workspace:${n}`):ec}return Wg(e.projectRoot)}function df(e){return String(e||"").trim().toLowerCase()===Gv}const Zv={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function Yv(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function Jv(e){return Zv[Yv(e)]}const kd={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 xm(e){const t=String(e||"").trim().toLowerCase();return t==="production"||t==="staging"||t==="performance"?t:null}function Qv(e){return xm(e)||"production"}function th(e){return kd[Qv(String(e||""))]}function Xv(e){const t=String(e||"").trim().toLowerCase();if(!t)return null;for(const[n,s]of Object.entries(kd))if(new URL(s.appBaseUrl).hostname.toLowerCase()===t||new URL(s.mcpBaseUrl).hostname.toLowerCase()===t)return n;return null}function uf(e){const t=String(e||"").trim();if(!t)return null;try{return Xv(new URL(t).hostname)}catch{return null}}function eS(e){const t=uf(e);return t?kd[t].mcpBaseUrl:null}function zi(e,t){return String(e[t]||"").trim()}function ah(e,t,n){e.push(t),n?.(t)}function tS(e,t){const n=[],s=zi(e,"ENV"),o=xm(s);if(o)return ah(n,`[Taskforce compat] ENV=${s} is deprecated; set TASKFORCE_CLOUD_ENVIRONMENT=${o} instead.`,t),{cloudEnvironment:o,warnings:n};const l=[{key:"TASKFORCE_CLOUD_PROXY_BASE_URL",value:zi(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:zi(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:zi(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:zi(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:zi(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:zi(e,"TASKFORCE_BASE_URL")}];for(const i of l){if(!i.value)continue;const d=uf(i.value);if(d)return ah(n,`[Taskforce compat] ${i.key} is being used to infer TASKFORCE_CLOUD_ENVIRONMENT=${d}. Set TASKFORCE_CLOUD_ENVIRONMENT explicitly.`,t),{cloudEnvironment:d,warnings:n}}return{cloudEnvironment:null,warnings:n}}function Xs(e,t){return String(e[t]||"").trim()}function aS(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function Gc(e){return String(e||"").trim().replace(/\/+$/,"")}function nS(e){return String(e||"").trim().replace(/\/+$/,"")}function jo(...e){for(const t of e)if(String(t||"").trim())return String(t||"").trim();return""}function rS(e,t={}){const n=[],s=ke=>{n.push(ke),t.onWarning?.(ke)},o=aS(Xs(e,"TASKFORCE_RUNTIME_MODE")),l=xm(Xs(e,"TASKFORCE_CLOUD_ENVIRONMENT")),i=l?{cloudEnvironment:l}:tS(e,s),d=l||i.cloudEnvironment,m=Gc(String(t.requestBaseUrl||"")),y=Gc(jo(Xs(e,"VITE_TASKFORCE_BASE_URL"),Xs(e,"TASKFORCE_BASE_URL"))),k=Gc(Xs(e,"VITE_TASKFORCE_API_BASE_URL")),S=Gc(Xs(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),h=Gc(jo(Xs(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),Xs(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),g=Gc(Xs(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),v=nS(Xs(e,"VITE_TASKFORCE_WS_BASE_URL")),_=d?kd[d].appBaseUrl:"",I=d?kd[d].mcpBaseUrl:"",C=jo(g,S,k,y,_),D=jo(h,I,C),q=jo(m,y,k,S,C),B=jo(m,k,y,C),X=jo(S,y,k,C),me=o==="local"?jo(v,m,k,y,g,S,_,C):jo(m,v,B,q,C);return{runtimeMode:o,cloudEnvironment:d,cloudBaseUrl:C,cloudMcpBaseUrl:D,baseUrl:q,apiBaseUrl:B,cloudAuthBaseUrl:X,wsBaseUrl:me,cloudAuthViaLocalProxy:o==="local"||!!g,warnings:n}}function mf(e){return rS({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 nh(e){const t=String(e.workspaceId||"default").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"default",n=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${n}-${o}`}function hp(e,t){const n=String(t||"").trim();if(!n)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",n),{...e||{},headers:s}}const im="unassigned",Fg="agent",sS="user",oS=/^[0-9a-f]{8,}$/i;function Og(e){const t=String(e||"").trim().toLowerCase();return t===Fg||t==="ai"||t.startsWith("ai-profile-")}function $g(e){const t=String(e||"").trim().toLowerCase();return!t||t===im||t==="none"||t==="null"||t===sS}function cm(e){return Og(e)?"agent":$g(e)?"unassigned":"member"}function iS(e){const t=String(e.displayName||"").trim(),n=String(e.email||"").trim().toLowerCase();return t||n||String(e.userId||"").trim()||"Workspace member"}function li(){return[{value:im,label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)",kind:"unassigned"}]}function cS(e){const t=new Map;for(const n of e){const s=String(n.userId||"").trim();s&&t.set(s,{value:s,label:iS(n),icon:"User",color:"#22c55e",kind:"member",avatarUrl:typeof n.avatarUrl=="string"&&n.avatarUrl.trim().length>0?n.avatarUrl.trim():null})}return vd(Array.from(t.values()))}function vd(e){const t=new Map;for(const s of li())t.set(s.value,s);for(const s of Array.isArray(e)?e:[]){const o=String(s?.value||"").trim(),l=typeof s?.archivedAt=="string"?s.archivedAt.trim():"";!o||l||o===im||o===Fg||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 n=[im];return Array.from(t.values()).sort((s,o)=>{const l=n.indexOf(s.value),i=n.indexOf(o.value);return l>=0||i>=0?l<0?1:i<0?-1:l-i:s.label.localeCompare(o.label,void 0,{sensitivity:"base"})})}function lS(e,t){const n=String(t||"").trim();if(!n||e.some(l=>l.value===n))return e;const s=n.replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),o=s?s.split(" ").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" "):n;if(cm(n)==="agent"){const l=String(n).toLowerCase().startsWith("ai-profile-")&&s.split(" ").every(i=>oS.test(i));return vd([...e,{value:n,label:l?"AI":o||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return cm(n)==="member"?vd([...e,{value:n,label:o||n,icon:"User",color:"#22c55e",kind:"member"}]):e}function Ug(e){const t=Array.isArray(e)?e.filter(Boolean):[];return vd(t)}function ud(e,t){const n=String(e||"").trim(),o=Ug(t).find(l=>l.value===n);return o?o.label:Og(n)?"AI":$g(n)?"Unassigned":n||"Unassigned"}const zg="taskforce.workspaceContext.v2",dS="taskforce.uiState.app.v1",uS="taskforce.bootstrapDebug.v1",rh=5e3,Mu=new Map;function mS(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(uS)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Ut(e,t){if(!mS())return;console.info("[Taskforce Bootstrap]",e,t&&typeof t=="object"?t:{})}function pS(e,t){const n=String(e).trim()||"default";return`${String(t).trim()||"default"}::${n}`}async function pf(e){const t=String(e.stateKey||"default").trim()||"default",n=String(e.workspaceId||"").trim(),s=e.patch&&typeof e.patch=="object"?e.patch:{},o=JSON.stringify(s),l=pS(t,n||"default"),i=Date.now(),d=Mu.get(l);if(d&&d.serializedPatch===o){if(d.status==="success"&&e.skipIfUnchanged!==!1)return Ut("ui_state_persist_skipped",{stateKey:t,workspaceId:n||"default",reason:"unchanged"}),{skipped:!0,reason:"unchanged"};if(e.respectFailureCooldown!==!1&&d.retryAfter>i)return Ut("ui_state_persist_skipped",{stateKey:t,workspaceId:n||"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,...n?{workspaceId:n}:{},patch:s})}),y=await m.json().catch(()=>({}));if(m.ok&&y?.success!==!1)return Mu.set(l,{serializedPatch:o,status:"success",retryAfter:0}),{skipped:!1,response:m,payload:y};if(Mu.set(l,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??rh)}),Ut("ui_state_persist_failed",{stateKey:t,workspaceId:n||"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(Mu.set(l,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??rh)}),Ut("ui_state_persist_failed",{stateKey:t,workspaceId:n||"default",error:m instanceof Error?m.message:String(m)}),e.throwOnError)throw m;return{skipped:!1,payload:null}}}function ff(e){const t=lf(e);return`${zg}.${t}`}function Hg(e){const t=Bg(e);return`${zg}.${t}`}function Wp(e){if(typeof window>"u")return"";try{const t=ff(e),n=String(window.localStorage.getItem(t)||"").trim();if(n&&n.length<=120&&!/\s/.test(n))return n;const s=Hg(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 fS(e,t){if(typeof window>"u")return;const n=String(e||"").trim();try{if(!n||df(n))return;const s=ff(t),o=String(window.localStorage.getItem(s)||"").trim();if(!n&&o&&o.toLowerCase()!=="default")return;window.localStorage.setItem(s,n)}catch{}}function sh(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(ff(e)),window.localStorage.removeItem(Hg(e))}catch{}}function Gg(e){const t=Bg(e);return`${dS}.${t}`}function oh(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Gg(e));if(!t)return null;const n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function hS(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Gg(t),JSON.stringify(e))}catch{}}const Fp="taskforce.localMutationActorUserId.v1";function Vg(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function gS(e){const t=String(e||"").trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function rd(e){if(!(typeof window>"u"))try{const t=String(e||"").trim();if(!t||t==="anonymous"){window.sessionStorage.removeItem(Fp);return}window.sessionStorage.setItem(Fp,t)}catch{}}function hf(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Fp)||"").trim()}catch{return""}}function yS(e,t){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!gS(window.location.hostname))return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function kS(e,t,n){if(!yS(e,t))return n;const s=hf();if(!s)return n;const o=new Headers(n?.headers||void 0);return o.has("x-taskforce-user-id")||o.set("x-taskforce-user-id",s),{...n,headers:o}}function vS(e,t){if(!e.startsWith("/"))return e;const n=Vg(t);return n?`${n}${e}`:e}async function LO(e,t,n){const s=vS(e,n),o=Vg(n).length>0,l=kS(e,s,t),i=typeof performance<"u"?performance.now():Date.now();try{const d=await fetch(s,l);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,l);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,l);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}}function SS(e){const t=Number(e?.status);return Number.isFinite(t)&&t>0?Math.floor(t):0}async function rl(e){try{const t=await e,n=await t.text().catch(()=>"");let s={};if(n)try{s=JSON.parse(n)}catch{s={error:!t.ok&&t.statusText?`${t.status} ${t.statusText}`:n.slice(0,400)}}else!t.ok&&t.statusText&&(s={error:`${t.status} ${t.statusText}`});const o=t.headers.get("retry-after");let l;if(o){const i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>0)l=i*1e3;else{const d=Date.parse(o);if(Number.isFinite(d)){const m=d-Date.now();m>0&&(l=m)}}}return{ok:t.ok,status:t.status,data:s,retryAfterMs:l}}catch(t){return{ok:!1,status:SS(t),data:{}}}}async function wS(e){return rl(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function bS(e,t){return rl(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function gp(e,t){return rl(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t})}))}async function ih(e,t){return rl(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function _S(e,t){const n=new URLSearchParams({limit:String(t.limit),workspaceId:t.workspaceId});t.cursor&&n.set("cursor",t.cursor),t.repairMode===!0&&n.set("repair","1");const s=e("/api/taskforce/sync/workspace/pull"),o=s.includes("?")?"&":"?";return rl(fetch(`${s}${o}${n.toString()}`,{method:"GET",credentials:"include"}))}async function CS(e,t){return rl(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 Op(e,t,n){const s=JSON.stringify({workspaceId:e,changes:t,workspaceMembers:Array.isArray(n?.workspaceMembers)?n.workspaceMembers:void 0,...n?.repairMode===!0?{repair:!0}:{},bootstrapSnapshot:n?.bootstrapSnapshot?{currentAnnotatedAttachmentSessionIds:Array.isArray(n.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds)?n.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds:[]}:void 0}),o="/api/taskforce/sync/workspace/apply-local",l=[];try{const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:s});if(i.ok){const y=await i.json().catch(()=>({}));return{ok:!0,status:i.status,data:y,failures:l}}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 l.push(`${o}:${i.status}`),{ok:!1,status:i.status,data:m,failures:l}}catch{l.push(`${o}:network`)}return{ok:!1,status:0,data:{},failures:l}}const $p="V1:AESGCM:",gf="AES-GCM",AS=12;async function qg(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:gf},!1,["encrypt","decrypt"])}async function ch(e,t){if(!e)return e;const n=crypto.getRandomValues(new Uint8Array(AS)),s=await qg(t),l=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:gf,iv:n},s,l),d=Buffer.from(i).toString("base64"),m=Buffer.from(n).toString("base64");return`${$p}${m}:${d}`}async function lh(e,t){if(!e||!e.startsWith($p))return e;const n=e.slice($p.length),[s,o]=n.split(":");if(!s||!o)throw new Error("Malformed encrypted document payload.");const l=Buffer.from(s,"base64"),i=Buffer.from(o,"base64"),d=await qg(t);try{const m=await crypto.subtle.decrypt({name:gf,iv:l},d,i);return new TextDecoder("utf-8").decode(m)}catch(m){throw new Error(`Failed to decrypt document: ${m.message}`)}}var Zc={};function is(e){return e&&typeof e=="object"?e:{}}function Bs(e){const t=Number(e||0);return t===0||t===429||t>=500}function dh(e,t){const n=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim();return n==="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 xS(e,t){if(t!==400)return!1;const n=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim().toLowerCase();return n==="WORKSPACE_ID_REQUIRED"&&s.includes("no cloud workspace is selected")}async function IS(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 gp(e.resolveCloudAuthUrl,e.workspaceId);if(t.ok)return{success:!0,provisioned:!1};const n=is(t.data);if(t.status===401)return{success:!1,statusCode:401,transient:!1,error:String(n.error||"Authentication required for workspace sync.")};if(t.status===429)return{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(n.error||"Workspace sync rate limited. Please retry later.")};if(xS(n,t.status)){const s=await ih(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=is(s.data);return{success:!1,statusCode:s.status,transient:Bs(s.status),retryAfterMs:s.retryAfterMs,error:dh(o,s.status)}}if(t=await gp(e.resolveCloudAuthUrl,e.workspaceId),!t.ok){const o=is(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:Bs(t.status),error:String(o.error||`Workspace sync handshake failed (${t.status})`)}}return{success:!0,provisioned:!0}}if(t.status===409&&n.code==="WORKSPACE_ID_MISMATCH"){if(e.allowProvisionOnMismatch===!1)return{success:!1,statusCode:409,transient:!1,error:String(n.error||"Selected cloud workspace could not be attached to this local workspace.")};const s=await ih(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=is(s.data);return{success:!1,statusCode:s.status,error:dh(o,s.status)}}if(t=await gp(e.resolveCloudAuthUrl,e.workspaceId),!t.ok){const o=is(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:Bs(t.status),error:String(o.error||`Workspace sync handshake failed (${t.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:t.status,transient:Bs(t.status),error:String(n.error||`Workspace sync handshake failed (${t.status})`)}}catch{return{success:!1,statusCode:0,transient:!0,error:"Failed to validate workspace sync access."}}}async function TS(e,t){const n=JSON.stringify([e,t]);try{const s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{let s=2166136261;for(let l=0;l<n.length;l+=1)s^=n.charCodeAt(l),s=Math.imul(s,16777619);const o=(s>>>0).toString(16).padStart(8,"0");return`${e}:fallback:${o}`}}async function RS(e){const t=e.payload.changes.length,n=e.payload.deleteTaskIds.size,s=await TS(e.workspaceId,e.payload.changes);let o=0,l=e.payload.changes;if(typeof process<"u"&&Zc?.TASKFORCE_SYNC_KEY){const S=Zc.TASKFORCE_SYNC_KEY,h=[];for(const g of l)g.op==="document-upsert"&&typeof g.content=="string"?h.push({...g,content:await ch(g.content,S)}):g.op==="asset-upsert"&&typeof g.contentBase64=="string"&&g.contentBase64.length>0?h.push({...g,contentBase64:await ch(g.contentBase64,S)}):h.push(g);l=h}const i=async()=>{const S=Date.now(),h=await CS(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,idempotencyKey:s,changes:l,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=is(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:Bs(d.status),requestMs:o,changeCount:t,deleteCount:n,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=is(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:n,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 jS(e){let t=e.cursor,n=!0,s=0,o=0,l=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(;n&&s<I;){const C=async()=>{const le=Date.now(),O=await _S(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:t,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0});return l+=Date.now()-le,O};let D=await C();if(!D.ok&&D.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(D=await C()),!D.ok){const le=is(D.data);return{success:!1,kind:"pull_http",status:D.status,errorCode:typeof le.code=="string"?le.code:void 0,error:typeof le.error=="string"?le.error:void 0,retryAfterMs:D.retryAfterMs,transient:Bs(D.status),cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),serverDiagnostics:null}}const q=D.data||{},B=Array.isArray(q?.changes)?q.changes:[],X=q?.diagnostics&&typeof q.diagnostics=="object"?q.diagnostics:null;_=X;const me=Array.isArray(q?.workspaceMembers),ke=me?q.workspaceMembers:void 0;for(const le of B){if(le.op==="upsert"){le?.archived===!0||le?.task?.isArchived===!0?y=!0:m=!0;continue}if(le.op==="annotated-attachment-session-upsert"){const A=String(le?.session?.id||"").trim();A&&v.add(A);continue}if(le.op==="task-event-upsert"||le.op==="entity-event-upsert"){k=!0;continue}if(le.op==="initiative-upsert"||le.op==="workstream-upsert"){S=!0;continue}if(le.op==="document-upsert"){if(typeof le.content=="string"&&typeof process<"u"&&Zc?.TASKFORCE_SYNC_KEY)try{le.content=await lh(le.content,Zc.TASKFORCE_SYNC_KEY)}catch{const A=String(le.path||"").trim();A&&h.add(A)}continue}if(le.op==="asset-upsert"){if(typeof le.contentBase64=="string"&&typeof process<"u"&&Zc?.TASKFORCE_SYNC_KEY)try{le.contentBase64=await lh(le.contentBase64,Zc.TASKFORCE_SYNC_KEY)}catch{const A=String(le.path||"").trim();A&&h.add(A)}continue}if(le.op!=="delete")continue;const O=String(le.taskId||"").trim();O&&d.add(O)}if(e.onPagePulled&&e.onPagePulled(),B.length>0||me){const le=Date.now(),O=await Op(e.workspaceId,B,{...me?{workspaceMembers:ke}:{},repairMode:e.repairMode===!0}),A=O.failures;if(!O.ok){i+=Date.now()-le;const ge=is(O.data);if(A.some(H=>H.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:A,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,documentDecryptFailures:Array.from(h),serverDiagnostics:X};const P=A.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:O.status||void 0,transient:P,error:String(ge.error||"").trim()||void 0,failures:A,hasTransientApplyFailure:P,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_}}const de=is(O.data);if(de.success===!1)return i+=Date.now()-le,{success:!1,kind:"apply_payload",transient:!1,error:String(de.error||"Workspace sync apply failed."),cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,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()-le,o+=B.length,Array.isArray(de.emittedEventIds))for(const ge of de.emittedEventIds)g.add(String(ge));e.onChangesApplied&&e.onChangesApplied(B.length)}q&&"nextCursor"in q&&(q.nextCursor===null||typeof q.nextCursor=="string")&&(t=q.nextCursor),n=!!q?.hasMore,s+=1}if(e.bootstrap){const C=Date.now(),D=await Op(e.workspaceId,[],{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(v)}}),q=D.failures;if(!D.ok){i+=Date.now()-C;const B=is(D.data);if(q.some(ke=>ke.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:q,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_};const me=q.some(ke=>{if(ke.endsWith(":network"))return!0;const le=ke.split(":").pop()||"",O=Number.parseInt(le,10);return Number.isFinite(O)&&(O===429||O>=500)});return{success:!1,kind:"apply_all_candidates",status:D.status||void 0,transient:me,error:String(B.error||"").trim()||void 0,failures:q,hasTransientApplyFailure:me,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_}}i+=Date.now()-C}return{success:!0,syncedAt:new Date().toISOString(),cursor:t||null,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:_}}catch(C){return{success:!1,kind:"exception",status:0,transient:!0,error:String(C?.message||C||"Workspace sync pull failed unexpectedly."),cursor:t||null,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:null}}}async function NS(e){const t=await wS(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:Bs(h)}}const n=is(t.data),s=n.settings&&typeof n.settings=="object"?n.settings:{},o=typeof n.updatedAt=="string"&&n.updatedAt.trim().length>0?n.updatedAt.trim():null,l=e.getLocalUpdatedAt(e.userId),i=l?Date.parse(l):NaN,d=o?Date.parse(o):NaN;if(!l&&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=l||new Date().toISOString(),y=await bS(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:Bs(h)}}const k=is(y.data);return{success:!0,mode:"pushed",updatedAt:typeof k.updatedAt=="string"&&k.updatedAt.trim().length>0?k.updatedAt.trim():m}}function PS(e){const t=Math.max(1,Math.floor(Number(e)||1)),n=Math.min(12e4,1500*2**Math.max(0,t-1)),s=Math.floor(n*(.15*Math.random()));return n+s}const MS=["chat_app","ide","cli","coding_tool","agent"],BO=["chat_app","ide","cli","coding_tool","agent","unclassified"],ES={chat_app:"Chat App",ide:"IDE",cli:"CLI",coding_tool:"Coding Tool",agent:"Agent"},DS={chat_app:"Chat Apps",ide:"IDEs",cli:"CLI",coding_tool:"Coding Tools",agent:"Agents",unclassified:"Unclassified"};function LS(e){return typeof e=="string"&&MS.includes(e)}function Kg(e){if(typeof e!="string")return null;const t=e.trim();return t==="other"?"agent":LS(t)?t:null}function WO(e){return ES[e]}function FO(e){return e??"unclassified"}function OO(e){return DS[e]}const BS=["cloud_metered","local_unmetered"],WS={cloud_metered:"Cloud MCP",local_unmetered:"Local MCP"};function FS(e){return typeof e=="string"&&BS.includes(e)}function Zg(e){if(typeof e!="string")return null;const t=e.trim();return FS(t)?t:null}function $O(e){return WS[e]}function ci(e){if(e==null)return;const t=String(e).trim();return t.length>0?t:void 0}function on(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Sd(e){return ci(e)}function lm(e){return on(e)}function Gr(e){return on(e)}function tl(e){const t=on(e);return t&&t.startsWith("/api/taskforce/context/")?t:null}function Eu(e){return ci(e)}function Du(e){if(e!==void 0)return on(e)}function OS(e){return typeof e=="boolean"?e:void 0}function Lu(e,t){if(e===void 0)return;if(e===null||e==="")return t?.nullable?null:void 0;const n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return t?.nullable?null:void 0;const s=Math.floor(n);return Number.isFinite(t?.min)&&s<Number(t?.min)?t?.nullable?null:void 0:s}function $S(e){if(!e||typeof e!="object"||Array.isArray(e))return;const n=Object.entries(e).reduce((s,[o,l])=>Array.isArray(l)?(s[o]=l.map(i=>String(i??"")),s):(l==null||(s[o]=String(l)),s),{});return Object.keys(n).length>0?n:{}}function US(e){return Array.isArray(e)?e:void 0}function zS(e){return Array.isArray(e)?e:void 0}function HS(e){return Array.isArray(e)?e:void 0}function Yg(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:Lu(t.priority,{min:1})??void 0,complexity:Lu(t.complexity,{min:1,nullable:!0}),type:String(t.type||"").trim(),category:String(t.category||"").trim(),approach:Eu(t.approach),canceledReason:t.canceledReason===void 0?void 0:t.canceledReason||null,createdAt:String(t.createdAt||"").trim(),updatedAt:Eu(t.updatedAt),completedAt:t.completedAt===void 0?void 0:t.completedAt||null,isArchived:OS(t.isArchived),taxonomies:$S(t.taxonomies),createdBy:Eu(t.createdBy),assignee:Eu(t.assignee),scheduledDate:Du(t.scheduledDate),dueDate:Du(t.dueDate),scheduledWeekKey:Du(t.scheduledWeekKey),orderInDay:Lu(t.orderInDay,{min:0,nullable:!0}),workstreamId:Du(t.workstreamId),referenceNumber:Lu(t.referenceNumber,{min:1,nullable:!0}),comments:US(t.comments),attachments:zS(t.attachments),checklistItems:HS(t.checklistItems)}}function GS(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)),n={};for(const[s,o]of t){if(Array.isArray(o)){n[s]=o.map(l=>String(l??"")).sort((l,i)=>l.localeCompare(i));continue}o!=null&&(n[s]=String(o))}return n}function VS(e){return Array.isArray(e)?e.map(t=>{const n=t&&typeof t=="object"?t:{};return{id:String(n.id||"").trim(),title:String(n.title||"").trim(),isCompleted:!!n.isCompleted,order:n.order===void 0||n.order===null?"":String(n.order)}}).sort((t,n)=>{const s=Number.parseInt(t.order,10),o=Number.parseInt(n.order,10);return Number.isFinite(s)&&Number.isFinite(o)&&s!==o?s-o:t.title!==n.title?t.title.localeCompare(n.title):t.id.localeCompare(n.id)}):[]}function qS(e){return Array.isArray(e)?e.map(t=>{const n=t&&typeof t=="object"?t:null;return{id:String(n?.id||"").trim(),author:String(n?.author||"").trim(),submittedAuthor:ci(n?.submittedAuthor)||"",text:String(n?.text||""),timestamp:Gr(n?.timestamp)||"",actor:n?.actor??null}}).sort((t,n)=>t.timestamp!==n.timestamp?t.timestamp.localeCompare(n.timestamp):t.id!==n.id?t.id.localeCompare(n.id):t.author!==n.author?t.author.localeCompare(n.author):t.text.localeCompare(n.text)):[]}function KS(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 n=t&&typeof t=="object"?t:null;return{path:String(n?.path||"").trim(),fsPath:ci(n?.fsPath)||"",caption:ci(n?.caption)||"",displayName:ci(n?.displayName)||"",originalFilename:ci(n?.originalFilename)||"",assetId:Sd(n?.assetId)||"",referenceNumber:n?.referenceNumber===void 0||n.referenceNumber===null?"":String(n.referenceNumber),taskId:lm(n?.taskId)||"",timestamp:Gr(n?.timestamp)||""}}).sort((t,n)=>t.path!==n.path?t.path.localeCompare(n.path):t.assetId!==n.assetId?t.assetId.localeCompare(n.assetId):t.timestamp!==n.timestamp?t.timestamp.localeCompare(n.timestamp):JSON.stringify(t).localeCompare(JSON.stringify(n))):[]}function ZS(e,t){const n=Yg(e);return JSON.stringify({id:n.id,title:n.title,description:on(n.description)||"",category:n.category,type:n.type,priority:n.priority===void 0||n.priority===null?"":String(n.priority),complexity:n.complexity===void 0||n.complexity===null?"":String(n.complexity),status:n.status,approach:ci(n.approach)||"",canceledReason:on(n.canceledReason)||"",createdAt:n.createdAt,completedAt:Gr(n.completedAt)||"",taxonomies:GS(n.taxonomies),createdBy:Sd(n.createdBy)||"",assignee:Sd(n.assignee)||"",scheduledDate:on(n.scheduledDate)||"",dueDate:on(n.dueDate)||"",scheduledWeekKey:on(n.scheduledWeekKey)||"",orderInDay:n.orderInDay===void 0||n.orderInDay===null?"":String(n.orderInDay),workstreamId:lm(n.workstreamId)||"",referenceNumber:n.referenceNumber===void 0||n.referenceNumber===null?"":String(n.referenceNumber),comments:qS(n.comments),attachments:KS(n.attachments),checklistItems:VS(n.checklistItems),isArchived:t?"1":"0"})}function YS(...e){return e.reduce((t,n)=>{const s=Gr(n)||"";return t?s&&s>t?s:t:s},"")}function JS(e){const t=e||{};return YS(t.createdAt,t.updatedAt,t.lastActiveAt,t.archivedAt,t.rosterStateUpdatedAt)}function QS(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:tl(t.avatarUrl)||"",avatarSourceUrl:tl(t.avatarSourceUrl)||"",avatarRevision:Number.isFinite(Number(t.avatarRevision))?Math.max(0,Math.floor(Number(t.avatarRevision))):0,avatarUpdatedAt:Gr(t.avatarUpdatedAt)||"",description:on(t.description)||"",role:on(t.role)||"",provider:on(t.provider)||"",model:on(t.model)||"",surfaceType:on(t.surfaceType)||"",seatScope:on(t.seatScope)||"",providerMetadata:t.providerMetadata&&typeof t.providerMetadata=="object"&&!Array.isArray(t.providerMetadata)?t.providerMetadata:null,archivedAt:Gr(t.archivedAt)||"",archivedBy:Sd(t.archivedBy)||"",archivedReason:on(t.archivedReason)||"",mergedIntoProfileId:Sd(t.mergedIntoProfileId)||"",rosterStateUpdatedAt:Gr(t.rosterStateUpdatedAt)||"",createdAt:Gr(t.createdAt)||"",updatedAt:Gr(t.updatedAt)||"",lastActiveAt:Gr(t.lastActiveAt)||""})}const Cs={kind:"task",getId:e=>String(e?.id||"").trim(),getWatermark:e=>String(e?.updatedAt||e?.createdAt||"").trim(),getChangeKey:e=>ZS(e,!!e?.isArchived)},md={kind:"ai-profile",getId:e=>String(e?.id||"").trim(),getWatermark:e=>JS(e),getChangeKey:e=>QS(e)};function uh(e,t,n){const s=e.getId(t);if(!s)return!1;const o=e.getChangeKey(t),l=n?.watermarks;if(!l||l.size===0||!l.has(s))return!0;const d=n?.changeKeys?.get(s);return typeof d=="string"?d!==o:(l.get(s)||"")!==o}function mh(e){return Yg(e)}function ph(e,t){const n=e??t;return new Set(Array.from(n).map(s=>String(s||"").trim()).filter(s=>s.length>0))}function XS(e){return[...e].sort((t,n)=>{const s=String(t?.createdAt||"").trim(),o=String(n?.createdAt||"").trim(),l=s.localeCompare(o);return l!==0?l:String(t?.id||"").trim().localeCompare(String(n?.id||"").trim())})}function fh(e){return[...e].sort((t,n)=>{const s=String(t?.id||"").trim(),o=String(n?.id||"").trim();return s.localeCompare(o)})}function dm(e){return Array.isArray(e)?e:void 0}function ew(e){const t=new Date().toISOString(),n=new Set(Array.from(e.pendingDeletedTaskIds).map(c=>String(c||"").trim()).filter(c=>c.length>0)),s=new Map(Array.from(e.pendingDeletedTaskWatermarks||new Map).map(([c,J])=>[String(c||"").trim(),String(J||"").trim()]).filter(([c,J])=>c.length>0&&Number.isFinite(Date.parse(J)))),o=e.lastPushedWatermarks,l=e.lastPushedTaskChangeKeys,i=(c,J)=>(c?.referenceNumber===void 0||c?.referenceNumber===null)&&Number.isFinite(Number(c?.localReferenceNumber))?!0:uh(Cs,{...c,isArchived:J},{watermarks:o,changeKeys:l}),d=fh(e.tasks||[]),m=fh(e.archivedTasks||[]),y=new Map,k=new Map,S=new Map,h=new Map,g=d.filter(c=>!n.has(String(c?.id||"").trim())&&i(c,!1)).map(c=>{const J=String(c?.id||"").trim(),we=Cs.getWatermark(c),xe=Cs.getChangeKey({...c,isArchived:!1});return J&&(S.set(J,we),h.set(J,xe)),{op:"upsert",archived:!1,task:mh(c)}}),v=m.filter(c=>!n.has(String(c?.id||"").trim())&&i(c,!0)).map(c=>{const J=String(c?.id||"").trim(),we=Cs.getWatermark(c),xe=Cs.getChangeKey({...c,isArchived:!0});return J&&(S.set(J,we),h.set(J,xe)),{op:"upsert",archived:!0,task:mh(c)}}),_=new Set;for(const c of e.tasks||[]){const J=String(c?.id||"").trim();J&&(_.add(J),y.set(J,Cs.getWatermark(c)),k.set(J,Cs.getChangeKey({...c,isArchived:!1})))}for(const c of e.archivedTasks||[]){const J=String(c?.id||"").trim();J&&(_.add(J),y.set(J,Cs.getWatermark(c)),k.set(J,Cs.getChangeKey({...c,isArchived:!0})))}const I=Array.from(e.lastPushedTaskIds).filter(c=>!_.has(c)).map(c=>({op:"delete",taskId:c,deletedAt:s.get(c)||t})),C=Array.from(n).map(c=>({op:"delete",taskId:c,deletedAt:s.get(c)||t})),D=new Set([...I.map(c=>String(c.taskId)),...C.map(c=>String(c.taskId))]),q=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),B=new Map((Array.isArray(e.initiatives)?e.initiatives:[]).map(c=>[String(c?.id||"").trim(),String(c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),X=e.lastPushedInitiativeWatermarks,me=!X||X.size===0,ke=(Array.isArray(e.initiatives)?e.initiatives:[]).map(c=>({op:"initiative-upsert",initiative:{id:String(c?.id||"").trim(),referenceNumber:Number.isFinite(Number(c?.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,referenceLabel:typeof c?.referenceLabel=="string"&&c.referenceLabel.trim().length>0?c.referenceLabel.trim():void 0,title:String(c?.title||"").trim(),description:typeof c?.description=="string"?c.description:null,ownerId:typeof c?.ownerId=="string"&&c.ownerId.trim().length>0?c.ownerId.trim():null,createdAt:String(c?.createdAt||"").trim(),updatedAt:String(c?.updatedAt||c?.createdAt||"").trim(),order:Number.isFinite(Number(c?.order))?Math.floor(Number(c.order)):null,attachments:dm(c?.attachments),isArchived:!!c?.isArchived}})).filter(c=>c.initiative.id.length>0).filter(c=>me?!0:X.get(c.initiative.id)!==c.initiative.updatedAt),le=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),O=new Map((Array.isArray(e.workstreams)?e.workstreams:[]).map(c=>[String(c?.id||"").trim(),String(c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),A=e.lastPushedWorkstreamWatermarks,de=!A||A.size===0,ge=(Array.isArray(e.workstreams)?e.workstreams:[]).map(c=>({op:"workstream-upsert",workstream:{id:String(c?.id||"").trim(),referenceNumber:Number.isFinite(Number(c?.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,referenceLabel:typeof c?.referenceLabel=="string"&&c.referenceLabel.trim().length>0?c.referenceLabel.trim():void 0,initiativeId:typeof c?.initiativeId=="string"&&c.initiativeId.trim().length>0?c.initiativeId.trim():null,title:String(c?.title||"").trim(),description:typeof c?.description=="string"?c.description:null,ownerId:typeof c?.ownerId=="string"&&c.ownerId.trim().length>0?c.ownerId.trim():null,createdAt:String(c?.createdAt||"").trim(),updatedAt:String(c?.updatedAt||c?.createdAt||"").trim(),order:Number.isFinite(Number(c?.order))?Math.floor(Number(c.order)):null,attachments:dm(c?.attachments),isArchived:!!c?.isArchived}})).filter(c=>c.workstream.id.length>0).filter(c=>de?!0:A.get(c.workstream.id)!==c.workstream.updatedAt),Y=new Set((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),P=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>[String(c?.id||"").trim(),md.getWatermark(c)]).filter(([c])=>c.length>0)),H=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>[String(c?.id||"").trim(),md.getChangeKey(c)]).filter(([c])=>c.length>0)),ue=e.lastPushedAiProfileWatermarks,ye=e.lastPushedAiProfileChangeKeys,V=!ue||ue.size===0,Me=(Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>({op:"ai-profile-upsert",profile:{id:String(c.id||"").trim(),workspaceId:String(c.workspaceId||"").trim(),profileToken:String(c.profileToken||"").trim(),name:String(c.name||"").trim(),username:String(c.username||"").trim(),icon:String(c.icon||"Bot").trim()||"Bot",color:String(c.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:tl(c.avatarUrl),avatarSourceUrl:tl(c.avatarSourceUrl),avatarRevision:Number.isFinite(Number(c.avatarRevision))?Math.max(0,Math.floor(Number(c.avatarRevision))):0,avatarUpdatedAt:typeof c.avatarUpdatedAt=="string"&&c.avatarUpdatedAt.trim().length>0?c.avatarUpdatedAt.trim():null,description:typeof c.description=="string"&&c.description.trim()||null,role:typeof c.role=="string"&&c.role.trim()||null,provider:typeof c.provider=="string"&&c.provider.trim()||null,model:typeof c.model=="string"&&c.model.trim()||null,surfaceType:Kg(c.surfaceType),seatScope:Zg(c.seatScope),providerMetadata:c.providerMetadata&&typeof c.providerMetadata=="object"&&!Array.isArray(c.providerMetadata)?c.providerMetadata:null,archivedAt:typeof c.archivedAt=="string"&&c.archivedAt.trim().length>0?c.archivedAt.trim():null,archivedBy:typeof c.archivedBy=="string"&&c.archivedBy.trim().length>0?c.archivedBy.trim():null,archivedReason:typeof c.archivedReason=="string"&&c.archivedReason.trim()||null,mergedIntoProfileId:typeof c.mergedIntoProfileId=="string"&&c.mergedIntoProfileId.trim().length>0?c.mergedIntoProfileId.trim():null,rosterStateUpdatedAt:typeof c.rosterStateUpdatedAt=="string"&&c.rosterStateUpdatedAt.trim().length>0?c.rosterStateUpdatedAt.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),lastActiveAt:typeof c.lastActiveAt=="string"&&c.lastActiveAt.trim().length>0?c.lastActiveAt.trim():null}})).filter(c=>c.profile.id.length>0&&c.profile.workspaceId.length>0).filter(c=>V?!0:uh(md,c.profile,{watermarks:ue,changeKeys:ye})),_e=ph(e.currentDocumentPaths,(Array.isArray(e.documents)?e.documents:[]).map(c=>String(c?.path||"").trim())),re=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!_e.has(c))),oe=new Map((Array.isArray(e.documents)?e.documents:[]).map(c=>[String(c?.path||"").trim(),String(c?.updatedAt||"").trim()]).filter(([c])=>c.length>0)),Ie=e.lastPushedDocumentWatermarks,Ee=!Ie||Ie.size===0,je=(Array.isArray(e.documents)?e.documents:[]).map(c=>({op:"document-upsert",path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),content:typeof c.content=="string"?c.content:"",assetId:typeof c.assetId=="string"&&c.assetId.trim().length>0?c.assetId.trim():void 0,documentId:typeof c.documentId=="string"&&c.documentId.trim().length>0?c.documentId.trim():null,referenceNumber:Number.isFinite(Number(c.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,version:Number.isFinite(Number(c.version))?Math.max(1,Math.floor(Number(c.version))):null,taskId:typeof c.taskId=="string"&&c.taskId.trim().length>0?c.taskId.trim():null,linkTargetType:c.linkTargetType==="initiative"||c.linkTargetType==="workstream"||c.linkTargetType==="task"?c.linkTargetType:null,linkTargetId:typeof c.linkTargetId=="string"&&c.linkTargetId.trim().length>0?c.linkTargetId.trim():null,logicalName:typeof c.logicalName=="string"&&c.logicalName.trim().length>0?c.logicalName.trim():null,caption:typeof c.caption=="string"&&c.caption.trim().length>0?c.caption.trim():null,originalFilename:typeof c.originalFilename=="string"&&c.originalFilename.trim().length>0?c.originalFilename.trim():null,linkRole:c.linkRole==="reference"?"reference":"attachment"})).filter(c=>c.path.length>0).filter(c=>Ee?!0:Ie.get(c.path)!==c.updatedAt),Pe=ph(e.currentAssetPaths,(Array.isArray(e.assets)?e.assets:[]).map(c=>String(c?.path||"").trim())),K=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!Pe.has(c))),x=new Map((Array.isArray(e.assets)?e.assets:[]).map(c=>[String(c?.path||"").trim(),String(c?.updatedAt||"").trim()]).filter(([c])=>c.length>0)),b=e.lastPushedAssetWatermarks,R=!b||b.size===0,F=(Array.isArray(e.assets)?e.assets:[]).map(c=>({op:"asset-upsert",path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),contentBase64:typeof c.contentBase64=="string"?c.contentBase64:"",assetId:typeof c.assetId=="string"&&c.assetId.trim().length>0?c.assetId.trim():void 0,kind:c.kind==="image"?"image":"file",mimeType:typeof c.mimeType=="string"&&c.mimeType.trim().length>0?c.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(c.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,taskId:typeof c.taskId=="string"&&c.taskId.trim().length>0?c.taskId.trim():null,linkTargetType:c.linkTargetType==="initiative"||c.linkTargetType==="workstream"||c.linkTargetType==="task"?c.linkTargetType:null,linkTargetId:typeof c.linkTargetId=="string"&&c.linkTargetId.trim().length>0?c.linkTargetId.trim():null,logicalName:typeof c.logicalName=="string"&&c.logicalName.trim().length>0?c.logicalName.trim():null,caption:typeof c.caption=="string"&&c.caption.trim().length>0?c.caption.trim():null,originalFilename:typeof c.originalFilename=="string"&&c.originalFilename.trim().length>0?c.originalFilename.trim():null,linkRole:c.linkRole==="reference"?"reference":c.linkRole==="image"?"image":"attachment"})).filter(c=>c.path.length>0&&c.contentBase64.length>0).filter(c=>R?!0:b.get(c.path)!==c.updatedAt),Q=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],M=new Set(Q.map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),$=new Set(Q.filter(c=>String(c?.deletedAt||"").trim().length===0).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),be=e.lastPushedDocumentReviewSessionIds||new Set,U=new Map(Q.map(c=>[String(c?.id||"").trim(),String(c?.deletedAt||c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),se=e.lastPushedDocumentReviewSessionWatermarks,pe=!se||se.size===0,z=Q.map(c=>({op:"document-review-session-upsert",session:{id:String(c.id||"").trim(),assetId:String(c.assetId||"").trim(),documentId:typeof c.documentId=="string"&&c.documentId.trim().length>0?c.documentId.trim():null,documentVersion:Number.isFinite(Number(c.documentVersion))?Math.max(1,Math.floor(Number(c.documentVersion))):null,title:typeof c.title=="string"&&c.title.trim().length>0?c.title.trim():null,status:c.status==="resolved"?"resolved":"open",comments:[],createdByActorId:typeof c.createdByActorId=="string"&&c.createdByActorId.trim().length>0?c.createdByActorId.trim():null,updatedByActorId:typeof c.updatedByActorId=="string"&&c.updatedByActorId.trim().length>0?c.updatedByActorId.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:typeof c.deletedAt=="string"&&c.deletedAt.trim().length>0?c.deletedAt.trim():null}})).filter(c=>c.session.id.length>0&&c.session.assetId.length>0&&!c.session.deletedAt).filter(c=>pe?!0:se.get(c.session.id)!==c.session.updatedAt),ne=Q.filter(c=>String(c?.deletedAt||"").trim().length>0).map(c=>({sessionId:String(c?.id||"").trim(),deletedAt:String(c?.deletedAt||c?.updatedAt||c?.createdAt||t).trim()||t})).filter(c=>c.sessionId.length>0).filter(c=>pe?!0:se.get(c.sessionId)!==c.deletedAt),ie=Array.from(be).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!M.has(c)),Re=[...ie.map(c=>({sessionId:c,deletedAt:t})),...ne],Te=new Set([...ie,...ne.map(c=>c.sessionId)]),De=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],Oe=new Set(De.map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),vt=new Set(De.filter(c=>String(c?.deletedAt||"").trim().length===0).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),st=e.lastPushedDocumentReviewCommentIds||new Set,kt=new Map(De.map(c=>[String(c?.id||"").trim(),String(c?.deletedAt||c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),Ye=e.lastPushedDocumentReviewCommentWatermarks,Ct=!Ye||Ye.size===0,dt=De.map(c=>({op:"document-review-comment-upsert",comment:{id:String(c.id||"").trim(),sessionId:String(c.sessionId||"").trim(),body:String(c.body||"").trim(),anchor:c.anchor??null,order:Number.isFinite(Number(c.order))?Math.max(0,Math.floor(Number(c.order))):0,authorActorId:typeof c.authorActorId=="string"&&c.authorActorId.trim().length>0?c.authorActorId.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:typeof c.deletedAt=="string"&&c.deletedAt.trim().length>0?c.deletedAt.trim():null}})).filter(c=>c.comment.id.length>0&&c.comment.sessionId.length>0&&!c.comment.deletedAt).filter(c=>Ct?!0:Ye.get(c.comment.id)!==c.comment.updatedAt),Qe=De.filter(c=>String(c?.deletedAt||"").trim().length>0).map(c=>({commentId:String(c?.id||"").trim(),deletedAt:String(c?.deletedAt||c?.updatedAt||c?.createdAt||t).trim()||t})).filter(c=>c.commentId.length>0).filter(c=>Ct?!0:Ye.get(c.commentId)!==c.deletedAt),Rt=Array.from(st).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!Oe.has(c)),ee=[...Rt.map(c=>({commentId:c,deletedAt:t})),...Qe],ze=new Set([...Rt,...Qe.map(c=>c.commentId)]),ft=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],it=new Set(ft.map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),Et=new Set(ft.filter(c=>String(c?.deletedAt||"").trim().length===0).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),ht=e.lastPushedAnnotatedAttachmentSessionIds||new Set,Ot=new Map(ft.map(c=>[String(c?.id||"").trim(),String(c?.deletedAt||c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),Dt=e.lastPushedAnnotatedAttachmentSessionWatermarks,We=!Dt||Dt.size===0,tt=ft.map(c=>({op:"annotated-attachment-session-upsert",session:{id:String(c.id||"").trim(),workspaceId:String(c.workspaceId||"").trim(),taskId:String(c.taskId||"").trim(),baseImageAssetId:String(c.baseImageAssetId||"").trim(),title:typeof c.title=="string"&&c.title.trim().length>0?c.title.trim():null,globalInstruction:typeof c.globalInstruction=="string"&&c.globalInstruction.trim().length>0?c.globalInstruction.trim():null,annotations:Array.isArray(c.annotations)?c.annotations:[],createdByActorId:typeof c.createdByActorId=="string"&&c.createdByActorId.trim().length>0?c.createdByActorId.trim():null,updatedByActorId:typeof c.updatedByActorId=="string"&&c.updatedByActorId.trim().length>0?c.updatedByActorId.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:typeof c.deletedAt=="string"&&c.deletedAt.trim().length>0?c.deletedAt.trim():null}})).filter(c=>c.session.id.length>0&&c.session.workspaceId.length>0&&c.session.baseImageAssetId.length>0&&!c.session.deletedAt).filter(c=>We?!0:Dt.get(c.session.id)!==c.session.updatedAt),Fe=ft.filter(c=>String(c?.deletedAt||"").trim().length>0).map(c=>({sessionId:String(c?.id||"").trim(),deletedAt:String(c?.deletedAt||c?.updatedAt||c?.createdAt||t).trim()||t})).filter(c=>c.sessionId.length>0).filter(c=>We?!0:Dt.get(c.sessionId)!==c.deletedAt),Ze=Array.from(ht).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!it.has(c)),St=[...Ze.map(c=>({sessionId:c,deletedAt:t})),...Fe],ot=new Set([...Ze,...Fe.map(c=>c.sessionId)]),te=XS(Array.isArray(e.taskEvents)?e.taskEvents:[]),Le=new Map(te.map(c=>[String(c?.id||"").trim(),String(c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),At=e.lastPushedTaskEventWatermarks,jt=!At||At.size===0,Wt=te.map(c=>{const J=c.entityType==="initiative"||c.entityType==="workstream"?c.entityType:"task",we=String(c.entityId||c.taskId||"").trim(),xe={id:String(c.id||"").trim(),workspaceId:String(c.workspaceId||"").trim(),entityType:J,entityId:we,taskId:J==="task"?String(c.taskId||we).trim():void 0,action:String(c.action||"").trim(),actor:String(c.actor||"system").trim()||"system",actorType:c.actorType==="ai"||c.actorType==="human"||c.actorType==="system"?c.actorType:"system",details:c.details&&typeof c.details=="object"&&!Array.isArray(c.details)?c.details:{},createdAt:String(c.createdAt||"").trim()};return J==="task"?{op:"task-event-upsert",event:{...xe,entityType:"task",taskId:String(xe.taskId||we).trim()}}:{op:"entity-event-upsert",event:{...xe,entityType:J,taskId:void 0}}}).filter(c=>c.event.id.length>0&&c.event.entityId.length>0&&c.event.workspaceId.length>0&&c.event.action.length>0&&Number.isFinite(Date.parse(c.event.createdAt))).filter(c=>jt?!0:At.get(c.event.id)!==c.event.createdAt),Ge=[...ke,...ge,...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}]:[],...Me,...je,...Array.from(re).map(c=>({op:"document-delete",path:c,deletedAt:t})),...F,...Array.from(K).map(c=>({op:"asset-delete",path:c,deletedAt:t})),...z,...Re.map(c=>({op:"document-review-session-delete",sessionId:c.sessionId,deletedAt:c.deletedAt})),...dt,...ee.map(c=>({op:"document-review-comment-delete",commentId:c.commentId,deletedAt:c.deletedAt})),...tt,...St.map(c=>({op:"annotated-attachment-session-delete",sessionId:c.sessionId,deletedAt:c.deletedAt})),...Wt,...g,...v,...Array.from(D).map(c=>({op:"delete",taskId:c,deletedAt:s.get(c)||t}))],$t=e.baselineResetReason??null,yt=c=>{const J=c.upsertCount+(c.deleteCount||0);if(c.currentCount===0&&J===0)return{mode:"none",reason:null,currentCount:0,baselineCount:c.baselineCount,changeCount:J};if(c.alwaysFull)return{mode:J>0?"send-all":"none",reason:J>0?"full-state-domain":null,currentCount:c.currentCount,baselineCount:c.baselineCount,changeCount:J};const we=c.baselineCount===0&&c.currentCount>0&&c.upsertCount>=c.currentCount;return{mode:we?"send-all":"delta",reason:we?$t||"missing-baseline":null,currentCount:c.currentCount,baselineCount:c.baselineCount,changeCount:J}},E=Ge.reduce((c,J)=>{const we=String(J.op||"").trim();return c[we]=(c[we]||0)+1,c},{});return{changes:Ge,currentTaskIds:new Set(Array.from(_).filter(c=>!n.has(c))),currentTaskWatermarks:new Map(Array.from(y.entries()).filter(([c])=>!n.has(c))),currentTaskChangeKeys:new Map(Array.from(k.entries()).filter(([c])=>!n.has(c))),deleteTaskIds:D,currentInitiativeIds:q,currentInitiativeWatermarks:B,currentWorkstreamIds:le,currentWorkstreamWatermarks:O,currentAiProfileIds:Y,currentAiProfileWatermarks:P,currentAiProfileChangeKeys:H,currentDocumentPaths:_e,deleteDocumentPaths:re,currentDocumentWatermarks:oe,currentAssetPaths:Pe,deleteAssetPaths:K,currentAssetWatermarks:x,currentDocumentReviewSessionIds:$,deleteDocumentReviewSessionIds:Te,currentDocumentReviewSessionWatermarks:U,currentDocumentReviewCommentIds:vt,deleteDocumentReviewCommentIds:ze,currentDocumentReviewCommentWatermarks:kt,currentAnnotatedAttachmentSessionIds:Et,deleteAnnotatedAttachmentSessionIds:ot,currentAnnotatedAttachmentSessionWatermarks:Ot,currentTaskEventWatermarks:Le,pushedWatermarks:S,pushedTaskChangeKeys:h,deltaDiagnostics:{totalChanges:Ge.length,byOp:E,baselineResetReason:$t,domains:{tasks:yt({currentCount:_.size,baselineCount:o?.size||0,upsertCount:g.length+v.length,deleteCount:D.size}),initiatives:yt({currentCount:q.size,baselineCount:X?.size||0,upsertCount:ke.length}),workstreams:yt({currentCount:le.size,baselineCount:A?.size||0,upsertCount:ge.length}),aiProfiles:yt({currentCount:Y.size,baselineCount:ue?.size||0,upsertCount:Me.length}),documents:yt({currentCount:_e.size,baselineCount:Ie?.size||0,upsertCount:je.length,deleteCount:re.size}),assets:yt({currentCount:Pe.size,baselineCount:b?.size||0,upsertCount:F.length,deleteCount:K.size}),documentReviewSessions:yt({currentCount:$.size,baselineCount:se?.size||0,upsertCount:z.length,deleteCount:Te.size}),documentReviewComments:yt({currentCount:vt.size,baselineCount:Ye?.size||0,upsertCount:dt.length,deleteCount:ze.size}),annotatedAttachmentSessions:yt({currentCount:Et.size,baselineCount:Dt?.size||0,upsertCount:tt.length,deleteCount:ot.size}),taskEvents:yt({currentCount:Le.size,baselineCount:At?.size||0,upsertCount:Wt.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 tw(e){const t=(e.tasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),n=(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:dm(i.attachments)||[],isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)),l=(e.workstreams||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),initiativeId:typeof i.initiativeId=="string"?i.initiativeId.trim():"",title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",attachments:dm(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:l,taxonomyState:e.taxonomyState&&typeof e.taxonomyState=="object"?e.taxonomyState:null,taxonomies:Array.isArray(e.taxonomies)?e.taxonomies:[],aiProfiles:Array.isArray(e.aiProfiles)?e.aiProfiles.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),name:String(i.name||"").trim(),username:String(i.username||"").trim(),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:n,pendingDeletes:s})}function Yu(){return{version:2,enabled:!1,phase:"idle",setupIntent:null,startupFullReconcileCompletedAt:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null,pushBaseline:null}}function eo(e){const t=String(e||"").trim();return t.length>0?t:null}function hh(e){return String(e||"").trim().toLowerCase()==="attach-cloud-import"?"attach-cloud-import":null}function aw(e){if(!Array.isArray(e)||e.length<2)return null;const t=String(e[0]||"").trim(),n=String(e[1]||"").trim();return!t||!n?null:[t,n]}function nw(e){return Array.isArray(e)?e.map(t=>String(t||"").trim()).filter(t=>t.length>0):[]}function gh(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=s=>Array.isArray(t[s])?t[s].map(o=>aw(o)).filter(o=>Array.isArray(o)):[];return{taskIds:nw(t.taskIds),taskWatermarks:n("taskWatermarks"),taskChangeKeys:n("taskChangeKeys"),initiativeWatermarks:n("initiativeWatermarks"),workstreamWatermarks:n("workstreamWatermarks"),aiProfileWatermarks:n("aiProfileWatermarks"),aiProfileChangeKeys:n("aiProfileChangeKeys"),documentWatermarks:n("documentWatermarks"),assetWatermarks:n("assetWatermarks"),documentReviewSessionWatermarks:n("documentReviewSessionWatermarks"),documentReviewCommentWatermarks:n("documentReviewCommentWatermarks"),annotatedAttachmentSessionWatermarks:n("annotatedAttachmentSessionWatermarks"),taskEventWatermarks:n("taskEventWatermarks"),taxonomyStateFingerprint:String(t.taxonomyStateFingerprint||"").trim()}}function rw(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 l=String(e.sourceOfTruth||"").trim().toLowerCase();return e.onboardingCompleted?"active":l==="cloud"?t.lastPullAt?"active":"attach-cloud":l==="local"?t.lastPullAt||t.lastPushAt?"active":"provision-local":(t.lastPullAt||t.lastPushAt,"active")}function sw(e){const t=Yu();if(!e||typeof e!="object")return{state:t,changed:!1};const n=e,s=n.lastErrorMessage,o=typeof s=="string"&&s.trim().length>0?s:null,l={version:2,enabled:!!(n.enabled??n.cloudSyncEnabled),phase:"idle",setupIntent:hh(n.setupIntent),startupFullReconcileCompletedAt:eo(n.startupFullReconcileCompletedAt),pullCursor:eo(n.pullCursor),lastPullAt:eo(n.lastPullAt),lastPushAt:eo(n.lastPushAt),lastSyncedAt:eo(n.lastSyncedAt),lastErrorMessage:o,pushBaseline:gh(n.pushBaseline)};l.phase=rw(n,l),l.enabled||(l.phase="idle",l.pullCursor=null);const d=Number(n.version||0)!==2||!!(n.enabled??n.cloudSyncEnabled)!==l.enabled||String(n.phase||"").trim()!==l.phase||hh(n.setupIntent)!==l.setupIntent||eo(n.startupFullReconcileCompletedAt)!==l.startupFullReconcileCompletedAt||eo(n.pullCursor)!==l.pullCursor||eo(n.lastPullAt)!==l.lastPullAt||eo(n.lastPushAt)!==l.lastPushAt||eo(n.lastSyncedAt)!==l.lastSyncedAt||o!==l.lastErrorMessage||JSON.stringify(gh(n.pushBaseline))!==JSON.stringify(l.pushBaseline);return{state:l,changed:d}}const ow="taskforce.sync.lease.v1",iw="taskforce.sync.lease.v1",cw=2500,lw=9e3;function ed(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function td(e){const t=String(e||"").trim();return t.length>0?t:null}function yp(e){return`${ow}.${e}`}function dw(e){if(!e)return null;try{const t=JSON.parse(e),n=String(t?.ownerId||"").trim(),s=String(t?.workspaceId||"").trim(),o=String(t?.operation||"").trim(),l=String(t?.heartbeatAt||"").trim(),i=String(t?.expiresAt||"").trim();return!n||!s||!l||!i||o!=="pull"&&o!=="push"&&o!=="repair"?null:{ownerId:n,workspaceId:s,operation:o,heartbeatAt:l,expiresAt:i}}catch{return null}}function uw(e,t,n,s){return{ownerId:e,workspaceId:t,operation:n,heartbeatAt:new Date(s).toISOString(),expiresAt:new Date(s+lw).toISOString()}}function mw(e,t=Date.now()){if(!e)return!0;const n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t}function kp(e,t){const n={...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:td(t.startupFullReconcileCompletedAt),pullCursor:t.pullCursor===void 0?e.pullCursor:td(t.pullCursor),lastPullAt:t.lastPullAt===void 0?e.lastPullAt:td(t.lastPullAt),lastPushAt:t.lastPushAt===void 0?e.lastPushAt:td(t.lastPushAt),lastSyncedAt:t.lastSyncedAt===void 0?e.lastSyncedAt:td(t.lastSyncedAt),lastErrorMessage:t.lastErrorMessage===void 0?e.lastErrorMessage:t.lastErrorMessage??null,pushBaseline:t.pushBaseline===void 0?e.pushBaseline??null:t.pushBaseline??null};return n.enabled||(n.phase="idle",n.setupIntent=null,n.pullCursor=null),n}function pw(e){return{...e,pushBaseline:null}}function fw(e){const{currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:n,setWorkspaceSyncPhase:s,setWorkspaceSyncSetupIntent:o,setWorkspaceLastPullAt:l,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(""),C=r.useRef(new Set),D=r.useRef(new Set),q=r.useRef(new Map),B=r.useRef(null),X=r.useRef(Yu()),me=r.useRef(""),ke=r.useRef(null),le=r.useRef(null),O=r.useRef(null),A=r.useRef(null);if(!me.current){const x=Date.now().toString(36),b=Math.random().toString(36).slice(2,10);me.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)},[]),ge=r.useCallback((x,b)=>{if(typeof window>"u")return;const R=Math.max(1,h.current+1);h.current=R;const F=PS(R),Q=Number(b?.minDelayMs),M=Number.isFinite(Q)&&Q>0?Math.max(F,Math.floor(Q)):F,$=Date.now()+M;S.current=$,y(new Date($).toISOString()),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,S.current=null,y(null),x()},M)},[]),Y=r.useCallback(()=>{const x=S.current;return typeof x=="number"&&Number.isFinite(x)&&x>Date.now()},[]),P=r.useCallback(x=>{if(typeof window>"u")return null;const b=String(x||"").trim();return ed(b)?dw(window.localStorage.getItem(yp(b))):null},[]),H=r.useCallback(x=>{const b=String(x||"").trim();if(b)try{A.current?.postMessage({workspaceId:b})}catch{}},[]),ue=r.useCallback((x,b)=>{if(typeof window>"u")return null;const R=String(x||"").trim();if(!ed(R))return null;const F=uw(me.current,R,b,Date.now());try{window.localStorage.setItem(yp(R),JSON.stringify(F))}catch{return null}return H(R),F},[H]),ye=r.useCallback(()=>{O.current!==null&&typeof window<"u"&&(window.clearInterval(O.current),O.current=null)},[]),V=r.useCallback((x,b)=>{if(typeof window>"u")return;const R=String(x||ke.current||"").trim();if(!R)return;const F=P(R),Q=F?.ownerId===me.current;if(!(!b?.force&&F&&!Q)){ye();try{window.localStorage.removeItem(yp(R))}catch{}ke.current=null,le.current=null,H(R)}},[H,P,ye]),Me=r.useCallback((x,b)=>{typeof window>"u"||(ye(),O.current=window.setInterval(()=>{const R=String(ke.current||"").trim(),F=le.current;if(!R||!F){ye();return}if(P(R)?.ownerId!==me.current){ye(),ke.current=null,le.current=null;return}ue(R,F)},cw),ke.current=x,le.current=b)},[P,ye,ue]),_e=r.useCallback(async(x,b)=>{if(typeof window>"u")return!0;const R=String(x||"").trim();if(!ed(R))return!1;const F=P(R);if(F?.ownerId===me.current)return ue(R,b)?(Me(R,b),!0):!1;if(F&&!mw(F)||!ue(R,b))return!1;const $=P(R);return!$||$.ownerId!==me.current?!1:(Me(R,b),!0)},[P,Me,ue]),re=r.useCallback(x=>{V(x,{force:!0})},[V]),oe=r.useCallback(x=>{const b=X.current,R=kp(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});X.current=R,B.current=R.pullCursor,n(R.enabled),s(R.phase),o(R.setupIntent??null),l(R.lastPullAt),i(R.lastPushAt),d(R.lastErrorMessage??null)},[n,s,o,l,i,d]),Ie=r.useCallback(x=>{const b=kp(X.current,x);return oe(b),b},[oe]),Ee=r.useCallback(()=>X.current,[]),je=r.useCallback(async x=>{const b=kp(X.current,x);X.current=b,B.current=b.pullCursor;const R=await pf({workspaceId:t,stateKey:"workspace-sync",patch:pw(b),throwOnError:!0,respectFailureCooldown:!1}),F=R.response,Q=R.payload;if(R.skipped)return oe(b),b;if(!F)throw new Error("Failed to persist workspace sync state (missing response)");if(!F.ok||Q?.success===!1)throw new Error(Q?.error||`Failed to persist workspace sync state (${F.status})`);return oe(b),b},[oe,t]),Pe=r.useCallback(async()=>{if(!ed(t)){const x=Yu();X.current=x,oe(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=sw(b?.state&&typeof b.state=="object"?b.state:null);X.current=R.state,oe(R.state),R.changed&&je(R.state)}catch{}},[oe,t,je]),K=r.useCallback(async(x,b)=>{if(!ed(t))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!x.enabled)return await je({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 je({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,je]);return r.useEffect(()=>{_.current="",I.current="",C.current=new Set,D.current=new Set,q.current=new Map,B.current=null,X.current=Yu(),g.current=!1,v.current=!1,V(),de()},[de,t,V]),r.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const x=new BroadcastChannel(iw);return A.current=x,()=>{x.close(),A.current===x&&(A.current=null)}},[]),r.useEffect(()=>()=>{k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),V()},[V]),{workspaceRetryAt:m,isWorkspaceRetryPending:Y,workspacePushInFlightRef:g,workspacePullInFlightRef:v,workspaceLastPushedSignatureRef:_,workspacePendingSignatureRef:I,workspaceLastPushedTaskIdsRef:C,workspaceDeletedTaskIdsRef:D,workspaceDeletedTaskWatermarksRef:q,workspacePullCursorRef:B,clearWorkspaceRetry:de,scheduleWorkspaceRetry:ge,persistWorkspaceSyncPatch:je,applyWorkspaceSyncPatchLocally:Ie,readWorkspaceSyncStateSnapshot:Ee,loadWorkspaceSyncState:Pe,applyWorkspaceSyncStateSnapshot:oe,saveWorkspaceCloudSyncSettings:K,acquireWorkspaceSyncLease:_e,releaseWorkspaceSyncLease:V,forceClearWorkspaceSyncLease:re,readWorkspaceSyncLease:P}}class hw{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 n=typeof t.eventId=="string"?t.eventId.trim():"";if(n&&this.seenEventIds.has(n))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 n?(this.rememberEventId(n),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,n&&this.rememberEventId(n),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=s,this.lastSeq=i,n&&this.rememberEventId(n),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,n&&this.rememberEventId(n),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 n=this.seenEventIdQueue.shift();n&&this.seenEventIds.delete(n)}}}function Jg(e){const{enabled:t,workspaceId:n,websocketUrl:s,reconnectBaseMs:o=400,reconnectMaxMs:l=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(""),C=r.useRef(!1),D=r.useRef(null),q=r.useRef(null),B=r.useRef(new hw),X=r.useRef(m),me=r.useRef(y);r.useEffect(()=>{X.current=m},[m]),r.useEffect(()=>{me.current=y},[y]);const[ke,le]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),O=r.useMemo(()=>String(n||"").trim(),[n]),A=r.useMemo(()=>String(s||"").trim(),[s]);return r.useEffect(()=>{let de=!1;const ge=()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},Y=()=>{const oe=g.current;if(g.current=null,oe)try{oe.close()}catch{}},P=oe=>oe==="taskforce:replay-gap"||oe==="taskforce:replay-reset"?4:oe==="taskforce:mutation"||oe==="taskforce:replay"?3:1,H=oe=>{const Ie=q.current;if(Ie){const Ee=P(Ie.type),je=P(oe.type);if(je<Ee||je===Ee&&Ie.eventId&&!oe.eventId)return}q.current=oe,D.current!==null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{D.current=null;const Ee=X.current;if(!q.current||typeof Ee!="function")return;const je=q.current;q.current=null,Ee(je)},80)},ue=oe=>{try{const Ie=JSON.parse(String(oe.data||""));return!Ie||typeof Ie!="object"?null:Ie}catch{return null}},ye=oe=>{const Ie=typeof oe.serverEpoch=="string"?oe.serverEpoch.trim():"",Ee=Number(oe.seq);!Ie||!Number.isFinite(Ee)||Ee<0||(I.current=`${Ie}:${Math.floor(Ee)}`,C.current=!1)},V=()=>{const oe=B.current.getTelemetry();le(oe);const Ie=me.current;typeof Ie=="function"&&Ie(oe)},Me=oe=>{const Ie={type:"taskforce:replay",workspaceId:O,limit:d},Ee=I.current;Ee&&(Ie.cursor=Ee),oe.send(JSON.stringify(Ie))},_e=()=>{if(!t||de)return;ge(),_.current+=1;const oe=_.current,Ie=Math.max(50,Math.floor(o)),Ee=Math.max(Ie,Math.floor(l)),je=Math.min(Ee,Ie*Math.pow(2,Math.max(0,oe-1)));h(oe>=i?"degraded-fallback":"reconnecting"),v.current=window.setTimeout(()=>{de||(v.current=null,re())},je)},re=()=>{if(!t||de||!O||!A)return;Y();let oe;try{oe=new WebSocket(A)}catch{_e();return}g.current=oe,oe.addEventListener("open",()=>{_.current=0,h("connected"),oe.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:O,userId:k||void 0})),Me(oe)}),oe.addEventListener("message",Ie=>{const Ee=ue(Ie);if(!Ee||typeof Ee.type!="string")return;const je=typeof Ee.workspaceId=="string"?Ee.workspaceId.trim():O;if(!(!je||je!==O)){if(Ee.type==="taskforce:update"){H({type:"taskforce:update",workspaceId:O,eventId:typeof Ee.eventId=="string"?Ee.eventId.trim():void 0});return}if(Ee.type==="taskforce:mutation"){const Pe=B.current.process({eventId:Ee.eventId,serverEpoch:Ee.serverEpoch,seq:Ee.seq});if(!Pe.accepted){V(),Pe.shouldRecover&&(I.current="",C.current||(C.current=!0,H({type:"taskforce:replay-gap",workspaceId:O})));return}ye(Ee),V(),H({type:Ee.type,workspaceId:O,eventId:typeof Ee.eventId=="string"?Ee.eventId.trim():void 0});return}if(Ee.type==="taskforce:replay"){const Pe=Array.isArray(Ee.events)?Ee.events:[];let K=0;for(const x of Pe)B.current.process({eventId:x.eventId,serverEpoch:x.serverEpoch,seq:x.seq}).accepted&&(K+=1,ye(x));C.current=!1,V(),(K>0||Ee.truncated===!0)&&H({type:"taskforce:replay",workspaceId:O}),Ee.truncated===!0&&Me(oe);return}if(Ee.type==="taskforce:replay-gap"||Ee.type==="taskforce:replay-reset"){if(I.current="",C.current)return;C.current=!0,H({type:Ee.type,workspaceId:O})}}}),oe.addEventListener("close",Ie=>{if(g.current===oe&&(g.current=null),!de&&t){const Ee=Number(Ie?.code||0),je=String(Ie?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${O} user=${String(k||"anonymous").trim()||"anonymous"} code=${Ee}${je?` reason=${je}`:""}`)}_e()}),oe.addEventListener("error",()=>{try{oe.close()}catch{}})};return!t||!O||!A?(h("degraded-fallback"),ge(),Y(),()=>{ge(),Y()}):(h("reconnecting"),re(),()=>{de=!0,ge(),D.current!==null&&(window.clearTimeout(D.current),D.current=null),q.current=null,Y()})},[t,O,A,o,l,i,d,k]),{connectionState:S,telemetry:ke}}const Up="taskforce:context-assets-mutated";function UO(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Up,{detail:e}))}const zp="taskforce:ai-profiles-mutated";function zO(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(zp,{detail:e}))}const gw=4,Bu=100;function sd(e,t,n){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>=gw)return"[MaxDepth]";if(typeof e=="function"||typeof e=="symbol"||typeof e>"u")return String(e);if(Array.isArray(e))return e.slice(0,Bu).map(s=>sd(s,t+1,n));if(e instanceof Set)return Array.from(e.values()).slice(0,Bu).map(s=>sd(s,t+1,n));if(e instanceof Map){const s={};for(const[o,l]of Array.from(e.entries()).slice(0,Bu))s[String(o)]=sd(l,t+1,n);return s}if(typeof e=="object"){if(n.has(e))return"[Circular]";n.add(e);const s={};for(const[o,l]of Object.entries(e).slice(0,Bu))s[o]=sd(l,t+1,n);return n.delete(e),s}return String(e)}function Im(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return sd(e,0,new WeakSet)}function yw(e){const t=Im(e);if(!t)return"null";try{return JSON.stringify(t)}catch{return"[UnserializableSyncEventDetails]"}}const Qg="taskforce.userGlobalSyncMeta.v1",kw="taskforce.syncDebug.v1",vw=12e4,Xg="taskforce.syncWatermarks.v3",Sw=300*1e3,yh="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function oi(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function ww(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(kw)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Gn(e,t){if(!ww())return;console.info("[Taskforce Sync]",e,t&&typeof t=="object"?t:{})}function bw(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:tl(e?.avatarUrl??e?.avatar_url),avatarSourceUrl:tl(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:Gr(e?.avatarUpdatedAt??e?.avatar_updated_at),description:on(e?.description),role:on(e?.role),provider:on(e?.provider),model:on(e?.model),surfaceType:Kg(e?.surfaceType??e?.surface_type),seatScope:Zg(e?.seatScope??e?.seat_scope),providerMetadata:t&&typeof t=="object"&&!Array.isArray(t)?t:null,archivedAt:Gr(e?.archivedAt??e?.archived_at),archivedBy:lm(e?.archivedBy??e?.archived_by),archivedReason:on(e?.archivedReason??e?.archived_reason),mergedIntoProfileId:lm(e?.mergedIntoProfileId??e?.merged_into_profile_id),rosterStateUpdatedAt:Gr(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:Gr(e?.lastActiveAt??e?.last_active_at)}}function kh(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Qg);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function _w(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Qg,JSON.stringify(e))}catch{}}function Cw(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function Aw(e){return e.flatMap(t=>{const n=String(t?.id||"").trim();return!n||!Array.isArray(t?.comments)?[]:t.comments.map(s=>({id:String(s?.id||"").trim(),sessionId:n,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 Wu(e,t,n=[],s=[]){const o=new Map;for(const l of[...e||[],...t||[]]){const i=Array.isArray(l?.taskEvents)?l.taskEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.taskId||l?.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 l of n||[]){const i=Array.isArray(l?.entityEvents)?l.entityEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.entityId||l?.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 l of s||[]){const i=Array.isArray(l?.entityEvents)?l.entityEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.entityId||l?.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((l,i)=>l.createdAt!==i.createdAt?l.createdAt.localeCompare(i.createdAt):l.id.localeCompare(i.id))}function ey(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 ty(e,t){if(!e||typeof e!="object")return null;const n=typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:"",s=!t||!n||n===t?new Map(Array.isArray(e.taskWatermarks)?e.taskWatermarks:[]):new Map;return{taskIds:new Set(Array.isArray(e.taskIds)?e.taskIds.map(l=>String(l||"").trim()).filter(l=>l.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 vh(e,t){if(typeof window>"u")return null;try{const n=`${Xg}.${e}`,s=window.localStorage.getItem(n);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:ty(o,t)}catch{return null}}function Sh(e,t){if(typeof window>"u")return!1;try{const n=`${Xg}.${e}`;return window.localStorage.setItem(n,JSON.stringify({v:11,savedAt:new Date().toISOString(),...ey(t)})),!0}catch{return!1}}function xw({currentWorkspaceId:e,workspaceSyncPhase:t,clearWorkspaceRetry:n,setWorkspaceSyncBusy:s,setUserGlobalSyncStatus:o,setUserGlobalSyncError:l,setWorkspaceLastErrorMessage:i,setWorkspaceLastErrorAt:d,reportSyncEvent:m,setAuthBlocked:y,setIsAuthenticated:k,checkAuthSession:S,ensureCloudWorkspaceReadyForSync:h,scheduleWorkspaceSyncRetry:g,persistWorkspaceSyncPatchSafely:v}){const _=async(C,D)=>{n(),s(!1),o("error");const q="Session expired. Sign in again to resume cloud sync.";l(q),i(q),d(new Date().toISOString()),m(e,{eventType:C==="handshake"?"handshake":C,status:"error",statusCode:D,errorMessage:q}),y(!0),k(!1),await S()};return{handleSyncAuthFailure:_,ensureWorkspaceSyncReady:async()=>{if(!oi(e)){const q="Workspace sync blocked: local workspace ID is unresolved.";return i(q),d(new Date().toISOString()),l(q),o("error"),!1}const C=await h();if(C.success)return!0;if(C.statusCode===401)return await _("handshake",401),!1;const D=C.error||"Workspace sync handshake failed.";return i(D),d(new Date().toISOString()),l(D),o("error"),m(e,{eventType:"handshake",status:"error",statusCode:C.statusCode,errorMessage:D}),C.transient||Bs(C.statusCode)?g(C.retryAfterMs):(t==="active"||t==="attach-cloud"||t==="provision-local")&&v({phase:"error",lastErrorMessage:D}),!1}}}function Iw({workspaceSyncPhase:e,lastBootstrapPhaseRef:t,bootstrapPhaseStartedAtRef:n,bootstrapLastProgressAtRef:s}){if(e==="attach-cloud"||e==="provision-local"){t.current=e,n.current===null&&(n.current=Date.now()),s.current=null;return}n.current=null,s.current=null}function Tw({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:n,workspacePullInFlightRef:s,workspacePushInFlightRef:o,bootstrapPhaseStartedAtRef:l,bootstrapLastProgressAtRef:i,setWorkspaceLastErrorMessage:d,setWorkspaceLastErrorAt:m,setUserGlobalSyncStatus:y,setUserGlobalSyncError:k,setWorkspaceSyncBusy:S,persistWorkspaceSyncPatchSafely:h}){if(!t||n!=="attach-cloud"&&n!=="provision-local")return;const g=window.setInterval(()=>{if(n!=="attach-cloud"&&n!=="provision-local"||s.current||o.current)return;const v=Math.max(l.current??0,i.current??0);if(v>0&&Date.now()-v<vw)return;const I=`Workspace sync ${n==="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}),Gn("workspace_sync_bootstrap_timeout",{workspaceId:e,phase:n})},1e4);return()=>window.clearInterval(g)}function Rw(e){const{workspaceSyncPhase:t,lastBootstrapPhase:n,workspaceLastPullAt:s}=e;return t==="provision-local"?"provision-local":t==="attach-cloud"?"attach-cloud":t==="active"||n==="active"?"active":n==="provision-local"||n==="attach-cloud"?n:s?"attach-cloud":"provision-local"}const yf={allowed:!0};function nr(e,t){return{allowed:!1,reason:e,retainPendingSignature:t?.retainPendingSignature===!0}}function kf(e,t){return e.cloudAuthConfigured?e.runtimeMode!=="local"?nr("runtime-not-local"):e.workspaceCloudSyncEnabled?(t?.requireValidWorkspace??!0)&&!oi(e.currentWorkspaceId)?nr("invalid-workspace"):null:nr("sync-disabled"):nr("cloud-auth-unconfigured")}function Hp(e){const t=kf(e);return t||(e.repairModeActive&&!e.repairModeBypass?nr("repair-active",{retainPendingSignature:!0}):e.workspaceSyncPhase==="attach-cloud"?nr("attach-cloud",{retainPendingSignature:!0}):e.isAuthenticated?e.pushInFlight?nr("push-in-flight",{retainPendingSignature:!0}):e.pullInFlight?nr("pull-in-flight",{retainPendingSignature:!0}):yf:nr("auth-required"))}function Gp(e){const t=kf(e);return t||(e.repairModeActive&&!e.repairModeBypass?nr("repair-active"):e.workspaceSyncPhase==="provision-local"?nr("provision-local"):e.retryPending?nr("retry-pending"):e.isAuthenticated?e.pullInFlight?nr("pull-in-flight"):e.pushInFlight?nr("push-in-flight"):yf:nr("auth-required"))}function Vp(e){const t=kf(e,{requireValidWorkspace:!1});return t||(e.isAuthenticated?yf:nr("auth-required"))}function jw(e){return nr("lease-held",{retainPendingSignature:e==="push"})}function _d(e){return e.cloudAuthConfigured&&e.runtimeMode==="local"&&e.workspaceCloudSyncEnabled&&e.authSessionResolved}function Nw({enabled:e,phase:t,busy:n,retryAt:s,lastErrorMessage:o}){return e?t==="provision-local"?{status:"syncing",summary:n?"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:n?"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."}:n?{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 Pw(e){return _d(e)&&e.workspaceSyncPhase!=="attach-cloud"&&e.workspaceSyncReferenceSnapshotsReady}function Mw(e){return _d(e)&&e.workspaceSyncPhase==="active"&&e.workspaceSyncReferenceSnapshotsReady}function Ew(e){return _d(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 Dw(e){return _d(e)&&e.isAuthenticated&&e.workspaceSyncPhase==="active"}function Lw(e){return _d(e)&&e.isAuthenticated&&e.workspaceSyncPhase!=="provision-local"&&e.workspaceSyncPhase!=="attach-cloud"&&!e.alreadyRan}function Bw({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,workspaceSyncPhase:s,workspacePullInFlightRef:o,realtimePullDebounceRef:l,realtimeSuppressedEventIdsRef:i,clearWorkspaceRetry:d,isWorkspaceRetryPending:m,pullWorkspaceChangesFromCloud:y}){return{handleRealtimeSignal:g=>{if(!e||t!=="local"||!n||s==="provision-local")return;const v=String(g?.eventId||"").trim();v&&i.current.delete(v)||o.current||(m()&&d(),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>{l.current=null,y()},180))},recordSuppressedEventIds:(g,v)=>{const _=v?.queueRef,I=Number.isFinite(v?.maxQueueSize)?Math.max(1,Number(v?.maxQueueSize)):2048,C=Number.isFinite(v?.ttlMs)?Math.max(0,Number(v?.ttlMs)):null;for(const D of g){const q=String(D||"").trim();!q||i.current.has(q)||(i.current.add(q),_&&_.current.push(q),C!==null&&window.setTimeout(()=>{i.current.delete(q)},C))}if(_)for(;_.current.length>I;){const D=_.current.shift();D&&i.current.delete(D)}},clearRealtimePullDebounce:()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null)}}}function ay(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 Ww(e){ay(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 Fw({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:n,workspaceLastPullAt:s,lastBootstrapPhaseRef:o,workspaceRepairModeRef:l,workspaceForceFullAiProfilePushRef:i,workspaceStartupRepairRanRef:d,workspaceStartupFullReconcileRanRef:m,workspaceFullReconcileInFlightRef:y,workspacePullCursorRef:k,workspaceAttachBootstrapBaselineSignatureRef:S,workspaceCaptureAttachBootstrapBaselineRef:h,workspacePendingSignatureRef:g,workspaceLastPushedSignatureRef:v,workspaceLastPushedWatermarksRef:_,workspaceLastPushedTaskChangeKeysRef:I,workspaceLastPushedInitiativeIdsRef:C,workspaceLastPushedInitiativeWatermarksRef:D,workspaceLastPushedWorkstreamIdsRef:q,workspaceLastPushedWorkstreamWatermarksRef:B,workspaceLastPushedAiProfileIdsRef:X,workspaceLastPushedAiProfileWatermarksRef:me,workspaceLastPushedAiProfileChangeKeysRef:ke,workspaceLastPushedDocumentPathsRef:le,workspaceLastPushedDocumentWatermarksRef:O,workspaceLastPushedAssetPathsRef:A,workspaceLastPushedAssetWatermarksRef:de,workspaceLastPushedDocumentReviewSessionIdsRef:ge,workspaceLastPushedDocumentReviewSessionWatermarksRef:Y,workspaceLastPushedDocumentReviewCommentIdsRef:P,workspaceLastPushedDocumentReviewCommentWatermarksRef:H,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:ue,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ye,workspaceLastPushedTaskEventWatermarksRef:V,workspaceBaselineResetReasonRef:Me,bootstrapPhaseStartedAtRef:_e,bootstrapLastProgressAtRef:re,acquireWorkspaceSyncLease:oe,releaseWorkspaceSyncLease:Ie,forceClearWorkspaceSyncLease:Ee,clearWorkspaceRetry:je,clearWorkspaceIssue:Pe,reportWorkspaceWindowContention:K,reportSyncEvent:x,persistWorkspaceSyncPatch:b,persistWorkspaceSyncWatermarksSnapshotBestEffort:R,buildWorkspaceSyncSignature:F,pullWorkspaceChangesFromCloud:Q,pushWorkspaceChangesToCloud:M,cloudAuthConfigured:$,runtimeMode:be,isAuthenticated:U,checkAuthSession:se}){const pe=n==="provision-local"?"push":n==="attach-cloud"?"bootstrap":"pull";return{retryWorkspaceCloudSync:async()=>{je();let ie=Vp({cloudAuthConfigured:$,runtimeMode:be,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:U});if(!ie.allowed&&ie.reason==="auth-required"){if(!await se())return x(e,{eventType:pe,status:"error",errorMessage:"Manual sync retry blocked: sign in is required.",details:{source:"retry.blocked",reason:"auth-required",phase:n}}),!1;ie=Vp({cloudAuthConfigured:$,runtimeMode:be,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:!0})}if(!ie.allowed)return x(e,{eventType:pe,status:"error",errorMessage:`Manual sync retry blocked: ${ie.reason}.`,details:{source:"retry.blocked",reason:ie.reason,phase:n}}),!1;if(i.current=!0,n==="provision-local"){const De=F();return De?M(De,{forceAllAiProfiles:!0}):!1}const Re=await Q();if(n==="attach-cloud")return Re;const Te=F();if(Te){g.current=Te;const De=await M(Te,{forceAllAiProfiles:i.current===!0});return Re||De}return Re},resetWorkspaceSyncCursorAndPull:async()=>{if(!await oe(e,"repair")&&(Ee(e),!await oe(e,"repair"))){K("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:n}});return}const Re=Rw({workspaceSyncPhase:n,lastBootstrapPhase:o.current,workspaceLastPullAt:s}),Te=Re==="provision-local",De=Re==="active";je(),Pe();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:n}});return}if(_e.current=null,re.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,Te?Ww({workspaceLastPushedWatermarksRef:_,workspaceLastPushedTaskChangeKeysRef:I,workspaceLastPushedInitiativeIdsRef:C,workspaceLastPushedInitiativeWatermarksRef:D,workspaceLastPushedWorkstreamIdsRef:q,workspaceLastPushedWorkstreamWatermarksRef:B,workspaceLastPushedAiProfileIdsRef:X,workspaceLastPushedAiProfileWatermarksRef:me,workspaceLastPushedAiProfileChangeKeysRef:ke,workspaceLastPushedDocumentPathsRef:le,workspaceLastPushedDocumentWatermarksRef:O,workspaceLastPushedAssetPathsRef:A,workspaceLastPushedAssetWatermarksRef:de,workspaceLastPushedDocumentReviewSessionIdsRef:ge,workspaceLastPushedDocumentReviewSessionWatermarksRef:Y,workspaceLastPushedDocumentReviewCommentIdsRef:P,workspaceLastPushedDocumentReviewCommentWatermarksRef:H,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:ue,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ye,workspaceLastPushedTaskEventWatermarksRef:V,workspaceBaselineResetReasonRef:Me}):De&&ay({workspaceLastPushedWatermarksRef:_,workspaceLastPushedTaskChangeKeysRef:I,workspaceLastPushedInitiativeIdsRef:C,workspaceLastPushedInitiativeWatermarksRef:D,workspaceLastPushedWorkstreamIdsRef:q,workspaceLastPushedWorkstreamWatermarksRef:B,workspaceLastPushedAiProfileIdsRef:X,workspaceLastPushedAiProfileWatermarksRef:me,workspaceLastPushedAiProfileChangeKeysRef:ke,workspaceLastPushedDocumentPathsRef:le,workspaceLastPushedDocumentWatermarksRef:O,workspaceLastPushedAssetPathsRef:A,workspaceLastPushedAssetWatermarksRef:de,workspaceBaselineResetReasonRef:Me}),R(),l.current=!0,x(e,{eventType:"bootstrap",status:"success",errorMessage:"Manual sync repair started.",details:{source:"repair.started",phase:n,repairPhase:Re,lastBootstrapPhase:o.current}}),await b({phase:Re,pullCursor:null,startupFullReconcileCompletedAt:null,lastErrorMessage:null}),Re==="provision-local"){const st=F();if(!st)return;await M(st,{forceAllAiProfiles:!0,repairMode:!0});return}const Oe=await Q({repairMode:!0});if(Re!=="active"||!Oe)return;const vt=F();if(!vt)return;g.current=vt,await M(vt,{forceAllAiProfiles:!0,repairMode:!0})}finally{l.current=!1,Ie(e)}}}}function Ow({workspaceSyncPhase:e,forceCursorNull:t,currentCursor:n}){const s=e==="attach-cloud";return{bootstrap:s,cursor:s||t===!0?null:n,successEventType:s?"bootstrap":"pull"}}function $w({workspaceSyncPhase:e,forceCursorNull:t,startupFullReconcileRan:n,pendingSignature:s,fallbackSignature:o,lastPushedSignature:l}){const i=e==="attach-cloud",d=s||o,m=!i&&d&&d!==l?d:null;return{successEventType:i?"bootstrap":"pull",shouldCaptureAttachBootstrapBaseline:i,shouldClearPendingSignature:i||m!==null,shouldRefreshReferenceSnapshots:i,shouldSeedWorkspaceSnapshotPushBaseline:i,shouldScheduleStartupFullReconcile:!t&&!i&&!n,deferredPushSignature:m}}function Uw({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:l,checkAuthSession:i,resolveCloudAuthUrl:d,ensureCloudWorkspaceReadyForSync:m,ensureWorkspaceSyncReady:y,handleSyncAuthFailure:k,clearWorkspaceRetry:S,clearWorkspaceIssue:h,isWorkspaceRetryPending:g,scheduleWorkspaceSyncRetry:v,persistWorkspaceSyncPatchSafely:_,persistWorkspaceSyncPatchBestEffort:I,persistWorkspaceSyncWatermarksSnapshotBestEffort:C,reportSyncEvent:D,acquireWorkspaceSyncLease:q,releaseWorkspaceSyncLease:B,reportWorkspaceWindowContention:X,refreshWorkspaceSyncMarkdownDocumentsSnapshot:me,refreshWorkspaceSyncAiProfilesSnapshot:ke,refreshWorkspaceSyncAssetsSnapshot:le,refreshWorkspaceSyncPlanningEntitiesSnapshot:O,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:A,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:de,refreshLocalWorkspaceTaskCollections:ge,buildWorkspaceSyncPayload:Y,buildWorkspaceSyncSignature:P,seedWorkspaceSnapshotPushBaseline:H,shouldSuppressAttachBootstrapPush:ue,recordSuppressedEventIds:ye,workspaceRepairModeRef:V,workspaceForceFullAiProfilePushRef:Me,workspacePushInFlightRef:_e,workspacePullInFlightRef:re,workspacePendingPushReplayRef:oe,workspaceLastPushedSignatureRef:Ie,workspacePendingSignatureRef:Ee,workspaceLastPushedTaskIdsRef:je,workspaceDeletedTaskIdsRef:Pe,workspaceDeletedTaskWatermarksRef:K,workspacePullCursorRef:x,workspaceLastPushedWatermarksRef:b,workspaceLastPushedTaskChangeKeysRef:R,workspaceLastPushedInitiativeIdsRef:F,workspaceLastPushedInitiativeWatermarksRef:Q,workspaceLastPushedWorkstreamIdsRef:M,workspaceLastPushedWorkstreamWatermarksRef:$,workspaceLastPushedAiProfileIdsRef:be,workspaceLastPushedAiProfileWatermarksRef:U,workspaceLastPushedAiProfileChangeKeysRef:se,workspaceLastPushedDocumentPathsRef:pe,workspaceLastPushedDocumentWatermarksRef:z,workspaceLastPushedAssetPathsRef:ne,workspaceLastPushedAssetWatermarksRef:ie,workspaceLastPushedDocumentReviewSessionIdsRef:Re,workspaceLastPushedDocumentReviewSessionWatermarksRef:Te,workspaceLastPushedDocumentReviewCommentIdsRef:De,workspaceLastPushedDocumentReviewCommentWatermarksRef:Oe,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:vt,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:st,workspaceLastPushedTaskEventWatermarksRef:kt,workspaceBaselineResetReasonRef:Ye,workspaceCaptureAttachBootstrapBaselineRef:Ct,workspaceStartupFullReconcileRanRef:dt,workspaceFullReconcileInFlightRef:Qe,bootstrapLastProgressAtRef:Rt,realtimeSuppressedEventQueueRef:ee,setWorkspaceSyncBusy:ze,setUserGlobalSyncStatus:ft,setUserGlobalSyncError:it,setWorkspaceLastErrorMessage:Et,setWorkspaceLastErrorAt:ht,setWorkspaceLastPullAt:Ot,setWorkspaceLastPushAt:Dt,setWorkspaceSyncPendingChanges:We,setTasks:tt,setArchivedTasks:Fe}){const Ze=async(ot,te)=>{let Le=Hp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:l,repairModeActive:V.current===!0,repairModeBypass:te?.repairMode===!0,pushInFlight:_e.current,pullInFlight:re.current});if(!Le.allowed&&Le.reason==="auth-required"){if(!await i())return!1;Le=Hp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:V.current===!0,repairModeBypass:te?.repairMode===!0,pushInFlight:_e.current,pullInFlight:re.current})}if(!Le.allowed)return Le.retainPendingSignature&&(Ee.current=ot),!1;if(ue(ot))return!1;if(!await q(s,"push")){const c=jw("push");return!c.allowed&&c.retainPendingSignature&&(Ee.current=ot),X("push"),!1}_e.current=!0,ze(!0),ft("syncing"),it(null);const jt=Date.now(),Wt=te?.forceAllAiProfiles===!0||Me.current===!0,Ge=te?.repairMode===!0||V.current===!0;let $t=null,yt=!1,E=ot;try{if(await me(),await ke(),await le(),await O(),await A(),!await y())return!1;const J=P();if(J&&(E=J),ue(E))return!1;const we=oe.current,Ke=we&&we.signature===E&&(!Wt||we.forceAllAiProfiles===!0)&&(!Ge||we.repairMode===!0)?we:null,Je=Ke?.payload||Y({forceAllAiProfiles:Wt});$t=Je,yt=Ke!==null,We(Je.changes.length);const Ne=await RS({resolveCloudAuthUrl:d,workspaceId:s,payload:Je,ensureCloudWorkspaceReadyForSync:m,repairMode:Ke?.repairMode??Ge});if(!Ne.success){if(Ne.status===401)return oe.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),Et(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}}),Ee.current=E,Ne.transient||Bs(Ne.status)?(oe.current={signature:E,payload:Je,forceAllAiProfiles:Ke?.forceAllAiProfiles??Wt,repairMode:Ke?.repairMode??Ge},v(Ne.retryAfterMs)):(oe.current=null,o==="active"&&_({phase:"error",lastErrorMessage:Pt})),!1}oe.current=null,Ie.current=E,je.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),F.current=new Set(Ne.currentInitiativeIds),Q.current=new Map(Ne.currentInitiativeWatermarks),M.current=new Set(Ne.currentWorkstreamIds),$.current=new Map(Ne.currentWorkstreamWatermarks),be.current=new Set(Ne.currentAiProfileIds),U.current=new Map(Ne.currentAiProfileWatermarks),se.current=Ne.currentAiProfileChangeKeys?new Map(Ne.currentAiProfileChangeKeys):new Map(se.current),pe.current=new Set(Ne.currentDocumentPaths),z.current=new Map(Ne.currentDocumentWatermarks),ne.current=new Set(Ne.currentAssetPaths),ie.current=new Map(Ne.currentAssetWatermarks),Re.current=new Set(Ne.currentDocumentReviewSessionIds),Te.current=new Map(Ne.currentDocumentReviewSessionWatermarks),De.current=new Set(Ne.currentDocumentReviewCommentIds),Oe.current=new Map(Ne.currentDocumentReviewCommentWatermarks),vt.current=new Set(Ne.currentAnnotatedAttachmentSessionIds),st.current=new Map(Ne.currentAnnotatedAttachmentSessionWatermarks),kt.current=new Map(Ne.currentTaskEventWatermarks),Wt&&(Me.current=!1);for(const[Pt,Ft]of Ne.pushedWatermarks)b.current.set(Pt,Ft);for(const[Pt,Ft]of Ne.pushedTaskChangeKeys||new Map)R.current.set(Pt,Ft);if(Ne.deleteTaskIds.size>0)for(const Pt of Ne.deleteTaskIds)Pe.current.delete(Pt),K.current.delete(Pt),b.current.delete(Pt),R.current.delete(Pt);const zt=await C();if(Ye.current=zt?null:"storage-write-failed",Array.isArray(Ne.emittedEventIds)&&Ne.emittedEventIds.length>0&&ye(Ne.emittedEventIds,{queueRef:ee,maxQueueSize:2048}),Array.isArray(Ne.appliedTaskUpserts)&&Ne.appliedTaskUpserts.length>0){const Pt=await Op(s,Ne.appliedTaskUpserts.map(Ft=>({op:"upsert",archived:Ft.archived===!0,task:Ft.task})));if(Pt.ok){for(const Ft of Ne.appliedTaskUpserts){const Lt=String(Ft?.task?.id||"").trim(),Ht=String(Ft?.task?.updatedAt||Ft?.task?.createdAt||"").trim();!Lt||!Ht||b.current.set(Lt,Ht)}try{await ge()}catch{Gn("push_local_task_refresh_failed",{workspaceId:s,taskCount:Ne.appliedTaskUpserts.length})}}else Gn("push_local_task_apply_failed",{workspaceId:s,taskCount:Ne.appliedTaskUpserts.length,status:Pt.status,failures:Pt.failures})}S(),h();const Jt=Ne.syncedAt||new Date().toISOString();return Ie.current=P(),Dt(Jt),We(0),ft("idle"),_({phase:"active",lastPushAt:Jt,lastSyncedAt:Jt,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(c){const J="Workspace sync push failed.";return ft("error"),it(J),Et(J),ht(new Date().toISOString()),Ee.current=E,$t&&(oe.current={signature:E,payload:$t,forceAllAiProfiles:Wt,repairMode:Ge}),v(),D(s,{eventType:"push",status:"error",errorMessage:`${J} ${String(c?.message||"").trim()}`.trim(),details:{replayedPayload:yt}}),Gn("push_failed_exception",{workspaceId:s,elapsedMs:Date.now()-jt}),!1}finally{_e.current=!1,ze(re.current),B(s);const c=Ee.current,J=P();c&&J&&J!==Ie.current&&!re.current&&!g()&&(Ee.current="",window.setTimeout(()=>{Ze(J)},120))}},St=async ot=>{let te=Gp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:l,repairModeActive:V.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:g(),pullInFlight:re.current,pushInFlight:_e.current});if(!te.allowed&&te.reason==="auth-required"){if(!await i())return!1;te=Gp({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:V.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:g(),pullInFlight:re.current,pushInFlight:_e.current})}if(!te.allowed)return!1;if(!await q(s,"pull"))return X("pull"),!1;re.current=!0,ze(!0),ft("syncing"),it(null);const At=Date.now();try{if(!await y())return!1;const Wt=Ow({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,currentCursor:x.current}),Ge=await jS({resolveCloudAuthUrl:d,workspaceId:s,cursor:Wt.cursor,bootstrap:Wt.bootstrap,ensureCloudWorkspaceReadyForSync:m,maxPages:20,repairMode:ot?.repairMode===!0||V.current===!0,onPagePulled:()=>{Rt.current=Date.now()},onChangesApplied:()=>{Rt.current=Date.now()}});if(!Ge.success){if(Ge.kind==="pull_http"&&Ge.status===401)return await k("pull",401),!1;if(Ge.kind==="apply_auth")return await k("apply",401),!1;if(Ge.kind==="pull_http"&&Ge.errorCode==="INVALID_SYNC_CURSOR"){const we="Saved sync cursor was invalid. Clearing it and retrying from the beginning.";return x.current=null,_({pullCursor:null}),ft("error"),it(we),Et(we),ht(new Date().toISOString()),D(s,{eventType:"pull",status:"error",statusCode:Ge.status,errorMessage:we,requestMs:Ge.pullRequestMs,details:{recovery:"cursor-reset",...Ge.serverDiagnostics?{serverPullDiagnostics:Ge.serverDiagnostics}:{}}}),v(150),!1}let J=Ge.kind==="apply_payload"||Ge.kind==="apply_all_candidates"||Ge.kind==="exception"?String(Ge.error||"Workspace sync apply failed."):`Workspace sync pull failed (${Ge.status||0})`;return Ge.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),Et(J),ht(new Date().toISOString()),D(s,{eventType:Ge.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:Ge.status,errorMessage:J,requestMs:Ge.pullRequestMs,details:{pages:Ge.pages,applyMs:Ge.applyMs,...Ge.serverDiagnostics?{serverPullDiagnostics:Ge.serverDiagnostics}:{}}}),Ge.transient||Ge.hasTransientApplyFailure||Bs(Ge.status)?v(Ge.retryAfterMs):_({phase:"error",lastErrorMessage:J}),!1}Array.isArray(Ge.emittedEventIds)&&ye(Ge.emittedEventIds,{ttlMs:6e4}),Ge.pulledDeleteTaskIds.size>0&&(tt(J=>J.filter(we=>!Ge.pulledDeleteTaskIds.has(String(we.id||"")))),Fe(J=>J.filter(we=>!Ge.pulledDeleteTaskIds.has(String(we.id||"")))));const $t=Array.isArray(Ge.documentDecryptFailures)?Ge.documentDecryptFailures.filter(J=>String(J||"").trim().length>0):[];if($t.length>0&&Gn("pull_document_decrypt_failures",{workspaceId:s,failureCount:$t.length}),x.current=Ge.cursor||null,Ge.appliedChanges>0&&(Ge.pulledActiveUpserts||Ge.pulledArchivedUpserts||Ge.pulledTaskEventUpserts||Ge.pulledPlanningUpserts))try{await ge()}catch{Gn("pull_local_refresh_failed",{workspaceId:s,appliedChanges:Ge.appliedChanges})}S(),h();const yt=Ge.syncedAt||new Date().toISOString();Ot(yt),We(0),ft("idle");const E=$w({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,startupFullReconcileRan:dt.current,pendingSignature:Ee.current,fallbackSignature:P(),lastPushedSignature:Ie.current});if(E.shouldCaptureAttachBootstrapBaseline&&(Ct.current=!0),E.shouldClearPendingSignature&&(Ee.current="",oe.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:Ge.appliedChanges,requestMs:Ge.pullRequestMs,details:{pages:Ge.pages,applyMs:Ge.applyMs,...Ge.serverDiagnostics?{serverPullDiagnostics:Ge.serverDiagnostics}:{}}}),E.shouldRefreshReferenceSnapshots&&(await me(),await le(),await A(),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=P();J&&(Me.current=!0,Ee.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(jt){const Wt=String(jt?.message||"").trim(),Ge=Wt?`Workspace sync pull failed. ${Wt}`:"Workspace sync pull failed.";return ft("error"),it(Ge),Et(Ge),ht(new Date().toISOString()),v(),D(s,{eventType:"pull",status:"error",errorMessage:Ge,requestMs:Date.now()-At}),Gn("pull_failed_exception",{workspaceId:s,elapsedMs:Date.now()-At,error:Wt||null}),!1}finally{re.current=!1,ze(_e.current),B(s)}};return{pushWorkspaceChangesToCloud:Ze,pullWorkspaceChangesFromCloud:St}}const wh={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1};function zw(e){const{currentWorkspaceId:t,cloudAuthConfigured:n,runtimeMode:s,authSessionResolved:o,isAuthenticated:l,authUserId:i,projectName:d,resolveCloudAuthUrl:m,resolveWebSocketUrl:y,realtimeSyncEnabled:k,tasks:S,archivedTasks:h,deletedTasks:g=[],initiatives:v,workstreams:_,taxonomies:I,taxonomyState:C,setupState:D,globalTheme:q,locale:B,globalWeekStartsOn:X,themeUseGlobalDefault:me,setTasks:ke,setArchivedTasks:le,setAuthBlocked:O,setIsAuthenticated:A,checkAuthSession:de,setGlobalTheme:ge,setCurrentTheme:Y,setSetupState:P,setLocale:H,setGlobalWeekStartsOn:ue,fetchPlanningEntities:ye}=e,V=r.useMemo(()=>Cw(C),[C]),[Me,_e]=r.useState("disconnected"),[re,oe]=r.useState(null),[Ie,Ee]=r.useState(null),[je,Pe]=r.useState(null),[K,x]=r.useState(null),[b,R]=r.useState(null),[F,Q]=r.useState(!1),[M,$]=r.useState("idle"),[be,U]=r.useState(null),[se,pe]=r.useState(!1),[z,ne]=r.useState(0),[ie,Re]=r.useState([]),[Te,De]=r.useState(""),Oe=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([]),[Rt,ee]=r.useState(""),[ze,ft]=r.useState(null),[it,Et]=r.useState(null),[ht,Ot]=r.useState(0),[Dt,We]=r.useState(null),tt=r.useRef([]),[Fe,Ze]=r.useState([]),[St,ot]=r.useState(""),te=r.useRef([]),Le=r.useRef(new Set),[At,jt]=r.useState([]),[Wt,Ge]=r.useState(""),$t=r.useRef([]),yt=r.useRef([]),[E,c]=r.useState([]),[J,we]=r.useState(""),xe=r.useRef([]),[Ke,Je]=r.useState(wh),[Ne,zt]=r.useState("degraded-fallback"),[Jt,Pt]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),Ft=r.useRef(!1),Lt=r.useRef(null),Ht=r.useRef("missing-baseline"),ra=r.useRef(0),Vt=r.useRef(!1),Ga=r.useRef(new Set),Va=r.useRef(""),qa=r.useRef(""),cn=r.useRef(""),he=r.useRef(""),rt=r.useRef(""),Ae=r.useRef(""),Nt=r.useRef(!1),pt=r.useRef(null),wt=r.useRef(new Set),Ca=r.useRef([]),ya=r.useRef(null),ia=r.useRef(()=>Promise.resolve(!1)),ca=r.useRef(async()=>{}),Oa=r.useRef(null),gt=r.useRef(null),rr=r.useRef("idle"),ua=r.useCallback(()=>{Lt.current!==null&&(window.clearTimeout(Lt.current),Lt.current=null)},[]),ta=r.useCallback(T=>{if(typeof window>"u")return;ua();const j=Math.max(1,Math.floor(ra.current)+1);ra.current=j;const at=1500*2**Math.max(0,j-1),bt=Number.isFinite(Number(T))?Math.max(0,Math.floor(Number(T))):0,ve=Math.max(Math.min(12e4,at),bt);Lt.current=window.setTimeout(()=>{Lt.current=null,ca.current({preferCloudOnFirstSync:!1})},ve)},[ua]),wa=r.useCallback(T=>{Je(j=>j[T]?j:{...j,[T]:!0})},[]),Kt=Object.values(Ke).every(Boolean),{workspaceRetryAt:vr,isWorkspaceRetryPending:Ta,workspacePushInFlightRef:Qa,workspacePullInFlightRef:Ra,workspaceLastPushedSignatureRef:Zt,workspacePendingSignatureRef:Ka,workspaceLastPushedTaskIdsRef:aa,workspaceDeletedTaskIdsRef:ln,workspaceDeletedTaskWatermarksRef:yn,workspacePullCursorRef:Sr,clearWorkspaceRetry:la,scheduleWorkspaceRetry:wr,persistWorkspaceSyncPatch:qr,applyWorkspaceSyncPatchLocally:Vn,readWorkspaceSyncStateSnapshot:kn,loadWorkspaceSyncState:$a,applyWorkspaceSyncStateSnapshot:br,saveWorkspaceCloudSyncSettings:dn,acquireWorkspaceSyncLease:Ea,releaseWorkspaceSyncLease:ja,forceClearWorkspaceSyncLease:_r}=fw({currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:Q,setWorkspaceSyncPhase:$,setWorkspaceSyncSetupIntent:U,setWorkspaceLastPullAt:Ee,setWorkspaceLastPushAt:Pe,setWorkspaceLastErrorMessage:R}),xt=r.useCallback(T=>{(T.phase==="attach-cloud"||T.phase==="provision-local")&&(rr.current=T.phase,Oa.current===null&&(Oa.current=Date.now()),gt.current=null),br(T)},[br]),vn=r.useRef(new Map),Sn=r.useRef(new Map),un=r.useRef(new Set),Ua=r.useRef(new Map),sr=r.useRef(new Set),Na=r.useRef(new Map),ka=r.useRef(new Set),Ln=r.useRef(new Map),wn=r.useRef(new Map),va=r.useRef(new Set),Yt=r.useRef(new Map),bn=r.useRef(new Set),za=r.useRef(new Map),Pa=r.useRef(new Set),Bn=r.useRef(new Map),Ma=r.useRef(new Set),Mr=r.useRef(new Map),na=r.useRef(new Set),da=r.useRef(new Map),Xa=r.useRef(new Map),or=r.useCallback(T=>T?(aa.current=new Set(T.taskIds),vn.current=T.taskWatermarks,Sn.current=T.taskChangeKeys||new Map,un.current=new Set(Array.from(T.initiativeWatermarks.keys())),Ua.current=T.initiativeWatermarks,sr.current=new Set(Array.from(T.workstreamWatermarks.keys())),Na.current=T.workstreamWatermarks,ka.current=new Set(Array.from(T.aiProfileWatermarks.keys())),Ln.current=T.aiProfileWatermarks,wn.current=T.aiProfileChangeKeys||new Map,va.current=new Set(Array.from(T.documentWatermarks.keys())),Yt.current=T.documentWatermarks,bn.current=new Set(Array.from(T.assetWatermarks.keys())),za.current=T.assetWatermarks,Pa.current=new Set(Array.from(T.documentReviewSessionWatermarks.keys())),Bn.current=T.documentReviewSessionWatermarks,Ma.current=new Set(Array.from(T.documentReviewCommentWatermarks.keys())),Mr.current=T.documentReviewCommentWatermarks,na.current=new Set(Array.from(T.annotatedAttachmentSessionWatermarks.keys())),da.current=T.annotatedAttachmentSessionWatermarks,Xa.current=T.taskEventWatermarks,Ht.current=null,!0):!1,[aa]),Er=r.useCallback(()=>({taskIds:aa.current,taskWatermarks:vn.current,taskChangeKeys:Sn.current,initiativeWatermarks:Ua.current,workstreamWatermarks:Na.current,aiProfileWatermarks:Ln.current,aiProfileChangeKeys:wn.current,documentWatermarks:Yt.current,assetWatermarks:za.current,documentReviewSessionWatermarks:Bn.current,documentReviewCommentWatermarks:Mr.current,annotatedAttachmentSessionWatermarks:da.current,taskEventWatermarks:Xa.current}),[]),Cr=r.useRef(!1),Xt=r.useRef(!1),_n=r.useRef(!1),Cn=r.useRef(""),Ar=r.useRef(!1),xr=3e4,qn=k?3e4:15e3,Kn=Math.max(3e4,qn),ir=r.useMemo(()=>{const T=Ie?Date.parse(Ie):NaN,j=je?Date.parse(je):NaN;return Number.isFinite(T)&&Number.isFinite(j)?T>=j?Ie:je:Number.isFinite(T)?Ie:Number.isFinite(j)?je:null},[Ie,je]),en=r.useMemo(()=>Nw({enabled:F,phase:M,busy:se,retryAt:vr,lastErrorMessage:b}),[F,M,se,vr,b]),An=en.status,Zn=en.summary,tn=en.recommendedAction,cs=r.useCallback(T=>{const j=String(T||"").trim();if(!j)return null;const bt=kh()[j]?.updatedAt;return typeof bt=="string"&&bt.trim().length>0?bt.trim():null},[]),Za=r.useCallback((T,j)=>{const at=String(T||"").trim(),bt=String(j||"").trim();if(!at||!bt)return;const ve=kh();ve[at]={updatedAt:bt},_w(ve)},[]),Kr=r.useCallback(()=>{const T=D?.mode==="operations"?"operations":"core";return{theme:q,operatingMode:T,localization:{locale:B,weekStartsOn:X}}},[q,D?.mode,B,X]),Dr=r.useCallback(async T=>{if(!(!T||typeof T!="object")){Vt.current=!0;try{const j={},at=Kc(T.theme);if(at&&(ge(at),me&&Y(at),j.theme=at),(T.operatingMode==="core"||T.operatingMode==="operations")&&(P(bt=>bt&&{...bt,mode:T.operatingMode}),j.setup={mode:T.operatingMode}),T.localization&&typeof T.localization=="object"){const bt={};if(typeof T.localization.locale=="string"&&T.localization.locale.trim().length>0){const ae=Lg(T.localization.locale.trim());H(ae)}const ve=String(T.localization.weekStartsOn||"").trim().toLowerCase();(ve==="sunday"||ve==="monday")&&(ue(ve),bt.weekStartsOn=ve),Object.keys(bt).length>0&&(j.schedulePreferences=bt)}Object.keys(j).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(j)})}finally{Vt.current=!1}}},[me,ge,Y,P,H,ue]),xn=r.useCallback(async T=>{const j=T?.preferCloudOnFirstSync!==!1;if(!n)return;if(s!=="local"||!l){ua(),ra.current=0,_e("disconnected");return}const at=String(i||"").trim();if(!at||at==="anonymous"){ua(),ra.current=0,_e("disconnected");return}if(!Ft.current){_e("syncing"),oe(null),Ft.current=!0;try{const bt=await NS({resolveCloudAuthUrl:m,userId:at,preferCloudOnFirstSync:j,getLocalUpdatedAt:cs,buildLocalSettings:Kr,applyRemoteSettings:Dr});if(!bt.success){_e("error"),bt.transient?(oe(bt.error||"Sync failed temporarily. Retrying automatically."),ta(bt.retryAfterMs)):(ua(),ra.current=0,oe(bt.error||"Sync failed."));return}ua(),ra.current=0;const ve=String(bt.updatedAt||"").trim()||new Date().toISOString();Za(at,ve),_e("idle"),oe(null),Ga.current.add(at),bt.mode==="pulled"&&(Va.current="")}catch{_e("error"),oe("Sync failed temporarily. Retrying automatically."),ta()}finally{Ft.current=!1}}},[n,s,l,i,m,cs,Kr,Dr,Za,ua,ta]);r.useEffect(()=>{ca.current=xn},[xn]),r.useEffect(()=>()=>{ua()},[ua]);const cr=r.useCallback(()=>{R(null),x(null)},[]),Wn=r.useCallback(T=>{R(yh),x(new Date().toISOString()),_e("error"),oe(yh),Gn("workspace_sync_window_contention",{workspaceId:t,operation:T})},[t]),mn=r.useCallback(async T=>{try{return await qr(T)}catch{return Vn(T)}},[Vn,qr]),lr=r.useCallback(T=>{mn(T).catch(()=>{})},[mn]),Zr=r.useCallback(()=>{const T={...Er(),taxonomyStateFingerprint:V},j=Sh(t,T);return mn({pushBaseline:ey(T)}).catch(()=>{}),j},[Er,t,mn,V]);r.useEffect(()=>{qa.current="",cn.current="",he.current="",rt.current="",Ae.current="",Cn.current="",Ar.current=!1,Re([]),De(""),tt.current=[],Qe([]),ee(""),Ze([]),ot(""),$t.current=[],yt.current=[],jt([]),Ge(""),xe.current=[],c([]),we(""),Je(wh),R(null),x(null),ne(0),wt.current=new Set,Ca.current=[],vn.current=new Map,Sn.current=new Map,un.current=new Set,Ua.current=new Map,sr.current=new Set,Na.current=new Map,ka.current=new Set,Ln.current=new Map,wn.current=new Map,va.current=new Set,Yt.current=new Map,bn.current=new Set,za.current=new Map,Pa.current=new Set,Bn.current=new Map,Ma.current=new Set,Mr.current=new Map,na.current=new Set,da.current=new Map,Xa.current=new Map,Xt.current=!!kn().startupFullReconcileCompletedAt,Da.current=!1;const T=vh(t,V);or(T)||(Ht.current="missing-baseline")},[t,or,V]),r.useEffect(()=>{if(Ht.current!=="missing-baseline")return;const T=vh(t,V);if(or(T))return;const j=ty(kn().pushBaseline,V);or(j)&&Sh(t,{...Er(),taxonomyStateFingerprint:V})},[Er,t,or,kn,V,F,M]),r.useEffect(()=>{Xt.current=!!kn().startupFullReconcileCompletedAt},[t,kn,Ie,M]);const ls=r.useCallback(T=>{wr(()=>ia.current(),{minDelayMs:T})},[wr]);r.useEffect(()=>{Iw({workspaceSyncPhase:M,lastBootstrapPhaseRef:rr,bootstrapPhaseStartedAtRef:Oa,bootstrapLastProgressAtRef:gt})},[M]),r.useEffect(()=>Tw({currentWorkspaceId:t,workspaceCloudSyncEnabled:F,workspaceSyncPhase:M,workspacePullInFlightRef:Ra,workspacePushInFlightRef:Qa,bootstrapPhaseStartedAtRef:Oa,bootstrapLastProgressAtRef:gt,setWorkspaceLastErrorMessage:T=>R(T),setWorkspaceLastErrorAt:T=>x(T),setUserGlobalSyncStatus:_e,setUserGlobalSyncError:T=>oe(T),setWorkspaceSyncBusy:pe,persistWorkspaceSyncPatchSafely:lr}),[t,F,M,lr,Ra,Qa]);const et=r.useCallback(async()=>IS({cloudAuthConfigured:n,runtimeMode:s,isAuthenticated:l,resolveCloudAuthUrl:m,workspaceId:t,workspaceName:d||t,allowProvisionOnMismatch:M!=="attach-cloud"}),[n,s,l,m,t,d,M]);r.useEffect(()=>{Oe.current=S||[]},[S]),r.useEffect(()=>{vt.current=h||[]},[h]),r.useEffect(()=>{ln.current=new Set((g||[]).map(T=>String(T?.taskId||"").trim()).filter(T=>T.length>0)),yn.current=new Map((g||[]).map(T=>[String(T?.taskId||"").trim(),String(T?.deletedAt||"").trim()]).filter(([T,j])=>T.length>0&&Number.isFinite(Date.parse(j))))},[g,ln,yn]),r.useEffect(()=>{st.current=v||[]},[v]),r.useEffect(()=>{kt.current=_||[]},[_]);const Bt=r.useRef(!1),Da=r.useRef(!1),Aa=r.useCallback(T=>{const j=T?.forceAllAiProfiles===!0;return ew({tasks:Oe.current,archivedTasks:vt.current,taskEvents:Wu(Oe.current,vt.current,st.current,kt.current),lastPushedTaskIds:aa.current,pendingDeletedTaskIds:ln.current,pendingDeletedTaskWatermarks:yn.current,initiatives:st.current,workstreams:kt.current,taxonomies:I||[],taxonomyState:C,lastPushedInitiativeIds:un.current,lastPushedInitiativeWatermarks:Ua.current,lastPushedWorkstreamIds:sr.current,lastPushedWorkstreamWatermarks:Na.current,aiProfiles:tt.current,lastPushedAiProfileIds:j?new Set:ka.current,lastPushedAiProfileWatermarks:j?new Map:Ln.current,lastPushedAiProfileChangeKeys:j?new Map:wn.current,documents:Ye.current,assets:te.current,currentDocumentPaths:Ct.current,currentAssetPaths:Le.current,documentReviewSessions:$t.current,documentReviewComments:yt.current,annotatedAttachmentSessions:xe.current,lastPushedDocumentPaths:va.current,lastPushedDocumentWatermarks:Yt.current,lastPushedAssetPaths:bn.current,lastPushedAssetWatermarks:za.current,lastPushedDocumentReviewSessionIds:Pa.current,lastPushedDocumentReviewSessionWatermarks:Bn.current,lastPushedDocumentReviewCommentIds:Ma.current,lastPushedDocumentReviewCommentWatermarks:Mr.current,lastPushedAnnotatedAttachmentSessionIds:na.current,lastPushedAnnotatedAttachmentSessionWatermarks:da.current,lastPushedTaskEventWatermarks:Xa.current,baselineResetReason:Ht.current,lastPushedWatermarks:vn.current,lastPushedTaskChangeKeys:Sn.current})},[I,C]),Sa=r.useCallback((T,j)=>{if(s==="local")try{const at={...j,workspaceId:T,details:Im(j.details)};fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(at)}).catch(bt=>{Gn("sync_event_post_failed",{workspaceId:T,eventType:j.eventType,status:j.status,error:String(bt?.message||bt||"")})})}catch(at){Gn("sync_event_post_failed",{workspaceId:T,eventType:j.eventType,status:j.status,error:String(at?.message||at||"")})}},[s]),In=r.useCallback(()=>tw({workspaceId:t,tasks:Oe.current,archivedTasks:vt.current,taskEvents:Wu(Oe.current,vt.current,st.current,kt.current),pendingDeletedTaskIds:ln.current,initiatives:st.current,workstreams:kt.current,taxonomies:I||[],aiProfiles:tt.current,documents:Ye.current,assets:te.current,documentReviewSessions:$t.current,documentReviewComments:yt.current,annotatedAttachmentSessions:xe.current}),[t,I,C]),Yn=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,j)=>T.id.localeCompare(j.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,j)=>T.id.localeCompare(j.id)),initiatives:(v||[]).map(T=>({id:String(T.id||"").trim(),updatedAt:String(T.updatedAt||T.createdAt||"").trim(),isArchived:!!T.isArchived})).sort((T,j)=>T.id.localeCompare(j.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,j)=>T.id.localeCompare(j.id)),taskEvents:Wu(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,j)=>T.id.localeCompare(j.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,j)=>T.taskId.localeCompare(j.taskId)),taxonomies:Array.isArray(I)?I:[],taxonomyState:C&&typeof C=="object"?C:null}),[S,h,g,v,_,I,C]),ds=r.useMemo(()=>{const T=[];for(const j of S||[]){const at=Array.isArray(j.attachments)?j.attachments.length:0;at>0&&T.push(`${j.id}:${at}`)}return T.join("|")},[S]),Fn=r.useCallback(T=>{if(!T)return!1;if(Ar.current)return Ar.current=!1,Cn.current=T,Zt.current=T,ne(0),!0;const j=Cn.current;return j?T===j?(Zt.current=T,ne(0),!0):(Cn.current="",!1):!1},[]),On=r.useCallback(async()=>{if(s==="local"&&oi(t)&&!(n&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const j=await T.json().catch(()=>({})),at=Array.isArray(j?.documents)?j.documents.map(ae=>({path:String(ae?.path||"").trim(),updatedAt:String(ae?.updatedAt||"").trim(),content:typeof ae?.content=="string"?ae.content:"",assetId:typeof ae?.assetId=="string"&&ae.assetId.trim().length>0?ae.assetId.trim():void 0,documentId:typeof ae?.documentId=="string"&&ae.documentId.trim().length>0?ae.documentId.trim():null,referenceNumber:Number.isFinite(Number(ae?.referenceNumber))?Math.max(1,Math.floor(Number(ae.referenceNumber))):null,version:Number.isFinite(Number(ae?.version))?Math.max(1,Math.floor(Number(ae.version))):null,taskId:typeof ae?.taskId=="string"&&ae.taskId.trim().length>0?ae.taskId.trim():null,logicalName:typeof ae?.logicalName=="string"&&ae.logicalName.trim().length>0?ae.logicalName.trim():null,caption:typeof ae?.caption=="string"&&ae.caption.trim().length>0?ae.caption.trim():null,originalFilename:typeof ae?.originalFilename=="string"&&ae.originalFilename.trim().length>0?ae.originalFilename.trim():null,linkRole:ae?.linkRole==="reference"?"reference":"attachment"})).filter(ae=>ae.path.length>0):[],bt=new Set(Array.isArray(j?.knownPaths)?j.knownPaths.map(ae=>String(ae||"").trim()).filter(ae=>ae.length>0):at.map(ae=>ae.path)),ve=typeof j?.fingerprint=="string"?j.fingerprint:JSON.stringify(at.map(ae=>`${ae.path}:${ae.updatedAt}:${ae.content.length}`).sort());if(ve===qa.current)return;qa.current=ve,Ye.current=at,Ct.current=bt,Re(at),De(ve)}catch(T){Gn("documents_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{wa("documents")}},[s,t,n,o,l,wa]),Tn=r.useCallback(async()=>{if(s!=="local"){We("runtime-not-local");return}if(!oi(t)){We("workspace-id-invalid");return}if(n&&(!o||!l)){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){Et(`HTTP ${T.status}`),ft(new Date().toISOString());return}const j=await T.json().catch(()=>({})),at=Array.isArray(j?.aiProfiles)?j.aiProfiles:[];Ot(at.length);const bt=Array.isArray(j?.aiProfiles)?j.aiProfiles.map(ae=>bw(ae)).filter(ae=>ae.id.length>0&&ae.workspaceId.length>0):[];Et(null),ft(new Date().toISOString());const ve=typeof j?.fingerprint=="string"?j.fingerprint:JSON.stringify(bt.map(ae=>[ae.id,ae.updatedAt,ae.name,ae.username,ae.archivedAt??"",ae.archivedReason??"",ae.mergedIntoProfileId??"",ae.rosterStateUpdatedAt??""].join(":")).sort());if(ve===cn.current)return;cn.current=ve,tt.current=bt,Qe(bt),ee(ve)}catch(T){Et(String(T?.message||T||"unknown-error")),ft(new Date().toISOString()),Gn("ai_profiles_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{wa("aiProfiles")}},[s,t,n,o,l,wa]),Gt=r.useCallback(async()=>{if(s==="local"&&oi(t)&&!(n&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const j=await T.json().catch(()=>({})),at=Array.isArray(j?.assets)?j.assets.map(ae=>({path:String(ae?.path||"").trim(),updatedAt:String(ae?.updatedAt||"").trim(),contentBase64:typeof ae?.contentBase64=="string"?ae.contentBase64:"",assetId:typeof ae?.assetId=="string"&&ae.assetId.trim().length>0?ae.assetId.trim():void 0,kind:ae?.kind==="image"?"image":"file",mimeType:typeof ae?.mimeType=="string"&&ae.mimeType.trim().length>0?ae.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(ae?.referenceNumber))?Math.max(1,Math.floor(Number(ae.referenceNumber))):null,taskId:typeof ae?.taskId=="string"&&ae.taskId.trim().length>0?ae.taskId.trim():null,logicalName:typeof ae?.logicalName=="string"&&ae.logicalName.trim().length>0?ae.logicalName.trim():null,caption:typeof ae?.caption=="string"&&ae.caption.trim().length>0?ae.caption.trim():null,originalFilename:typeof ae?.originalFilename=="string"&&ae.originalFilename.trim().length>0?ae.originalFilename.trim():null,linkRole:ae?.linkRole==="reference"?"reference":ae?.linkRole==="image"?"image":"attachment"})).filter(ae=>ae.path.length>0&&ae.contentBase64.length>0):[],bt=new Set(Array.isArray(j?.knownPaths)?j.knownPaths.map(ae=>String(ae||"").trim()).filter(ae=>ae.length>0):at.map(ae=>ae.path)),ve=typeof j?.fingerprint=="string"?j.fingerprint:JSON.stringify(at.map(ae=>`${ae.path}:${ae.updatedAt}:${ae.contentBase64.length}`).sort());if(ve===he.current)return;he.current=ve,te.current=at,Le.current=bt,Ze(at),ot(ve)}catch(T){Gn("assets_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{wa("assets")}},[s,t,n,o,l,wa]),$n=r.useCallback(async()=>{if(s==="local"&&oi(t)&&!(n&&(!o||!l)))try{const T=await fetch(`/api/taskforce/planning/bootstrap?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const j=await T.json().catch(()=>({})),at=Array.isArray(j?.initiatives)?j.initiatives.filter(ve=>!!(ve&&typeof ve=="object"&&typeof ve.id=="string")):[],bt=Array.isArray(j?.workstreams)?j.workstreams.filter(ve=>!!(ve&&typeof ve=="object"&&typeof ve.id=="string")):[];st.current=at,kt.current=bt}catch(T){Gn("planning_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}},[s,t,n,o,l]),pn=r.useCallback(async()=>{if(s==="local"&&oi(t)&&!(n&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const j=await T.json().catch(()=>({})),at=Array.isArray(j?.sessions)?j.sessions.map(ae=>({id:String(ae?.id||"").trim(),assetId:String(ae?.assetId||"").trim(),documentId:typeof ae?.documentId=="string"&&ae.documentId.trim().length>0?ae.documentId.trim():null,documentVersion:Number.isFinite(Number(ae?.documentVersion))?Math.max(1,Math.floor(Number(ae.documentVersion))):null,title:typeof ae?.title=="string"&&ae.title.trim().length>0?ae.title.trim():null,status:ae?.status==="resolved"?"resolved":"open",comments:Array.isArray(ae?.comments)?ae.comments:[],createdByActorId:typeof ae?.createdByActorId=="string"&&ae.createdByActorId.trim().length>0?ae.createdByActorId.trim():null,updatedByActorId:typeof ae?.updatedByActorId=="string"&&ae.updatedByActorId.trim().length>0?ae.updatedByActorId.trim():null,createdAt:String(ae?.createdAt||"").trim(),updatedAt:String(ae?.updatedAt||ae?.createdAt||"").trim(),deletedAt:typeof ae?.deletedAt=="string"&&ae.deletedAt.trim().length>0?ae.deletedAt.trim():null})).filter(ae=>ae.id.length>0&&ae.assetId.length>0):[],bt=Array.isArray(j?.comments)?j.comments.map(ae=>({id:String(ae?.id||"").trim(),sessionId:String(ae?.sessionId||"").trim(),body:typeof ae?.body=="string"?ae.body:"",anchor:ae?.anchor??null,order:Number.isFinite(Number(ae?.order))?Math.max(0,Math.floor(Number(ae.order))):0,authorActorId:typeof ae?.authorActorId=="string"&&ae.authorActorId.trim().length>0?ae.authorActorId.trim():null,createdAt:String(ae?.createdAt||"").trim(),updatedAt:String(ae?.updatedAt||ae?.createdAt||"").trim(),deletedAt:typeof ae?.deletedAt=="string"&&ae.deletedAt.trim().length>0?ae.deletedAt.trim():null})).filter(ae=>ae.id.length>0&&ae.sessionId.length>0):Aw(at),ve=typeof j?.fingerprint=="string"?j.fingerprint:JSON.stringify([...at.map(ae=>`${ae.id}:${ae.updatedAt}:${ae.status}:${ae.deletedAt||""}:${ae.comments.length}`).sort(),...bt.map(ae=>`${ae.id}:${ae.sessionId}:${ae.updatedAt}:${ae.deletedAt||""}`).sort()]);if(ve===rt.current)return;rt.current=ve,$t.current=at,yt.current=bt,jt(at),Ge(ve)}catch(T){Gn("document_review_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{wa("documentReviewSessions")}},[s,t,n,o,l,wa]),La=r.useCallback(async()=>{if(s==="local"&&oi(t)&&!(n&&(!o||!l)))try{const T=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const j=await T.json().catch(()=>({})),at=Array.isArray(j?.sessions)?j.sessions.map(ve=>({id:String(ve?.id||"").trim(),workspaceId:String(ve?.workspaceId||"").trim(),taskId:String(ve?.taskId||"").trim(),baseImageAssetId:String(ve?.baseImageAssetId||"").trim(),title:typeof ve?.title=="string"&&ve.title.trim().length>0?ve.title.trim():null,globalInstruction:typeof ve?.globalInstruction=="string"&&ve.globalInstruction.trim().length>0?ve.globalInstruction.trim():null,annotations:Array.isArray(ve?.annotations)?ve.annotations:[],createdByActorId:typeof ve?.createdByActorId=="string"&&ve.createdByActorId.trim().length>0?ve.createdByActorId.trim():null,updatedByActorId:typeof ve?.updatedByActorId=="string"&&ve.updatedByActorId.trim().length>0?ve.updatedByActorId.trim():null,createdAt:String(ve?.createdAt||"").trim(),updatedAt:String(ve?.updatedAt||ve?.createdAt||"").trim(),deletedAt:typeof ve?.deletedAt=="string"&&ve.deletedAt.trim().length>0?ve.deletedAt.trim():null})).filter(ve=>ve.id.length>0&&ve.workspaceId.length>0&&ve.taskId.length>0&&ve.baseImageAssetId.length>0):[],bt=typeof j?.fingerprint=="string"?j.fingerprint:JSON.stringify(at.map(ve=>`${ve.id}:${ve.updatedAt}:${ve.taskId}:${ve.baseImageAssetId}:${ve.annotations.length}:${ve.deletedAt||""}`).sort());if(bt===Ae.current)return;Ae.current=bt,xe.current=at,c(at),we(bt)}catch(T){Gn("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(T?.message||T||"")})}finally{wa("annotatedAttachmentSessions")}},[s,t,n,o,l,wa]),Lr=r.useCallback(()=>{aa.current=new Set([...Oe.current,...vt.current].map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),vn.current=new Map([...Oe.current,...vt.current].map(j=>[String(j?.id||"").trim(),Cs.getWatermark(j)]).filter(([j])=>j.length>0)),Sn.current=new Map([...Oe.current.map(j=>[String(j?.id||"").trim(),Cs.getChangeKey({...j,isArchived:!1})]),...vt.current.map(j=>[String(j?.id||"").trim(),Cs.getChangeKey({...j,isArchived:!0})])].filter(([j])=>j.length>0)),un.current=new Set(st.current.map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),Ua.current=new Map(st.current.map(j=>[String(j?.id||"").trim(),String(j?.updatedAt||j?.createdAt||"").trim()]).filter(([j])=>j.length>0)),sr.current=new Set(kt.current.map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),Na.current=new Map(kt.current.map(j=>[String(j?.id||"").trim(),String(j?.updatedAt||j?.createdAt||"").trim()]).filter(([j])=>j.length>0)),ka.current=new Set(tt.current.map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),Ln.current=new Map(tt.current.map(j=>[String(j?.id||"").trim(),md.getWatermark(j)]).filter(([j])=>j.length>0)),wn.current=new Map(tt.current.map(j=>[String(j?.id||"").trim(),md.getChangeKey(j)]).filter(([j])=>j.length>0)),va.current=new Set(Ye.current.map(j=>String(j?.path||"").trim()).filter(j=>j.length>0)),Yt.current=new Map(Ye.current.map(j=>[String(j?.path||"").trim(),String(j?.updatedAt||"").trim()]).filter(([j])=>j.length>0)),bn.current=new Set(te.current.map(j=>String(j?.path||"").trim()).filter(j=>j.length>0)),za.current=new Map(te.current.map(j=>[String(j?.path||"").trim(),String(j?.updatedAt||"").trim()]).filter(([j])=>j.length>0)),Pa.current=new Set($t.current.map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),Bn.current=new Map($t.current.map(j=>[String(j?.id||"").trim(),String(j?.updatedAt||j?.createdAt||"").trim()]).filter(([j])=>j.length>0)),Ma.current=new Set(yt.current.map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),Mr.current=new Map(yt.current.map(j=>[String(j?.id||"").trim(),String(j?.updatedAt||j?.createdAt||"").trim()]).filter(([j])=>j.length>0)),na.current=new Set(xe.current.map(j=>String(j?.id||"").trim()).filter(j=>j.length>0)),da.current=new Map(xe.current.map(j=>[String(j?.id||"").trim(),String(j?.updatedAt||j?.createdAt||"").trim()]).filter(([j])=>j.length>0)),Xa.current=new Map(Wu(Oe.current,vt.current,st.current,kt.current).map(j=>[String(j?.id||"").trim(),String(j?.createdAt||"").trim()]).filter(([j])=>j.length>0));const T=Zr();Ht.current=T?null:"storage-write-failed"},[Zr]),Br=r.useCallback(async()=>{const[T,j]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(T.ok){const at=await T.json().catch(()=>({})),bt=Array.isArray(at?.tasks)?at.tasks.map(ve=>Do(ve)):[];ke(bt)}if(j.ok){const at=await j.json().catch(()=>({})),bt=Array.isArray(at?.archived)?at.archived.map(ve=>({...Do(ve),isArchived:!0})):[];le(bt)}await ye().catch(()=>{Gn("refresh_planning_entities_failed",{workspaceId:t})})},[t,ye,le,ke]),{handleSyncAuthFailure:dr,ensureWorkspaceSyncReady:ur}=r.useMemo(()=>xw({currentWorkspaceId:t,workspaceSyncPhase:M,clearWorkspaceRetry:la,setWorkspaceSyncBusy:pe,setUserGlobalSyncStatus:_e,setUserGlobalSyncError:T=>oe(T),setWorkspaceLastErrorMessage:T=>R(T),setWorkspaceLastErrorAt:T=>x(T),reportSyncEvent:Sa,setAuthBlocked:O,setIsAuthenticated:A,checkAuthSession:de,ensureCloudWorkspaceReadyForSync:et,scheduleWorkspaceSyncRetry:ls,persistWorkspaceSyncPatchSafely:lr}),[t,M,la,Sa,O,A,de,et,ls,lr]),Fs=r.useMemo(()=>Uw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:t,workspaceSyncPhase:M,isAuthenticated:l,checkAuthSession:de,resolveCloudAuthUrl:m,ensureCloudWorkspaceReadyForSync:et,ensureWorkspaceSyncReady:ur,handleSyncAuthFailure:dr,clearWorkspaceRetry:la,clearWorkspaceIssue:cr,isWorkspaceRetryPending:Ta,scheduleWorkspaceSyncRetry:ls,persistWorkspaceSyncPatchSafely:lr,persistWorkspaceSyncPatchBestEffort:mn,persistWorkspaceSyncWatermarksSnapshotBestEffort:Zr,reportSyncEvent:Sa,acquireWorkspaceSyncLease:Ea,releaseWorkspaceSyncLease:ja,reportWorkspaceWindowContention:Wn,refreshWorkspaceSyncMarkdownDocumentsSnapshot:On,refreshWorkspaceSyncAiProfilesSnapshot:Tn,refreshWorkspaceSyncAssetsSnapshot:Gt,refreshWorkspaceSyncPlanningEntitiesSnapshot:$n,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:pn,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:La,refreshLocalWorkspaceTaskCollections:Br,buildWorkspaceSyncPayload:Aa,buildWorkspaceSyncSignature:In,seedWorkspaceSnapshotPushBaseline:Lr,shouldSuppressAttachBootstrapPush:Fn,recordSuppressedEventIds:(...T)=>so.current.recordSuppressedEventIds(...T),workspaceRepairModeRef:_n,workspaceForceFullAiProfilePushRef:Bt,workspacePushInFlightRef:Qa,workspacePullInFlightRef:Ra,workspacePendingPushReplayRef:ya,workspaceLastPushedSignatureRef:Zt,workspacePendingSignatureRef:Ka,workspaceLastPushedTaskIdsRef:aa,workspaceDeletedTaskIdsRef:ln,workspaceDeletedTaskWatermarksRef:yn,workspacePullCursorRef:Sr,workspaceLastPushedWatermarksRef:vn,workspaceLastPushedTaskChangeKeysRef:Sn,workspaceLastPushedInitiativeIdsRef:un,workspaceLastPushedInitiativeWatermarksRef:Ua,workspaceLastPushedWorkstreamIdsRef:sr,workspaceLastPushedWorkstreamWatermarksRef:Na,workspaceLastPushedAiProfileIdsRef:ka,workspaceLastPushedAiProfileWatermarksRef:Ln,workspaceLastPushedAiProfileChangeKeysRef:wn,workspaceLastPushedDocumentPathsRef:va,workspaceLastPushedDocumentWatermarksRef:Yt,workspaceLastPushedAssetPathsRef:bn,workspaceLastPushedAssetWatermarksRef:za,workspaceLastPushedDocumentReviewSessionIdsRef:Pa,workspaceLastPushedDocumentReviewSessionWatermarksRef:Bn,workspaceLastPushedDocumentReviewCommentIdsRef:Ma,workspaceLastPushedDocumentReviewCommentWatermarksRef:Mr,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:na,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:da,workspaceLastPushedTaskEventWatermarksRef:Xa,workspaceBaselineResetReasonRef:Ht,workspaceCaptureAttachBootstrapBaselineRef:Ar,workspaceStartupFullReconcileRanRef:Xt,workspaceFullReconcileInFlightRef:Da,bootstrapLastProgressAtRef:gt,realtimeSuppressedEventQueueRef:Ca,setWorkspaceSyncBusy:pe,setUserGlobalSyncStatus:_e,setUserGlobalSyncError:oe,setWorkspaceLastErrorMessage:R,setWorkspaceLastErrorAt:x,setWorkspaceLastPullAt:Ee,setWorkspaceLastPushAt:Pe,setWorkspaceSyncPendingChanges:ne,setTasks:ke,setArchivedTasks:le}),[n,s,F,t,M,V,l,de,m,et,ur,dr,la,cr,ls,lr,mn,Zr,Sa,Ea,ja,Wn,On,Tn,Gt,$n,pn,La,Br,Aa,In,Lr,Fn,ke,le]),{pushWorkspaceChangesToCloud:nn,pullWorkspaceChangesFromCloud:fn}=Fs,so=r.useRef({handleRealtimeSignal:()=>{},recordSuppressedEventIds:()=>{},clearRealtimePullDebounce:()=>{}}),Wr=r.useMemo(()=>Bw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,workspaceSyncPhase:M,workspacePullInFlightRef:Ra,realtimePullDebounceRef:pt,realtimeSuppressedEventIdsRef:wt,clearWorkspaceRetry:la,isWorkspaceRetryPending:Ta,pullWorkspaceChangesFromCloud:fn}),[n,s,F,M,la,Ta,fn]);so.current=Wr;const mr=y("/taskforce-ws"),W=String(i||"").trim(),It=Jg({enabled:!!(k&&n&&s==="local"&&F&&o&&l&&W&&W!=="anonymous"&&mr),workspaceId:t,websocketUrl:mr,onSignal:Wr.handleRealtimeSignal,onTelemetry:Pt,userId:W||void 0});r.useEffect(()=>{zt(It.connectionState)},[It.connectionState]),r.useEffect(()=>()=>Wr.clearRealtimePullDebounce(),[Wr]);const Mt=r.useCallback(async T=>dn(T,{cloudAuthConfigured:n,isAuthenticated:l,ensureCloudWorkspaceReadyForSync:et}),[dn,n,l,et]),Ha=r.useCallback(async()=>{await xn({preferCloudOnFirstSync:!1})},[xn]),Jn=r.useMemo(()=>Fw({currentWorkspaceId:t,workspaceCloudSyncEnabled:F,workspaceSyncPhase:M,workspaceLastPullAt:Ie,lastBootstrapPhaseRef:rr,workspaceRepairModeRef:_n,workspaceForceFullAiProfilePushRef:Bt,workspaceStartupRepairRanRef:Cr,workspaceStartupFullReconcileRanRef:Xt,workspaceFullReconcileInFlightRef:Da,workspacePullCursorRef:Sr,workspaceAttachBootstrapBaselineSignatureRef:Cn,workspaceCaptureAttachBootstrapBaselineRef:Ar,workspacePendingSignatureRef:Ka,workspaceLastPushedSignatureRef:Zt,workspaceLastPushedWatermarksRef:vn,workspaceLastPushedTaskChangeKeysRef:Sn,workspaceLastPushedInitiativeIdsRef:un,workspaceLastPushedInitiativeWatermarksRef:Ua,workspaceLastPushedWorkstreamIdsRef:sr,workspaceLastPushedWorkstreamWatermarksRef:Na,workspaceLastPushedAiProfileIdsRef:ka,workspaceLastPushedAiProfileWatermarksRef:Ln,workspaceLastPushedAiProfileChangeKeysRef:wn,workspaceLastPushedDocumentPathsRef:va,workspaceLastPushedDocumentWatermarksRef:Yt,workspaceLastPushedAssetPathsRef:bn,workspaceLastPushedAssetWatermarksRef:za,workspaceLastPushedDocumentReviewSessionIdsRef:Pa,workspaceLastPushedDocumentReviewSessionWatermarksRef:Bn,workspaceLastPushedDocumentReviewCommentIdsRef:Ma,workspaceLastPushedDocumentReviewCommentWatermarksRef:Mr,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:na,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:da,workspaceLastPushedTaskEventWatermarksRef:Xa,workspaceBaselineResetReasonRef:Ht,bootstrapPhaseStartedAtRef:Oa,bootstrapLastProgressAtRef:gt,acquireWorkspaceSyncLease:Ea,releaseWorkspaceSyncLease:ja,forceClearWorkspaceSyncLease:_r,clearWorkspaceRetry:la,clearWorkspaceIssue:cr,reportWorkspaceWindowContention:Wn,reportSyncEvent:Sa,persistWorkspaceSyncPatch:qr,persistWorkspaceSyncWatermarksSnapshotBestEffort:Zr,buildWorkspaceSyncSignature:In,pullWorkspaceChangesFromCloud:fn,pushWorkspaceChangesToCloud:nn,cloudAuthConfigured:n,runtimeMode:s,isAuthenticated:l,checkAuthSession:de}),[t,V,F,M,Ie,Ea,ja,_r,la,cr,Wn,Sa,qr,Zr,In,fn,nn,n,s,l,de]),{retryWorkspaceCloudSync:Yr,resetWorkspaceSyncCursorAndPull:Ba}=Jn,Fr=r.useCallback(()=>{const T=Hp({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:t,workspaceSyncPhase:M,isAuthenticated:l,repairModeActive:_n.current===!0,repairModeBypass:!1,pushInFlight:Qa.current,pullInFlight:Ra.current}),j=Ta(),at=Gp({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:t,workspaceSyncPhase:M,isAuthenticated:l,repairModeActive:_n.current===!0,repairModeBypass:!1,retryPending:j,pushInFlight:Qa.current,pullInFlight:Ra.current}),bt=Vp({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:t,isAuthenticated:l});return{workspaceId:t,enabled:F,phase:M,status:An,summary:Zn,lastSuccessfulSyncAt:ir,lastPullAt:Ie,lastPushAt:je,lastErrorAt:K,pendingChanges:z,lastErrorMessage:b,recommendedAction:tn,pushBlockedReason:T.allowed?null:T.reason,pullBlockedReason:at.allowed?null:at.reason,retryBlockedReason:bt.allowed?null:bt.reason,repairActive:_n.current===!0,pushInFlight:Qa.current===!0,pullInFlight:Ra.current===!0,retryPending:j,documentSnapshotCount:ie.length,aiProfileSnapshotCount:dt.length,aiProfileSnapshotRawCount:ht,aiProfileSnapshotLastFetchAt:ze,aiProfileSnapshotLastFetchError:it,aiProfileSnapshotLastSkipReason:Dt,assetSnapshotCount:Fe.length,documentReviewSessionSnapshotCount:At.length,documentReviewSessionSnapshotFingerprint:Wt,annotatedAttachmentSessionSnapshotCount:E.length,annotatedAttachmentSessionSnapshotFingerprint:J,lastPushedAiProfileCount:ka.current.size,lastPushedAiProfileWatermarkCount:Ln.current.size,forceFullAiProfilePushQueued:Bt.current===!0}},[n,t,s,F,M,l,An,Zn,ir,Ie,je,K,z,b,tn,ie.length,dt.length,ht,ze,it,Dt,Fe.length,At.length,Wt,E.length,J,Ta]);r.useEffect(()=>{ia.current=Yr},[Yr]);const Wa=r.useCallback(()=>{On(),Gt()},[On,Gt]);return r.useEffect(()=>{if(!n||s!=="local"||!F||!o||!l)return;On(),Tn(),Gt(),pn(),La();const T=jn=>{const hn=jn.detail;(String(hn?.workspaceId||"").trim()||"default")===t&&Wa()},j=jn=>{const hn=jn.detail;(String(hn?.workspaceId||"").trim()||"default")===t&&(Tn(),Gt())};window.addEventListener(Up,T),window.addEventListener(zp,j);const at=window.setInterval(()=>{On()},xr),bt=window.setInterval(()=>{Tn()},xr),ve=window.setInterval(()=>{Gt()},xr),ae=window.setInterval(()=>{pn()},xr),Rn=window.setInterval(()=>{La()},xr);return()=>{window.removeEventListener(Up,T),window.removeEventListener(zp,j),window.clearInterval(at),window.clearInterval(bt),window.clearInterval(ve),window.clearInterval(ae),window.clearInterval(Rn)}},[n,s,F,o,l,t,Wa,On,Tn,Gt,pn,La,xr]),r.useEffect(()=>{!n||s!=="local"||!F||!o||!l||ds&&Wa()},[n,s,F,o,l,ds,Wa]),r.useEffect(()=>{if(!Pw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,workspaceSyncPhase:M,workspaceSyncReferenceSnapshotsReady:Kt}))return;const T=In();if(Fn(T)||!T||T===Zt.current)return;const j=Aa();if(ne(j.changes.length),Qa.current||Ra.current){Ka.current=T;return}const at=window.setTimeout(()=>{nn(T)},1500);return()=>window.clearTimeout(at)},[n,s,F,o,M,Kt,In,Fn,Aa,Yn,Rt,Te,St,Wt,J,nn,Qa,Ra]),r.useEffect(()=>{if(!Mw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,workspaceSyncPhase:M,workspaceSyncReferenceSnapshotsReady:Kt}))return;const T=window.setInterval(()=>{if(Qa.current||Ra.current||Ta())return;const j=Ka.current||In();if(!j||j===Zt.current)return;const at=Aa();ne(at.changes.length),at.changes.length!==0&&nn(j)},Kn);return()=>window.clearInterval(T)},[n,s,F,o,M,Kt,In,Aa,nn,Ta,Kn]),r.useEffect(()=>{n&&s==="local"&&F||(la(),pe(!1))},[n,s,F,la]),r.useEffect(()=>{const T=Ew({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,workspaceSyncPhase:M,lastPullAt:Ie,retryPending:Ta()});if(!T.shouldStart)return;T.shouldKickOffImmediately&&fn();const j=window.setInterval(()=>{fn()},qn);return()=>{window.clearInterval(j)}},[n,s,F,o,M,Ie,Ta,fn,qn]),r.useEffect(()=>{if(!Dw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,isAuthenticated:l,workspaceSyncPhase:M}))return;const T=window.setInterval(()=>{Da.current||(Da.current=!0,fn({forceCursorNull:!0}).finally(()=>{Da.current=!1}))},Sw);return()=>window.clearInterval(T)},[n,s,F,o,l,M,fn]),r.useEffect(()=>{s!=="local"||!l||!i||i==="anonymous"||xn({preferCloudOnFirstSync:!0})},[s,l,i,xn]),r.useEffect(()=>{if(s!=="local"||!l||!i||i==="anonymous"||!Ga.current.has(i)||Vt.current)return;const T=Kr(),j=JSON.stringify(T);if(!Va.current){Va.current=j;return}if(j===Va.current)return;Va.current=j,Za(i,new Date().toISOString());const at=window.setTimeout(()=>{xn({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(at)},[s,l,i,Kr,Za,xn]),r.useEffect(()=>{Lw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,isAuthenticated:l,workspaceSyncPhase:M,alreadyRan:Cr.current})&&(Cr.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 j=await T.json().catch(()=>({}));j?.applied>0&&(Gn("startup_repair_applied",{workspaceId:t,applied:j.applied,skipped:j.skipped,failed:j.failed}),On(),Tn(),Gt(),pn())}).catch(()=>{}))},[n,s,F,o,l,M,t,On,Tn,Gt,pn]),{userGlobalSyncStatus:Me,setUserGlobalSyncStatus:_e,userGlobalSyncError:re,setUserGlobalSyncError:oe,workspaceLastPullAt:Ie,workspaceLastPushAt:je,workspaceLastErrorAt:K,workspaceLastErrorMessage:b,workspaceLastSuccessfulSyncAt:ir,workspaceCloudSyncEnabled:F,workspaceSyncPhase:M,workspaceSyncSetupIntent:be,workspaceSyncStatus:An,workspaceSyncSummary:Zn,workspaceSyncRecommendedAction:tn,workspaceSyncBusy:se,workspaceSyncPendingChanges:z,syncInFlightRef:Nt,workspaceRetryAt:vr,isWorkspaceRetryPending:Ta,workspacePushInFlightRef:Qa,workspacePullInFlightRef:Ra,workspaceLastPushedSignatureRef:Zt,workspacePendingSignatureRef:Ka,workspaceLastPushedTaskIdsRef:aa,workspaceDeletedTaskIdsRef:ln,workspaceDeletedTaskWatermarksRef:yn,workspacePullCursorRef:Sr,clearWorkspaceRetry:la,persistWorkspaceSyncPatch:qr,loadWorkspaceSyncState:$a,applyWorkspaceSyncStateSnapshot:xt,syncUserGlobalSettings:xn,buildWorkspaceSyncSignature:In,pushWorkspaceChangesToCloud:nn,pullWorkspaceChangesFromCloud:fn,saveWorkspaceCloudSyncSettings:Mt,retryUserGlobalSettingsSync:Ha,retryWorkspaceCloudSync:Yr,resetWorkspaceSyncCursorAndPull:Ba,getWorkspaceSyncDiagnostics:Fr}}function Hw(e,t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e==="error"?3600:2600}function Gw(){const[e,t]=r.useState(null),n=r.useRef(null),s=r.useCallback(()=>{n.current!==null&&(window.clearTimeout(n.current),n.current=null),t(null)},[]),o=r.useCallback((l,i="info",d)=>{if(!l)return;n.current!==null&&(window.clearTimeout(n.current),n.current=null),t({message:l,tone:i,ttlMs:d});const m=Hw(i,d);n.current=window.setTimeout(()=>{n.current=null,t(null)},m)},[]);return r.useEffect(()=>()=>{n.current!==null&&(window.clearTimeout(n.current),n.current=null)},[]),{uiNotice:e,pushNotice:o,clearNotice:s}}function Vw({storagePath:e,shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:n}){const[s,o]=r.useState("antigravity"),[l,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||n;r.useEffect(()=>{const D=l.find(q=>q.id===s);D&&m(D.directory)},[s,l]);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 q=await D.json().catch(()=>({}));q.environments&&i(q.environments)},[v]),C=r.useCallback(async(D,q)=>{k("workflows"),h(null);try{const X=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:D,workflowNames:q,variables:{STORAGE_PATH:e.replace(/\/$/,"")||".Taskforce"}})})).json();X.success?h({type:"success",message:`Successfully exported ${X.count} workflows to ${D}`}):h({type:"error",message:X.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:l,loadAvailableEnvironments:I,exportWorkflowsPath:d,setExportWorkflowsPath:m,exportingResource:y,exportResult:S,handleExportWorkflows:C}}function qw(e){const{resolveCloudAuthUrl:t,currentWorkspaceId:n,normalizedCloudAuthBaseUrl:s,normalizedCloudMcpBaseUrl:o,mergedConfig:l,availableWorkspaces:i,currentTheme:d,configLoaded:m,globalTheme:y,themeUseGlobalDefault:k,keyShortcut:S,jsonBackupEnabled:h,globalJsonBackupEnabled:g,globalWeekStartsOn:v,locale:_,supportedLocales:I,jsonBackupUseGlobalDefault:C,manualComplexityEnabled:D,checklistDropdownEnabled:q,showTaskCardStatusLabel:B,exportWorkflowsPath:X,exportingResource:me,exportResult:ke,pathSaved:le,settingsSection:O,exportEnvironment:A,setupState:de,buildInfo:ge,saveSetupMode:Y,saveWorkspaceProfile:P,setCurrentTheme:H,handleSaveTheme:ue,handleSaveGlobalTheme:ye,setKeyShortcut:V,handleJsonBackupEnabledChange:Me,handleSaveGlobalJsonBackupEnabled:_e,handleSaveGlobalWeekStartsOn:re,handleSaveLocale:oe,handleManualComplexityEnabledChange:Ie,handleChecklistDropdownEnabledChange:Ee,handleShowTaskCardStatusLabelChange:je,handleResetProjectToGlobal:Pe,handleSaveSettings:K,setExportWorkflowsPath:x,setExportEnvironment:b,availableWorkflows:R,initiativeTemplates:F,availableEnvironments:Q,fetchWorkflows:M,fetchInitiativeTemplates:$,createInitiativeFromTemplate:be,fetchWorkflowTemplate:U,fetchWorkflowOverrideNames:se,saveWorkflowTemplateDraft:pe,resetWorkflowTemplateDraft:z,handleExportWorkflows:ne,setShowFolderBrowser:ie,setBrowserTarget:Re,fetchFolders:Te,activeCategories:De,pathValidation:Oe,taxonomyDisplayLabels:vt,handleUpdateCategory:st,handleRemoveCategory:kt,handleSaveCategory:Ye,handleAddPath:Ct,handleRemovePath:dt,handleUpdateCategoryIcon:Qe,handleUpdateCategoryColor:Rt,activeTypes:ee,handleSaveType:ze,handleRemoveType:ft,handleUpdateType:it,taxonomies:Et,handleUpdateTaxonomies:ht,priorities:Ot,handleUpdatePriorities:Dt,analyzeSystemTaxonomyPack:We,handleApplySystemTaxonomyPack:tt,handleUpdateTaxonomyDisplayLabels:Fe,projectRoot:Ze,projectName:St,mcpHostRoot:ot,serverHostRoot:te,mcpScriptPath:Le,tenantId:At,runtimeMode:jt,workspaceSwitchingEnabled:Wt,deleteWorkspace:Ge,setMcpHostRoot:$t,isAuthenticated:yt}=e,E=r.useCallback(async(J,we)=>{const xe=t(J),Ke=new Headers(we?.headers||void 0);if(J.startsWith("/api/taskforce/settings/mcp/")){const Ne=String(n||"").trim();Ne&&Ne!=="default"&&!Ke.has("x-taskforce-workspace-id")&&Ke.set("x-taskforce-workspace-id",Ne)}const Je={...we,headers:Ke,credentials:we?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(xe))try{new URL(xe,window.location.origin).origin!==window.location.origin&&Je.mode===void 0&&(Je.mode="cors")}catch{}return fetch(xe,Je)},[n,t]),c=i.find(J=>J.id===n);return{fetchCloudAuthApi:E,currentTheme:d,configLoaded:m,globalTheme:y,themeUseGlobalDefault:k,keyShortcut:S,jsonBackupEnabled:h,globalJsonBackupEnabled:g,globalWeekStartsOn:v,locale:_,supportedLocales:I,jsonBackupUseGlobalDefault:C,manualComplexityEnabled:D,checklistDropdownEnabled:q,showTaskCardStatusLabel:B,exportWorkflowsPath:X,exportingResource:me,exportResult:ke,pathSaved:le,initialSection:O,exportEnvironment:A,setupState:de,buildInfo:ge,onSaveSetupMode:Y,onSaveWorkspaceProfile:P,onThemeChange:H,onSaveTheme:ue,onSaveGlobalTheme:ye,onKeyShortcutChange:V,onJsonBackupEnabledChange:Me,onSaveGlobalJsonBackupEnabled:_e,onSaveGlobalWeekStartsOn:re,onSaveLocale:oe,onManualComplexityEnabledChange:Ie,onChecklistDropdownEnabledChange:Ee,onShowTaskCardStatusLabelChange:je,onResetProjectToGlobal:Pe,onSaveSettings:K,onExportWorkflowsPathChange:x,onExportEnvironmentChange:b,availableWorkflows:R,initiativeTemplates:F,availableEnvironments:Q,onRefreshWorkflows:M,onRefreshInitiativeTemplates:$,onCreateInitiativeFromTemplate:be,onFetchWorkflowTemplate:U,onFetchWorkflowOverrideNames:se,onSaveWorkflowTemplateDraft:pe,onResetWorkflowTemplateDraft:z,onExportWorkflows:ne,onShowFolderBrowserChange:ie,onBrowserTargetChange:Re,onFetchFolders:Te,categories:De,pathValidation:Oe,taxonomyDisplayLabels:vt,onUpdateCategory:st,onRemoveCategory:kt,onSaveCategory:Ye,onAddPath:Ct,onRemovePath:dt,onUpdateCategoryIcon:Qe,onUpdateCategoryColor:Rt,types:ee,onSaveType:ze,onRemoveType:ft,onUpdateType:it,taxonomies:Et,onUpdateTaxonomies:ht,priorities:Ot,onUpdatePriorities:Dt,onAnalyzeSystemTaxonomyPack:We,onApplySystemTaxonomyPack:tt,onUpdateTaxonomyDisplayLabels:Fe,projectRoot:Ze,projectName:St,mcpHostRoot:ot,serverHostRoot:te,mcpScriptPath:Le,tenantId:At,workspaceId:n,runtimeMode:jt,cloudAuthBaseUrl:s||l.cloudAuthBaseUrl,cloudMcpBaseUrl:o||void 0,workspaceSwitchingEnabled:Wt,currentWorkspaceRole:c?.role||"member",currentWorkspaceName:String(c?.name||""),onDeleteWorkspace:Ge,onMcpHostRootChange:$t,isAuthenticated:yt}}function Kw(e){const{keyShortcut:t,themeUseGlobalDefault:n,runtimeMode:s,jsonBackupUseGlobalDefault:o,globalTheme:l,globalJsonBackupEnabled:i,setCurrentTheme:d,setThemeUseGlobalDefault:m,setGlobalTheme:y,setJsonBackupEnabled:k,setJsonBackupUseGlobalDefault:S,setGlobalJsonBackupEnabled:h,setGlobalWeekStartsOn:g,setLocale:v,setManualComplexityEnabled:_,setChecklistDropdownEnabled:I,setShowTaskCardStatusLabel:C,setShowChecklist:D}=e,q=r.useCallback(async()=>{try{const P=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:t})});if(!P.ok)throw new Error(`Failed to save global settings (${P.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[t]),B=r.useCallback(async P=>{d(P),m(!1);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:P})});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]),X=r.useCallback(async P=>{y(P),n&&d(P);try{const H=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:P})});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,n,d]),me=r.useCallback(async P=>{if(s==="cloud")return k(!1),S(!1),!1;k(P),S(!1);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:P})});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]),ke=r.useCallback(async P=>{if(s==="cloud")return h(!1),o&&k(!1),!1;h(P),o&&k(P);try{const H=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:P})});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]),le=r.useCallback(async P=>{g(P);try{const H=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:P}})});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]),O=r.useCallback(async P=>{const H=Lg(P);return v(H),!0},[v]),A=r.useCallback(async P=>{_(P);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:P})});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 P=>{I(P),P||D(!1);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:P})});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]),ge=r.useCallback(async P=>{C(P);try{const H=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:P})});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}},[C]),Y=r.useCallback(async()=>{m(!0),S(!0),d(l),k(i),_(!1),I(!0),C(!0),D(!1);try{const P=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(!P.ok)throw new Error(`Failed to save config (${P.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[m,S,d,l,k,i,_,I,C,D]);return{handleSaveSettings:q,handleSaveTheme:B,handleSaveGlobalTheme:X,handleJsonBackupEnabledChange:me,handleSaveGlobalJsonBackupEnabled:ke,handleSaveGlobalWeekStartsOn:le,handleSaveLocale:O,handleManualComplexityEnabledChange:A,handleChecklistDropdownEnabledChange:de,handleShowTaskCardStatusLabelChange:ge,handleResetProjectToGlobal:Y}}function Zw(e){const{activeCategories:t,activeTab:n,activeTypes:s,archivedTasks:o,browserTarget:l,category:i,configLoaded:d,customCategories:m,refreshTaskCollections:y,fetchTasks:k,filterCategories:S,getCategoryPaths:h,normalizePath:g,pathValidation:v,setBrowserTarget:_,setCategory:I,setCustomCategories:C,setCustomTypes:D,setFilterCategories:q,setPathValidation:B,setPriorities:X,setShowFolderBrowser:me,setTaxonomies:ke,tasks:le}=e,O=r.useCallback(async(x,b)=>{const R=await x.json().catch(()=>({}));return String(R?.error||b)},[]),A=r.useCallback(()=>[...le,...o],[o,le]),de=r.useCallback(x=>x.priorities.find(b=>b.value===2)?.value||x.priorities[0]?.value||2,[]),ge=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();B(F=>({...F,...R.results}))}}catch(b){console.error("[Taskforce] Failed to validate paths:",b)}},[B]);r.useEffect(()=>{if(n!=="settings"||!d)return;const x=[];t.forEach(R=>{h(R).forEach(Q=>{x.includes(Q)||x.push(Q)})});const b=x.filter(R=>!v[R]);b.length>0&&ge(b)},[t,n,d,h,v,ge]);const Y=r.useCallback(async(x,b)=>{if(d){C(R=>(R.length>0?R:t).map(Q=>Q.value===x.value?x:Q)),b&&b!==x.label&&(i===b&&I(x.label),S.includes(b)&&q(R=>R.map(F=>F===b?x.label:F)));try{const Q={categories:(m.length>0?m:t).map(M=>M.value===x.value?x:M)};b&&b!==x.label&&(Q.reassignFrom=b,Q.reassignTo=x.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)}),b&&await k()}catch(R){console.error("[Taskforce] Failed to update category",R)}}},[t,i,d,m,k,S,I,C,q]),P=r.useCallback(async x=>{if(!d)return;const b=x.trim().toLowerCase().replace(/\s+/g,"-");if(t.some(F=>F.value===b))return;const R={value:b,label:x.trim(),color:"blue-200",icon:"Folder"};C(F=>[...F.length>0?F:t,R]);try{const Q=[...m.length>0?m:t,R];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:Q})})}catch(F){console.error("[Taskforce] Failed to create category",F)}},[t,d,m,C]),H=r.useCallback((x,b)=>{if(!b.trim())return;const R=t.find($=>$.value===x);if(!R)return;const F=h(R),Q=b.trim();if(F.includes(Q))return;const M=[...F,Q];Y({...R,path:void 0,paths:M}),ge(M)},[t,h,Y,ge]),ue=r.useCallback((x,b)=>{const R=t.find(F=>F.value===x);R&&Y({...R,icon:b})},[t,Y]),ye=r.useCallback((x,b)=>{const R=t.find(F=>F.value===x);R&&Y({...R,color:b})},[t,Y]),V=r.useCallback((x,b)=>{const R=t.find(M=>M.value===x);if(!R)return;const Q=h(R).filter(M=>M!==b);Y({...R,path:void 0,paths:Q})},[t,h,Y]),Me=r.useCallback(x=>{const b=g(x);if(l&&typeof l=="object"&&l.type==="category"){const R=t.find(F=>F.value===l.value);if(R){const F=h(R);if(!F.includes(b)){const Q=[...F,b];Y({...R,path:void 0,paths:Q})}}}me(!1),_(null)},[t,l,h,Y,g,_,me]),_e=r.useCallback(async x=>{if(!d)return;const b=Qc,R=t.find($=>$.value===b),F=R?{...R}:{value:b,label:Cm,icon:"Inbox"},Q=F.label,M=t.find($=>$.value===x);C($=>{let U=($.length>0?$:t).filter(se=>se.value!==x);return U.some(se=>se.value===b)||(U=[F,...U]),U}),M&&((i===M.label||i===M.value)&&I(b),(S.includes(M.label)||S.includes(M.value))&&q($=>{const be=$.filter(U=>U!==M.label&&U!==M.value);return be.includes(b)?be:[...be,b]}));try{let $=(m.length>0?m:t).filter(be=>be.value!==x);$.some(be=>be.value===b)||($=[F,...$]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:$,reassignFrom:M?.label||x,reassignTo:Q})}),await k()}catch($){console.error("[Taskforce] Failed to remove category",$)}},[t,i,d,m,k,S,I,C,q]),re=r.useCallback(async x=>{if(!x.trim())return;const b=x.trim().toLowerCase().replace(/\s+/g,"-");if(s.some(F=>F.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(F){console.error("Failed to save type",F)}},[s,D]),oe=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]),Ie=r.useCallback(async(x,b)=>{const R=s.find($=>$.value===x);if(!R)return;const F=typeof b.label=="string"?b.label.trim():R.label;if(!F)return;const Q=s.map($=>$.value===x?{...$,...b,label:F}:$);if(JSON.stringify(Q)!==JSON.stringify(s)){D(Q);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:Q})})}catch($){console.error("Failed to update type",$)}}},[s,D]),Ee=r.useCallback(async x=>{if(d){ke(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,ke]),je=r.useCallback(async x=>{if(d){X(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,X]),Pe=r.useCallback(x=>{const b=A(),R=new Set(x.categories.map(U=>U.value)),F=new Set(x.types.map(U=>U.value)),Q=new Set(x.priorities.map(U=>Number(U.value))),M=Array.from(new Set(b.map(U=>String(U.category||"").trim()).filter(U=>U.length>0&&!R.has(U)))).sort(),$=Array.from(new Set(b.map(U=>String(U.type||"").trim()).filter(U=>U.length>0&&!F.has(U)))).sort(),be=Array.from(new Set(b.map(U=>Number(U.priority)).filter(U=>Number.isFinite(U)&&U>0&&!Q.has(U)))).sort((U,se)=>U-se);return{unmatchedCategoryValues:M,unmatchedTypeValues:$,incompatiblePriorityValues:be}},[A]),K=r.useCallback(async x=>{if(!d)return{success:!1,error:"Settings are still loading."};const{pack:b,sections:R,remapExistingValuesToDefault:F,workspaceIdOverride:Q}=x,M=String(Q||"").trim(),$=M.length>0,be=$?[]:A(),U=pe=>{if(!M)return pe;const z=pe.includes("?")?"&":"?";return`${pe}${z}workspaceId=${encodeURIComponent(M)}`},se=()=>{const pe={"Content-Type":"application/json"};return M&&(pe["x-taskforce-workspace-id"]=M),pe};try{if(R.categories){const pe=new Set(b.categories.map(ie=>ie.value)),z=F?[...b.categories]:[...b.categories,...t.filter(ie=>!pe.has(ie.value)).map(ie=>({...ie,disabled:!0}))];$||C(z);const ne=await fetch(U("/api/taskforce/categories"),{method:"POST",headers:se(),body:JSON.stringify({categories:z})});if(!ne.ok)return{success:!1,error:await O(ne,"Failed to apply category library pack.")}}if(R.types){const pe=new Set(b.types.map(Re=>Re.value)),z=b.types.find(Re=>Re.value===Vr)?.value||b.types[0]?.value||Vr;if(F){const Re=be.filter(Te=>Te.type&&!pe.has(String(Te.type))).map(Te=>({id:Te.id,type:z}));if(Re.length>0){const Te=await fetch(U("/api/taskforce/bulk-update-fields"),{method:"POST",headers:se(),body:JSON.stringify({updates:Re})});if(!Te.ok)return{success:!1,error:await O(Te,"Failed to remap task types to the pack default.")}}}const ne=F?[...b.types]:[...b.types,...s.filter(Re=>!pe.has(Re.value)).map(Re=>({...Re,status:"retired"}))];$||D(ne);const ie=await fetch(U("/api/taskforce/types"),{method:"POST",headers:se(),body:JSON.stringify({types:ne})});if(!ie.ok)return{success:!1,error:await O(ie,"Failed to apply task type library pack.")}}if(R.priorities){const pe=new Set(b.priorities.map(Re=>Re.value)),z=Array.from(new Set(be.map(Re=>Number(Re.priority)).filter(Re=>Number.isFinite(Re)&&Re>0&&!pe.has(Re)))).sort((Re,Te)=>Re-Te);if(z.length>0&&!F)return{success:!1,error:`This workspace still uses priority levels ${z.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(z.length>0){const Re=de(b),Te=be.filter(De=>z.includes(Number(De.priority))).map(De=>({id:De.id,priority:Re}));if(Te.length>0){const De=await fetch(U("/api/taskforce/bulk-update-fields"),{method:"POST",headers:se(),body:JSON.stringify({updates:Te})});if(!De.ok)return{success:!1,error:await O(De,"Failed to remap task priorities to the pack default.")}}}const ne=b.priorities.map(Re=>({...Re,value:Number(Re.value)}));$||X(ne);const ie=await fetch(U("/api/taskforce/priorities"),{method:"POST",headers:se(),body:JSON.stringify({priorities:ne})});if(!ie.ok)return{success:!1,error:await O(ie,"Failed to apply priority library pack.")}}return $||await y({isSilent:!0}),{success:!0}}catch(pe){return console.error("[Taskforce] Failed to apply system taxonomy pack",pe),{success:!1,error:pe instanceof Error?pe.message:"Failed to apply system taxonomy pack."}}},[t,s,d,A,de,O,y,C,D,X]);return{getCategoryPaths:h,validatePaths:ge,handleUpdateCategory:Y,handleSaveCategory:P,handleAddPath:H,handleUpdateCategoryIcon:ue,handleUpdateCategoryColor:ye,handleRemovePath:V,handleSelectPath:Me,handleRemoveCategory:_e,handleSaveType:re,handleRemoveType:oe,handleUpdateType:Ie,handleUpdateTaxonomies:Ee,handleUpdatePriorities:je,analyzeSystemTaxonomyPack:Pe,handleApplySystemTaxonomyPack:K}}function Yw({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:t}){const[n,s]=r.useState([]),[o,l]=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 l(_),_}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 C=await I.json();if(C?.template)return C.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:n,initiativeTemplates:o,fetchWorkflows:d,fetchInitiativeTemplates:m,fetchWorkflowTemplate:y,fetchWorkflowOverrideNames:k,saveWorkflowTemplateDraft:S,resetWorkflowTemplateDraft:h}}function Jw(){const[e,t]=r.useState(!1),n=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:n}}async function Qw(e,t,n){if(e.current){t.current=!0;return}e.current=!0;try{do t.current=!1,await n();while(t.current)}finally{e.current=!1}}function Xw({tasks:e,archivedTasks:t,setTasks:n,setArchivedTasks:s,setLoadingTasks:o,getCurrentWorkspaceId:l,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),C=r.useRef(null),D=r.useRef(null);r.useEffect(()=>{g.current=e},[e]),r.useEffect(()=>{v.current=t},[t]);const q=r.useCallback(P=>`${P.updatedAt||P.createdAt||""}|${P.status}|${P.priority}|${P.title}`,[]),B=r.useCallback((P,H)=>H.aborted?P===H.reason?!0:P instanceof DOMException?P.name==="AbortError":String(P?.name||"").toLowerCase()==="aborterror":!1,[]),[X,me]=r.useState([]),ke=r.useRef(new Map),le=r.useCallback(P=>{!P.length||typeof window>"u"||(me(H=>Array.from(new Set([...H,...P]))),P.forEach(H=>{const ue=ke.current.get(H);ue&&window.clearTimeout(ue);const ye=window.setTimeout(()=>{ke.current.delete(H),me(V=>V.filter(Me=>Me!==H))},4e3);ke.current.set(H,ye)}))},[]);r.useEffect(()=>()=>{typeof window>"u"||(ke.current.forEach(P=>window.clearTimeout(P)),ke.current.clear())},[]),r.useEffect(()=>{S.current=new Map,h.current=!1,_.current=!1,I.current=!1,C.current?.abort("workspace-reset"),C.current=null,D.current?.abort("workspace-reset"),D.current=null,typeof window<"u"&&(ke.current.forEach(P=>window.clearTimeout(P)),ke.current.clear()),me([])},[i]);const O=r.useCallback(async(P=!1,H)=>{if(!(H?.ignoreAuthGuard===!0)&&(d||m))return;o(!P);const ye=String(l()||"").trim();C.current?.abort("superseded");const V=new AbortController;C.current=V;try{const Me=await fetch("/api/taskforce/tasks",{signal:V.signal});if(Me.status===401){y(),n([]),P||o(!1);return}if(Me.ok){const re=((await Me.json()).tasks||[]).map(je=>Do(je));if(String(l()||"").trim()!==ye)return;const Ie=new Map,Ee=[];for(const je of re){const Pe=q(je);if(Ie.set(je.id,Pe),!h.current)continue;const K=S.current.get(je.id);(!K||K!==Pe)&&Ee.push(je.id)}S.current=Ie,h.current?le(Ee):h.current=!0,n(re)}}catch(Me){if(B(Me,V.signal))return;console.error("[Taskforce] Failed to fetch tasks:",Me)}finally{C.current===V&&(C.current=null,o(!1))}},[q,l,le,y,n,o,k,d,m]),A=r.useCallback(async(P=!1,H)=>{if(!(H?.ignoreAuthGuard===!0)&&(d||m))return;const ye=String(l()||"").trim();D.current?.abort("superseded");const V=new AbortController;D.current=V;try{const Me=await fetch("/api/taskforce/archive",{signal:V.signal});if(Me.ok){const _e=await Me.json();if(String(l()||"").trim()!==ye)return;const oe=(_e.archived||[]).map(Ie=>({...Do(Ie),isArchived:!0}));s(oe)}}catch(Me){if(B(Me,V.signal))return;console.error("[Taskforce] Failed to fetch archive:",Me)}finally{D.current===V&&(D.current=null)}},[l,B,s,d,m]),de=r.useCallback(async P=>{const H=P?.isSilent!==!1,ue=P?.ignoreAuthGuard===!0;await Promise.all([O(H,{ignoreAuthGuard:ue}),A(H,{ignoreAuthGuard:ue})])},[A,O]),ge=r.useCallback(async()=>{await Qw(_,I,async()=>{await de({isSilent:!0})})},[de]),Y=r.useCallback(P=>{const H=Lv(P,g.current,v.current);g.current=H.tasks,v.current=H.archivedTasks,n(H.tasks),s(H.archivedTasks)},[n,s]);return{tasksRef:g,archivedTasksRef:v,recentlyChangedTaskIds:X,markRecentlyChangedTasks:le,fetchTasks:O,fetchArchive:A,refreshTaskCollections:de,refreshTaskCollectionsFromInvalidation:ge,mergeTaskFromServer:Y,getTaskRevisionKey:q}}function eb(e){const{editingTaskId:t,relationshipTasks:n,initiatives:s=[],workstreams:o=[],supplementalTasks:l=[],setComments:i}=e,d=r.useMemo(()=>{if(l.length===0)return n;const S=new Map;return n.forEach(h=>S.set(h.id,h)),l.forEach(h=>S.set(h.id,h)),Array.from(S.values())},[n,l]),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 vf="WS-",Sf="IN-";function Eo(e){return el(vf,e)}function ny(e){return of(vf,e)}function um(e){return Am(vf,e)}function os(e){return el(Sf,e)}function tb(e){return of(Sf,e)}function ry(e){return Am(Sf,e)}function vp(e,t){const n=String(t||"").trim();if(!n)return null;const s=tb(n);return e.find(o=>o.id===n||os(o)===n||s!==null&&o.referenceNumber===s)||null}function ab(e){const t={};return e.forEach(n=>{const s=n.defaultValue;if(s!=null){if(Array.isArray(s)){s.length>0&&(t[n.id]=s.map(o=>typeof o=="number"?o:String(o)));return}t[n.id]=typeof s=="number"?s:String(s)}}),t}function nb(e,t){return e.filter(n=>{const s=t[n.id],o=Array.isArray(s)?s.length>0:s!=null&&s!=="";return n.status==="retired"&&!o?!1:n.formEnabled!==!1||n.isRequired===!0||o})}function rb(e){const{activeCategories:t,activeTypes:n,activeTab:s,attachments:o,checklistItems:l,comments:i,description:d,editingTaskId:m,flushPendingAutoSave:y,getPreferredCategoryValue:k,lastUsedCategory:S,newCommentText:h,relationshipTasks:g,workstreams:v,showArchive:_,taxonomies:I,setActiveTab:C,setApproach:D,setAssignee:q,setAttachments:B,setAttachmentsDirty:X,setCategory:me,setChecklistItems:ke,setComments:le,setComplexity:O,setDescription:A,setDueDate:de,setEditingTaskId:ge,setError:Y,setFormTaxonomies:P,setIsOpen:H,setNewCommentText:ue,setPendingNavigation:ye,setWorkstreamInput:V,setPriority:Me,setScheduledDate:_e,setShowArchive:re,setStatus:oe,setTaskReturnTrail:Ie,setTitle:Ee,setType:je,setUnsavedModalOpen:Pe,taskReturnTrail:K,title:x}=e,b=r.useCallback(()=>n.find(z=>String(z.value||"").trim().length>0)?.value||Vr,[n]),R=r.useCallback(z=>{if(m){y(),z();return}if(!(x.trim()!==""||d.trim()!==""||l.length>0||h.trim()!==""||i.length>0||o.length>0)){z();return}ye(()=>z),Pe(!0)},[o,i.length,d,m,y,l,h,ye,Pe,x]),F=r.useCallback(()=>{H(!1)},[H]),Q=r.useCallback(()=>{ge(null),Ee(""),A("");const z=S,ne=t.some(ie=>ie.label===z||ie.value===z);if(z&&ne){const ie=t.find(Re=>Re.label===z||Re.value===z);me(ie?.value||z)}else me(k(t));je(b()),Me(2),O(3),oe("task"),D("default"),q("unassigned"),_e(""),de(""),V(""),ke([]),P(ab(I)),le([]),ue(""),B([]),X(!1),Y("")},[t,k,b,S,D,q,B,X,me,ke,le,O,A,de,ge,Y,P,ue,Me,_e,oe,Ee,je,I]),M=r.useCallback(z=>{const ne=z.trim();if(!ne)return null;const ie=jg(ne);if(ie){const De=g.find(Oe=>Oe.referenceNumber===ie);if(De)return De}const Re=g.find(De=>De.id===ne);if(Re)return Re;const Te=g.find(De=>Xi(De)===ne);return Te||null},[g]),$=r.useCallback(z=>{const ne=z.trim();if(!ne)return null;const ie=ne.toLowerCase(),Re=ny(ne);if(Re){const Oe=v.find(vt=>vt.referenceNumber===Re);if(Oe)return Oe}const Te=v.find(Oe=>Oe.id===ne);if(Te)return Te;const De=v.find(Oe=>Oe.title.trim().toLowerCase()===ie);return De||null},[v]),be=r.useCallback((z,ne)=>{ne?.preserveReturnTrail||Ie([]),ge(z.id),Ee(z.title),A(z.description||""),me(z.category||k(t)),je(z.type||b()),Me(typeof z.priority=="number"?z.priority:2),O(typeof z.complexity=="number"?z.complexity:3),oe(z.status||"task"),D(z.approach||"default"),q(z.assignee||"unassigned"),_e(z.scheduledDate||""),de(z.dueDate||"");const ie=z.workstreamId&&v.find(Re=>Re.id===z.workstreamId)||null;V(ie?Eo(ie)||ie.id:""),ke(z.checklistItems||[]),le(z.comments||[]),P(z.taxonomies||{}),z.taxonomies?.approach&&D(z.taxonomies.approach),B(z.attachments||[]),X(!1),C("add")},[t,k,b,C,D,q,B,X,me,ke,le,O,A,de,ge,P,Me,_e,oe,Ie,Ee,je,v]),U=r.useCallback(z=>{const ne=g.find(ie=>ie.id===z);ne&&(s==="add"&&m&&m!==ne.id&&Ie(ie=>ie[ie.length-1]===m?ie:[...ie,m]),ne.isArchived&&!_&&re(!0),be(ne,{preserveReturnTrail:!0}))},[s,m,be,g,re,Ie,_]),se=r.useCallback(()=>{if(s!=="add"||!m||K.length===0)return!1;const z=[...K];for(;z.length>0;){const ne=z.pop();if(!ne)continue;const ie=g.find(Re=>Re.id===ne);if(ie)return ie.isArchived&&!_&&re(!0),Ie(z),be(ie,{preserveReturnTrail:!0}),!0}return Ie([]),!1},[s,m,be,g,re,Ie,_,K]),pe=r.useCallback(()=>{Ie([])},[Ie]);return{handleNavigation:R,handleClose:F,resetForm:Q,resolveTaskIdInput:M,resolveWorkstreamIdInput:$,handleEdit:be,handleOpenTaskById:U,returnToPreviousTask:se,clearReturnToParentTask:pe}}function sb(e){return e.map(t=>({...t}))}function ob(e){return e.map(t=>({...t}))}function ib(e){return e.map(t=>({...t}))}const cb={id:"software-development",label:"Software Development",description:"A software-oriented starter pack with developer-focused work types and a 4-level priority scale.",categories:[{value:"default",label:"General",icon:"Inbox"},{value:"product",label:"Product",icon:"Layers",color:"blue-500"},{value:"ui-ux",label:"UI/UX",icon:"Palette",color:"violet-500"},{value:"backend",label:"Backend",icon:"Server",color:"emerald-500"}],types:[{value:"feature",label:"Feature",icon:"Star",color:"teal-500",status:"active"},{value:"bug",label:"Bug",icon:"Bug",color:"red-500",status:"active"},{value:"chore",label:"Chore",icon:"Zap",color:"amber-500",status:"active"},{value:"refactor",label:"Refactor",icon:"Code",color:"blue-500",status:"active"},{value:"documentation",label:"Docs",icon:"Book",color:"sky-500",status:"active"}],priorities:[{value:1,label:"Low",color:"amber-200",icon:"ArrowDown"},{value:2,label:"Medium",color:"yellow-500",icon:"Minus"},{value:3,label:"High",color:"orange-500",icon:"ArrowUp"},{value:4,label:"Critical",color:"red-500",icon:"AlertTriangle"}]},lb=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",isDefaultStarter:!0,categories:[{value:Qc,label:Cm,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"}]},cb];function sy(){return lb.map(e=>({...e,categories:sb(e.categories),types:ob(e.types),priorities:ib(e.priorities)}))}const Yc=[{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"}],ao=Yc.map(({value:e,label:t,icon:n,color:s})=>({value:e,label:t,icon:n,color:s}));function pd(e){const t=String(e||"task").trim().toLowerCase();return t==="completed"?Yc.find(n=>n.value==="done")||Yc[0]:Yc.find(n=>n.value===t)||Yc[0]}const oy=["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"],tc=oy.reduce((e,t)=>(e[t]=As[t]||Ji,e),{}),HO=oy,mm=Object.fromEntries(sy().flatMap(e=>e.types).filter(e=>e.icon&&e.color).reduce((e,t)=>(e.some(([n])=>n===t.value)||e.push([t.value,{icon:t.icon,color:t.color}]),e),[])),db={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"},bh={"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"},GO=["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 Dn(e){if(e)return bh[e]?bh[e]:e}function ub(e){const t=String(e||"").trim().toLowerCase();return Dn(mm[t]?.color)||Dn("violet-200")||"#9c7aeb"}function VO(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 mb(e){const t=String(e||"").trim().toUpperCase();return Dn(db[t])||"var(--text-muted)"}const pb=/[\u2010-\u2015\u2212]/g;function wf(e){return String(e??"").trim().replace(pb,"-").replace(/\s+/g," ").toLowerCase()}function Tm(e){const t=wf(e);if(!t)return null;const n=t.match(/^(l\s*t|t)\s*(?:-\s*)?(\d+)$/i);return n?`${n[1].replace(/\s+/g,"").toLowerCase()}-${n[2]}`:null}function Rm(e){const t=wf(e);return{raw:t,tokens:t?t.split(" ").filter(Boolean):[],referenceToken:Tm(e)}}function ss(e,t){const n=String(t??"").trim();n&&e.push(n)}function Vc(e,t,n){const s=String(n??"").trim();if(!s)return;const o=t?.find(l=>String(l.value)===s);ss(e,o?.label)}function fb(e,t={}){const n=[];return ss(n,e.title),ss(n,e.description),ss(n,e.id),ss(n,Xi(e)),ss(n,e.category),ss(n,e.type),ss(n,e.priority),ss(n,e.status),ss(n,e.assignee||"unassigned"),ss(n,e.canceledReason),Vc(n,t.categories,e.category),Vc(n,t.types,e.type),Vc(n,t.priorities,e.priority),Vc(n,ao,e.status),Vc(n,t.assigneeOptions,e.assignee||"unassigned"),Object.entries(e.taxonomies||{}).forEach(([s,o])=>{const l=t.taxonomies?.find(d=>d.id===s);ss(n,l?.label),(Array.isArray(o)?o:[o]).forEach(d=>{ss(n,d),Vc(n,l?.options,d)})}),n}function pm(e,t,n={}){const s=typeof t=="string"?Rm(t):t;if(!s.raw)return!0;const o=fb(e,n),i=o.map(wf).filter(Boolean).join(" ");return i.includes(s.raw)||s.referenceToken&&o.map(Tm).some(m=>m?.includes(s.referenceToken))?!0:s.tokens.length>0&&s.tokens.every(d=>i.includes(d))}function hb(e,t){const n=e.taxonomies?.[t];return n==null||n===""?!1:Array.isArray(n)?n.some(s=>String(s).trim().length>0):String(n).trim().length>0}function Cd(e,t){const n=e.filter(o=>o.status!=="retired"),s=e.filter(o=>o.status==="retired"&&t.some(l=>hb(l,o.id)));return[...n,...s.filter(o=>!n.some(l=>l.id===o.id))]}function iy(e,t=[]){return Cd(e,t).filter(n=>n.sortEnabled===!0).map(n=>({value:`taxonomy:${n.id}`,label:n.status==="retired"?`${n.label} (Retired)`:n.label}))}function _h(e,t){const n=e.taxonomies?.[t.id];if(n==null||n==="")return null;const s=Array.isArray(n)?n.map(o=>String(o)):[String(n)];for(let o=0;o<t.options.length;o+=1)if(s.includes(String(t.options[o]?.value)))return o;return null}function Hi(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()}function fm(e,t,n,s,o=[]){let l=0;if(n==="created")return l=Hi(e,t),s==="desc"?l:-l;if(n==="updated"){const i=e.updatedAt||e.createdAt,d=t.updatedAt||t.createdAt;return l=new Date(d).getTime()-new Date(i).getTime(),s==="desc"?l:-l}if(n==="priority"){const i=sm(e.priority),d=sm(t.priority);return l=i!==d?d-i:Hi(e,t),s==="desc"?l:-l}if(n==="complexity"){const i=typeof e.complexity=="number"?e.complexity:3,d=typeof t.complexity=="number"?t.complexity:3;return l=i!==d?d-i:Hi(e,t),s==="desc"?l:-l}if(n.startsWith("taxonomy:")){const i=n.slice(9),d=o.find(k=>k.id===i);if(!d)return l=Hi(e,t),s==="desc"?l:-l;const m=_h(e,d),y=_h(t,d);return m===null&&y===null?Hi(e,t):m===null?1:y===null?-1:m!==y?s==="desc"?y-m:m-y:Hi(e,t)}return l=Hi(e,t),s==="desc"?l:-l}function gb(e,t,n){const s=e.taxonomies?.[t];return s==null||s===""?!1:Array.isArray(s)?s.some(o=>String(o)===String(n)):String(s)===String(n)}function bf(e,t){const n=e.options.filter(o=>o.status!=="retired"),s=e.options.filter(o=>o.status==="retired"&&t.some(l=>gb(l,e.id,o.value)));return[...n,...s.filter(o=>!n.some(l=>String(l.value)===String(o.value)))]}function yb({tasks:e,archivedTasks:t,activeCategories:n,activeTypes:s,priorities:o,taxonomies:l,configLoaded:i,referenceDataLoaded:d,assigneeOptionsLoaded:m,assigneeOptions:y}){const k=r.useMemo(()=>Ug(y),[y]),S=r.useMemo(()=>Cd(l,[...e,...t]).filter(U=>U.filterEnabled!==!1).map(U=>({...U,options:bf(U,[...e,...t])})),[t,e,l]),h=r.useMemo(()=>k.map(U=>U.value),[k]),[g,v]=r.useState(""),[_,I]=r.useState([]),[C,D]=r.useState([]),[q,B]=r.useState([]),[X,me]=r.useState(!1),[ke,le]=r.useState(ao.map(U=>U.value)),[O,A]=r.useState(h),[de,ge]=r.useState(!0),[Y,P]=r.useState({}),[H,ue]=r.useState("created"),[ye,V]=r.useState("desc"),Me=r.useCallback(()=>{V(U=>U==="asc"?"desc":"asc")},[]),[_e,re]=r.useState("status"),[oe,Ie]=r.useState("show"),[Ee,je]=r.useState({}),Pe=r.useCallback((U,se)=>se.length===0?!0:se.every(pe=>U.includes(pe)),[]),K=r.useCallback((U,se)=>U.length===se.length&&U.every((pe,z)=>pe===se[z]),[]);r.useEffect(()=>{_e==="approach"&&re("status")},[_e]),r.useEffect(()=>{if(!(!i||!d)&&m&&!X&&n.length>0&&s.length>0&&o.length>0){I(n.map(se=>se.value)),D(o.map(se=>se.value)),B(s.map(se=>se.value)),A(h),ge(!0);const U={};S.forEach(se=>{U[se.id]=se.options.map(pe=>pe.value)}),P(U),me(!0)}},[i,d,m,n,s,o,S,X,h]),r.useEffect(()=>{if(!X||!m)return;const U=new Set(h),se=O.filter(ne=>U.has(ne)),pe=de?h:se.length>0||O.length===0?se:h;(pe.length!==O.length||pe.some((ne,ie)=>ne!==O[ie]))&&A(pe)},[h,O,de,X,m]),r.useEffect(()=>{if(!X||!m)return;const U=O.filter(pe=>h.includes(pe)),se=h.length>0&&h.every(pe=>U.includes(pe));se!==de&&ge(se)},[h,O,de,X,m]),r.useEffect(()=>{if(!i||!d||!X||n.length===0)return;const U=Wv(_,n);(U.length!==_.length||U.some((pe,z)=>pe!==_[z]))&&I(U)},[i,d,n,X,_]),r.useEffect(()=>{if(!i||!d||!X||o.length===0||C.length===0)return;const U=Bv(C,o),se=Array.from(new Set(C.map(z=>Number(z)).filter(z=>Number.isFinite(z))));(U.length!==se.length||U.some((z,ne)=>z!==se[ne]))&&D(U)},[i,d,X,o,C]),r.useEffect(()=>{if(!i||!d||!X||s.length===0)return;const U=new Set(s.map(z=>z.value)),se=q.filter(z=>U.has(z)),pe=se.length>0||q.length===0?se:s.map(z=>z.value);K(pe,q)||B(pe)},[s,i,q,X,K,d]),r.useEffect(()=>{if(!i||!d||!X)return;const U={};S.forEach(ie=>{const Re=ie.options.map(Oe=>Oe.value);if(Re.length===0)return;const Te=Array.isArray(Y[ie.id])?Y[ie.id]:[],De=Te.filter(Oe=>Re.includes(Oe));U[ie.id]=De.length>0||Te.length===0?De:Re});const se=Object.keys(Y).sort(),pe=Object.keys(U).sort(),z=se.length!==pe.length||se.some((ie,Re)=>ie!==pe[Re]),ne=pe.some(ie=>!K(Y[ie]||[],U[ie]||[]));(z||ne)&&P(U)},[i,Y,S,X,K,d]);const x=r.useCallback(()=>{v(""),I(n.map(se=>se.value)),D(o.map(se=>se.value)),B(s.map(se=>se.value)),le(ao.map(se=>se.value)),A(h),ge(!0);const U={};S.forEach(se=>{U[se.id]=se.options.map(pe=>pe.value)}),P(U),ue("created"),V("desc")},[n,o,s,S,h]),b=r.useCallback(U=>{A(se=>{const pe=typeof U=="function"?U(se):U,z=Array.from(new Set(pe.filter(ie=>typeof ie=="string"&&ie.trim().length>0))),ne=h.length>0&&h.every(ie=>z.includes(ie));return ge(ne),z})},[h]),R=r.useMemo(()=>Rm(g),[g]),F=r.useMemo(()=>({categories:n,types:s,priorities:o,assigneeOptions:k,taxonomies:l}),[n,s,o,k,l]),Q=r.useMemo(()=>{const U=Pe(_,n.map(ne=>ne.value)),se=Pe(q,s.map(ne=>ne.value)),pe=Pe(Array.from(new Set(C.map(ne=>Number(ne)).filter(ne=>Number.isFinite(ne)))),o.map(ne=>Number(ne.value)).filter(ne=>Number.isFinite(ne))),z=Pe(ke,ao.map(ne=>ne.value));return e.filter(ne=>{const ie=pm(ne,R,F),Re=!X||U||_.includes(ne.category),Te=!X||pe||up(ne.priority,C),De=!X||se||q.includes(ne.type||Vr),Oe=!X||z||ke.includes(ne.status),vt=!X||de||O.includes(ne.assignee||"unassigned"),st=Object.entries(Y).every(([kt,Ye])=>{const Ct=S.find(Rt=>Rt.id===kt);if(!Ct)return!0;const dt=Ct?.options.every(Rt=>Ye.includes(Rt.value))??!0;if(dt)return!0;const Qe=ne.taxonomies?.[kt];return Qe?Array.isArray(Qe)?Qe.some(Rt=>Ye.includes(Rt)):Ye.includes(Qe):dt||Ye.includes("")});return ie&&Re&&Te&&De&&Oe&&vt&&st}).sort((ne,ie)=>fm(ne,ie,H,ye,l))},[e,t,R,F,_,C,q,ke,O,de,Y,H,ye,X,S,n,s,o,Pe,l]),M=r.useMemo(()=>{const U=Pe(_,n.map(ne=>ne.value)),se=Pe(q,s.map(ne=>ne.value)),pe=Pe(Array.from(new Set(C.map(ne=>Number(ne)).filter(ne=>Number.isFinite(ne)))),o.map(ne=>Number(ne.value)).filter(ne=>Number.isFinite(ne))),z=Pe(ke,ao.map(ne=>ne.value));return e.filter(ne=>{const ie=!X||U||_.includes(ne.category),Re=!X||pe||up(ne.priority,C),Te=!X||se||q.includes(ne.type||Vr),De=!X||z||ke.includes(ne.status),Oe=!X||de||O.includes(ne.assignee||"unassigned"),vt=Object.entries(Y).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=ne.taxonomies?.[st];return dt?Array.isArray(dt)?dt.some(Qe=>kt.includes(Qe)):kt.includes(dt):Ct||kt.includes("")});return ie&&Re&&Te&&De&&Oe&&vt})},[e,t,_,C,q,ke,O,de,Y,X,S,n,s,o,Pe]),$=r.useMemo(()=>{const U=n.every(z=>_.includes(z.value)),se=Pe(q,s.map(z=>z.value)),pe=Pe(Array.from(new Set(C.map(z=>Number(z)).filter(z=>Number.isFinite(z)))),o.map(z=>Number(z.value)).filter(z=>Number.isFinite(z)));return t.filter(z=>{const ne=pm(z,R,F),ie=!X||U||_.includes(z.category),Re=!X||pe||up(z.priority,C),Te=!X||se||q.includes(z.type||Vr),De=!X||de||O.includes(z.assignee||"unassigned"),Oe=Object.entries(Y).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=z.taxonomies?.[vt];return Ct?Array.isArray(Ct)?Ct.some(dt=>st.includes(dt)):st.includes(Ct):Ye||st.includes("")});return ne&&ie&&Re&&Te&&De&&Oe}).sort((z,ne)=>fm(z,ne,H,ye,l))},[t,R,F,_,C,q,O,de,Y,H,ye,X,n,s,o,S,Pe,l]),be=r.useMemo(()=>{const U={};return Q.forEach(se=>{const pe=n.find(ne=>ne.value===se.category),z=pe?pe.label:se.category||"General";U[z]||(U[z]=[]),U[z].push(se)}),U},[Q,n]);return{searchQuery:g,setSearchQuery:v,filterCategories:_,setFilterCategories:I,filterPriorities:C,setFilterPriorities:D,filterTypes:q,setFilterTypes:B,filterStatus:ke,setFilterStatus:le,filterAssignees:O,setFilterAssignees:b,filterAssigneesAllSelected:de,setFilterAssigneesAllSelected:ge,filterTaxonomies:Y,setFilterTaxonomies:P,hasInitedFilters:X,setHasInitedFilters:me,sortBy:H,setSortBy:ue,sortOrder:ye,setSortOrder:V,toggleSortOrder:Me,groupBy:_e,setGroupBy:re,emptyColumnMode:oe,setEmptyColumnMode:Ie,collapsedCategories:Ee,setCollapsedCategories:je,clearFilters:x,filteredTasks:Q,searchAgnosticTasks:M,filteredArchive:$,groupedTasks:be}}const kb=yb;function vb(e){const{activeCategories:t,activeTab:n,apiEndpoint:s,approach:o,assignee:l,attachments:i,attachmentsDirty:d,category:m,checklistItems:y,comments:k,complexity:S,description:h,dueDate:g,editingTaskId:v,fetchTasks:_,formTaxonomies:I,getPreferredCategoryValue:C,mergeTaskFromServer:D,workstreamInput:q,priority:B,pushNotice:X,queueWorkspaceSyncFromAuthoritativeTaskState:me,relationshipTasks:ke,resetForm:le,resolveWorkstreamIdInput:O,scheduledDate:A,setActiveTab:de,setAttachmentsDirty:ge,setComments:Y,setError:P,setLastUsedCategory:H,setLoading:ue,setNewCommentText:ye,status:V,title:Me,taxonomies:_e,type:re}=e,[oe,Ie]=r.useState(null),[Ee,je]=r.useState("idle"),[Pe,K]=r.useState(null),x=r.useRef(null),b=r.useCallback(()=>JSON.stringify({title:Me.trim(),description:h||"",category:typeof m=="string"?m:m.label||C(t),type:typeof re=="string"?re:re.label||Vr,priority:Number(B),complexity:Number(S)||3,approach:o||"default",assignee:l||"agent",scheduledDate:A||"",dueDate:g||"",workstreamInput:q.trim(),checklistItems:y,comments:k,taxonomies:I,attachments:i}),[t,o,l,i,m,y,k,S,h,g,I,C,B,A,Me,re,q]),R=r.useCallback(()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null)},[]),F=r.useCallback(async pe=>{const z=pe?.quiet??!1,ne=pe?.source??"manual";if(!Me.trim())return P("Title is required"),v&&je(ne==="autosave"?"error":"idle"),!1;const ie=_e.filter(Re=>Re.isRequired).filter(Re=>{const Te=I[Re.id];return Array.isArray(Te)?Te.filter(De=>String(De).trim().length>0).length===0:typeof Te!="string"&&typeof Te!="number"||String(Te).trim().length===0}).map(Re=>Re.label);if(ie.length>0)return P(`Required taxonomy values are missing: ${ie.join(", ")}`),v&&je(ne==="autosave"?"error":"idle"),!1;if(v&&ke.find(Te=>Te.id===v)?.isArchived)return P("Archived tasks are read-only. Unarchive first to make changes."),je(ne==="autosave"?"error":"idle"),!1;ue(!0),P(""),v&&je("saving");try{const Re=v?`/api/taskforce/task/${v}`:s.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),Te=v?"PATCH":"POST",De=typeof m=="string"?m:m.label||C(t),Oe=typeof re=="string"?re:re.label||Vr,vt=q.trim()?O(q):null,st={title:Me,description:h||null,category:De||C(t),type:Oe,priority:B,complexity:Number(S)||3,status:v?void 0:V,completedAt:v?void 0:V==="done"?new Date().toISOString():null,approach:o||"default",assignee:l||"agent",scheduledDate:A||null,dueDate:g||null,workstreamId:q.trim()?vt?.id||q.trim():null,checklistItems:y,comments:k,taxonomies:I,...v?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};(!v||d)&&(st.attachments=i),v&&(st.saveSource=ne);const kt=await fetch(Re,{method:Te,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 P(dt),z||X(dt,"error"),ue(!1),v&&je("error"),!1}const Ye=await kt.json().catch(()=>null);return v&&Ye&&typeof Ye=="object"&&(D(Ye),me()),H(De),ge(!1),ue(!1),v&&je("saved"),!0}catch{return P("Failed to connect to server"),z||X("Failed to connect to server","error"),ue(!1),v&&je("error"),!1}},[t,s,o,l,i,d,m,y,k,S,h,g,v,I,C,D,q,B,X,me,O,ge,P,H,ue,A,V,Me,_e,re]),Q=r.useCallback(async()=>{await F({source:"manual"})&&(v||X("Task added successfully","success"),n==="add"&&!v&&(le(),de("tasks"),await _()))},[n,v,_,X,le,F,de]);r.useEffect(()=>{if(R(),!v){K(null),je("idle");return}K(b()),je("idle")},[R,v]);const M=r.useCallback(async()=>{if(R(),!v||Pe===null)return;const pe=b();if(pe===Pe||!Me.trim()||g&&A&&g<A)return;await F({quiet:!0,source:"autosave"})&&K(pe)},[b,R,g,v,Pe,F,A,Me]);r.useEffect(()=>{if(!v||Pe===null)return;const pe=b();if(pe!==Pe){if(!Me.trim()){je("idle");return}if(g&&A&&g<A){je("error");return}return je(z=>z==="error"?"error":"idle"),R(),x.current=window.setTimeout(async()=>{await F({quiet:!0,source:"autosave"})&&K(pe)},700),()=>{R()}}},[b,R,g,v,Pe,F,A,Me]);const $=r.useCallback(async pe=>{if(pe.preventDefault(),g&&A&&g<A){Ie({dueDate:g,scheduledDate:A});return}await Q()},[g,Q,A]),be=r.useCallback(async()=>{Ie(null),await Q()},[Q]),U=r.useCallback(()=>{Ie(null)},[]),se=r.useCallback(async pe=>{if(!v||!pe.trim())return;const z=pe.trim();try{const ne=await fetch(`/api/taskforce/task/${v}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:z,author:"user"})});if(!ne.ok){const Te=(await ne.json().catch(()=>({}))).error||"Failed to add comment.";P(Te),X(Te,"error");return}const ie=await ne.json().catch(()=>null);if(ye(""),ie&&typeof ie=="object"){const Re=Do(ie);Y(Re.comments||[]),D(ie),K(b()),je("saved")}else await _(!0);me()}catch(ne){console.error("Failed to add comment",ne),P("Failed to add comment."),X("Failed to add comment.","error")}},[v,_,b,D,X,me,Y,P,ye]);return{autoSaveState:Ee,flushAutoSave:M,scheduleWarningPrompt:oe,saveTask:F,handleSubmit:$,confirmScheduleWarning:be,cancelScheduleWarning:U,handleAddComment:se}}function Sb(e){const{editingTaskId:t,fetchTasks:n,mergeTaskFromServer:s,workstreamInput:o,pushNotice:l,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)===_){l(_?"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 q=(await I.json().catch(()=>({}))).error||"Failed to set workstream.";y(q),l(q,"error");return}y(""),l(_?"Workstream set":"Workstream removed","info");const C=await I.json().catch(()=>null);C?(s(C),i()):(await n(!0),i())}catch{y("Failed to set workstream."),l("Failed to set workstream.","error")}},[t,n,s,o,l,i,d,m,y])}}function wb({tasks:e,archivedTasks:t,editingTaskId:n,setTasks:s,setArchivedTasks:o,setDeletedTasks:l,setError:i,resetForm:d,setActiveTab:m,fetchTasks:y,fetchArchive:k,fetchDeletedTasks:S,mergeTaskFromServer:h,pushNotice:g,cloudAuthConfigured:v,runtimeMode:_,isAuthenticated:I,workspaceCloudSyncEnabled:C,buildWorkspaceSyncSignature:D,pushWorkspaceChangesToCloud:q,workspacePendingSignatureRef:B,workspaceDeletedTaskIdsRef:X,workspaceDeletedTaskWatermarksRef:me}){const[ke,le]=r.useState(null),O=r.useRef(null),A=r.useRef(null),de=r.useRef(null);r.useEffect(()=>()=>{typeof window>"u"||(A.current!==null&&(window.clearTimeout(A.current),A.current=null),de.current=null)},[]);const ge=r.useCallback((K=0)=>{if(!(v&&_==="local"&&I&&C)||typeof window>"u")return;const x=Math.max(0,K),b=Date.now()+x,R=de.current;if(A.current!==null){if(x<=0||R!==null&&R>=b)return;window.clearTimeout(A.current),A.current=null}de.current=b,A.current=window.setTimeout(()=>{A.current=null,de.current=null;const F=D();F&&(B.current=F,q(F))},x)},[v,_,I,C,D,B,q]),Y=r.useCallback(async(K,x)=>{let b=await fetch(`/api/taskforce/deleted${K}`,x);return b.status===404&&(b=await fetch(`/api/taskforce/trash${K}`,x)),b},[]),P=async(K,x=!1,b={})=>{if(!b.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const R=x||t.some(F=>F.id===K);try{const F=await fetch(`/api/taskforce/task/${K}`,{method:"DELETE"});if(!F.ok){const be=(await F.json().catch(()=>({}))).error||"Failed to delete task.";return i(be),g(be,"error"),!1}const Q=await F.json().catch(()=>({})),M=Q?.deleted&&typeof Q.deleted=="object"&&Q.deleted.taskSnapshot?{...Q.deleted,taskSnapshot:Do(Q.deleted.taskSnapshot)}:null;if(window.location.search.includes(K)){const $=new URL(window.location.href);$.searchParams.delete("task"),window.history.pushState({},"",$.toString())}if(R?o($=>$.filter(be=>be.id!==K)):s($=>$.filter(be=>be.id!==K)),M){l(be=>[M,...be.filter(U=>U.taskId!==K)]);const $=String(M.deletedAt||"").trim();Number.isFinite(Date.parse($))&&me.current.set(K,$)}else await S(!0),me.current.set(K,new Date().toISOString());if(X.current.add(K),v&&_==="local"&&I&&C){const $=D();B.current=$,q($)}return n===K&&(d(),m("tasks")),i(""),g("Task moved to Trash.","info"),!0}catch(F){return console.error("Failed to delete task:",F),i("Failed to delete task."),g("Failed to delete task.","error"),!1}},H=r.useCallback(async K=>{try{const x=await Y(`/${K}/restore`,{method:"POST"});if(!x.ok){const Q=(await x.json().catch(()=>({}))).error||"Failed to restore deleted task.";return i(Q),g(Q,"error"),null}const b=await x.json().catch(()=>null);b?h(b):await y(!0),l(F=>F.filter(Q=>Q.id!==K&&Q.taskId!==K));const R=String(b?.id||"").trim();return X.current.delete(K),me.current.delete(K),R&&(X.current.delete(R),me.current.delete(R)),ge(),i(""),g("Task restored from Trash.","info"),b?Do(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,ge,Y,l,i]),ue=r.useCallback(async K=>{try{const x=await Y(`/${K}`,{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 l(b=>b.filter(R=>R.id!==K&&R.taskId!==K)),ge(),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,ge,Y,l,i]),ye=r.useCallback(async()=>{try{const K=await Y("/empty",{method:"POST"});if(!K.ok){const F=(await K.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return i(F),g(F,"error"),null}const x=await K.json().catch(()=>({})),b=Number(x?.deleted||0);return l([]),ge(),i(""),g(b===1?"Deleted task permanently removed.":`${b} deleted tasks permanently removed.`,"info"),b}catch(K){return console.error("Failed to empty deleted tasks:",K),i("Failed to permanently delete deleted tasks."),g("Failed to permanently delete deleted tasks.","error"),null}},[g,ge,Y,l,i]),V=r.useCallback(async(K,x)=>{const b=e,R=t;s(F=>F.map(Q=>Q.id===K?{...Q,...x}:Q)),o(F=>F.map(Q=>Q.id===K?{...Q,...x}:Q));try{const F=await fetch(`/api/taskforce/task/${K}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});if(!F.ok){const $=(await F.json().catch(()=>({}))).error||`Failed to update task ${K}.`;i($),g($,"error"),s(b),o(R);return}const Q=await F.json().catch(()=>null);h(Q),ge(x.attachments!==void 0?150:0),i("")}catch(F){console.error("Failed to update task",F);const Q=`Failed to update task ${K}.`;i(Q),g(Q,"error"),s(b),o(R)}},[e,t,g,h,ge]);return{copiedId:ke,handleDelete:P,handleUpdateTask:V,handleToggleComplete:async K=>{const x=K.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},F=e,Q=t;s(M=>M.map($=>$.id===K.id?{...$,...R}:$)),o(M=>M.map($=>$.id===K.id?{...$,...R}:$));try{const M=await fetch(`/api/taskforce/task/${K.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:x,completedAt:b})});if(!M.ok){const U=(await M.json().catch(()=>({}))).error||"Failed to update task status.";i(U),g(U,"error"),s(F),o(Q);return}const $=await M.json().catch(()=>null);$?(h($),ge()):(await y(!0),ge()),i("")}catch(M){console.error("Failed to toggle complete",M),i("Failed to update task status."),g("Failed to update task status.","error"),s(F),o(Q)}},handleToggleCancel:async K=>{const x=K.status==="cancelled"?"task":"cancelled";try{const b=await fetch(`/api/taskforce/task/${K.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:x})});if(!b.ok){const Q=(await b.json().catch(()=>({}))).error||"Failed to update task status.";i(Q),g(Q,"error"),await y(!0);return}const R=await b.json().catch(()=>null);R?(h(R),ge()):(await y(!0),ge()),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 K=>{const x=K.status==="in-progress"?"task":"in-progress";s(b=>b.map(R=>R.id===K.id?{...R,status:x}:R));try{const b=await fetch(`/api/taskforce/task/${K.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),ge()}catch{y()}},handleToggleReview:async K=>{const x=K.status==="review"?"task":"review";s(b=>b.map(R=>R.id===K.id?{...R,status:x}:R));try{const b=await fetch(`/api/taskforce/task/${K.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),ge()}catch{y()}},handleArchiveTask:async K=>{try{const b=K.status==="cancelled"?"cancel":"complete",R=await fetch(`/api/taskforce/task/${K.id}/${b}`,{method:"POST"});if(R.ok){const F=await R.json().catch(()=>null),Q=[];if(F&&typeof F=="object"&&Q.push(F),Q.length>0){for(const $ of Q)h($);ge()}else k();const M=new Set(Q.map($=>String($?.id||"").trim()).filter($=>$.length>0));n&&M.has(n)&&(d(),m("tasks"))}else{const Q=(await R.json().catch(()=>({}))).error||"Failed to archive task.";i(Q),g(Q,"error")}}catch(x){console.error("Failed to archive",x),i("Failed to archive task."),g("Failed to archive task.","error")}},handleBulkArchive:async()=>{const K=e.filter(x=>x.status==="done"||x.status==="cancelled");if(K.length!==0&&confirm(`Archive ${K.length} completed/cancelled tasks?`))try{const x=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:K.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 F of R)h(F);ge()}else s(F=>F.filter(Q=>!["done","cancelled"].includes(Q.status))),k();g(`${b.archived||K.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 K=>{try{const x=await fetch(`/api/taskforce/task/${K}/unarchive`,{method:"POST"});if(x.ok){const b=await x.json().catch(()=>null);b?(h(b),ge()):(o(R=>R.filter(F=>F.id!==K)),await y(!0),ge()),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:(K,x)=>{K.stopPropagation(),navigator.clipboard.writeText(x),le(x),O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{O.current=null,le(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:ge}}const bb=wb;function Fu(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function _b(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 Cb({currentWorkspaceIdRef:e,resolveApiUrl:t,runtimeMode:n}){r.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const s=window.fetch.bind(window),o=l=>{if(typeof l=="string")return n!=="cloud"?l:l.startsWith("/api/taskforce")&&!Fu(l)?t(l):l;if(l instanceof URL)return n!=="cloud"?l:l.origin===window.location.origin&&l.pathname.startsWith("/api/taskforce")?Fu(l.pathname)?l:new URL(t(`${l.pathname}${l.search}${l.hash}`)):l;if(typeof Request<"u"&&l instanceof Request){if(n!=="cloud")return l;const i=new URL(l.url,window.location.origin);if(i.origin===window.location.origin&&i.pathname.startsWith("/api/taskforce"))return Fu(i.pathname)?l:t(`${i.pathname}${i.search}${i.hash}`)}return l};return window.fetch=((l,i)=>{const d=o(l),m=_b(d);if(!!!(m&&m.pathname.startsWith("/api/taskforce")&&!Fu(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,n])}const od=12e3,Ab=3e4,xb=2e4;function Ou(e){return e==="cloud"?Ab:od}function Ch(){return typeof performance<"u"?performance.now():Date.now()}function Ib({runtimeConfigReady:e,shouldProbeCloudAuth:t,authSessionResolved:n,resolveCloudAuthUrl:s,authOnlyCloudMode:o,authRequiredError:l,runtimeMode:i,workspaceSelectionScope:d,markBootstrapPhase:m,markBootstrapStalled:y,setRuntimeMode:k,setAuthRequiredForApi:S,setIsAuthenticated:h,setAuthUserId:g,setAuthWorkspaceId:v,setAuthUserEmail:_,setAuthUserDisplayName:I,setAuthUserAvatarUrl:C,setUserGlobalSyncStatus:D,setUserGlobalSyncError:q,setHasBetaAccess:B,setAvailableWorkspaces:X,setHydratedWorkspaceRole:me,setAssigneeOptions:ke,setAuthBlocked:le,setAuthSessionResolved:O,setError:A,applyResolvedWorkspaceId:de,readPersistedWorkspaceId:ge,authSessionRequestRef:Y,authSessionEpochRef:P,authSessionLastCheckedAtRef:H,authSessionLastResultRef:ue,isLoopbackHost:ye,setAuthStateReadyRefs:V}){const Me=r.useCallback(async re=>{const oe=re?.force===!0;if(m("auth"),!e)return ue.current;if(!t)return k("local"),S(!1),h(!1),g("anonymous"),v(""),rd(null),_(""),I(""),C(""),D("disconnected"),q(null),B(!0),X([]),me(null),ke(li()),le(!1),O(!0),V(!1,!0,!1),ue.current=!1,H.current=Date.now(),!1;const Ie=s("/api/taskforce/auth/session"),Ee=Date.now();if(!oe&&Y.current)return Y.current;if(!oe&&n&&Ee-H.current<1500)return ue.current;const je=++P.current;let Pe=null;return Pe=(async()=>{const K=Ch(),x=new AbortController,b=typeof window<"u"?window.setTimeout(()=>x.abort(),xb):null,R=()=>P.current!==je,F=(Q,M)=>{Ut(Q,{durationMs:Math.max(0,Math.round(Ch()-K)),force:oe,sessionUrl:Ie,...M})};try{const Q=await fetch(Ie,{method:"GET",credentials:"include",mode:"cors",signal:x.signal});if(R())return ue.current;if(Q.status===429)return O(!0),V(ue.current,!0,!1),F("auth_session_rate_limited",{status:Q.status}),ue.current;if(!Q.ok)return R()?ue.current:(ye&&rd(null),O(!0),V(!1,!0,!1),ue.current=!1,F("auth_session_request_failed",{status:Q.status}),!1);const M=await Q.json();if(R())return ue.current;const $=!!M.authRequiredForApi,be=!!M.authenticated,U=be?M.betaAccess!==!1:!0,se=typeof M.workspaceId=="string"&&M.workspaceId.trim().length>0?M.workspaceId.trim():"",pe=typeof M.userId=="string"&&M.userId.trim().length>0?M.userId.trim():"anonymous",z=typeof M.email=="string"&&M.email.trim().length>0?M.email.trim().toLowerCase():"",ne=typeof M.displayName=="string"?M.displayName.trim():"",ie=typeof M.avatarUrl=="string"?M.avatarUrl.trim():"",Re=i==="local",Te=i==="local"||o,De=o||Re?!1:$;return S(De),h(be),g(be?pe:"anonymous"),v(be?se:""),ye&&rd(be?pe:null),_(be?z:""),I(be?ne:""),C(be?ie:""),be&&A(Oe=>Oe===l?"":Oe),D(be?"idle":"disconnected"),q(null),B(U),Te||de(se||ge(d)||"default",{preserveNonDefaultDefault:!0}),le(o||Re?!1:$&&!be),O(!0),V(be,!0,De),ue.current=be,be&&m("ready"),F("auth_session_resolved",{status:Q.status,authenticated:be,workspaceId:be?se:"",userId:be?pe:"anonymous",authRequiredForApi:De}),be}catch(Q){return R()||(ye&&rd(null),O(!0),V(!1,!0,!1),ue.current=!1,y("Unable to verify your session."),F("auth_session_exception",{error:Q instanceof Error?Q.message:String(Q)})),ue.current}finally{b!==null&&typeof window<"u"&&window.clearTimeout(b),R()||(H.current=Date.now()),Pe&&Y.current===Pe&&(Y.current=null)}})(),Y.current=Pe,Pe},[e,t,n,s,o,l,i,d,m,y,k,S,h,g,v,_,I,C,D,q,B,X,me,ke,le,O,A,de,ge,Y,P,H,ue,ye,V]),_e=i==="local"&&ye&&t?hf():"";return r.useEffect(()=>{_e&&(h(!0),O(!0),g(_e),V(!0,!0,!1),ue.current=!0)},[_e,O,V,g,h,ue]),r.useEffect(()=>{if(i!=="local"||!t||typeof window>"u")return;const re=()=>{Me()},oe=()=>{document.visibilityState==="visible"&&re()};window.addEventListener("focus",re),window.addEventListener("online",re),document.addEventListener("visibilitychange",oe);const Ie=window.setInterval(re,3e4);return()=>{window.removeEventListener("focus",re),window.removeEventListener("online",re),document.removeEventListener("visibilitychange",oe),window.clearInterval(Ie)}},[i,t,Me]),{checkAuthSession:Me}}function Tb(e){const t=e.runtimeMode==="cloud",n=!!(e.shouldGateProtectedApiCalls&&t&&!e.authSessionResolved),s=!!(e.shouldGateProtectedApiCalls&&t&&e.authSessionResolved&&e.authRequiredForApi&&!e.isAuthenticated);return{shouldDeferProtectedApiCalls:n,shouldBlockProtectedApiCalls:s,canCallProtectedApi:!(n||s)}}function Rb(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function jb(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}function Ah(e){if(!Array.isArray(e))return;const t=e.filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());return t.length>0?t:void 0}function Nb(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 Pb(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=>({...wv(s.value),...s,aliases:Array.isArray(s.aliases)?s.aliases.filter(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.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:Ah(s.aliases),options:Array.isArray(s.options)?s.options.map(o=>({...o,aliases:Ah(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 xa(){return typeof performance<"u"?performance.now():Date.now()}function Mb(e){const{shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:n,getWorkspaceRequestState:s,isWorkspaceRequestStale:o,isWorkspaceEpochStale:l,isAbortError:i,isBootstrapTimeoutError:d,fetchWithTimeout:m,handleUnauthorized:y,applyBootstrapConfig:k,loadPersistedUiState:S,fetchBuildInfo:h,markBootstrapPhase:g,markBootstrapStalled:v,fetchWorkflows:_,fetchInitiativeTemplates:I,loadAvailableEnvironments:C,setReferenceDataLoaded:D,setCustomCategories:q,setCustomTypes:B,setPriorities:X,setTaxonomies:me,setTaxonomyDisplayLabels:ke,setConfigLoaded:le,hasLoadedUiStateRef:O,currentWorkspaceIdRef:A,referenceDataRequestRef:de,referenceDataAbortRef:ge,bootstrapConfigAbortRef:Y,workspaceListAbortRef:P,assigneeOptionsAbortRef:H,workspaceListHydratedRef:ue,setAvailableWorkspaces:ye,runtimeMode:V,applyResolvedWorkspaceId:Me,workspaceSwitchingEnabled:_e,authSessionResolved:re,isAuthenticated:oe,authUserId:Ie,authUserAvatarUrl:Ee,setHydratedWorkspaceRole:je,setAssigneeOptions:Pe,setAssigneeOptionsLoaded:K,commitCurrentWorkspaceId:x,currentWorkspaceId:b,workspaceSelectionScope:R,abortWorkspaceScopedRequests:F,setWorkspaceBootstrapPending:Q,checkAuthSession:M,lastConfigRefreshKeyRef:$,lastAssigneeOptionsLoadKeyRef:be,lastWorkspaceSyncStateLoadKeyRef:U,lastTaskSurfaceLoadKeyRef:se,lastSettingsSurfaceLoadKeyRef:pe,isOpen:z,activeTab:ne,showArchive:ie,taskScope:Re,settingsSection:Te,workspaceBootstrapPending:De,fetchTasks:Oe,fetchArchive:vt,fetchPlanningEntities:st,refreshTaskCollections:kt,loadWorkspaceSyncState:Ye,archiveBootstrapTimerRef:Ct,hasBootstrappedDataRef:dt}=e,Qe=r.useCallback(async We=>{const tt=We?.ignoreAuthGuard===!0,Fe=We?.force===!0;if(!tt&&(t||n)){Ut("bootstrap_reference_data_skipped",{reason:n?"auth_blocked":"auth_deferred",runtimeMode:V,workspaceId:String(s().workspaceId||"").trim()||"default",force:Fe});return}const Ze=s(),St=String(Ze.workspaceId||"").trim()||"default";if(!(V!=="cloud"||!re||!oe||St!==""&&St!=="default")){Ut("bootstrap_reference_data_skipped",{reason:"workspace_unresolved",runtimeMode:V,workspaceId:St,force:Fe});return}if(!Fe&&de.current?.workspaceId===Ze.workspaceId){Ut("bootstrap_reference_data_reused",{workspaceId:St,force:Fe}),await de.current.promise;return}D(!1);const te=xa(),Le=new AbortController;ge.current=Le;const At=(async()=>{await Promise.allSettled([(async()=>{let jt="empty-taxonomy-state";const Wt=await fetch("/api/taskforce/taxonomy-state",{signal:Le.signal});if(!Wt.ok)return;const Ge=await Wt.json().catch(()=>({}));if(Nb(Ge))jt="taxonomy-state";else{jt="fallback-endpoints";const[yt,E,c,J]=await Promise.all([fetch("/api/taskforce/categories",{signal:Le.signal}),fetch("/api/taskforce/types",{signal:Le.signal}),fetch("/api/taskforce/priorities",{signal:Le.signal}),fetch("/api/taskforce/taxonomies",{signal:Le.signal})]),[we,xe,Ke,Je]=await Promise.all([yt.ok?yt.json().catch(()=>({})):Promise.resolve({}),E.ok?E.json().catch(()=>({})):Promise.resolve({}),c.ok?c.json().catch(()=>({})):Promise.resolve({}),J.ok?J.json().catch(()=>({})):Promise.resolve({})]);Ge.categories=we.categories,Ge.types=xe.types,Ge.priorities=Ke.priorities,Ge.taxonomies=Je.taxonomies}const $t=Pb(Ge);if(o(Ze)){Ut("bootstrap_reference_data_stale_drop",{workspaceId:St,source:jt});return}$t.categories.length>0&&q($t.categories),$t.types.length>0&&B($t.types),$t.priorities.length>0&&X($t.priorities),me($t.taxonomies),ke($t.displayLabels||{}),Ut("bootstrap_reference_data_source",{workspaceId:St,source:jt,categories:$t.categories.length,types:$t.types.length,priorities:$t.priorities.length,taxonomies:$t.taxonomies.length})})(),_(),I(),C()]),!o(Ze)&&(D(!0),Ut("bootstrap_reference_data_loaded",{durationMs:Math.max(0,Math.round(xa()-te)),workspaceId:St,force:Fe}))})();de.current={workspaceId:Ze.workspaceId,promise:At};try{await At}finally{de.current?.promise===At&&(de.current=null),ge.current===Le&&(ge.current=null)}},[re,I,_,s,oe,o,C,ge,de,V,q,B,X,D,me,ke,n,t]),Rt=r.useCallback(async We=>{if(!(We?.ignoreAuthGuard===!0)&&(t||n))return;g("config");const Fe=s(),Ze=xa(),St=new AbortController;Y.current=St;try{const ot=await m("/api/taskforce/config",void 0,Ou(V),{signal:St.signal});if(l(Fe))return;if(ot.status===401){y(),le(!0);return}let te="";if(ot.ok){const Le=await ot.json();if(l(Fe))return;te=typeof Le?.workspaceId=="string"&&Le.workspaceId.trim().length>0?Le.workspaceId.trim():"",k(Le)}if(l(Fe)){const Le=String(A.current||"default").trim()||"default";if(!te||Le!==te)return}if(O.current||(O.current=!0,await S(te||Fe.workspaceId)),l(Fe)){const Le=String(A.current||"default").trim()||"default";if(!te||Le!==te)return}le(!0),g("ready"),Ut("bootstrap_config_loaded",{durationMs:Math.max(0,Math.round(xa()-Ze)),status:ot.status,workspaceId:te||Fe.workspaceId}),h()}catch(ot){if(i(ot)||l(Fe))return;O.current||(O.current=!0,await S(Fe.workspaceId)),v(d(ot)?"Startup checks timed out.":"Unable to finish startup checks."),le(!0),Ut("bootstrap_config_failed",{durationMs:Math.max(0,Math.round(xa()-Ze)),workspaceId:Fe.workspaceId,error:ot instanceof Error?ot.message:String(ot)})}finally{Y.current===St&&(Y.current=null)}},[k,Y,A,h,m,s,y,O,i,d,l,S,g,v,V,le,n,t]),ee=r.useCallback(async We=>{await Rt(We),await Qe(We)},[Rt,Qe]),ze=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(!_e)return ye([]),ue.current=!1,{success:!0,workspaces:[]};const We=s(),tt=xa(),Fe=new AbortController;P.current=Fe;try{const Ze=await m("/api/taskforce/workspaces",{method:"GET",credentials:"include"},Ou(V),{signal:Fe.signal});if(l(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(l(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(te=>({id:String(te?.id||"").trim(),name:String(te?.name||"").trim(),role:String(te?.role||"member").trim().toLowerCase(),slug:typeof te?.slug=="string"?te.slug:null,description:typeof te?.description=="string"?te.description:null,status:typeof te?.status=="string"?te.status:"",betaAccess:te?.betaAccess===!0})).filter(te=>te.id&&te.name):[];return ye(ot),ue.current=!0,V!=="local"&&typeof St?.currentWorkspaceId=="string"&&St.currentWorkspaceId.trim().length>0&&Me(St.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),Ut("bootstrap_workspaces_loaded",{durationMs:Math.max(0,Math.round(xa()-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(xa()-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{P.current===Fe&&(P.current=null)}},[Me,m,s,i,d,l,v,V,ye,P,ue,_e]),it=r.useCallback(async()=>{const We=s(),tt=xa(),Fe=new AbortController;H.current=Fe,K(!1);try{const[Ze,St]=await Promise.all([m("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},Ou(V),{signal:Fe.signal}),re&&oe?m("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},Ou(V),{signal:Fe.signal}).catch(()=>null):Promise.resolve(null)]);if(o(We))return{success:!1,error:"Workspace changed while loading assignee options."};if(Ze.status===401)return Pe(li()),K(!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 Pe(li()),K(!0),{success:!1,error:ot?.error||`Failed to load assignee options (${Ze.status})`};const te=String(Ie||"").trim(),Le=String(Ee||"").trim(),At=(E,c)=>{const J=typeof E?.avatarUrl=="string"&&E.avatarUrl.trim().length>0?E.avatarUrl.trim():"";if(J)return J;const we=String(E?.userId||c||"").trim();return te&&we===te&&Le?Le:null},jt=Array.isArray(ot?.assignees)?ot.assignees:[],Wt=jt.map(E=>{const c=String(E?.value||"").trim(),J=String(E?.kind||"").trim().toLowerCase();return c?J==="agent"||J==="ai"?{value:c,label:String(E?.label||c).trim()||c,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:c,label:String(E?.label||c).trim()||c,icon:String(E?.icon||"User"),color:String(E?.color||"#22c55e"),kind:"member",avatarUrl:At(E,c)}:null:null}).filter(Boolean),Ge=jt.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 $t=Ge;if(St?.ok){const E=await St.json().catch(()=>({})),c=Array.isArray(E?.users)?E.users:[],J=c.find(Ke=>String(Ke?.userId||"").trim()===te),we=String(J?.role||"").trim().toLowerCase();we==="owner"||we==="admin"||we==="member"||we==="read-only"?je(we):!_e&&c.length===0&&je(null);const xe=c.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);$t=Array.from(new Map([...Ge,...xe].map(Ke=>[Ke.userId,Ke])).values())}else!_e&&!Ge.length&&je(null);const yt=vd([...Wt,...cS($t).filter(E=>E.kind==="member")]);return o(We)?{success:!1,error:"Workspace changed while loading assignee options."}:(Pe(yt),K(!0),Ut("bootstrap_assignee_options_loaded",{durationMs:Math.max(0,Math.round(xa()-tt)),workspaceId:We.workspaceId,count:yt.length}),{success:!0})}catch(Ze){return o(We)||(Pe(li()),K(!0)),Ut("bootstrap_assignee_options_failed",{durationMs:Math.max(0,Math.round(xa()-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===Fe&&(H.current=null)}},[H,re,Ee,Ie,m,s,i,oe,o,V,Pe,K,je,_e]),Et=r.useCallback(async(We,tt)=>{if(!_e)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const Fe=String(We||"").trim();if(!Fe)return{success:!1,error:"workspaceId is required."};const Ze=String(A.current||"").trim()||"default",St=xa();try{Ut("bootstrap_workspace_switch_started",{fromWorkspaceId:Ze,toWorkspaceId:Fe,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:Fe})}),te=await ot.json().catch(()=>({}));if(!ot.ok||te?.success===!1)return{success:!1,error:te?.error||`Failed to switch workspace (${ot.status})`,code:te?.code};x(Fe,{clearExplicitSelection:!1}),F(),Q(!0),g("workspace");const Le=await M({force:!0});return tt?.hydrate===!1?await ft():($.current=`${V}:${Fe}:${R}`,be.current=`${V}:${Le?"auth":"guest"}:${Fe}`,U.current=Fe,z&&ne==="tasks"&&(se.current=`${Fe}:${ne}:${ie?"archive":"active"}:${Re}`),z&&ne==="settings"&&(pe.current=`${Fe}:${ne}:${Te}`),await Promise.all([ee(),ft(),kt({isSilent:!1}),Ye()]),st({ignoreAuthGuard:!0})),Ut("bootstrap_workspace_switch_completed",{fromWorkspaceId:Ze,toWorkspaceId:Fe,hydrate:tt?.hydrate!==!1,durationMs:Math.max(0,Math.round(xa()-St))}),{success:!0}}catch(ot){return Ut("bootstrap_workspace_switch_failed",{fromWorkspaceId:Ze,toWorkspaceId:Fe,hydrate:tt?.hydrate!==!1,durationMs:Math.max(0,Math.round(xa()-St)),error:ot instanceof Error?ot.message:String(ot)}),{success:!1,error:"Failed to switch workspace."}}finally{Q(!1)}},[F,ne,M,x,A,ee,st,ft,z,be,$,pe,se,U,Ye,g,kt,V,Te,Q,ie,Re,R,_e]),ht=r.useCallback(async We=>{g("workspace"),Q(!0);try{if(!_e){const At=String(b||"").trim()||"default";return x(At),{success:!0,workspaceSetupRequired:!1,workspaceId:At}}const tt=String(We?.preferredWorkspaceId||"").trim(),Fe=Wp(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)),te=String(A.current||"").trim(),Le=(tt&&ot.has(tt)?tt:"")||(te&&ot.has(te)?te:"")||(Fe&&ot.has(Fe)?Fe:"")||String(St[0]?.id||"").trim();if(!Le)return x("default"),{success:!0,workspaceSetupRequired:!0};if(te!==Le){const At=await Et(Le,{hydrate:!1});if(!At.success)return{success:!1,workspaceSetupRequired:!1,error:At.error||"Failed to set workspace after authentication.",code:At.code}}else x(Le);return{success:!0,workspaceSetupRequired:!1,workspaceId:Le}}catch{return v("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{Q(!1)}},[x,b,A,ft,g,v,Q,Et,R,_e]),Ot=r.useCallback(async()=>{g("auth");const We=xa();Ut("bootstrap_retry_started",{workspaceId:String(A.current||"default").trim()||"default"});const tt=await M({force:!0});let Fe=!1;if(_e&&tt){const Ze=await ht();if(!Ze.success||Ze.workspaceSetupRequired){await ee({ignoreAuthGuard:!0}),Ut("bootstrap_retry_completed",{workspaceId:String(A.current||"default").trim()||"default",authenticated:tt,workspaceSetupRequired:Ze.workspaceSetupRequired===!0,success:Ze.success,durationMs:Math.max(0,Math.round(xa()-We))});return}}Q(!0);try{await ee({ignoreAuthGuard:!0}),tt&&!Fe&&(await Promise.all([Oe(!0,{ignoreAuthGuard:!0}),Qe({ignoreAuthGuard:!0,force:!0})]),st({ignoreAuthGuard:!0})),Ut("bootstrap_retry_completed",{workspaceId:String(A.current||"default").trim()||"default",authenticated:tt,workspaceSetupRequired:Fe,success:!0,durationMs:Math.max(0,Math.round(xa()-We))})}finally{Q(!1)}},[M,A,ee,st,Qe,Oe,g,ht,Q,_e]),Dt=r.useCallback(async We=>{const tt=We?.reason||"initial-load",Fe=We?.ignoreAuthGuard===!0,Ze=We?.tasksSilent!==!1,St=We?.includeDeferredArchive!==!1,ot=xa();if(g("auth"),!await M({force:!0}))return await ee({ignoreAuthGuard:!0}),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(xa()-ot)),authenticated:!1,workspaceSetupRequired:!1,success:!1}),{success:!1,authenticated:!1,workspaceSetupRequired:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};if(_e){const Le=await ht();if(!Le.success)return await ee({ignoreAuthGuard:!0}),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(xa()-ot)),authenticated:!0,workspaceSetupRequired:!1,success:!1,error:Le.error||"Workspace resolution failed."}),{success:!1,authenticated:!0,workspaceSetupRequired:!1,error:Le.error||"Unable to resolve workspace access.",code:Le.code};if(Le.workspaceSetupRequired)return await ee({ignoreAuthGuard:!0}),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(xa()-ot)),authenticated:!0,workspaceSetupRequired:!0,success:!0}),{success:!0,authenticated:!0,workspaceSetupRequired:!0}}Q(!0);try{await Rt({ignoreAuthGuard:Fe});const Le=String(A.current||"default").trim()||"default",At=xa();return Oe(Ze,{ignoreAuthGuard:Fe}).then(()=>{Ut("cloud_bootstrap_tasks_loaded_deferred",{reason:tt,workspaceId:Le,durationMs:Math.max(0,Math.round(xa()-At))})}).catch(jt=>{Ut("cloud_bootstrap_tasks_deferred_failed",{reason:tt,workspaceId:Le,error:jt instanceof Error?jt.message:String(jt)})}),Qe({ignoreAuthGuard:Fe}).then(()=>{Ut("cloud_bootstrap_reference_data_loaded_deferred",{reason:tt,workspaceId:Le,durationMs:Math.max(0,Math.round(xa()-At))})}).catch(jt=>{Ut("cloud_bootstrap_reference_data_deferred_failed",{reason:tt,workspaceId:Le,error:jt instanceof Error?jt.message:String(jt)})}),st({ignoreAuthGuard:Fe}),St&&ze(),Ut("cloud_bootstrap_completed",{reason:tt,durationMs:Math.max(0,Math.round(xa()-ot)),authenticated:!0,workspaceSetupRequired:!1,success:!0,workspaceId:Le}),{success:!0,authenticated:!0,workspaceSetupRequired:!1}}finally{Q(!1)}},[M,A,Rt,st,Qe,Oe,g,ht,ze,Q,_e]);return r.useEffect(()=>{!t&&!n&&!dt.current&&(dt.current=!0,(async()=>{const We=xa();if(V==="cloud"&&re&&oe){const tt=await Dt({reason:"initial-load",tasksSilent:!1,includeDeferredArchive:!0});if(!tt.success||tt.workspaceSetupRequired)return}else await Promise.all([Rt(),Oe(!1),Qe()]),st();V!=="cloud"&&ze(),Ut("bootstrap_initial_load_completed",{durationMs:Math.max(0,Math.round(xa()-We)),runtimeMode:V,workspaceId:String(A.current||"default").trim()||"default"})})())},[re,A,Rt,st,Qe,Oe,dt,oe,Dt,V,ze,n,t]),r.useEffect(()=>{if(t||n||De||R==="bootstrap"||!dt.current)return;const We=`${V}:${b}:${R}`;$.current!==We&&($.current=We,ee())},[b,ee,dt,$,V,n,t,De,R]),r.useEffect(()=>{if(t||n||De)return;const We=b;U.current!==We&&(U.current=We,Ye())},[b,U,Ye,n,t,De]),r.useEffect(()=>{if(V!=="cloud"||!re||!oe){V!=="cloud"&&ye([]),ue.current=!1;return}De||!dt.current||ue.current||ft()},[re,ft,dt,oe,V,ye,De,ue]),{fetchReferenceData:Qe,fetchBootstrapConfig:Rt,fetchConfig:ee,fetchWorkspaces:ft,fetchAssigneeOptions:it,switchWorkspace:Et,resolveWorkspaceAfterAuth:ht,retryBootstrapChecks:Ot,runCloudBootstrap:Dt}}function Eb({isOpen:e,authBlocked:t,authRequiredForApi:n,isAuthenticated:s,canCallProtectedApi:o,shouldGateProtectedApiCalls:l,authSessionResolvedRef:i,authRequiredForApiRef:d,isAuthenticatedRef:m,dataVersionRef:y,refreshTaskCollectionsForDataVersion:k}){r.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||Rb({isOpen:e,authBlocked:t,authRequiredForApi:n,isAuthenticated:s,canCallProtectedApi:o}))return;let S=!1;const h=async()=>{if(!(S||document.visibilityState!=="visible")&&!jb({shouldGateProtectedApiCalls:l,authSessionResolved:i.current,authRequiredForApi:d.current,isAuthenticated:m.current}))try{const _=await fetch("/api/taskforce/data-version");if(!_.ok)return;const I=await _.json(),C=Number(I?.dataVersion);if(!Number.isFinite(C))return;if(y.current===null){y.current=C;return}C!==y.current&&(y.current=C,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,n,s,o,l,i,d,m,y,k])}const Db={};function si(e,t){const n=e.findIndex(s=>s.id===t.id);return n===-1?[...e,t]:e.map((s,o)=>o===n?t:s)}const No=mf(Db),Sp=(()=>{const e=No.baseUrl,t=No.cloudAuthBaseUrl;if(t)return t;const n=No.apiBaseUrl;return n||e||"https://app.taskforcehq.ai"})(),$u=2e4,Lb=new Set(["external-abort","superseded","workspace-reset","workspace-transition"]);function Ju(e){return typeof DOMException<"u"&&e instanceof DOMException?e.name==="AbortError":String(e?.name||"").toLowerCase()==="aborterror"}function qp(e){return typeof e=="string"&&Lb.has(e)}function wp(e,t){return t.aborted?e===t.reason||qp(e)||qp(t.reason)?!0:Ju(e):!1}function xh(e){const t=new Error(`Startup checks timed out after ${e}ms.`);return t.name="BootstrapTimeoutError",t}function Ih(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.initiatives)?t.initiatives.filter(l=>!!(l&&typeof l=="object"&&typeof l.id=="string")):[],s=Array.isArray(t.workstreams)?t.workstreams.filter(l=>!!(l&&typeof l=="object"&&typeof l.id=="string")):[],o=Array.isArray(t.workstreamTaskSummaries)?t.workstreamTaskSummaries.flatMap(l=>{if(!l||typeof l!="object")return[];const i=String(l.workstreamId||"").trim();if(!i)return[];const d=Array.isArray(l.tasks)?l.tasks:[],m=Math.max(0,Number(l.taskCount)||0),y=Math.max(0,Number(l.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:n,workstreams:s,workstreamTaskSummaries:o}}function Bb({config:e={},initialTaskId:t,onTaskCountChange:n,onClose:s}){const o={...Cv,...e},{categories:l,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,C]=r.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[D,q]=r.useState(!1),B=r.useCallback(f=>typeof f=="string"?f.trim().replace(/\/+$/,""):"",[]);r.useEffect(()=>{if(typeof window>"u"){q(!0);return}let f=!1;return(async()=>{try{const L=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!L.ok)return;const G=await L.json().catch(()=>({})),Z=G?.config&&typeof G.config=="object"?G.config:{};if(f)return;const Be=String(Z.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",Ve=String(Z.workspaceMode||"").trim(),pa=Ve==="single-local"||Ve==="multi-cloud"?Ve:Be==="cloud"?"multi-cloud":"single-local";R(Be),C({cloudEnvironment:typeof Z.cloudEnvironment=="string"?String(Z.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:B(Z.cloudBaseUrl),cloudMcpBaseUrl:B(Z.cloudMcpBaseUrl),baseUrl:B(Z.baseUrl),apiBaseUrl:B(Z.apiBaseUrl),cloudAuthBaseUrl:B(Z.cloudAuthBaseUrl),wsBaseUrl:B(Z.wsBaseUrl),cloudAuthViaLocalProxy:!!Z.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:pa,workspaceSwitchingEnabled:typeof Z.workspaceSwitchingEnabled=="boolean"?!!Z.workspaceSwitchingEnabled:pa==="multi-cloud"})}catch{}finally{f||q(!0)}})(),()=>{f=!0}},[B]);const X=typeof window>"u"?"":v?Sp:"",me=B(No.baseUrl),ke=B(No.apiBaseUrl),le=B(No.cloudBaseUrl),O=B(No.cloudMcpBaseUrl),A=B(No.cloudAuthBaseUrl),de=B(No.wsBaseUrl),ge=B(m),Y=B(y),P=B(k),H=I.apiBaseUrl||I.baseUrl,ye=ge||H||(v?"":ke||me)||"",V=Y||A||me,Me=I.cloudAuthBaseUrl||I.baseUrl,re=((v?Me||V:V||Me)||ye||X).trim().replace(/\/+$/,""),oe=B(eS(I.cloudMcpBaseUrl||I.cloudAuthBaseUrl||I.cloudBaseUrl||P||Y||O||A||le||re)),Ie=(I.cloudMcpBaseUrl||P||oe||I.cloudBaseUrl||O||le||re||X).trim().replace(/\/+$/,""),Ee=!_&&!!re&&!ye,je=_||D&&!!(re||ye),Pe=je&&!Ee,K=!!(re||ye||_),x=_?"cloud":"local",[b,R]=r.useState(()=>x),F=x==="local"&&v&&K?hf():"",Q=F.length>0,M=r.useCallback(f=>!f||/^https?:\/\//i.test(f)||!ye||!f.startsWith("/")?f:`${ye}${f}`,[ye]),$=r.useCallback(f=>{if(!f||/^https?:\/\//i.test(f)||!f.startsWith("/"))return f;const L=f.startsWith("/api/taskforce/auth/")||f.startsWith("/api/taskforce/account/")||f.startsWith("/api/taskforce/billing/")||f.startsWith("/api/taskforce/sync/")||f.startsWith("/api/taskforce/settings/mcp/");if(!_&&L&&(b==="cloud"||!D||I.cloudAuthViaLocalProxy||I.workspaceMode==="multi-cloud"))return f;const G=re||ye;if(G){const Z=`${G}${f}`;if(typeof window<"u"&&!_&&L)try{if(new URL(Z,window.location.origin).origin===window.location.origin)return`${Sp}${f}`}catch{return`${Sp}${f}`}return Z}return f},[D,I.cloudAuthViaLocalProxy,I.workspaceMode,re,ye,_,b]),be=r.useCallback(f=>{const L=String(f||"").trim()||"/taskforce-ws",G=L.startsWith("/")?L:`/${L}`,Z=String(S||I.wsBaseUrl||de||ye||"").trim().replace(/\/+$/,""),He=typeof window<"u"?window.location.origin:"",Be=Z||He;if(!Be)return"";try{const Ve=new URL(G,Be);return Ve.protocol==="https:"&&(Ve.protocol="wss:"),Ve.protocol==="http:"&&(Ve.protocol="ws:"),Ve.toString()}catch{return""}},[S,I.wsBaseUrl,de,ye]),[U,se]=r.useState("tasks"),[pe,z]=r.useState(!1),[ne,ie]=r.useState(!1),[Re,Te]=r.useState("open"),[De,Oe]=r.useState(Kc(o.theme)||rm),[vt,st]=r.useState(Kc(o.theme)||rm),[kt,Ye]=r.useState(!0),[Ct]=r.useState(".taskforce"),dt=!1,[Qe,Rt]=r.useState(!1),[ee,ze]=r.useState([]),[ft,it]=r.useState([]),[Et,ht]=r.useState(""),[Ot,Dt]=r.useState(null),[We,tt]=r.useState(null),[Fe,Ze]=r.useState(""),[St,ot]=r.useState(""),te=r.useMemo(()=>qv({projectRoot:Fe,runtimeMode:x}),[Fe,x]),[Le,At]=r.useState(""),[jt,Wt]=r.useState(""),Ge=Jv(b),$t=I.workspaceMode==="single-local"||I.workspaceMode==="multi-cloud"?I.workspaceMode:Ge.workspaceMode,yt=typeof I.workspaceSwitchingEnabled=="boolean"?I.workspaceSwitchingEnabled:Ge.workspaceSwitchingEnabled,[E,c]=r.useState(!1),[J,we]=r.useState(!1),[xe,Ke]=r.useState(Q),[Je,Ne]=r.useState(Q?F:"anonymous"),[zt,Jt]=r.useState(""),[Pt,Ft]=r.useState(""),[Lt,Ht]=r.useState(""),[ra,Vt]=r.useState([]),[Ga,Va]=r.useState(""),[qa,cn]=r.useState(!0),[he,rt]=r.useState(null),[Ae,Nt]=r.useState(()=>{if(x==="local")return"default";const f=Wp(te);return f&&f.toLowerCase()!=="default"?f:"default"}),pt=r.useMemo(()=>Kv({projectRoot:Fe,runtimeMode:b,workspaceId:Ae}),[Fe,b,Ae]),[wt,Ca]=r.useState([]),[ya,ia]=r.useState(()=>li()),[ca,Oa]=r.useState(!1),[gt,rr]=r.useState(Q),[ua,ta]=r.useState("idle"),[wa,Kt]=r.useState(null),[vr,Ta]=r.useState(null),Qa=r.useRef(null),Ra=r.useRef(0),Zt=r.useRef(0),Ka=r.useRef(Q),aa=r.useRef(Ae),ln=r.useRef(null),yn=r.useRef(0),Sr=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"),[la,wr]=r.useState(0),qr=r.useRef(null),Vn=r.useRef(null),kn=r.useRef(null),$a=r.useRef(null),br=r.useRef(null),dn=r.useRef(null),Ea=r.useRef(null),ja=r.useCallback((f,L)=>{const G=String(f||"").trim();if(!G)return;const Z=String(aa.current||"").trim();Z&&Z!==G&&(yn.current+=1,wr(yn.current)),aa.current=G,L?.clearExplicitSelection!==!1&&(ln.current=null),Nt(G)},[]);r.useEffect(()=>{aa.current=Ae},[Ae]);const _r=r.useCallback(f=>{const L=String(f||"").trim();L&&Nt(()=>{const G=String(ln.current||"").trim();let Z=L;return G&&G!==L&&(Z=G),aa.current=Z,Z})},[]),xt=r.useCallback(()=>({workspaceId:String(aa.current||"default").trim()||"default",epoch:yn.current}),[]),vn=r.useCallback(f=>(String(aa.current||"default").trim()||"default")!==f.workspaceId||yn.current!==f.epoch,[]),Sn=r.useCallback(f=>yn.current!==f.epoch,[]),un=r.useCallback(f=>Ju(f)||qp(f),[]),Ua=r.useCallback(()=>{[qr,Vn,kn,$a,br,dn].forEach(f=>{f.current?.abort("workspace-transition"),f.current=null}),Ea.current!==null&&typeof window<"u"&&(window.clearTimeout(Ea.current),Ea.current=null),Nc.current=null},[]),sr=r.useMemo(()=>Tb({shouldGateProtectedApiCalls:Pe,runtimeMode:b,authSessionResolved:gt,authRequiredForApi:E,isAuthenticated:xe}),[Pe,b,gt,E,xe]),Na=sr.shouldDeferProtectedApiCalls,ka=sr.shouldBlockProtectedApiCalls,[Ln,wn]=r.useState(null),[va,Yt]=r.useState(null),[bn,za]=r.useState(!1),[Pa,Bn]=r.useState("unknown"),[Ma,Mr]=r.useState(null),[na,da]=r.useState(o.shortcut||"Alt+T"),[Xa,or]=r.useState(o.priorities||[]),[Er]=r.useState(Ig()),[Cr,Xt]=r.useState(""),[_n,Cn]=r.useState(!1),[Ar,xr]=r.useState(!1),[qn,Kn]=r.useState(!0),[ir,en]=r.useState(()=>Hv()),An=r.useMemo(()=>zv(),[]),[Zn,tn]=r.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[cs,Za]=r.useState(!1),[Kr,Dr]=r.useState(!0),[xn,cr]=r.useState(!0),[Wn,mn]=r.useState(""),[lr,Zr]=r.useState(null);Cb({currentWorkspaceIdRef:aa,resolveApiUrl:M,runtimeMode:b});const{availableWorkflows:ls,initiativeTemplates:et,fetchWorkflows:Bt,fetchInitiativeTemplates:Da,fetchWorkflowTemplate:Aa,fetchWorkflowOverrideNames:Sa,saveWorkflowTemplateDraft:In,resetWorkflowTemplateDraft:Yn}=Yw({shouldDeferProtectedApiCalls:Na,shouldBlockProtectedApiCalls:ka}),{zenMode:ds,setZenModeState:Fn,toggleZenMode:On}=Jw(),{exportEnvironment:Tn,setExportEnvironment:Gt,availableEnvironments:$n,loadAvailableEnvironments:pn,exportWorkflowsPath:La,setExportWorkflowsPath:Lr,exportingResource:Br,exportResult:dr,handleExportWorkflows:ur}=Vw({storagePath:Ct,shouldDeferProtectedApiCalls:Na,shouldBlockProtectedApiCalls:ka}),[Fs,nn]=r.useState(!1),[fn,so]=r.useState(null),{uiNotice:Wr,pushNotice:mr,clearNotice:W}=Gw(),[$e,It]=r.useState([]),Mt=r.useRef(null),[Ha,Jn]=r.useState(0),Yr=r.useCallback(f=>!f||!Fe?f:f.startsWith(Fe)?f.slice(Fe.length).replace(/^[/\\]+/,""):f,[Fe]),[Ba,Fr]=r.useState([]),[Wa,T]=r.useState([]),[j,at]=r.useState([]),[bt,ve]=r.useState([]),[ae,Rn]=r.useState([]),[jn,hn]=r.useState([]),[Os,Jr]=r.useState(!1),[Nn,$s]=r.useState(null),[oo,Lo]=r.useState(!1),[us,di]=r.useState([]),[Pn,io]=r.useState(!1),[ui,mi]=r.useState({}),pi=r.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});r.useEffect(()=>{pi.current={authSessionResolved:gt,configLoaded:Pn,workspaceBootstrapPending:ca}},[gt,Pn,ca]);const Or=r.useCallback(f=>{ta(f),f!=="ready"&&(Kt(null),Ta(Date.now()))},[]),Bo=r.useCallback(f=>{const L=pi.current;L.authSessionResolved&&L.configLoaded&&!L.workspaceBootstrapPending||(ta("stalled"),Kt(f),Ta(G=>G??Date.now()))},[]),ms=r.useCallback(async(f,L,G=od,Z)=>{const He=new AbortController,Be=Z?.signal,Ve=Number(G)>0?Number(G):od,pa=xt(),fa=f.startsWith("/api/taskforce/")?hp(L,nh({workspaceId:pa.workspaceId,epoch:pa.epoch,seed:Sr.current})):L,Fa=typeof window<"u"?window.setTimeout(()=>He.abort("bootstrap-timeout"),Ve):null,ba=()=>{He.abort(Be?.reason||"external-abort")};Be&&(Be.aborted?ba():Be.addEventListener("abort",ba,{once:!0}));try{return await fetch(f,{...fa||{},signal:He.signal})}catch(En){throw Be?.aborted&&wp(En,Be)?Be.reason||En:Ju(En)||En==="bootstrap-timeout"?xh(Ve):En}finally{Be&&Be.removeEventListener("abort",ba),Fa!==null&&typeof window<"u"&&window.clearTimeout(Fa)}},[xt]),rc=r.useMemo(()=>{const f=!gt,L=ua==="stalled",G=gt&&(!Pn||ca||L);let Z="Checking account, workspace access, and setup status...";return ua==="auth"?Z="Verifying session...":ua==="workspace"?Z="Resolving workspace access...":ua==="config"&&(Z="Loading configuration..."),{phase:ua,auth:{resolved:gt,pending:f},config:{loaded:Pn},workspace:{pending:ca},pending:f||G,authPending:f,appPending:G,ready:gt&&Pn&&!ca&&ua==="ready",stalled:L,subtitle:Z,error:wa,startedAt:vr}},[gt,wa,ua,vr,Pn,ca]),Qr=r.useCallback(f=>String(f?.name||"")==="BootstrapTimeoutError",[]),[co,Is]=r.useState([]),[Ts,lo]=r.useState({}),[ps,fi]=r.useState(o.taxonomies||[]),ha=r.useMemo(()=>(us.length>0?us:l||[]).map(L=>typeof L=="string"?{value:L.toLowerCase().replace(/\s+/g,"-"),label:L}:L).sort((L,G)=>L.label.localeCompare(G.label)),[us,l]),sc=r.useMemo(()=>({categories:ha,types:co,priorities:Xa,taxonomies:ps,displayLabels:Ts}),[ha,co,Xa,ps,Ts]);r.useMemo(()=>ha.filter(f=>!f.disabled),[ha]);const Qn=r.useCallback(f=>f.find(G=>G.value==="default"||G.value==="general"||G.label==="General"||G.value==="Taskforce"||G.label==="Taskforce")?.value||f[0]?.value||"default",[]),sa=co.length>0?co:i,[uo,Xr]=r.useState(!1),[mo,$r]=r.useState(""),oc="Authentication required. Sign in to continue.",[Rs,pr]=r.useState(!1),[Us,rn]=r.useState(!1),fs=r.useCallback(()=>{we(b==="cloud"),Ke(!1),Ft(""),Ht(""),Va(""),$r(oc)},[oc,b]),{recentlyChangedTaskIds:zs,fetchTasks:po,fetchArchive:Hs,refreshTaskCollections:Wo,refreshTaskCollectionsFromInvalidation:Gs,mergeTaskFromServer:fo}=Xw({tasks:Ba,archivedTasks:Wa,setTasks:Fr,setArchivedTasks:T,setLoadingTasks:Jr,getCurrentWorkspaceId:()=>aa.current,workspaceResetKey:`${Ae}:${la}`,shouldDeferProtectedApiCalls:Na,shouldBlockProtectedApiCalls:ka,handleUnauthorized:fs,authRequiredForApi:E});r.useEffect(()=>{la!==0&&(Nc.current=null,Pi.current="",Ko.current="",Mi.current="",Rc.current="",Ps.current="",Ei.current="",Ms(!1),pr(!1),ia(li()),rn(!1),hn([]),Fr([]),T([]),Jr(!1),Mn.current!==null&&typeof window<"u"&&(window.clearTimeout(Mn.current),Mn.current=null),vs.current!==null&&typeof window<"u"&&(window.clearTimeout(vs.current),vs.current=null))},[T,Jr,Fr,la]);const fr=r.useCallback(async(f=!1,L)=>{if(!(L?.ignoreAuthGuard===!0)&&(Na||ka))return;f||Jr(!0);const Z=xt(),He=new AbortController;br.current=He;try{let Be=await fetch("/api/taskforce/deleted",{signal:He.signal});if(Be.status===404&&(Be=await fetch("/api/taskforce/trash",{signal:He.signal})),Be.status===401){fs(),hn([]);return}if(Be.status===404){hn([]);return}if(Be.ok){const Ve=await Be.json();if(vn(Z))return;const pa=Array.isArray(Ve?.deleted)?Ve.deleted.map(fa=>{const Fa=fa?.taskSnapshot&&typeof fa.taskSnapshot=="object"?Do(fa.taskSnapshot):null;return Fa?{...fa,taskSnapshot:Fa}:null}).filter(fa=>!!fa):[];hn(pa)}}catch(Be){if(wp(Be,He.signal)||un(Be))return;console.error("[Taskforce] Failed to fetch deleted tasks:",Be)}finally{br.current===He&&(br.current=null),f||Jr(!1)}},[xt,fs,un,vn,Na,ka]),ma=r.useCallback(async f=>{if(!(f?.ignoreAuthGuard===!0)&&(Na||ka))return;const G=xt();dn.current?.abort("superseded"),Ea.current!==null&&typeof window<"u"&&(window.clearTimeout(Ea.current),Ea.current=null);const Z=new AbortController;dn.current=Z;try{const He=nh({workspaceId:G.workspaceId,epoch:G.epoch,seed:Sr.current}),Be=async fa=>{if(typeof window>"u")return fetch(fa,hp({signal:Z.signal},He));const Fa=new AbortController,ba=window.setTimeout(()=>Fa.abort("planning-timeout"),$u),En=()=>Fa.abort(Z.signal.reason||"external-abort");Z.signal.aborted?En():Z.signal.addEventListener("abort",En,{once:!0});try{return await fetch(fa,hp({signal:Fa.signal},He))}catch(Pr){if(Z.signal.aborted)throw Z.signal.reason||Pr;if(Ju(Pr)||Pr==="planning-timeout")return null;throw Pr}finally{window.clearTimeout(ba),Z.signal.removeEventListener("abort",En)}};let Ve=null;const pa=await Be("/api/taskforce/planning/bootstrap");if(pa?.status===401){fs(),at([]),ve([]),Rn([]);return}if(pa===null)throw xh($u);if(pa.ok)Ve=Ih(await pa.json().catch(()=>({})));else{const[fa,Fa]=await Promise.all([Be("/api/taskforce/initiatives"),Be("/api/taskforce/workstreams")]);if(!fa||!Fa)throw new Error("Planning endpoints timed out during startup.");if(fa.status===401||Fa.status===401){fs(),at([]),ve([]),Rn([]);return}const[ba,En]=await Promise.all([fa.ok?fa.json().catch(()=>[]):[],Fa.ok?Fa.json().catch(()=>[]):[]]);Ve=Ih({initiatives:ba,workstreams:En,workstreamTaskSummaries:[]})}if(vn(G))return;at(Ve.initiatives),ve(Ve.workstreams),Rn(Ve.workstreamTaskSummaries)}catch(He){if(wp(He,Z.signal)||un(He))return;Qr(He)?(Ut("planning_bootstrap_timeout",{workspaceId:G.workspaceId,epoch:G.epoch,timeoutMs:$u}),console.warn("[Taskforce] Planning bootstrap timed out during startup; retrying in background.")):console.error("[Taskforce] Failed to fetch planning entities:",He),typeof window<"u"&&!vn(G)&&j.length===0&&bt.length===0&&(Ea.current=window.setTimeout(()=>{Ea.current=null,ma(f)},3e3))}finally{dn.current===Z&&(dn.current=null)}},[od,$u,j.length,xt,fs,un,vn,Na,ka,bt.length]),an=r.useCallback(async(f=!1,L)=>{await po(f,L)},[po]),Xn=r.useCallback(async(f=!1,L)=>{await Hs(f,L)},[Hs]),es=r.useCallback(async f=>{const L=f?.isSilent!==!1,G=f?.ignoreAuthGuard===!0;await Promise.all([Wo({isSilent:L,ignoreAuthGuard:G}),fr(L,{ignoreAuthGuard:G}),ma({ignoreAuthGuard:G})])},[fr,ma,Wo]),hi=r.useCallback(async()=>{await Gs(),await fr(!0),await ma()},[fr,ma,Gs]),Vs=r.useRef(()=>{}),ic=r.useRef(()=>{}),sl=r.useRef(async()=>!1),sn=r.useCallback(f=>sl.current(f),[]),{userGlobalSyncStatus:ho,setUserGlobalSyncStatus:Fo,userGlobalSyncError:go,setUserGlobalSyncError:Oo,workspaceLastPullAt:Nm,workspaceLastPushAt:ol,workspaceLastErrorAt:Pm,workspaceLastErrorMessage:il,workspaceLastSuccessfulSyncAt:er,workspaceCloudSyncEnabled:hs,workspaceSyncPhase:yo,workspaceSyncSetupIntent:gi,workspaceSyncStatus:Mm,workspaceSyncSummary:Ad,workspaceSyncRecommendedAction:$o,workspaceSyncBusy:Em,workspaceSyncPendingChanges:xd,workspacePendingSignatureRef:Id,workspaceDeletedTaskIdsRef:qs,workspaceDeletedTaskWatermarksRef:Td,loadWorkspaceSyncState:cl,applyWorkspaceSyncStateSnapshot:Rd,syncUserGlobalSettings:cc,buildWorkspaceSyncSignature:ll,pushWorkspaceChangesToCloud:Uo,saveWorkspaceCloudSyncSettings:ko,retryUserGlobalSettingsSync:lc,retryWorkspaceCloudSync:gs,resetWorkspaceSyncCursorAndPull:yi,getWorkspaceSyncDiagnostics:zo}=zw({currentWorkspaceId:Ae,cloudAuthConfigured:K,runtimeMode:b,authSessionResolved:gt,isAuthenticated:xe,authUserId:Je,projectName:St,resolveCloudAuthUrl:$,resolveWebSocketUrl:be,realtimeSyncEnabled:bn,tasks:Ba,archivedTasks:Wa,deletedTasks:jn,initiatives:j,workstreams:bt,taxonomies:ps,taxonomyState:Rs?sc:void 0,setupState:Ln,globalTheme:vt,locale:ir,globalWeekStartsOn:Zn,themeUseGlobalDefault:kt,setTasks:Fr,setArchivedTasks:T,setAuthBlocked:we,setIsAuthenticated:Ke,checkAuthSession:sn,setGlobalTheme:st,setCurrentTheme:Oe,setSetupState:wn,setLocale:en,setGlobalWeekStartsOn:tn,fetchPlanningEntities:ma}),ki=r.useCallback((f=sa)=>f.find(L=>String(L.value||"").trim().length>0)?.value||Vr,[sa]),[Ks,Ir]=r.useState(()=>Qn(ha)),[vo,js]=r.useState(()=>ki(sa)),[oa,Ho]=r.useState(2),[dc,dl]=r.useState(3),[ul,So]=r.useState("task"),[ml,pl]=r.useState("default"),[fl,vi]=r.useState("unassigned"),[Un,Ns]=r.useState(""),[jd,Nd]=r.useState(""),[zn,Si]=r.useState(""),[wi,bi]=r.useState(""),[uc,hl]=r.useState(""),[Zs,mc]=r.useState([]),[gl,_i]=r.useState([]),[Ci,pc]=r.useState(""),[fc,_t]=r.useState({}),Pd=r.useRef(null),[hc,ys]=r.useState(!1),[Go,gc]=r.useState("");r.useEffect(()=>{if(Nn)return;const f=String(vo||"").trim();sa.some(G=>String(G.value||"").trim()===f)||js(ki(sa))},[sa,Nn,ki,vo]);const{searchQuery:yc,setSearchQuery:Md,filterCategories:kc,setFilterCategories:Tr,filterPriorities:Ya,setFilterPriorities:Ai,filterTypes:yl,setFilterTypes:Ed,filterStatus:wo,setFilterStatus:Dd,filterAssignees:kl,setFilterAssignees:ts,filterAssigneesAllSelected:Ld,setFilterAssigneesAllSelected:Bd,filterTaxonomies:vc,setFilterTaxonomies:xi,hasInitedFilters:bo,setHasInitedFilters:Ii,sortBy:Sc,setSortBy:wc,sortOrder:vl,setSortOrder:Wd,toggleSortOrder:Vo,groupBy:ks,setGroupBy:tr,emptyColumnMode:_o,setEmptyColumnMode:Co,collapsedCategories:Sl,setCollapsedCategories:wl,clearFilters:Dm,filteredTasks:bc,searchAgnosticTasks:_c,filteredArchive:Fd,groupedTasks:Od}=kb({tasks:Ba,archivedTasks:Wa,activeCategories:ha,activeTypes:sa,priorities:Xa,taxonomies:ps,configLoaded:Pn,referenceDataLoaded:Rs,assigneeOptionsLoaded:Us,assigneeOptions:ya});Vs.current=Fo,ic.current=Oo;const{checkAuthSession:bl}=Ib({runtimeConfigReady:D,shouldProbeCloudAuth:je,authSessionResolved:gt,resolveCloudAuthUrl:$,authOnlyCloudMode:Ee,authRequiredError:oc,runtimeMode:b,workspaceSelectionScope:te,markBootstrapPhase:Or,markBootstrapStalled:Bo,setRuntimeMode:R,setAuthRequiredForApi:c,setIsAuthenticated:Ke,setAuthUserId:Ne,setAuthWorkspaceId:Jt,setAuthUserEmail:Ft,setAuthUserDisplayName:Ht,setAuthUserAvatarUrl:Va,setUserGlobalSyncStatus:f=>Vs.current(f),setUserGlobalSyncError:f=>ic.current(f),setHasBetaAccess:cn,setAvailableWorkspaces:Ca,setHydratedWorkspaceRole:rt,setAssigneeOptions:ia,setAuthBlocked:we,setAuthSessionResolved:rr,setError:$r,applyResolvedWorkspaceId:_r,readPersistedWorkspaceId:Wp,authSessionRequestRef:Qa,authSessionEpochRef:Ra,authSessionLastCheckedAtRef:Zt,authSessionLastResultRef:Ka,isLoopbackHost:v,setAuthStateReadyRefs:(f,L,G)=>{Ic.current=L,Tc.current=G,qo.current=f}});sl.current=bl;const[_l,Ti]=r.useState("tasks"),[Lm,$d]=r.useState(!1),[Bm,Ri]=r.useState(!1),[Cc,Ac]=r.useState(!1),[xc,ji]=r.useState([]),[Ud,Ni]=r.useState(!1),Wm=r.useRef(null),Mn=r.useRef(null),vs=r.useRef(null),Rr=r.useRef(!1),Ic=r.useRef(gt),Tc=r.useRef(E),qo=r.useRef(xe),Cl=r.useRef(!1),Pi=r.useRef(""),Ko=r.useRef(""),Mi=r.useRef(""),Rc=r.useRef(""),Ps=r.useRef(""),Ei=r.useRef(""),Di=r.useRef(!1),jc=r.useRef(!1),Nc=r.useRef(null),Al=r.useRef(!1),zd=r.useRef(!1),[Zo,Ms]=r.useState(!1),Fm=r.useCallback(f=>{Zo||(jc.current=!0),Ti(f)},[Zo]),{handleSaveSettings:Hd,handleSaveTheme:Gd,handleSaveGlobalTheme:Om,handleJsonBackupEnabledChange:$m,handleSaveGlobalJsonBackupEnabled:Um,handleSaveGlobalWeekStartsOn:zm,handleSaveLocale:Vd,handleManualComplexityEnabledChange:Hm,handleChecklistDropdownEnabledChange:gn,handleShowTaskCardStatusLabelChange:xl,handleResetProjectToGlobal:qd}=Kw({keyShortcut:na,themeUseGlobalDefault:kt,runtimeMode:b,jsonBackupUseGlobalDefault:qn,globalTheme:vt,globalJsonBackupEnabled:Ar,setCurrentTheme:Oe,setThemeUseGlobalDefault:Ye,setGlobalTheme:st,setJsonBackupEnabled:Cn,setJsonBackupUseGlobalDefault:Kn,setGlobalJsonBackupEnabled:xr,setGlobalWeekStartsOn:tn,setLocale:en,setManualComplexityEnabled:Za,setChecklistDropdownEnabled:Dr,setShowTaskCardStatusLabel:cr,setShowChecklist:ys});r.useEffect(()=>{b==="cloud"&&te!==ec&&fS(Ae,te)},[b,Ae,te]),r.useEffect(()=>{Ic.current=gt,Tc.current=E,qo.current=xe},[gt,E,xe]);const Pc=r.useCallback((f,L)=>{if(!f)return;const G=Array.isArray(f.filterCategories)||Array.isArray(f.filterPriorities)||Array.isArray(f.filterTypes)||Array.isArray(f.filterStatus)||Array.isArray(f.filterAssignees)||typeof f.filterAssigneesAllSelected=="boolean"||f.filterTaxonomies&&typeof f.filterTaxonomies=="object";L?.skipActiveWorkspaceModule||(typeof f.activeWorkspaceModule=="string"?Ti(f.activeWorkspaceModule):f.groupBy==="docs"&&Ti("docs")),f.groupBy&&f.groupBy!=="docs"&&tr(f.groupBy),(f.emptyColumnMode==="show"||f.emptyColumnMode==="collapse"||f.emptyColumnMode==="hide")&&Co(f.emptyColumnMode),typeof f.zenMode=="boolean"&&Fn(f.zenMode),typeof f.searchQuery=="string"&&Md(f.searchQuery),Array.isArray(f.filterCategories)&&Tr(f.filterCategories),Array.isArray(f.filterPriorities)&&Ai(f.filterPriorities),Array.isArray(f.filterTypes)&&Ed(f.filterTypes),Array.isArray(f.filterStatus)&&Dd(f.filterStatus),Array.isArray(f.filterAssignees)&&ts(f.filterAssignees),typeof f.filterAssigneesAllSelected=="boolean"&&Bd(f.filterAssigneesAllSelected),f.filterTaxonomies&&typeof f.filterTaxonomies=="object"&&xi(f.filterTaxonomies),(f.sortBy==="created"||f.sortBy==="priority"||f.sortBy==="updated"||f.sortBy==="complexity")&&wc(f.sortBy),(f.sortOrder==="asc"||f.sortOrder==="desc")&&Wd(f.sortOrder),typeof f.hasInitedFilters=="boolean"?Ii(f.hasInitedFilters):G&&Ii(!0),typeof f.showChecklist=="boolean"&&ys(f.showChecklist),typeof f.lastCategory=="string"&&gc(f.lastCategory),typeof f.exportEnvironment=="string"&&f.exportEnvironment.trim().length>0&&Gt(f.exportEnvironment.trim())},[]),Mc=r.useCallback(async f=>{const L=String(f||aa.current||Ae||"default").trim()||"default",G=`${b}:${pt}:${L}`;try{const Z=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(L)}`,{method:"GET",credentials:"include"}),He=Z.ok?await Z.json().catch(()=>({})):{},Be=He?.state&&typeof He.state=="object"?He.state:null,Ve=oh(pt),pa=Be||Ve?{...Ve||{},...Be||{}}:null;if(aa.current!==L)return;Pc(pa,{skipActiveWorkspaceModule:jc.current}),Pi.current=G}catch{const Z=oh(pt);aa.current===L&&(Pc(Z,{skipActiveWorkspaceModule:jc.current}),Pi.current=G)}finally{if(aa.current!==L)return;jc.current=!1,Di.current=!0,Ms(!0)}},[Pc,Ae,b,pt]);r.useEffect(()=>{const f=`${b}:${pt}:${Ae}`;Cl.current&&Pi.current!==f&&(Ms(!1),Mc(Ae))},[Ae,Mc,b,pt]),r.useEffect(()=>{if(!Zo)return;if(Di.current){Di.current=!1;return}const f={groupBy:ks,activeWorkspaceModule:_l,emptyColumnMode:_o,zenMode:ds,searchQuery:yc,filterCategories:kc,filterPriorities:Ya,filterTypes:yl,filterStatus:wo,filterAssignees:kl,filterAssigneesAllSelected:Ld,filterTaxonomies:vc,sortBy:Sc,sortOrder:vl,hasInitedFilters:bo,showChecklist:hc,lastCategory:Go||"",exportEnvironment:Tn};hS(f,pt);const L=window.setTimeout(async()=>{try{await pf({stateKey:"app",workspaceId:aa.current,patch:f})}catch{}},250);return()=>window.clearTimeout(L)},[Zo,ks,_l,_o,ds,yc,kc,Ya,yl,wo,kl,Ld,vc,Sc,vl,bo,hc,Go,Tn,pt]);const Il=r.useCallback(f=>{const L=f.runtimeMode==="cloud"?"cloud":"local",G=!!f.authRequiredForApi,Z=typeof f.userId=="string"&&f.userId.trim().length>0?f.userId.trim():"anonymous",He=L==="cloud"&&Z!=="anonymous",Be=He||qo.current,Ve=Ic.current;if(R(L),c(G),He&&(Ke(!0),Ne(Z),we(!1),Ve||rr(!0)),typeof f.workspaceId=="string"&&f.workspaceId.trim().length>0){const Jl=f.workspaceId.trim();L==="local"?ja(Jl):_r(Jl)}we(L==="cloud"&&G?!Be:!1),f.setupState&&typeof f.setupState=="object"?wn(f.setupState):wn(null),f.runtimeCapabilities&&typeof f.runtimeCapabilities=="object"?Yt(f.runtimeCapabilities):Yt(null),za(!!f.realtimeSyncEnabled);const pa=String(f.realtimeSyncFlagSource||"").trim().toLowerCase();Bn(pa==="env"||pa==="settings"||pa==="default"?pa:"unknown"),typeof f.shortcut=="string"&&f.shortcut.trim().length>0&&da(f.shortcut);const fa=Kc(f.theme);fa&&Oe(fa);const Fa=Kc(f.globalTheme);Fa&&st(Fa),typeof f.themeUseGlobalDefault=="boolean"&&Ye(f.themeUseGlobalDefault);const ba=f.runtimeMode==="cloud"?"cloud":"local";typeof f.projectRoot=="string"?Ze(f.projectRoot):ba==="cloud"&&Ze(""),typeof f.tenantId=="string"?Wt(f.tenantId.trim()):ba==="cloud"&&Wt("");const En=ba==="cloud"?String(f.projectName||"").trim():f.projectName||f.paths?.projectName||"";(String(En||"").trim().length>0||ba==="cloud")&&ot(En),typeof f.mcpScript=="string"?At(f.mcpScript):ba==="cloud"&&At(""),typeof f.hostRoot=="string"?mn(f.hostRoot):ba==="cloud"&&mn(""),typeof f.jsonBackupEnabled=="boolean"&&Cn(f.jsonBackupEnabled),typeof f.globalJsonBackupEnabled=="boolean"&&xr(f.globalJsonBackupEnabled),typeof f.jsonBackupUseGlobalDefault=="boolean"&&Kn(f.jsonBackupUseGlobalDefault);const Pr=f?.schedulePreferences?.weekStartsOn;(Pr==="sunday"||Pr==="monday")&&tn(Pr),typeof f.manualComplexityEnabled=="boolean"&&Za(f.manualComplexityEnabled),typeof f.checklistDropdownEnabled=="boolean"?Dr(f.checklistDropdownEnabled):Dr(!0),typeof f.showTaskCardStatusLabel=="boolean"?cr(f.showTaskCardStatusLabel):cr(!0)},[_r,ja]),Kd=r.useCallback(async()=>{const f=typeof performance<"u"?performance.now():Date.now();try{const L=await ms("/api/taskforce/version",void 0,od);if(!L.ok)return;const G=await L.json().catch(()=>({}));G?.build&&typeof G.build=="object"&&Mr({version:String(G.build.version||""),gitSha:G.build.gitSha?String(G.build.gitSha):null,buildTime:G.build.buildTime?String(G.build.buildTime):null,deployId:G.build.deployId?String(G.build.deployId):null}),Ut("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-f)})}catch(L){Qr(L)&&Ut("build_info_timeout",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-f)})}},[ms,Qr]),{fetchReferenceData:Li,fetchConfig:Ur,fetchWorkspaces:zr,fetchAssigneeOptions:Yo,switchWorkspace:Hr,resolveWorkspaceAfterAuth:Zd,retryBootstrapChecks:Tl,runCloudBootstrap:Ys}=Mb({shouldDeferProtectedApiCalls:Na,shouldBlockProtectedApiCalls:ka,getWorkspaceRequestState:xt,isWorkspaceRequestStale:vn,isWorkspaceEpochStale:Sn,isAbortError:un,isBootstrapTimeoutError:Qr,fetchWithTimeout:ms,handleUnauthorized:fs,applyBootstrapConfig:Il,loadPersistedUiState:Mc,fetchBuildInfo:Kd,markBootstrapPhase:Or,markBootstrapStalled:Bo,fetchWorkflows:Bt,fetchInitiativeTemplates:Da,loadAvailableEnvironments:pn,setReferenceDataLoaded:pr,setCustomCategories:di,setCustomTypes:Is,setPriorities:or,setTaxonomies:fi,setTaxonomyDisplayLabels:lo,setConfigLoaded:io,hasLoadedUiStateRef:Cl,currentWorkspaceIdRef:aa,referenceDataRequestRef:Nc,referenceDataAbortRef:Vn,bootstrapConfigAbortRef:qr,workspaceListAbortRef:kn,assigneeOptionsAbortRef:$a,workspaceListHydratedRef:Al,setAvailableWorkspaces:Ca,runtimeMode:b,applyResolvedWorkspaceId:_r,workspaceSwitchingEnabled:yt,authSessionResolved:gt,isAuthenticated:xe,authUserId:Je,authUserAvatarUrl:Ga,setHydratedWorkspaceRole:rt,setAssigneeOptions:ia,setAssigneeOptionsLoaded:rn,commitCurrentWorkspaceId:(f,L)=>{ln.current=f,ja(f,L),L?.clearExplicitSelection!==!1&&(ln.current=null)},currentWorkspaceId:Ae,workspaceSelectionScope:te,abortWorkspaceScopedRequests:Ua,setWorkspaceBootstrapPending:Oa,checkAuthSession:sn,lastConfigRefreshKeyRef:Mi,lastAssigneeOptionsLoadKeyRef:Ko,lastWorkspaceSyncStateLoadKeyRef:Rc,lastTaskSurfaceLoadKeyRef:Ps,lastSettingsSurfaceLoadKeyRef:Ei,isOpen:pe,activeTab:U,showArchive:ne,taskScope:Re,settingsSection:We,workspaceBootstrapPending:ca,fetchTasks:an,fetchArchive:Xn,fetchPlanningEntities:ma,refreshTaskCollections:es,loadWorkspaceSyncState:cl,archiveBootstrapTimerRef:vs,hasBootstrappedDataRef:zd}),Bi=r.useCallback(async()=>{await sn(),await Ur()},[sn,Ur]);r.useEffect(()=>{if(!Pn||ca)return;const f=`${b}:${xe?"auth":"guest"}:${Ae}:${Ga||"no-avatar"}`;Us&&Ko.current===f||(Ko.current=f,Yo())},[Us,Ga,Pn,Ae,Yo,xe,b,ca]),r.useEffect(()=>{if(!gt||!xe)return;const f=String(Je||"").trim();if(!f||f==="anonymous")return;const L=String(Ga||"").trim()||null;ia(G=>{let Z=!1;const He=G.map(Be=>Be.kind!=="member"||String(Be.value||"").trim()!==f||(typeof Be.avatarUrl=="string"&&Be.avatarUrl.trim().length>0?Be.avatarUrl.trim():null)===L?Be:(Z=!0,{...Be,avatarUrl:L}));return Z?He:G})},[gt,Ga,Je,xe]);const Rl=r.useMemo(()=>yt?wt.find(L=>L.id===Ae)?.role??null:he,[wt,Ae,he,yt]);r.useEffect(()=>{xe||rt(null)},[xe]);const Yd=r.useCallback(async()=>{Kt(null);const f=await Ys({reason:"post-plans",ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return f.authenticated?f.success?f.workspaceSetupRequired?{success:!0,destination:"setup"}:{success:!0,destination:"app"}:{success:!1,destination:"app",error:f.error||"Unable to resolve workspace after plan selection.",code:f.code}:{success:!1,destination:"login",error:f.error||"Sign in required.",code:f.code||"AUTH_REQUIRED"}},[Ys]),Ss=r.useCallback(async f=>{const L=f?.reason||"retry",G=typeof f?.preferredWorkspaceId=="string"?f.preferredWorkspaceId.trim():"",Z=f?.allowCommercialGate===!0;if(G&&yt){if(!await sn({force:!0}))return await Ur({ignoreAuthGuard:!0}),{success:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};const Ve=await Zd({preferredWorkspaceId:G});if(!Ve.success)return await Ur({ignoreAuthGuard:!0}),{success:!1,error:Ve.error||"Unable to resolve workspace access.",code:Ve.code};if(Ve.workspaceSetupRequired)return await Ur({ignoreAuthGuard:!0}),{success:!0,workspaceSetupRequired:!0}}const He=await Ys({reason:L,ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return He.authenticated?He.success?He.workspaceSetupRequired?Z?{success:!0,workspaceSetupRequired:!1}:{success:!0,workspaceSetupRequired:!0}:(Z||cc({preferCloudOnFirstSync:!0}),{success:!0,workspaceSetupRequired:!1}):{success:!1,error:He.error||"Unable to resolve workspace access.",code:He.code}:{success:!1,error:He.error||"Sign in required.",code:He.code||"AUTH_REQUIRED"}},[sn,Ur,Zd,Ys,cc,yt]),Jo=r.useCallback(async(f,L)=>{if(!yt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const G=String(f||"").trim();if(!G)return{success:!1,error:"Workspace name is required."};try{const Z=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:G,description:typeof L=="string"?L:void 0})}),He=await Z.json().catch(()=>({}));if(!Z.ok||He?.success===!1)return{success:!1,error:He?.error||`Failed to create workspace (${Z.status})`,code:He?.code};const Be=He?.workspace;if(await zr(),Be?.id){const Ve=await Hr(Be.id);if(!Ve.success)return{success:!1,error:Ve.error||"Workspace created but failed to activate.",code:Ve.code}}return{success:!0,workspace:Be}}catch{return{success:!1,error:"Failed to create workspace."}}},[zr,Hr,yt]),hr=r.useCallback(async f=>{if(!yt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const L=String(f||"").trim();if(!L)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const G=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(L)}`,{method:"DELETE",credentials:"include"}),Z=await G.json().catch(()=>({}));if(!G.ok||Z?.success===!1)return{success:!1,error:Z?.error||`Failed to delete workspace (${G.status})`,code:Z?.code};await sn({force:!0}),await Promise.all([Ur(),zr()]);const He=typeof Z?.nextWorkspaceId=="string"?Z.nextWorkspaceId.trim():"";return He&&ja(He),{success:!0,nextWorkspaceId:He||void 0,workspaceSetupRequired:Z?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(Z?.cleanupWarnings)?Z.cleanupWarnings.map(Be=>String(Be||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[sn,ja,Ur,zr,yt]),Qo=r.useCallback(async f=>{const L=f==="operations"?"operations":"core";try{const G=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:L}})}),Z=await G.json().catch(()=>({}));return!G.ok||Z?.success===!1?!1:(await Bi(),!0)}catch{return!1}},[Bi]),jl=r.useCallback(async f=>{const L=String(f?.name||"").trim(),G=typeof f?.workspaceId=="string"?f.workspaceId.trim():"";if(!L)return{success:!1,error:"Workspace name is required.",code:"WORKSPACE_NAME_REQUIRED"};try{const Z=await fetch("/api/taskforce/workspace-profile",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-runtime-mode":b},credentials:"include",body:JSON.stringify({workspaceId:G&&G!=="default"?G:void 0,name:L,description:typeof f.description=="string"?f.description:void 0,allowCreate:!0})}),He=await Z.json().catch(()=>({}));if(!Z.ok||He?.success===!1)return{success:!1,error:He?.error||`Failed to save workspace (${Z.status})`,code:He?.code};const Be=String(He?.workspace?.id||"").trim();if(Be&&(ja(Be),await new Promise(Ve=>window.setTimeout(Ve,0)),b==="cloud"&&xe&&Be!==Ae)){const Ve=await Hr(Be);if(!Ve.success)return{success:!1,error:Ve.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await Bi(),{success:!0,workspaceId:Be||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[ja,Bi,b,xe,Ae,Hr]),Jd=r.useCallback(async(f,L)=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const G=f.trim().toLowerCase(),Z=L;if(!G||!Z)return{success:!1,error:"Email and password are required."};try{const He=await fetch($("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:G,password:Z})}),Be=await He.json().catch(()=>({}));if(!He.ok||!Be?.success)return{success:!1,error:Be?.error||"Sign in failed.",code:Be?.code};$r("");const Ve=await Ss();return Ve.success?{success:!0,workspaceSetupRequired:Ve.workspaceSetupRequired===!0}:{success:!1,error:Ve.error||"Unable to resolve workspace after sign in.",code:Ve.code}}catch{return{success:!1,error:"Sign in failed."}}},[$,K,Ss]),Gm=r.useCallback((f,L,G)=>{const Z=L&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(L)?L:"/";let He=`/api/taskforce/auth/oauth/${encodeURIComponent(f)}/start?return_to=${encodeURIComponent(Z)}`;G&&(He+=`&invite_token=${encodeURIComponent(G)}`),window.location.href=$(He)},[$]),Nl=r.useCallback(async(f,L,G)=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const Z=f.trim().toLowerCase(),He=L;if(!Z||!He)return{success:!1,error:"Email and password are required."};try{const Be=await fetch($("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:Z,password:He,...typeof G?.displayName=="string"&&G.displayName.trim()?{displayName:G.displayName.trim()}:{},...typeof G?.planId=="string"&&G.planId.trim()?{planId:G.planId.trim()}:{},...typeof G?.planVersionId=="string"&&G.planVersionId.trim()?{planVersionId:G.planVersionId.trim()}:{},...typeof G?.interval=="string"&&G.interval.trim()?{interval:G.interval.trim()}:{}})}),Ve=await Be.json().catch(()=>({}));if(!Be.ok||!Ve?.success)return{success:!1,error:Ve?.error||"Create account failed.",code:Ve?.code,verificationRequired:!!Ve?.verificationRequired,verificationToken:typeof Ve?.verificationToken=="string"?Ve.verificationToken:void 0,emailSent:Ve?.emailSent!==!1,emailError:typeof Ve?.emailError=="string"?Ve.emailError:void 0};const pa=Ve?.planSelectionRequired===!0,fa=Ve?.checkoutPending===!0,Fa=typeof Ve?.commercialState=="string"?Ve.commercialState:null,ba=!!Ve?.verificationRequired;if(!ba){if($r(""),!!(pa||fa||Fa==="pending_plan_selection"||Fa==="checkout_pending"))return await sn({force:!0})?{success:!0,workspaceSetupRequired:!1,planSelectionRequired:pa,checkoutPending:fa,commercialState:Fa,verificationRequired:ba,verificationToken:typeof Ve?.verificationToken=="string"?Ve.verificationToken:void 0,emailSent:Ve?.emailSent!==!1,emailError:typeof Ve?.emailError=="string"?Ve.emailError:void 0}:{success:!1,error:"Unable to resolve workspace after registration.",code:"AUTH_REQUIRED"};const Pr=await Ss({allowCommercialGate:!1});return Pr.success?{success:!0,workspaceSetupRequired:Pr.workspaceSetupRequired===!0,planSelectionRequired:pa,checkoutPending:fa,commercialState:Fa,verificationRequired:ba,verificationToken:typeof Ve?.verificationToken=="string"?Ve.verificationToken:void 0,emailSent:Ve?.emailSent!==!1,emailError:typeof Ve?.emailError=="string"?Ve.emailError:void 0}:{success:!1,error:Pr.error||"Unable to resolve workspace after registration.",code:Pr.code}}return{success:!0,workspaceSetupRequired:!!Ve?.workspaceSetupRequired,planSelectionRequired:pa,checkoutPending:fa,commercialState:Fa,verificationRequired:ba,verificationToken:typeof Ve?.verificationToken=="string"?Ve.verificationToken:void 0,emailSent:Ve?.emailSent!==!1,emailError:typeof Ve?.emailError=="string"?Ve.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[sn,$,K,Ss]),Qd=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const L=String(f.displayName||"").trim(),G=typeof f.avatarDraftId=="string"?f.avatarDraftId.trim():"",Z=f.clearAvatar===!0;if(!L)return{success:!1,error:"Display name is required."};try{const He=await fetch($("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:L,...G?{avatarDraftId:G}:{},...Z?{clearAvatar:!0}:{}})}),Be=await He.json().catch(()=>({}));if(!He.ok||!Be?.success)return{success:!1,error:Be?.error||"Failed to update profile.",code:Be?.code};const Ve={userId:typeof Be?.profile?.userId=="string"?Be.profile.userId:Je,email:typeof Be?.profile?.email=="string"?Be.profile.email:Pt,displayName:typeof Be?.profile?.displayName=="string"?Be.profile.displayName:null,avatarUrl:typeof Be?.profile?.avatarUrl=="string"?Be.profile.avatarUrl:null};return Ht(Ve.displayName||""),Va(Ve.avatarUrl||""),{success:!0,profile:Ve}}catch{return{success:!1,error:"Failed to update profile."}}},[$,K,Pt,Je]),as=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const L=f.trim().toLowerCase();if(!L)return{success:!1,error:"Email is required."};try{const G=await fetch($("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:L})}),Z=await G.json().catch(()=>({}));return!G.ok||!Z?.success?{success:!1,error:Z?.error||"Failed to request verification email.",code:Z?.code}:{success:!0,verificationToken:Z?.verificationToken??null,emailSent:Z?.emailSent!==!1,deliveryAttempted:Z?.deliveryAttempted===!0||typeof Z?.verificationToken=="string"&&Z.verificationToken.trim().length>0,emailError:typeof Z?.emailError=="string"?Z.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[$,K]),Xd=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const L=f.trim();if(!L)return{success:!1,error:"Token is required."};try{const G=await fetch($("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:L})}),Z=await G.json().catch(()=>({}));return!G.ok||!Z?.success?{success:!1,error:Z?.error||"Verification failed.",code:Z?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[$,K]),ns=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const L=f.trim().toLowerCase();if(!L)return{success:!1,error:"Email is required."};try{const G=await fetch($("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:L})}),Z=await G.json().catch(()=>({}));return!G.ok||!Z?.success?{success:!1,error:Z?.error||"Failed to request password reset.",code:Z?.code}:{success:!0,resetToken:Z?.resetToken??null,emailSent:Z?.emailSent!==!1,deliveryAttempted:Z?.deliveryAttempted===!0||typeof Z?.resetToken=="string"&&Z.resetToken.trim().length>0,emailError:typeof Z?.emailError=="string"?Z.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[$,K]),eu=r.useCallback(async(f,L)=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const G=f.trim(),Z=L;if(!G||!Z)return{success:!1,error:"Token and password are required."};try{const He=await fetch($("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:G,password:Z})}),Be=await He.json().catch(()=>({}));return!He.ok||!Be?.success?{success:!1,error:Be?.error||"Failed to reset password.",code:Be?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[$,K]),tu=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const L=f.trim();if(!L)return{success:!1,error:"Token is required."};try{const G=await fetch($("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:L})}),Z=await G.json().catch(()=>({}));return!G.ok||!Z?.success?{success:!1,error:Z?.error||"Invite inspection failed.",code:Z?.code,state:Z?.state}:{success:!0,state:Z?.state,email:typeof Z?.email=="string"?Z.email:void 0,workspaceId:typeof Z?.workspaceId=="string"?Z.workspaceId:void 0,inviteeKind:Z?.inviteeKind==="existing_user"?"existing_user":"new_user",passwordRequired:Z?.passwordRequired===!0,inviteeState:Z?.inviteeState==="existing_account"?"existing_account":"pending_setup",availableMethods:Array.isArray(Z?.availableMethods)?Z.availableMethods:[]}}catch{return{success:!1,error:"Invite inspection failed."}}},[$,K]),Wi=r.useCallback(async(f,L)=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const G=f.trim(),Z=L;if(!G||!Z)return{success:!1,error:"Token and password are required."};try{const He=await fetch($("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:G,password:Z})}),Be=await He.json().catch(()=>({}));if(!He.ok||!Be?.success)return{success:!1,error:Be?.error||"Invite acceptance failed.",code:Be?.code};$r("");const Ve=typeof Be?.workspaceId=="string"?Be.workspaceId:null;if(Ve&&yt){const fa=await Hr(Ve,{hydrate:!1});if(!fa.success)return{success:!1,error:fa.error||"Unable to resolve workspace after invite acceptance.",code:fa.code}}const pa=await Ss({preferredWorkspaceId:Ve});return pa.success?(Ve&&aa.current!==Ve&&ja(Ve,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:pa.workspaceSetupRequired===!0}):{success:!1,error:pa.error||"Unable to resolve workspace after invite acceptance.",code:pa.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[ja,$,K,aa,Ss,Hr,yt]),Pl=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth endpoint is not configured."};const L=f.trim();if(!L)return{success:!1,error:"Token is required."};try{const G=await fetch($("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:L})}),Z=await G.json().catch(()=>({}));if(!G.ok||!Z?.success)return{success:!1,error:Z?.error||"Invite join failed.",code:Z?.code};$r("");const He=typeof Z?.workspaceId=="string"?Z.workspaceId:null;if(He&&yt){const Ve=await Hr(He,{hydrate:!1});if(!Ve.success)return{success:!1,error:Ve.error||"Unable to resolve workspace after invite join.",code:Ve.code}}const Be=await Ss({preferredWorkspaceId:He});return Be.success?(He&&aa.current!==He&&ja(He,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:Be.workspaceSetupRequired===!0}):{success:!1,error:Be.error||"Unable to resolve workspace after invite join.",code:Be.code}}catch{return{success:!1,error:"Invite join failed."}}},[ja,$,K,aa,Ss,Hr,yt]),Fi=r.useCallback(async()=>{if(!K)return{success:!1,error:"Cloud auth not configured."};try{const f=await fetch($("/api/taskforce/account/login-methods"),{credentials:"include"}),L=await f.json().catch(()=>({}));return!f.ok||!L?.success?{success:!1,error:L?.error||"Failed to fetch login methods."}:{success:!0,methods:Array.isArray(L?.methods)?L.methods:[]}}catch{return{success:!1,error:"Failed to fetch login methods."}}},[$,K]),Vm=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth not configured."};try{const L=await fetch($(`/api/taskforce/account/login-methods/${encodeURIComponent(f)}`),{method:"DELETE",credentials:"include"}),G=await L.json().catch(()=>({}));return!L.ok||!G?.success?{success:!1,error:G?.error||"Unlink failed.",code:G?.code}:{success:!0}}catch{return{success:!1,error:"Unlink failed."}}},[$,K]),Xo=r.useCallback(async f=>{if(!K)return{success:!1,error:"Cloud auth not configured."};try{const L=await fetch($("/api/taskforce/account/login-methods/password"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({password:f})}),G=await L.json().catch(()=>({}));return!L.ok||!G?.success?{success:!1,error:G?.error||"Failed to add password.",code:G?.code}:{success:!0}}catch{return{success:!1,error:"Failed to add password."}}},[$,K]),Ml=r.useCallback((f,L)=>{const G=L&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(L)?L:"/",Z=`/api/taskforce/auth/oauth/${encodeURIComponent(f)}/start?flow=link&return_to=${encodeURIComponent(G)}`;window.location.href=$(Z)},[$]),El=r.useCallback(()=>{Ua(),Nc.current=null,Pi.current="",Ko.current="",Mi.current="",Rc.current="",Ps.current="",Ei.current="",Ms(!1),pr(!1),ia(li()),rn(!1),hn([]),Fr([]),T([]),at([]),ve([]),Rn([]),Jr(!1),Mn.current!==null&&typeof window<"u"&&(window.clearTimeout(Mn.current),Mn.current=null),vs.current!==null&&typeof window<"u"&&(window.clearTimeout(vs.current),vs.current=null)},[Ua,T,Fr]),qm=r.useCallback(async()=>{try{K&&await fetch($("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if(Ua(),Ra.current+=1,Qa.current=null,Ka.current=!1,Zt.current=Date.now(),Ke(!1),rr(!0),Ne("anonymous"),Jt(""),rd(null),Ft(""),Ht(""),Va(""),Fo("disconnected"),Oo(null),cn(!0),ot(""),io(!1),pr(!1),wn(null),ta("idle"),Kt(null),Cl.current=!1,b!=="local"&&sh(te),we(b==="cloud"&&E),ja("default"),Ca([]),Al.current=!1,rt(null),b==="local"){await Promise.allSettled([Ur({ignoreAuthGuard:!0}),an(!0,{ignoreAuthGuard:!0}),ma({ignoreAuthGuard:!0}),Li({ignoreAuthGuard:!0,force:!0})]);return}zd.current=!1,El()}},[Ua,E,sh,ja,$,K,te,b,Ur,ma,Li,an,El]),Dl=r.useCallback(async f=>{try{const L=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}),G=await L.json().catch(()=>({}));return!L.ok||!G?.success?{success:!1,error:G?.error||`Create failed (${L.status})`}:(await an(!0),{success:!0,result:G?.results})}catch(L){return{success:!1,error:L.message}}},[an]),au=r.useCallback(async f=>{const L=await fetch("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f||{})}),G=await L.json().catch(()=>({}));if(!L.ok)throw new Error(G?.error||`Failed to create initiative (${L.status})`);return await ma(),at(Z=>si(Z,G)),G},[ma]),Km=r.useCallback(async(f,L)=>{const G=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(L||{})}),Z=await G.json().catch(()=>({}));if(!G.ok)throw new Error(Z?.error||`Failed to update initiative (${G.status})`);return await ma(),at(He=>si(He,Z)),Z},[ma]),Ll=r.useCallback(async f=>{const L=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}/archive`,{method:"POST"}),G=await L.json().catch(()=>({}));if(!L.ok)throw new Error(G?.error||`Failed to archive initiative (${L.status})`);return await ma(),at(Z=>si(Z,G)),G},[ma]),nu=r.useCallback(async f=>{const L=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}/unarchive`,{method:"POST"}),G=await L.json().catch(()=>({}));if(!L.ok)throw new Error(G?.error||`Failed to unarchive initiative (${L.status})`);return await ma(),at(Z=>si(Z,G)),G},[ma]),Zm=r.useCallback(async f=>{const L=await fetch("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f||{})}),G=await L.json().catch(()=>({}));if(!L.ok)throw new Error(G?.error||`Failed to create workstream (${L.status})`);return await ma(),ve(Z=>si(Z,G)),G},[ma]),Ym=r.useCallback(async(f,L)=>{const G=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(L||{})}),Z=await G.json().catch(()=>({}));if(!G.ok)throw new Error(Z?.error||`Failed to update workstream (${G.status})`);return await ma(),ve(He=>si(He,Z)),Z},[ma]),Bl=r.useCallback(async f=>{const L=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}/archive`,{method:"POST"}),G=await L.json().catch(()=>({}));if(!L.ok)throw new Error(G?.error||`Failed to archive workstream (${L.status})`);return await ma(),ve(Z=>si(Z,G)),G},[ma]),Ec=r.useCallback(async f=>{const L=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}/unarchive`,{method:"POST"}),G=await L.json().catch(()=>({}));if(!L.ok)throw new Error(G?.error||`Failed to unarchive workstream (${L.status})`);return await ma(),ve(Z=>si(Z,G)),G},[ma]),Ao=r.useRef(!1);r.useEffect(()=>{z(!0),!Ao.current&&(Ao.current=!0,sn())},[sn]),r.useEffect(()=>{D&&sn()},[D,sn]),r.useEffect(()=>{if(!K)return;let f=!1;const L=new AbortController,G=typeof window<"u"?window.setTimeout(()=>L.abort(),5e3):null;return fetch($("/api/taskforce/auth/providers"),{credentials:"include",signal:L.signal}).then(Z=>Z.ok?Z.json():null).then(Z=>{!f&&Array.isArray(Z?.providers)&&Vt(Z.providers)}).catch(()=>{}).finally(()=>{G!==null&&typeof window<"u"&&window.clearTimeout(G)}),()=>{f=!0,L.abort()}},[K,$]),r.useEffect(()=>{if(b!=="local"||!je||typeof window>"u")return;const f=()=>{sn()},L=()=>{document.visibilityState==="visible"&&f()};window.addEventListener("focus",f),window.addEventListener("online",f),document.addEventListener("visibilitychange",L);const G=window.setInterval(f,3e4);return()=>{window.removeEventListener("focus",f),window.removeEventListener("online",f),document.removeEventListener("visibilitychange",L),window.clearInterval(G)}},[b,je,sn]),r.useEffect(()=>{n&&n(Ba.length)},[Ba.length,n]);const ei=r.useRef(null);r.useEffect(()=>{if(!t){ei.current=null;return}if(ei.current===t||Ba.length===0)return;const f=Ba.find(L=>L.id.endsWith(t)||L.id===t);f&&(ei.current=t,ai(f),Nr("add"))},[t,Ba]);const jr=r.useRef(!1);r.useEffect(()=>{if(!Pn)return;if(!jr.current&&ha.length>0){jr.current=!0;const L=Go,G=ha.some(Z=>Z.label===L||Z.value===L);if(L&&G){const Z=ha.find(He=>He.label===L||He.value===L);Ir(Z?.value||L)}else Ir(Qn(ha));return}const f=ha.some(L=>L.value===Ks);ha.length>0&&!f&&Ir(Qn(ha))},[Pn,ha,Ks,Qn,Go]),r.useEffect(()=>{if(!Pn||ha.length===0)return;const f=Z=>!ha.some(He=>He.value===Z.category),L=Ba.some(f),G=Wa.some(f);if(L||G){const Z=Qn(ha);L&&Fr(He=>He.map(Be=>f(Be)?{...Be,category:Z}:Be)),G&&T(He=>He.map(Be=>f(Be)?{...Be,category:Z}:Be))}},[Pn,ha,Ba,Wa,Qn]),r.useEffect(()=>()=>{vs.current!==null&&typeof window<"u"&&(window.clearTimeout(vs.current),vs.current=null),Mn.current!==null&&typeof window<"u"&&(window.clearTimeout(Mn.current),Mn.current=null)},[]),r.useEffect(()=>{},[es]);const xo=r.useCallback(async()=>{await hi()},[hi]),Js=String(Ae||"").trim(),Dc=String(Je||"").trim(),ru=be("/taskforce-ws"),Jm=!!(K&&b==="cloud"&&gt&&xe&&Dc&&Dc!=="anonymous"&&Js&&!df(Js)&&ru),su=r.useCallback(()=>{b==="cloud"&&(hi(),!(typeof window>"u")&&(Mn.current!==null&&window.clearTimeout(Mn.current),Mn.current=window.setTimeout(()=>{Mn.current=null,hi()},250)))},[b,hi]);Jg({enabled:Jm,workspaceId:Js,websocketUrl:ru,onSignal:su,userId:Dc||void 0}),Eb({isOpen:pe,authBlocked:J,authRequiredForApi:E,isAuthenticated:xe,canCallProtectedApi:sr.canCallProtectedApi,shouldGateProtectedApiCalls:Pe,authSessionResolvedRef:Ic,authRequiredForApiRef:Tc,isAuthenticatedRef:qo,dataVersionRef:Wm,refreshTaskCollectionsForDataVersion:xo});const Wl=r.useMemo(()=>{const f=new Map;for(const L of Wa)f.set(L.id,L);for(const L of Ba)f.set(L.id,L);return Array.from(f.values())},[Ba,Wa]),Lc=r.useMemo(()=>jn.map(f=>({...f.taskSnapshot,isDeleted:!0,deletedRecordId:f.id})),[jn]);r.useEffect(()=>{if(!(Na||ka)&&pe&&!ca){if(U==="tasks"){const f=`${Ae}:${U}:${ne?"archive":"active"}:${Re}`;if(!Rr.current){Rr.current=!0,Ps.current=f;return}if(Ps.current===f)return;Ps.current=f,an(),ma(),(ne||Re==="archived")&&Xn(!0),Re==="deleted"&&fr();return}if(U==="settings"){const f=`${Ae}:${U}:${We}`;if(Ei.current===f)return;Ei.current=f,Ur(),(We==="commands"||We==="resources")&&Bt()}}},[Ae,pe,U,We,ne,Re,an,ma,Xn,fr,Ur,Bt,Na,ka,ca]);const Fl=r.useCallback(async(f="")=>{try{const L=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(f)}`);if(L.ok){const G=await L.json();ze(G.folders||[]),it(G.files||[]),ht(f)}}catch(L){console.error("[Taskforce] Failed to fetch folders:",L)}},[]),ou=r.useCallback(f=>{const L=[];if(f.path&&L.push(f.path),f.paths&&f.paths.length>0)for(const G of f.paths)L.includes(G)||L.push(G);return L},[]),{validatePaths:Ol,handleUpdateCategory:Bc,handleSaveCategory:iu,handleAddPath:Es,handleUpdateCategoryIcon:cu,handleUpdateCategoryColor:$l,handleRemovePath:lu,handleSelectPath:du,handleRemoveCategory:Ds,handleSaveType:uu,handleRemoveType:mu,handleUpdateType:pu,handleUpdateTaxonomies:fu,handleUpdatePriorities:hu,analyzeSystemTaxonomyPack:rs,handleApplySystemTaxonomyPack:Ul}=Zw({activeCategories:ha,activeTab:U,activeTypes:sa,archivedTasks:Wa,browserTarget:Ot,category:Ks,configLoaded:Pn,customCategories:us,refreshTaskCollections:es,fetchTasks:an,filterCategories:kc,getCategoryPaths:ou,normalizePath:Yr,pathValidation:ui,setBrowserTarget:Dt,setCategory:Ir,setCustomCategories:di,setCustomTypes:Is,setFilterCategories:Tr,setPathValidation:mi,setPriorities:or,setShowFolderBrowser:Rt,setTaxonomies:fi,tasks:Ba}),ti=r.useCallback(async f=>{const L=Ts,G={...L,...f};lo(G);try{const Z=await fetch("/api/taskforce/taxonomy-display-labels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLabels:f})});if(!Z.ok)throw new Error(`Failed to save taxonomy display labels (${Z.status})`);const He=await Z.json().catch(()=>({}));He?.displayLabels&&typeof He.displayLabels=="object"&&lo({...G,...He.displayLabels})}catch(Z){console.error("[Taskforce] Failed to update taxonomy display labels",Z),lo(L)}},[Ts]),Nr=r.useCallback(f=>{U==="tasks"&&Mt.current&&Jn(Mt.current.scrollTop),se(f)},[U]),gu=r.useRef(async()=>{}),{handleNavigation:zl,handleClose:Qm,resetForm:Wc,resolveWorkstreamIdInput:yu,handleEdit:ai,handleOpenTaskById:Io,returnToPreviousTask:Fc,clearReturnToParentTask:Oc}=rb({activeCategories:ha,activeTypes:sa,activeTab:U,attachments:xc,checklistItems:Zs,comments:gl,description:uc,editingTaskId:Nn,flushPendingAutoSave:()=>gu.current(),getPreferredCategoryValue:Qn,lastUsedCategory:Go,newCommentText:Ci,relationshipTasks:Wl,workstreams:bt,showArchive:ne,taxonomies:ps,setActiveTab:Nr,setApproach:pl,setAssignee:vi,setAttachments:ji,setAttachmentsDirty:Ni,setCategory:Ir,setChecklistItems:mc,setComments:_i,setComplexity:dl,setDescription:hl,setDueDate:Nd,setEditingTaskId:$s,setError:$r,setFormTaxonomies:_t,setIsOpen:z,setNewCommentText:pc,setPendingNavigation:so,setWorkstreamInput:Si,setPriority:Ho,setScheduledDate:Ns,setShowArchive:ie,setStatus:So,setTaskReturnTrail:It,setTitle:bi,setType:js,setUnsavedModalOpen:nn,taskReturnTrail:$e,title:wi}),{copiedId:Oi,handleDelete:ni,handleUpdateTask:Hl,handleToggleComplete:Gl,handleToggleCancel:$c,handleToggleInProgress:To,handleToggleReview:Vl,handleArchiveTask:$i,handleBulkArchive:Xm,handleUnarchive:ql,handleRestoreDeletedTask:ku,handlePermanentlyDeleteDeletedTask:vu,handleEmptyDeletedTasks:Qs,handleCopyId:Su,queueWorkspaceSyncFromAuthoritativeTaskState:Kl}=bb({tasks:Ba,archivedTasks:Wa,editingTaskId:Nn,setTasks:Fr,setArchivedTasks:T,setDeletedTasks:hn,setError:$r,resetForm:Wc,setActiveTab:Nr,fetchTasks:an,fetchArchive:Xn,fetchDeletedTasks:fr,mergeTaskFromServer:fo,pushNotice:mr,cloudAuthConfigured:K,runtimeMode:b,isAuthenticated:xe,workspaceCloudSyncEnabled:hs,buildWorkspaceSyncSignature:ll,pushWorkspaceChangesToCloud:Uo,workspacePendingSignatureRef:Id,workspaceDeletedTaskIdsRef:qs,workspaceDeletedTaskWatermarksRef:Td}),{autoSaveState:wu,flushAutoSave:bu,scheduleWarningPrompt:ep,handleSubmit:Zl,confirmScheduleWarning:tp,cancelScheduleWarning:ri,handleAddComment:Yl}=vb({activeCategories:ha,activeTab:U,apiEndpoint:d,approach:ml,assignee:fl,attachments:xc,attachmentsDirty:Ud,category:Ks,checklistItems:Zs,comments:gl,complexity:dc,description:uc,dueDate:jd,editingTaskId:Nn,fetchTasks:an,formTaxonomies:fc,getPreferredCategoryValue:Qn,mergeTaskFromServer:fo,workstreamInput:zn,priority:oa,pushNotice:mr,queueWorkspaceSyncFromAuthoritativeTaskState:Kl,relationshipTasks:Wl,resetForm:Wc,resolveWorkstreamIdInput:yu,scheduledDate:Un,setActiveTab:Nr,setAttachmentsDirty:Ni,setComments:_i,setError:$r,setLastUsedCategory:gc,setLoading:Xr,setNewCommentText:pc,status:ul,title:wi,taxonomies:ps,type:vo});r.useEffect(()=>{gu.current=bu},[bu]);const{handleSetWorkstreamForCurrentTask:_u}=Sb({editingTaskId:Nn,mergeTaskFromServer:fo,workstreamInput:zn,pushNotice:mr,queueWorkspaceSyncFromAuthoritativeTaskState:Kl,relationshipTasks:Wl,resolveWorkstreamIdInput:yu,setError:$r,fetchTasks:an}),{currentTask:Cu,currentTaskWorkstream:Au,currentTaskInitiative:ws}=eb({editingTaskId:Nn,relationshipTasks:Wl,initiatives:j,workstreams:bt,supplementalTasks:Lc,setComments:_i}),bs=qw({resolveCloudAuthUrl:$,currentWorkspaceId:Ae,normalizedCloudAuthBaseUrl:re,normalizedCloudMcpBaseUrl:Ie,mergedConfig:o,availableWorkspaces:wt,currentTheme:De,configLoaded:Pn,globalTheme:vt,themeUseGlobalDefault:kt,keyShortcut:na,jsonBackupEnabled:_n,globalJsonBackupEnabled:Ar,globalWeekStartsOn:Zn,locale:ir,supportedLocales:An,jsonBackupUseGlobalDefault:qn,manualComplexityEnabled:cs,checklistDropdownEnabled:Kr,showTaskCardStatusLabel:xn,exportWorkflowsPath:La,exportingResource:Br,exportResult:dr,pathSaved:dt,settingsSection:We,exportEnvironment:Tn,setupState:Ln,buildInfo:Ma,saveSetupMode:Qo,saveWorkspaceProfile:jl,setCurrentTheme:Oe,handleSaveTheme:Gd,handleSaveGlobalTheme:Om,setKeyShortcut:da,handleJsonBackupEnabledChange:$m,handleSaveGlobalJsonBackupEnabled:Um,handleSaveGlobalWeekStartsOn:zm,handleSaveLocale:Vd,handleManualComplexityEnabledChange:Hm,handleChecklistDropdownEnabledChange:gn,handleShowTaskCardStatusLabelChange:xl,handleResetProjectToGlobal:qd,handleSaveSettings:Hd,setExportWorkflowsPath:Lr,setExportEnvironment:Gt,availableWorkflows:ls,initiativeTemplates:et,availableEnvironments:$n,fetchWorkflows:Bt,fetchInitiativeTemplates:Da,createInitiativeFromTemplate:Dl,fetchWorkflowTemplate:Aa,fetchWorkflowOverrideNames:Sa,saveWorkflowTemplateDraft:In,resetWorkflowTemplateDraft:Yn,handleExportWorkflows:ur,setShowFolderBrowser:Rt,setBrowserTarget:Dt,fetchFolders:Fl,activeCategories:ha,pathValidation:ui,taxonomyDisplayLabels:Ts,handleUpdateCategory:Bc,handleRemoveCategory:Ds,handleSaveCategory:iu,handleAddPath:Es,handleRemovePath:lu,handleUpdateCategoryIcon:cu,handleUpdateCategoryColor:$l,activeTypes:sa,handleSaveType:uu,handleRemoveType:mu,handleUpdateType:pu,taxonomies:ps,handleUpdateTaxonomies:fu,priorities:Xa,handleUpdatePriorities:hu,analyzeSystemTaxonomyPack:rs,handleApplySystemTaxonomyPack:Ul,handleUpdateTaxonomyDisplayLabels:ti,projectRoot:Fe,projectName:St,mcpHostRoot:Cr,serverHostRoot:Wn,mcpScriptPath:Le,tenantId:jt,runtimeMode:b,workspaceSwitchingEnabled:yt,deleteWorkspace:hr,setMcpHostRoot:Xt,isAuthenticated:xe});r.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:Ba,archivedTasks:Wa,runtimeMode:b,currentWorkspaceId:Ae,isAuthenticated:xe,workspaceCloudSyncEnabled:hs,realtimeSyncEnabled:bn,fetchTasks:an,fetchArchive:Xn,retryWorkspaceCloudSync:gs,resetWorkspaceSyncCursorAndPull:yi,getSyncDiagnostics:zo,__dispatch:{handleUpdateTask:Hl,handleToggleComplete:Gl,handleArchiveTask:$i,handleToggleCancel:$c,handleToggleInProgress:To,handleToggleReview:Vl,handleSubmit:Zl,handleDelete:ni}})},[Ba,Wa,b,Ae,xe,hs,bn,an,Xn,gs,yi,zo,Hl,Gl,$i,$c,To,Vl,Zl,ni]);const xu=Wr&&Wr.tone!=="error"?{message:Wr.message,type:"info"}:null,Iu=String(S||I.wsBaseUrl||ye||"").trim().replace(/\/+$/,"");return{config:{...o,cloudEnvironment:I.cloudEnvironment||o.cloudEnvironment||"",apiBaseUrl:ye||o.apiBaseUrl,cloudAuthBaseUrl:re||o.cloudAuthBaseUrl,wsBaseUrl:Iu||o.wsBaseUrl},isOpen:pe,setIsOpen:z,activeTab:U,setActiveTab:Nr,currentTheme:De,setCurrentTheme:Oe,configLoaded:Pn,storagePath:Ct,saveSettings:Hd,pathSaved:dt,keyShortcut:na,setKeyShortcut:da,globalWeekStartsOn:Zn,locale:ir,supportedLocales:An,saveLocale:Vd,jsonBackupEnabled:_n,setJsonBackupEnabled:Cn,manualComplexityEnabled:cs,checklistDropdownEnabled:Kr,showTaskCardStatusLabel:xn,setManualComplexityEnabled:Za,mcpHostRoot:Cr,setMcpHostRoot:Xt,settingsSection:We,setSettingsSection:tt,runtimeMode:b,workspaceMode:$t,workspaceSwitchingEnabled:yt,cloudAuthConfigured:K,authRequiredForApi:E,authBlocked:J,isAuthenticated:xe,authUserId:Je,authUserEmail:Pt,authUserDisplayName:Lt,authUserAvatarUrl:Ga,authWorkspaceId:zt,userGlobalSyncStatus:ho,workspaceLastPullAt:Nm,workspaceLastPushAt:ol,workspaceLastErrorAt:Pm,userGlobalSyncError:go,workspaceLastErrorMessage:il,workspaceLastSuccessfulSyncAt:er,workspaceSyncPhase:yo,workspaceSyncSetupIntent:gi,workspaceSyncStatus:Mm,workspaceSyncSummary:Ad,workspaceSyncRecommendedAction:$o,workspaceSyncBusy:Em,workspaceSyncPendingChanges:xd,retryUserGlobalSettingsSync:lc,retryWorkspaceCloudSync:gs,resetWorkspaceSyncCursorAndPull:yi,getWorkspaceSyncDiagnostics:zo,hasBetaAccess:qa,realtimeSyncEnabled:bn,realtimeSyncFlagSource:Pa,currentWorkspaceId:Ae,currentWorkspaceRole:Rl,availableWorkspaces:wt,assigneeOptions:ya,workspaceCloudSyncEnabled:hs,saveWorkspaceCloudSyncSettings:ko,applyWorkspaceSyncStateSnapshot:Rd,bootstrapState:rc,authSessionResolved:gt,workspaceBootstrapPending:ca,bootstrapPhase:ua,bootstrapError:wa,bootstrapStartedAt:vr,setupState:Ln,runtimeCapabilities:va,refreshSetupContext:Bi,retryBootstrapChecks:Tl,continueAfterCommercialOnboarding:Yd,saveWorkspaceProfile:jl,fetchWorkspaces:zr,createWorkspace:Jo,deleteWorkspace:hr,switchWorkspace:Hr,loginWithCredentials:Jd,beginOAuthLogin:Gm,availableAuthProviders:ra,fetchLoginMethods:Fi,unlinkLoginMethod:Vm,addPasswordToAccount:Xo,beginOAuthLink:Ml,registerWithCredentials:Nl,updateCurrentUserProfile:Qd,requestEmailVerification:as,confirmEmailVerification:Xd,requestPasswordReset:ns,confirmPasswordReset:eu,inspectInviteAcceptance:tu,acceptInviteWithToken:Wi,joinInviteWithToken:Pl,logout:qm,showFolderBrowser:Qe,setShowFolderBrowser:Rt,folders:ee,files:ft,currentBrowsePath:Et,fetchFolders:Fl,browserTarget:Ot,setBrowserTarget:Dt,groupBy:ks,setGroupBy:tr,activeWorkspaceModule:_l,setActiveWorkspaceModule:Fm,emptyColumnMode:_o,setEmptyColumnMode:Co,zenMode:ds,setZenMode:On,handleSelectPath:du,handleAddPath:Es,handleRemovePath:lu,tasks:Ba,loadingTasks:Os,archivedTasks:Wa,initiatives:j,workstreams:bt,planningBootstrapTaskSummaries:ae,deletedTasks:jn,activeCategories:ha,activeTypes:sa,priorities:Xa,taxonomyDisplayLabels:Ts,approaches:Er,taxonomies:ps,searchQuery:yc,setSearchQuery:Md,filterCategories:kc,setFilterCategories:Tr,filterTypes:yl,setFilterTypes:Ed,filterPriorities:Ya,setFilterPriorities:Ai,filterStatus:wo,setFilterStatus:Dd,filterAssignees:kl,setFilterAssignees:ts,filterTaxonomies:vc,setFilterTaxonomies:xi,hasInitedFilters:bo,sortBy:Sc,setSortBy:wc,sortOrder:vl,setSortOrder:Wd,toggleSortOrder:Vo,showArchive:ne,setShowArchive:ie,taskScope:Re,setTaskScope:Te,clearFilters:Dm,filteredTasks:bc,searchAgnosticTasks:_c,filteredArchive:Fd,groupedTasks:Od,collapsedCategories:Sl,setCollapsedCategories:wl,fetchTasks:an,fetchArchive:Xn,fetchDeletedTasks:fr,fetchPlanningEntities:ma,fetchAssigneeOptions:Yo,createInitiative:au,updateInitiative:Km,archiveInitiative:Ll,unarchiveInitiative:nu,createWorkstream:Zm,updateWorkstream:Ym,archiveWorkstream:Bl,unarchiveWorkstream:Ec,handleEdit:ai,handleDelete:ni,handleCopyId:Su,handleToggleComplete:Gl,handleToggleCancel:$c,handleToggleInProgress:To,handleToggleReview:Vl,handleArchiveTask:$i,handleBulkArchive:Xm,handleUnarchive:ql,handleRestoreDeletedTask:ku,handlePermanentlyDeleteDeletedTask:vu,handleEmptyDeletedTasks:Qs,handleUpdateTask:Hl,editingTaskId:Nn,loading:uo,error:mo,title:wi,setTitle:bi,description:uc,setDescription:hl,checklistItems:Zs,setChecklistItems:mc,category:Ks,setCategory:Ir,type:vo,setType:js,priority:oa,setPriority:Ho,complexity:dc,setComplexity:dl,status:ul,setStatus:So,approach:ml,setApproach:pl,assignee:fl,setAssignee:vi,scheduledDate:Un,setScheduledDate:Ns,dueDate:jd,setDueDate:Nd,workstreamInput:zn,setWorkstreamInput:Si,formTaxonomies:fc,setFormTaxonomies:_t,comments:gl,newCommentText:Ci,setNewCommentText:pc,attachments:xc,setAttachments:ji,attachmentsDirty:Ud,setAttachmentsDirty:Ni,descriptionFocused:Bm,setDescriptionFocused:Ri,showMarkdownHelp:oo,setShowMarkdownHelp:Lo,showChecklist:hc,setShowChecklist:ys,showComments:Lm,setShowComments:$d,isCapturingScreenshot:Cc,setIsCapturingScreenshot:Ac,handleSubmit:Zl,resetForm:Wc,handleAddComment:Yl,handleSetWorkstreamForCurrentTask:_u,handleOpenTaskById:Io,returnToPreviousTask:Fc,autoSaveState:wu,unsavedModalOpen:Fs,setUnsavedModalOpen:nn,pendingNavigation:fn,handleNavigation:zl,handleClose:Qm,uiNotice:Wr,pushNotice:mr,clearNotice:W,successBanner:xu,taskReturnTrail:$e,clearReturnToParentTask:Oc,copiedId:Oi,recentlyChangedTaskIds:zs,scheduleWarningPrompt:ep,confirmScheduleWarning:tp,cancelScheduleWarning:ri,tasksScrollRef:Mt,setTasksScrollPos:Jn,exportEnvironment:Tn,setExportEnvironment:Gt,exportWorkflowsPath:La,setExportWorkflowsPath:Lr,exportResult:dr,exportingResource:Br,handleUpdateCategory:Bc,handleRemoveCategory:Ds,handleSaveCategory:iu,handleUpdateCategoryIcon:cu,handleUpdateCategoryColor:$l,handleSaveType:uu,handleRemoveType:mu,handleUpdateType:pu,handleUpdateTaxonomies:fu,handleUpdatePriorities:hu,handleUpdateTaxonomyDisplayLabels:ti,pathValidation:ui,validatePaths:Ol,getCategoryPaths:ou,customCategories:us,setCustomCategories:di,projectRoot:Fe,projectName:St,mcpScriptPath:Le,serverHostRoot:Wn,commentsEndRef:Pd,currentTask:Cu,currentTaskWorkstream:Au,currentTaskInitiative:ws,availableWorkflows:ls,initiativeTemplates:et,availableEnvironments:$n,fetchWorkflows:Bt,fetchInitiativeTemplates:Da,createInitiativeFromTemplate:Dl,fetchWorkflowTemplate:Aa,fetchWorkflowOverrideNames:Sa,saveWorkflowTemplateDraft:In,resetWorkflowTemplateDraft:Yn,onExportWorkflows:ur,settingsModel:bs}}const Wb="modulepreload",Fb=function(e){return"/taskforce/"+e},Th={},xs=function(t,n,s){let o=Promise.resolve();if(n&&n.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(n.map(y=>{if(y=Fb(y),y in Th)return;Th[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":Wb,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 l(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"&&l(d.reason);return t().catch(l)})},Ob="_filterGlow_1a4uy_8",$b="_floatingButton_1a4uy_18",Ub="_badge_1a4uy_49",zb="_configBadge_1a4uy_66",Hb="_configBadgeActive_1a4uy_76",Gb="_configBadgeRevoked_1a4uy_82",Vb="_configBadgeExpired_1a4uy_88",qb="_header_1a4uy_98",Kb="_headerTitle_1a4uy_113",Zb="_brandIcon_1a4uy_130",Yb="_brandHomeButton_1a4uy_136",Jb="_brandHomeStatic_1a4uy_137",Qb="_brandCloudSuffix_1a4uy_162",Xb="_projectSlash_1a4uy_167",e_="_projectName_1a4uy_174",t_="_taskCountBadge_1a4uy_193",a_="_taskCountBadgeIcon_1a4uy_210",n_="_taskCountBadgeAlert_1a4uy_214",r_="_headerActions_1a4uy_220",s_="_sortDirectionBtn_1a4uy_227",o_="_sortDirectionBtnWidget_1a4uy_234",i_="_form_1a4uy_242",c_="_topRow_1a4uy_254",l_="_field_1a4uy_260",d_="_labelRow_1a4uy_266",u_="_label_1a4uy_266",m_="_manageLink_1a4uy_280",p_="_input_1a4uy_299",f_="_select_1a4uy_300",h_="_textarea_1a4uy_301",g_="_taskIdInlineLink_1a4uy_335",y_="_readOnly_1a4uy_354",k_="_selectWithConfig_1a4uy_362",v_="_configBtn_1a4uy_372",S_="_configBtnActive_1a4uy_402",w_="_hasPath_1a4uy_410",b_="_pathIndicator_1a4uy_415",__="_formActions_1a4uy_421",C_="_hasCancel_1a4uy_428",A_="_submitBtn_1a4uy_432",x_="_cancelBtn_1a4uy_448",I_="_successMessage_1a4uy_480",T_="_errorMessage_1a4uy_486",R_="_successIcon_1a4uy_498",j_="_spinner_1a4uy_518",N_="_spin_1a4uy_518",P_="_boardRefreshIndicator_1a4uy_522",M_="_destructiveBtn_1a4uy_552",E_="_warningBtn_1a4uy_575",D_="_viewTab_1a4uy_598",L_="_deleteBtn_1a4uy_609",B_="_loading_1a4uy_619",W_="_emptyState_1a4uy_625",F_="_taskList_1a4uy_635",O_="_taskIdBadge_1a4uy_641",$_="_taskIdBadgeLabel_1a4uy_663",U_="_copiedId_1a4uy_682",z_="_highlight_1a4uy_688",H_="_modal_1a4uy_700",G_="_priorityEmoji_1a4uy_708",V_="_metaItem_1a4uy_712",q_="_taskFormDateInput_1a4uy_726",K_="_metaBadge_1a4uy_736",Z_="_complexityPill_1a4uy_751",Y_="_complexityDots_1a4uy_755",J_="_dot_1a4uy_761",Q_="_dotFilled_1a4uy_769",X_="_typePill_1a4uy_775",eC="_type_bug_1a4uy_779",tC="_type_feature_1a4uy_783",aC="_type_chore_1a4uy_787",nC="_type_refactor_1a4uy_791",rC="_type_documentation_1a4uy_795",sC="_type_research_1a4uy_799",oC="_type_security_1a4uy_807",iC="_approachPill_1a4uy_812",cC="_approach_evaluate_1a4uy_817",lC="_approach_collaborate_1a4uy_823",dC="_approach_plan_1a4uy_829",uC="_approachActive_1a4uy_835",mC="_statusActionsGroup_1a4uy_840",pC="_statusActionsGroupCompact_1a4uy_846",fC="_statusSelectWrap_1a4uy_850",hC="_statusTaxonomyDropdownWrap_1a4uy_856",gC="_statusTaxonomyDropdown_1a4uy_856",yC="_statusTaxonomyDropdownCompact_1a4uy_864",kC="_statusTaxonomyDropdownIconOnly_1a4uy_868",vC="_taxonomyDropdownButton_1a4uy_873",SC="_taxonomyDropdownButtonContent_1a4uy_890",wC="_statusTaxonomyDropdownIconOnlyPanel_1a4uy_894",bC="_actionBtn_1a4uy_900",_C="_startWorkBtn_1a4uy_924",CC="_workingBtn_1a4uy_933",AC="_pulse_1a4uy_1",xC="_reviewBtn_1a4uy_939",IC="_reviewActiveBtn_1a4uy_949",TC="_reviewPill_1a4uy_955",RC="_archiveTaskBtn_1a4uy_962",jC="_bulkArchiveBtn_1a4uy_971",NC="_bulkDeleteBtn_1a4uy_993",PC="_completeBtn_1a4uy_1034",MC="_completeActiveBtn_1a4uy_1044",EC="_deleteActiveBtn_1a4uy_1050",DC="_disabledBtn_1a4uy_1056",LC="_archiveList_1a4uy_1063",BC="_archiveHeader_1a4uy_1071",WC="_settingsTab_1a4uy_1082",FC="_settingsTabMcpOnly_1a4uy_1091",OC="_settingsTabs_1a4uy_1100",$C="_settingsLayout_1a4uy_1114",UC="_settingsLayoutMcpOnly_1a4uy_1121",zC="_settingsSidebar_1a4uy_1127",HC="_settingsSidebarHeader_1a4uy_1137",GC="_settingsSidebarNav_1a4uy_1146",VC="_settingsSidebarBtn_1a4uy_1155",qC="_settingsSidebarBtnActive_1a4uy_1179",KC="_settingsSidebarGroup_1a4uy_1186",ZC="_settingsSidebarGroupBtn_1a4uy_1192",YC="_settingsSidebarGroupLabel_1a4uy_1196",JC="_settingsSidebarGroupChevron_1a4uy_1200",QC="_settingsSidebarSubnav_1a4uy_1206",XC="_settingsSidebarSubBtn_1a4uy_1213",eA="_appScrollbar_1a4uy_1236",tA="_settingsTabBtn_1a4uy_1240",aA="_settingsTabBtnActive_1a4uy_1266",nA="_settingsContent_1a4uy_1272",rA="_mcpRegistrationHint_1a4uy_1298",sA="_mcpRegistrationPrompt_1a4uy_1309",oA="_mcpAuthRequiredCard_1a4uy_1328",iA="_mcpAuthRequiredIcon_1a4uy_1340",cA="_mcpAuthRequiredBody_1a4uy_1353",lA="_mcpAuthRequiredActions_1a4uy_1360",dA="_settingsToast_1a4uy_1404",uA="_settingsToastSuccess_1a4uy_1421",mA="_settingsToastError_1a4uy_1427",pA="_inputWithPrefix_1a4uy_1433",fA="_pathHint_1a4uy_1440",hA="_settingGroup_1a4uy_1453",gA="_settingTitle_1a4uy_1459",yA="_settingTitleRow_1a4uy_1468",kA="_settingTitleActionBtn_1a4uy_1475",vA="_themeOptions_1a4uy_1495",SA="_buttonGrid_1a4uy_1500",wA="_themeBtn_1a4uy_1512",bA="_activeTheme_1a4uy_1536",_A="_pathInputGroup_1a4uy_1544",CA="_saveSettingsBtn_1a4uy_1553",AA="_shortcutInputWrapper_1a4uy_1574",xA="_inputIcon_1a4uy_1579",IA="_settingHelper_1a4uy_1588",TA="_browseBtn_1a4uy_1595",RA="_inlineCategoryManager_1a4uy_1614",jA="_categoryManager_1a4uy_1625",NA="_categoryList_1a4uy_1631",PA="_categoryChip_1a4uy_1643",MA="_categoryChipLabel_1a4uy_1656",EA="_chipActionBtn_1a4uy_1664",DA="_removeCategoryBtn_1a4uy_1684",LA="_addCategoryForm_1a4uy_1704",BA="_addCategoryBtn_1a4uy_1709",WA="_filesList_1a4uy_1734",FA="_helpLink_1a4uy_1761",OA="_inlineCode_1a4uy_1782",$A="_codeBlock_1a4uy_1793",UA="_taskChildrenSummaryBadges_1a4uy_1817",zA="_taskChildrenProgressBar_1a4uy_1825",HA="_taskChildrenProgressBarSegmentDone_1a4uy_1836",GA="_taskChildrenProgressBarSegmentReview_1a4uy_1842",VA="_taskChildrenProgressBarSegmentInProgress_1a4uy_1848",qA="_taskChildrenProgressBarSegmentBlocked_1a4uy_1854",KA="_taskChildrenProgressText_1a4uy_1860",ZA="_taskChildUnlinkBtn_1a4uy_1869",YA="_aboutText_1a4uy_1887",JA="_versionInfo_1a4uy_1894",QA="_filterBar_1a4uy_1902",XA="_kanbanHintText_1a4uy_1916",ex="_searchContainer_1a4uy_1922",tx="_searchIcon_1a4uy_1929",ax="_searchInput_1a4uy_1937",nx="_searchActive_1a4uy_1963",rx="_searchCount_1a4uy_1968",sx="_clearSearchBtn_1a4uy_1984",ox="_filterRow_1a4uy_2006",ix="_sortLabel_1a4uy_2012",cx="_archiveToggle_1a4uy_2020",lx="_filterContainer_1a4uy_2057",dx="_filterButton_1a4uy_2062",ux="_filterActive_1a4uy_2087",mx="_filterDropdown_1a4uy_2093",px="_filterOption_1a4uy_2108",fx="_filterDivider_1a4uy_2138",hx="_filterSelect_1a4uy_2144",gx="_filterToggleBtn_1a4uy_2185",yx="_inProgressToggle_1a4uy_2207",kx="_activeInProgress_1a4uy_2225",vx="_activeFilter_1a4uy_2234",Sx="_resetFiltersBtn_1a4uy_2244",wx="_categoryChip_disabled_1a4uy_2277",bx="_categoryVisibilityToggle_1a4uy_2287",_x="_editCategoryInput_1a4uy_2300",Cx="_categoryChipActionBtn_1a4uy_2311",Ax="_categoryChipActionBtn_active_1a4uy_2329",xx="_categoryGroup_1a4uy_2334",Ix="_categoryHeader_1a4uy_2342",Tx="_categoryTitle_1a4uy_2356",Rx="_categoryCount_1a4uy_2366",jx="_categoryItems_1a4uy_2372",Nx="_priorityItem_low_1a4uy_2381",Px="_priorityItem_medium_1a4uy_2385",Mx="_priorityItem_high_1a4uy_2389",Ex="_priorityItem_critical_1a4uy_2393",Dx="_priorityPill_low_1a4uy_2397",Lx="_priorityPill_medium_1a4uy_2403",Bx="_priorityPill_high_1a4uy_2409",Wx="_priorityPill_critical_1a4uy_2415",Fx="_selectPriority_low_1a4uy_2430",Ox="_selectPriority_medium_1a4uy_2435",$x="_selectPriority_high_1a4uy_2440",Ux="_selectPriority_critical_1a4uy_2445",zx="_levelSelect_1a4uy_2454",Hx="_levelOption_1a4uy_2467",Gx="_levelOptionFilled_1a4uy_2484",Vx="_levelOption_priority_low_1a4uy_2491",qx="_levelOption_priority_medium_1a4uy_2496",Kx="_levelOption_priority_high_1a4uy_2501",Zx="_levelOption_priority_critical_1a4uy_2506",Yx="_levelOption_complexity_tiny_1a4uy_2513",Jx="_levelOption_complexity_low_1a4uy_2518",Qx="_levelOption_complexity_medium_1a4uy_2523",Xx="_levelOption_complexity_high_1a4uy_2528",eI="_levelOption_complexity_epic_1a4uy_2533",tI="_levelOptionActive_1a4uy_2540",aI="_levelOptionSelected_1a4uy_2545",nI="_levelLabel_1a4uy_2553",rI="_fadeIn_1a4uy_1",sI="_closeConfigBtn_1a4uy_2578",oI="_configItem_1a4uy_2600",iI="_settingsLabel_1a4uy_2606",cI="_settingsHint_1a4uy_2615",lI="_pathList_1a4uy_2622",dI="_pathChip_1a4uy_2629",uI="_pathValid_1a4uy_2642",mI="_pathInvalid_1a4uy_2647",pI="_pathValidIcon_1a4uy_2652",fI="_pathInvalidIcon_1a4uy_2657",hI="_pathText_1a4uy_2662",gI="_removePathBtn_1a4uy_2669",yI="_pathCount_1a4uy_2691",kI="_specialistSection_1a4uy_2714",vI="_toggleHeading_1a4uy_2722",SI="_dropdownList_1a4uy_2762",wI="_specialistBadge_1a4uy_2771",bI="_iconGrid_1a4uy_2801",_I="_iconPickerBtn_1a4uy_2812",CI="_iconPickerBtnActive_1a4uy_2831",AI="_categorySubConfig_1a4uy_2838",xI="_colorPickerRow_1a4uy_2846",II="_colorPickerGrid_1a4uy_2852",TI="_colorSwatch_1a4uy_2859",RI="_colorSwatchActive_1a4uy_2878",jI="_categoryChipIcon_1a4uy_2884",NI="_fieldIconWrapper_1a4uy_2889",PI="_fieldIcon_1a4uy_2889",MI="_field_dynamic_1a4uy_2911",EI="_fieldIcon_dynamic_1a4uy_2917",DI="_categoryTitleIcon_1a4uy_2921",LI="_editActionsHeader_1a4uy_2927",BI="_editActionsGroup_1a4uy_2936",WI="_urlInputGroup_1a4uy_2943",FI="_iconBtn_1a4uy_2956",OI="_stickyActionHeader_1a4uy_2977",$I="_taskHierarchyHeader_1a4uy_2994",UI="_taskHierarchyBadgeRow_1a4uy_3001",zI="_taskHierarchyDivider_1a4uy_3009",HI="_taskHierarchySegment_1a4uy_3015",GI="_taskHierarchyMeta_1a4uy_3022",VI="_taskHierarchyActionBtn_1a4uy_3035",qI="_taskHierarchyEditor_1a4uy_3041",KI="_taskHierarchyInput_1a4uy_3048",ZI="_taskSaveStatus_1a4uy_3057",YI="_taskSaveStatusCenter_1a4uy_3068",JI="_taskSaveStatusError_1a4uy_3076",QI="_headerSuccessFeedback_1a4uy_3080",XI="_slideInUp_1a4uy_1",eT="_successCheck_1a4uy_3092",tT="_scaleIn_1a4uy_1",aT="_primaryUpdateBtn_1a4uy_3128",nT="_secondaryHeaderBtn_1a4uy_3156",rT="_secondaryHeaderBtnDestructive_1a4uy_3177",sT="_commentSection_1a4uy_3190",oT="_attachmentCaptureContainer_1a4uy_3226",iT="_capturePrompt_1a4uy_3234",cT="_previewContainer_1a4uy_3248",lT="_previewHeader_1a4uy_3254",dT="_attachmentCapturePreview_1a4uy_3264",uT="_actions_1a4uy_3271",mT="_primaryButton_1a4uy_3277",pT="_secondaryButton_1a4uy_3292",fT="_iconButton_1a4uy_3307",hT="_attachmentGrid_1a4uy_3329",gT="_attachmentCard_1a4uy_3336",yT="_attachmentPreviewContainer_1a4uy_3350",kT="_contextFileLink_1a4uy_3371",vT="_attachmentActions_1a4uy_3397",ST="_attachmentActionBtn_1a4uy_3411",wT="_attachmentCaptionInput_1a4uy_3433",bT="_hiddenInput_1a4uy_3451",_T="_contextUploadPanel_1a4uy_3455",CT="_contextUploadActions_1a4uy_3463",AT="_contextDropzone_1a4uy_3471",xT="_contextDropzoneActive_1a4uy_3487",IT="_contextDropzonePulse_1a4uy_1",TT="_contextLinkRow_1a4uy_3495",RT="_contextNotice_1a4uy_3501",jT="_documentAttachmentList_1a4uy_3507",NT="_documentAttachmentItem_1a4uy_3514",PT="_documentAttachmentRow_1a4uy_3521",MT="_documentAttachmentLink_1a4uy_3529",ET="_documentAttachmentMain_1a4uy_3543",DT="_documentAttachmentText_1a4uy_3550",LT="_documentAttachmentIcon_1a4uy_3558",BT="_documentAttachmentName_1a4uy_3569",WT="_documentAttachmentType_1a4uy_3578",FT="_documentAttachmentActions_1a4uy_3591",OT="_documentAttachmentActionBtn_1a4uy_3597",$T="_documentAttachmentCaptionInput_1a4uy_3618",UT="_brokenImage_1a4uy_3646",zT="_brokenImagePlaceholder_1a4uy_3654",HT="_regionOverlay_1a4uy_3668",GT="_selectionBox_1a4uy_3679",VT="_exportRow_1a4uy_3687",qT="_exportItem_1a4uy_3692",KT="_taxonomyDrillDown_1a4uy_3701",ZT="_drillDownList_1a4uy_3711",YT="_drillDownSection_1a4uy_3719",JT="_drillDownSectionHeader_1a4uy_3725",QT="_drillDownSectionTitle_1a4uy_3732",XT="_drillDownItem_1a4uy_3741",eR="_drillDownItemDimmed_1a4uy_3763",tR="_drillDownItemActive_1a4uy_3771",aR="_drillDownItemInfo_1a4uy_3776",nR="_drillDownItemText_1a4uy_3782",rR="_drillDownItemLabel_1a4uy_3787",sR="_drillDownItemSubtext_1a4uy_3792",oR="_addTaxonomyBtnSmall_1a4uy_3797",iR="_taxonomyDetailView_1a4uy_3819",cR="_slideIn_1a4uy_1",lR="_detailHeader_1a4uy_3839",dR="_detailTitle_1a4uy_3848",uR="_detailContent_1a4uy_3855",mR="_createOverlay_1a4uy_3862",pR="_createDialog_1a4uy_3874",fR="_zoomIn_1a4uy_1",hR="_dialogActions_1a4uy_3902",gR="_settingsGroup_1a4uy_3920",yR="_settingsItem_1a4uy_3926",kR="_settingLabelGroup_1a4uy_3932",vR="_settingLabel_1a4uy_3932",SR="_settingDescription_1a4uy_3944",wR="_settingInput_1a4uy_3951",bR="_codeBlockWrapper_1a4uy_3974",_R="_codeHeader_1a4uy_3983",CR="_codeHeaderActions_1a4uy_3994",AR="_codeLabel_1a4uy_4001",xR="_codeHeaderDescription_1a4uy_4009",IR="_mcpTokenCardBody_1a4uy_4017",TR="_mcpTokenFormGrid_1a4uy_4025",RR="_mcpTokenOutputWrap_1a4uy_4032",jR="_mcpTokenValueField_1a4uy_4039",NR="_mcpTokenValueText_1a4uy_4049",PR="_mcpTokenValueInput_1a4uy_4062",MR="_mcpTokenActionRow_1a4uy_4067",ER="_copyBtn_1a4uy_4090",DR="_copyBtnActive_1a4uy_4111",LR="_copyBtnNeutralActive_1a4uy_4117",BR="_headerDivider_1a4uy_4135",WR="_groupByContainer_1a4uy_4141",FR="_groupByLabel_1a4uy_4149",OR="_groupBySelect_1a4uy_4154",$R="_viewSwitcher_1a4uy_4176",UR="_selectWithIcon_1a4uy_4184",zR="_marginBottom16_1a4uy_4188",HR="_headerDraggable_1a4uy_4193",GR="_headerDragging_1a4uy_4197",VR="_filterSelectSort_1a4uy_4205",qR="_archiveRow_1a4uy_4209",KR="_taskScopeToggle_1a4uy_4215",ZR="_taskScopeTabs_1a4uy_4223",YR="_taskScopeTab_1a4uy_4223",JR="_taskScopeTabActive_1a4uy_4256",QR="_taskToolbarAction_1a4uy_4268",XR="_overlayHighZ_1a4uy_4284",ej="_savedText_1a4uy_4294",tj="_shortcutInput_1a4uy_1574",aj="_saveSettingsBtnWrapper_1a4uy_4302",nj="_marginBottom12_1a4uy_4306",rj="_exportRowGrid_1a4uy_4310",sj="_settingSubtitleCustom_1a4uy_4315",oj="_capitalize_1a4uy_4321",ij="_marginTop12_1a4uy_4325",cj="_marginTop16_1a4uy_4329",lj="_labelGroupFlex_1a4uy_4333",dj="_codeBlockWrapperCustom_1a4uy_4339",uj="_kanbanWrapper_1a4uy_4345",mj="_kanbanContainer_1a4uy_4353",pj="_kanbanTopScroll_1a4uy_4375",fj="_kanbanTopScrollSpacer_1a4uy_4384",hj="_kanbanColumn_1a4uy_4388",gj="_kanbanColumnSticky_1a4uy_4404",yj="_kanbanColumnCollapsed_1a4uy_4410",kj="_kanbanColumnPast_1a4uy_4415",vj="_kanbanColumnSelectedDay_1a4uy_4420",Sj="_kanbanHeader_1a4uy_4427",wj="_kanbanCount_1a4uy_4437",bj="_kanbanHeaderDraggable_1a4uy_4457",_j="_kanbanHeaderPanning_1a4uy_4461",Cj="_kanbanQuickAdd_1a4uy_4465",Aj="_kanbanColorDot_1a4uy_4486",xj="_kanbanDroppable_1a4uy_4498",Ij="_kanbanDroppableScroll_1a4uy_4507",Tj="_kanbanEmpty_1a4uy_4517",Rj="_kanbanCard_1a4uy_4527",jj="_kanbanCardWrapper_1a4uy_4537",Nj="_taxonomyDropdownActive_1a4uy_4545",Pj="_kanbanCardWrapperRaised_1a4uy_4549",Mj="_kanbanCardTitle_1a4uy_4553",Ej="_kanbanBadges_1a4uy_4557",Dj="_kanbanBadge_1a4uy_4557",Lj="_headerFlex_1a4uy_4573",Bj="_marginBottom8_1a4uy_4580",Wj="_marginBottom20_1a4uy_4584",Fj="_configPanel_1a4uy_4588",Oj="_configPanelLarge_1a4uy_4597",$j="_subLabelBlock_1a4uy_4601",Uj="_subLabelBlock12_1a4uy_4608",zj="_flexBetween_1a4uy_4612",Hj="_flexBetweenCenter_1a4uy_4619",Gj="_deleteBtnSmall_1a4uy_4624",Vj="_deleteBtnMedium_1a4uy_4630",qj="_trashIcon_1a4uy_4637",Kj="_gridConfig_1a4uy_4641",Zj="_flexColGap4_1a4uy_4648",Yj="_flexColGap4Center_1a4uy_4654",Jj="_flex1_1a4uy_4661",Qj="_flexCol_1a4uy_4648",Xj="_flexGrow1_1a4uy_4671",eN="_inputLabel_1a4uy_4675",tN="_inputLabelBlock_1a4uy_4679",aN="_checkboxInput_1a4uy_4685",nN="_configDividerMargin_1a4uy_4691",rN="_configDividerMargin24_1a4uy_4696",sN="_pathListMargin_1a4uy_4701",oN="_cancelBtnRed_1a4uy_4705",iN="_code_1a4uy_1793",cN="_workflowList_1a4uy_4732",lN="_workflowActions_1a4uy_4740",dN="_textBtn_1a4uy_4749",uN="_workflowGrid_1a4uy_4763",mN="_checkboxLabel_1a4uy_4771",pN="_checkboxSmall_1a4uy_4785",fN="_docWorkspace_1a4uy_4804",hN="_docIndexPanel_1a4uy_4815",gN="_docWorkspaceTrayMode_1a4uy_4827",yN="_docViewerPanel_1a4uy_4827",kN="_docWorkspaceTrayOpen_1a4uy_4832",vN="_docTrayPanel_1a4uy_4836",SN="_docTrayPanelOpen_1a4uy_4860",wN="_docSpinning_1a4uy_4868",bN="_docSpin_1a4uy_4868",_N="_docViewerEmpty_1a4uy_4887",CN="_agentsModuleRoot_1a4uy_4902",AN="_agentsModuleWithTray_1a4uy_4914",xN="_agentsModuleTrayOpen_1a4uy_4918",IN="_agentTrayPanel_1a4uy_4922",TN="_agentTrayPanelOpen_1a4uy_4945",RN="_agentTrayHeader_1a4uy_4953",jN="_agentTrayTitle_1a4uy_4968",NN="_agentTrayContent_1a4uy_4980",PN="_agentTrayContentInner_1a4uy_4988",MN="_agentsModuleContent_1a4uy_4992",EN="_agentsModuleGroup_1a4uy_4997",DN="_marginTop24_1a4uy_5001",LN="_settingSubTitle_1a4uy_5005",BN="_dangerBtn_1a4uy_5014",WN="_aiProfilesExplorer_1a4uy_5030",FN="_aiProfilesListPane_1a4uy_5041",ON="_aiProfilesList_1a4uy_5041",$N="_aiProfilesSection_1a4uy_5060",UN="_aiProfilesSectionHeader_1a4uy_5066",zN="_aiProfileGroup_1a4uy_5074",HN="_aiProfileGroupSelected_1a4uy_5097",GN="_aiProfileGroupDuplicate_1a4uy_5106",VN="_aiProfileGroupHeader_1a4uy_5111",qN="_aiProfileGroupAvatar_1a4uy_5119",KN="_aiProfileGroupIdentity_1a4uy_5141",ZN="_aiProfileName_1a4uy_5150",YN="_aiProfileHandle_1a4uy_5158",JN="_aiProfileRole_1a4uy_5159",QN="_aiProfileSeatSummary_1a4uy_5170",XN="_aiProfileSeatScopeIcon_1a4uy_5179",eP="_aiProfileSeatScopeIconDetail_1a4uy_5190",tP="_aiProfileSeatScopeIconCloud_1a4uy_5195",aP="_aiProfileSeatScopeIconLocal_1a4uy_5199",nP="_aiProfileDuplicateBadge_1a4uy_5203",rP="_aiProfileMergeSection_1a4uy_5215",sP="_aiProfileMergeRow_1a4uy_5222",oP="_aiProfileIdChip_1a4uy_5229",iP="_aiProfileKeepBadge_1a4uy_5241",cP="_aiProfileMergeActions_1a4uy_5255",lP="_aiProfileDetailPane_1a4uy_5262",dP="_aiProfileDetailCard_1a4uy_5268",uP="_aiProfileDetailHero_1a4uy_5280",mP="_aiProfileDetailIcon_1a4uy_5286",pP="_aiProfileDetailAvatar_1a4uy_5300",fP="_aiProfileDetailHeading_1a4uy_5304",hP="_aiProfileDetailTitleRow_1a4uy_5309",gP="_aiProfileDetailTitle_1a4uy_5309",yP="_aiProfileDetailMetaRow_1a4uy_5324",kP="_aiProfileDetailHandle_1a4uy_5332",vP="_aiProfileDetailRole_1a4uy_5337",SP="_aiProfileDetailLinkedCount_1a4uy_5344",wP="_aiProfileDetailDescription_1a4uy_5349",bP="_aiProfileSignatureColor_1a4uy_5356",_P="_aiProfileSignatureSwatch_1a4uy_5366",CP="_aiProfileDetailDataList_1a4uy_5376",AP="_aiProfileDetailDataGroup_1a4uy_5385",xP="_aiProfileDetailDateGroup_1a4uy_5392",IP="_aiProfileDetailDataRow_1a4uy_5397",TP="_aiProfileDetailDataLabel_1a4uy_5406",RP="_aiProfileDetailDataValue_1a4uy_5413",jP="_aiProfileStatusSelect_1a4uy_5419",NP="_aiProfileInstanceSection_1a4uy_5461",PP="_aiProfileInstanceSectionHeader_1a4uy_5467",MP="_aiProfileInstanceList_1a4uy_5477",EP="_aiProfileInstanceCard_1a4uy_5483",DP="_aiProfileIdFooter_1a4uy_5496",LP="_aiProfileIdFooterValue_1a4uy_5506",BP="_aiProfileDangerTextButton_1a4uy_5516",WP="_aiProfileInstanceTopRow_1a4uy_5548",FP="_aiProfileInstanceName_1a4uy_5555",OP="_aiProfileInstanceMeta_1a4uy_5562",$P="_aiProfileInlineError_1a4uy_5570",p={filterGlow:Ob,floatingButton:$b,badge:Ub,configBadge:zb,configBadgeActive:Hb,configBadgeRevoked:Gb,configBadgeExpired:Vb,header:qb,headerTitle:Kb,brandIcon:Zb,brandHomeButton:Yb,brandHomeStatic:Jb,brandCloudSuffix:Qb,projectSlash:Xb,projectName:e_,taskCountBadge:t_,taskCountBadgeIcon:a_,taskCountBadgeAlert:n_,headerActions:r_,sortDirectionBtn:s_,sortDirectionBtnWidget:o_,form:i_,topRow:c_,field:l_,labelRow:d_,label:u_,manageLink:m_,input:p_,select:f_,textarea:h_,taskIdInlineLink:g_,readOnly:y_,selectWithConfig:k_,configBtn:v_,configBtnActive:S_,hasPath:w_,pathIndicator:b_,formActions:__,hasCancel:C_,submitBtn:A_,cancelBtn:x_,successMessage:I_,errorMessage:T_,successIcon:R_,spinner:j_,spin:N_,boardRefreshIndicator:P_,destructiveBtn:M_,warningBtn:E_,viewTab:D_,deleteBtn:L_,loading:B_,emptyState:W_,taskList:F_,taskIdBadge:O_,taskIdBadgeLabel:$_,copiedId:U_,highlight:z_,modal:H_,priorityEmoji:G_,metaItem:V_,taskFormDateInput:q_,metaBadge:K_,complexityPill:Z_,complexityDots:Y_,dot:J_,dotFilled:Q_,typePill:X_,type_bug:eC,type_feature:tC,type_chore:aC,type_refactor:nC,type_documentation:rC,type_research:sC,"type_ui-ux":"_type_ui-ux_1a4uy_803",type_security:oC,approachPill:iC,approach_evaluate:cC,approach_collaborate:lC,approach_plan:dC,approachActive:uC,statusActionsGroup:mC,statusActionsGroupCompact:pC,statusSelectWrap:fC,statusTaxonomyDropdownWrap:hC,statusTaxonomyDropdown:gC,statusTaxonomyDropdownCompact:yC,statusTaxonomyDropdownIconOnly:kC,taxonomyDropdownButton:vC,taxonomyDropdownButtonContent:SC,statusTaxonomyDropdownIconOnlyPanel:wC,actionBtn:bC,startWorkBtn:_C,workingBtn:CC,pulse:AC,reviewBtn:xC,reviewActiveBtn:IC,reviewPill:TC,archiveTaskBtn:RC,bulkArchiveBtn:jC,bulkDeleteBtn:NC,completeBtn:PC,completeActiveBtn:MC,deleteActiveBtn:EC,disabledBtn:DC,archiveList:LC,archiveHeader:BC,settingsTab:WC,settingsTabMcpOnly:FC,settingsTabs:OC,settingsLayout:$C,settingsLayoutMcpOnly:UC,settingsSidebar:zC,settingsSidebarHeader:HC,settingsSidebarNav:GC,settingsSidebarBtn:VC,settingsSidebarBtnActive:qC,settingsSidebarGroup:KC,settingsSidebarGroupBtn:ZC,settingsSidebarGroupLabel:YC,settingsSidebarGroupChevron:JC,settingsSidebarSubnav:QC,settingsSidebarSubBtn:XC,appScrollbar:eA,settingsTabBtn:tA,settingsTabBtnActive:aA,settingsContent:nA,mcpRegistrationHint:rA,mcpRegistrationPrompt:sA,mcpAuthRequiredCard:oA,mcpAuthRequiredIcon:iA,mcpAuthRequiredBody:cA,mcpAuthRequiredActions:lA,settingsToast:dA,settingsToastSuccess:uA,settingsToastError:mA,inputWithPrefix:pA,pathHint:fA,settingGroup:hA,settingTitle:gA,settingTitleRow:yA,settingTitleActionBtn:kA,themeOptions:vA,buttonGrid:SA,themeBtn:wA,activeTheme:bA,pathInputGroup:_A,saveSettingsBtn:CA,shortcutInputWrapper:AA,inputIcon:xA,settingHelper:IA,browseBtn:TA,inlineCategoryManager:RA,categoryManager:jA,categoryList:NA,categoryChip:PA,categoryChipLabel:MA,chipActionBtn:EA,removeCategoryBtn:DA,addCategoryForm:LA,addCategoryBtn:BA,filesList:WA,helpLink:FA,inlineCode:OA,codeBlock:$A,taskChildrenSummaryBadges:UA,taskChildrenProgressBar:zA,taskChildrenProgressBarSegmentDone:HA,taskChildrenProgressBarSegmentReview:GA,taskChildrenProgressBarSegmentInProgress:VA,taskChildrenProgressBarSegmentBlocked:qA,taskChildrenProgressText:KA,taskChildUnlinkBtn:ZA,aboutText:YA,versionInfo:JA,filterBar:QA,kanbanHintText:XA,searchContainer:ex,searchIcon:tx,searchInput:ax,searchActive:nx,searchCount:rx,clearSearchBtn:sx,filterRow:ox,sortLabel:ix,archiveToggle:cx,filterContainer:lx,filterButton:dx,filterActive:ux,filterDropdown:mx,filterOption:px,filterDivider:fx,filterSelect:hx,filterToggleBtn:gx,inProgressToggle:yx,activeInProgress:kx,activeFilter:vx,resetFiltersBtn:Sx,categoryChip_disabled:wx,categoryVisibilityToggle:bx,editCategoryInput:_x,categoryChipActionBtn:Cx,categoryChipActionBtn_active:Ax,categoryGroup:xx,categoryHeader:Ix,categoryTitle:Tx,categoryCount:Rx,categoryItems:jx,priorityItem_low:Nx,priorityItem_medium:Px,priorityItem_high:Mx,priorityItem_critical:Ex,priorityPill_low:Dx,priorityPill_medium:Lx,priorityPill_high:Bx,priorityPill_critical:Wx,selectPriority_low:Fx,selectPriority_medium:Ox,selectPriority_high:$x,selectPriority_critical:Ux,"critical-glow":"_critical-glow_1a4uy_1",levelSelect:zx,levelOption:Hx,levelOptionFilled:Gx,levelOption_priority_low:Vx,levelOption_priority_medium:qx,levelOption_priority_high:Kx,levelOption_priority_critical:Zx,levelOption_complexity_tiny:Yx,levelOption_complexity_low:Jx,levelOption_complexity_medium:Qx,levelOption_complexity_high:Xx,levelOption_complexity_epic:eI,levelOptionActive:tI,levelOptionSelected:aI,levelLabel:nI,fadeIn:rI,closeConfigBtn:sI,configItem:oI,settingsLabel:iI,settingsHint:cI,pathList:lI,pathChip:dI,pathValid:uI,pathInvalid:mI,pathValidIcon:pI,pathInvalidIcon:fI,pathText:hI,removePathBtn:gI,pathCount:yI,specialistSection:kI,toggleHeading:vI,dropdownList:SI,specialistBadge:wI,iconGrid:bI,iconPickerBtn:_I,iconPickerBtnActive:CI,categorySubConfig:AI,colorPickerRow:xI,colorPickerGrid:II,colorSwatch:TI,colorSwatchActive:RI,categoryChipIcon:jI,fieldIconWrapper:NI,fieldIcon:PI,field_dynamic:MI,fieldIcon_dynamic:EI,categoryTitleIcon:DI,editActionsHeader:LI,editActionsGroup:BI,urlInputGroup:WI,iconBtn:FI,stickyActionHeader:OI,taskHierarchyHeader:$I,taskHierarchyBadgeRow:UI,taskHierarchyDivider:zI,taskHierarchySegment:HI,taskHierarchyMeta:GI,taskHierarchyActionBtn:VI,taskHierarchyEditor:qI,taskHierarchyInput:KI,taskSaveStatus:ZI,taskSaveStatusCenter:YI,taskSaveStatusError:JI,headerSuccessFeedback:QI,slideInUp:XI,successCheck:eT,scaleIn:tT,primaryUpdateBtn:aT,secondaryHeaderBtn:nT,secondaryHeaderBtnDestructive:rT,commentSection:sT,attachmentCaptureContainer:oT,capturePrompt:iT,previewContainer:cT,previewHeader:lT,attachmentCapturePreview:dT,actions:uT,primaryButton:mT,secondaryButton:pT,iconButton:fT,attachmentGrid:hT,attachmentCard:gT,attachmentPreviewContainer:yT,contextFileLink:kT,attachmentActions:vT,attachmentActionBtn:ST,attachmentCaptionInput:wT,hiddenInput:bT,contextUploadPanel:_T,contextUploadActions:CT,contextDropzone:AT,contextDropzoneActive:xT,contextDropzonePulse:IT,contextLinkRow:TT,contextNotice:RT,documentAttachmentList:jT,documentAttachmentItem:NT,documentAttachmentRow:PT,documentAttachmentLink:MT,documentAttachmentMain:ET,documentAttachmentText:DT,documentAttachmentIcon:LT,documentAttachmentName:BT,documentAttachmentType:WT,documentAttachmentActions:FT,documentAttachmentActionBtn:OT,documentAttachmentCaptionInput:$T,brokenImage:UT,brokenImagePlaceholder:zT,regionOverlay:HT,selectionBox:GT,exportRow:VT,exportItem:qT,taxonomyDrillDown:KT,drillDownList:ZT,drillDownSection:YT,drillDownSectionHeader:JT,drillDownSectionTitle:QT,drillDownItem:XT,drillDownItemDimmed:eR,drillDownItemActive:tR,drillDownItemInfo:aR,drillDownItemText:nR,drillDownItemLabel:rR,drillDownItemSubtext:sR,addTaxonomyBtnSmall:oR,taxonomyDetailView:iR,slideIn:cR,detailHeader:lR,detailTitle:dR,detailContent:uR,createOverlay:mR,createDialog:pR,zoomIn:fR,dialogActions:hR,settingsGroup:gR,settingsItem:yR,settingLabelGroup:kR,settingLabel:vR,settingDescription:SR,settingInput:wR,codeBlockWrapper:bR,codeHeader:_R,codeHeaderActions:CR,codeLabel:AR,codeHeaderDescription:xR,mcpTokenCardBody:IR,mcpTokenFormGrid:TR,mcpTokenOutputWrap:RR,mcpTokenValueField:jR,mcpTokenValueText:NR,mcpTokenValueInput:PR,mcpTokenActionRow:MR,copyBtn:ER,copyBtnActive:DR,copyBtnNeutralActive:LR,headerDivider:BR,groupByContainer:WR,groupByLabel:FR,groupBySelect:OR,viewSwitcher:$R,selectWithIcon:UR,marginBottom16:zR,headerDraggable:HR,headerDragging:GR,filterSelectSort:VR,archiveRow:qR,taskScopeToggle:KR,taskScopeTabs:ZR,taskScopeTab:YR,taskScopeTabActive:JR,taskToolbarAction:QR,overlayHighZ:XR,savedText:ej,shortcutInput:tj,saveSettingsBtnWrapper:aj,marginBottom12:nj,exportRowGrid:rj,settingSubtitleCustom:sj,capitalize:oj,marginTop12:ij,marginTop16:cj,labelGroupFlex:lj,codeBlockWrapperCustom:dj,kanbanWrapper:uj,kanbanContainer:mj,kanbanTopScroll:pj,kanbanTopScrollSpacer:fj,kanbanColumn:hj,kanbanColumnSticky:gj,kanbanColumnCollapsed:yj,kanbanColumnPast:kj,kanbanColumnSelectedDay:vj,kanbanHeader:Sj,kanbanCount:wj,kanbanHeaderDraggable:bj,kanbanHeaderPanning:_j,kanbanQuickAdd:Cj,kanbanColorDot:Aj,kanbanDroppable:xj,kanbanDroppableScroll:Ij,kanbanEmpty:Tj,kanbanCard:Rj,kanbanCardWrapper:jj,taxonomyDropdownActive:Nj,kanbanCardWrapperRaised:Pj,kanbanCardTitle:Mj,kanbanBadges:Ej,kanbanBadge:Dj,headerFlex:Lj,marginBottom8:Bj,marginBottom20:Wj,configPanel:Fj,configPanelLarge:Oj,subLabelBlock:$j,subLabelBlock12:Uj,flexBetween:zj,flexBetweenCenter:Hj,deleteBtnSmall:Gj,deleteBtnMedium:Vj,trashIcon:qj,gridConfig:Kj,flexColGap4:Zj,flexColGap4Center:Yj,flex1:Jj,flexCol:Qj,flexGrow1:Xj,inputLabel:eN,inputLabelBlock:tN,checkboxInput:aN,configDividerMargin:nN,configDividerMargin24:rN,pathListMargin:sN,cancelBtnRed:oN,code:iN,workflowList:cN,workflowActions:lN,textBtn:dN,workflowGrid:uN,checkboxLabel:mN,checkboxSmall:pN,docWorkspace:fN,docIndexPanel:hN,docWorkspaceTrayMode:gN,docViewerPanel:yN,docWorkspaceTrayOpen:kN,docTrayPanel:vN,docTrayPanelOpen:SN,docSpinning:wN,docSpin:bN,docViewerEmpty:_N,agentsModuleRoot:CN,agentsModuleWithTray:AN,agentsModuleTrayOpen:xN,agentTrayPanel:IN,agentTrayPanelOpen:TN,agentTrayHeader:RN,agentTrayTitle:jN,agentTrayContent:NN,agentTrayContentInner:PN,agentsModuleContent:MN,agentsModuleGroup:EN,marginTop24:DN,settingSubTitle:LN,dangerBtn:BN,aiProfilesExplorer:WN,aiProfilesListPane:FN,aiProfilesList:ON,aiProfilesSection:$N,aiProfilesSectionHeader:UN,aiProfileGroup:zN,aiProfileGroupSelected:HN,aiProfileGroupDuplicate:GN,aiProfileGroupHeader:VN,aiProfileGroupAvatar:qN,aiProfileGroupIdentity:KN,aiProfileName:ZN,aiProfileHandle:YN,aiProfileRole:JN,aiProfileSeatSummary:QN,aiProfileSeatScopeIcon:XN,aiProfileSeatScopeIconDetail:eP,aiProfileSeatScopeIconCloud:tP,aiProfileSeatScopeIconLocal:aP,aiProfileDuplicateBadge:nP,aiProfileMergeSection:rP,aiProfileMergeRow:sP,aiProfileIdChip:oP,aiProfileKeepBadge:iP,aiProfileMergeActions:cP,aiProfileDetailPane:lP,aiProfileDetailCard:dP,aiProfileDetailHero:uP,aiProfileDetailIcon:mP,aiProfileDetailAvatar:pP,aiProfileDetailHeading:fP,aiProfileDetailTitleRow:hP,aiProfileDetailTitle:gP,aiProfileDetailMetaRow:yP,aiProfileDetailHandle:kP,aiProfileDetailRole:vP,aiProfileDetailLinkedCount:SP,aiProfileDetailDescription:wP,aiProfileSignatureColor:bP,aiProfileSignatureSwatch:_P,aiProfileDetailDataList:CP,aiProfileDetailDataGroup:AP,aiProfileDetailDateGroup:xP,aiProfileDetailDataRow:IP,aiProfileDetailDataLabel:TP,aiProfileDetailDataValue:RP,aiProfileStatusSelect:jP,aiProfileInstanceSection:NP,aiProfileInstanceSectionHeader:PP,aiProfileInstanceList:MP,aiProfileInstanceCard:EP,aiProfileIdFooter:DP,aiProfileIdFooterValue:LP,aiProfileDangerTextButton:BP,aiProfileInstanceTopRow:WP,aiProfileInstanceName:FP,aiProfileInstanceMeta:OP,aiProfileInlineError:$P},UP="_standaloneWrapper_1r0om_1",zP="_standalonePage_1r0om_11",HP="_standaloneHeader_1r0om_21",GP="_standaloneTitle_1r0om_27",VP="_standaloneContent_1r0om_31",qP="_workspaceToolRail_1r0om_37",KP="_workspaceToolRailMain_1r0om_54",ZP="_workspaceToolRailBottom_1r0om_62",YP="_workspaceToolRailDivider_1r0om_72",JP="_workspaceToolButton_1r0om_79",QP="_workspaceToolButtonActive_1r0om_99",XP="_workspaceToolButtonDisabled_1r0om_106",e0="_headerTitleWidget_1r0om_137",ea={standaloneWrapper:UP,standalonePage:zP,standaloneHeader:HP,standaloneTitle:GP,standaloneContent:VP,workspaceToolRail:qP,workspaceToolRailMain:KP,workspaceToolRailBottom:ZP,workspaceToolRailDivider:YP,workspaceToolButton:JP,workspaceToolButtonActive:QP,workspaceToolButtonDisabled:XP,headerTitleWidget:e0},t0="_overlay_11v7l_1",a0="_browser_11v7l_16",n0="_header_11v7l_27",r0="_pathInfo_11v7l_36",s0="_actions_11v7l_52",o0="_list_11v7l_57",i0="_item_11v7l_63",c0="_itemCurrent_11v7l_80",l0="_itemFile_11v7l_86",d0="_empty_11v7l_90",Ia={overlay:t0,browser:a0,header:n0,pathInfo:r0,actions:s0,list:o0,item:i0,itemCurrent:c0,itemFile:l0,empty:d0},u0="_overlay_1hk7m_2",m0="_overlayHighZ_1hk7m_15",p0="_modal_1hk7m_20",f0="_draggableModal_1hk7m_46",h0="_draggableHeader_1hk7m_53",g0="_headerActions_1hk7m_61",y0="_modalContent_1hk7m_69",k0="_form_1hk7m_80",v0="_formActions_1hk7m_91",S0="_modalFooter_1hk7m_98",w0="_modalSizeSm_1hk7m_104",b0="_modalSizeMd_1hk7m_108",_0="_modalSizeMdWide_1hk7m_112",C0="_modalSizeLg_1hk7m_116",A0="_modalSizeXl_1hk7m_120",x0="_modalSizeFull_1hk7m_124",I0="_settingsViewModal_1hk7m_129",T0="_unsavedOverlay_1hk7m_148",R0="_unsavedModal_1hk7m_153",j0="_unsavedHeader_1hk7m_159",N0="_unsavedTitle_1hk7m_164",P0="_unsavedContent_1hk7m_168",M0="_unsavedText_1hk7m_172",E0="_unsavedActions_1hk7m_177",Tt={overlay:u0,overlayHighZ:m0,modal:p0,draggableModal:f0,draggableHeader:h0,headerActions:g0,modalContent:y0,form:k0,formActions:v0,modalFooter:S0,modalSizeSm:w0,modalSizeMd:b0,modalSizeMdWide:_0,modalSizeLg:C0,modalSizeXl:A0,modalSizeFull:x0,settingsViewModal:I0,unsavedOverlay:T0,unsavedModal:R0,unsavedHeader:j0,unsavedTitle:N0,unsavedContent:P0,unsavedText:M0,unsavedActions:E0};function D0(e){const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),n={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return n[t]?n[t]:`${e}s`}function qi({label:e,options:t,selected:n,onChange:s,variant:o="label",containerStyle:l}){const[i,d]=r.useState(!1),m=r.useRef(null);r.useEffect(()=>{const I=C=>{m.current&&!m.current.contains(C.target)&&d(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[]);const y=I=>{n.includes(I)?s(n.filter(C=>C!==I)):s([...n,I])},k=t.length>0&&t.every(I=>{const C=o==="label"?I.label:I.value;return n.includes(C)}),S=!t.some(I=>{const C=o==="label"?I.label:I.value;return n.includes(C)}),h=()=>{s(k?[]:t.map(I=>o==="label"?I.label:I.value))},g=t.filter(I=>{const C=o==="label"?I.label:I.value;return n.includes(C)}).length,v=D0(e),_=k?`All ${v}`:S?`No ${v}`:g===1?`1 ${e}`:`${g} ${v}`;return a.jsxs("div",{className:p.filterContainer,ref:m,style:l,children:[a.jsxs("button",{className:`${p.filterButton} ${k?"":p.filterActive}`,onClick:()=>d(!i),title:`Filter by ${e}`,children:[a.jsx("span",{children:_}),a.jsx(nl,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&a.jsxs("div",{className:`${p.filterDropdown} ${p.appScrollbar} tf-scrollbar`,children:[a.jsxs("div",{className:p.filterOption,onClick:h,children:[a.jsx("input",{type:"checkbox",checked:k,onChange:()=>{}}),a.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),a.jsx("div",{className:p.filterDivider}),t.map(I=>{const C=o==="label"?I.label:I.value,D=n.includes(C);return a.jsxs("div",{className:p.filterOption,onClick:()=>y(C),children:[a.jsx("input",{type:"checkbox",checked:D,onChange:()=>{}}),a.jsx("span",{children:I.label})]},I.value)})]})]})}const L0="_taskItem_zvr7q_1",B0="_compressed_zvr7q_20",W0="_taskHeader_zvr7q_25",F0="_taskReferenceCluster_zvr7q_30",O0="_taskMeta_zvr7q_34",$0="_taskTitle_zvr7q_40",U0="_taskItemRecentlyChanged_zvr7q_67",z0="_assigneeAvatarImage_zvr7q_107",H0="_assigneeAvatarIndicator_zvr7q_115",G0="_assigneeAvatarEmpty_zvr7q_137",V0="_inProgress_zvr7q_164",q0="_onHold_zvr7q_175",K0="_readyForReview_zvr7q_186",Z0="_completed_zvr7q_197",Y0="_cancelled_zvr7q_208",J0="_archived_zvr7q_219",Q0="_taskContent_zvr7q_229",X0="_kanbanCardOverlay_zvr7q_238",e1="_taskReferenceText_zvr7q_277",t1="_taskReferenceDivider_zvr7q_286",a1="_taskActions_zvr7q_293",n1="_taskMetaCompact_zvr7q_318",r1="_taskMetaRow_zvr7q_325",s1="_taskMetaBadgeGroup_zvr7q_333",o1="_taskDescription_zvr7q_339",i1="_taskLatestComment_zvr7q_398",c1="_taskCancellationReason_zvr7q_419",l1="_archiveBadge_zvr7q_573",d1="_attachmentThumbnails_zvr7q_578",u1="_attachmentImageRow_zvr7q_585",m1="_attachmentDocumentList_zvr7q_592",p1="_attachmentThumbnail_zvr7q_578",f1="_contextDocThumb_zvr7q_625",h1="_contextDocMain_zvr7q_651",g1="_contextDocText_zvr7q_658",y1="_contextDocIcon_zvr7q_666",k1="_contextDocName_zvr7q_677",v1="_contextDocType_zvr7q_687",S1="_taskSpecialists_zvr7q_699",w1="_taxonomiesList_zvr7q_708",Qt={taskItem:L0,compressed:B0,taskHeader:W0,taskReferenceCluster:F0,taskMeta:O0,taskTitle:$0,taskItemRecentlyChanged:U0,assigneeAvatarImage:z0,assigneeAvatarIndicator:H0,assigneeAvatarEmpty:G0,inProgress:V0,onHold:q0,readyForReview:K0,completed:Z0,cancelled:Y0,archived:J0,taskContent:Q0,kanbanCardOverlay:X0,taskReferenceText:e1,taskReferenceDivider:t1,taskActions:a1,taskMetaCompact:n1,taskMetaRow:r1,taskMetaBadgeGroup:s1,taskDescription:o1,taskLatestComment:i1,taskCancellationReason:c1,archiveBadge:l1,attachmentThumbnails:d1,attachmentImageRow:u1,attachmentDocumentList:m1,attachmentThumbnail:p1,contextDocThumb:f1,contextDocMain:h1,contextDocText:g1,contextDocIcon:y1,contextDocName:k1,contextDocType:v1,taskSpecialists:S1,taxonomiesList:w1},cy=({children:e,className:t,onTaskIdClick:n})=>{if(!e)return null;const s=i=>Ue.Children.toArray(i).some(m=>Ue.isValidElement(m)?String(m.props?.className||"").includes("task-list-item"):!1),o=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,l=i=>{if(!n)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(a.jsx("button",{type:"button",className:p.taskIdInlineLink,onClick:I=>{I.preventDefault(),I.stopPropagation(),n(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(l);if(!Ue.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:Ue.cloneElement(i,{},Ue.Children.map(m,l))};return a.jsx("div",{className:t,children:a.jsx(av,{remarkPlugins:[nv,rv],components:{p:({children:i})=>a.jsx("p",{children:l(i)}),ul:({children:i})=>a.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 a.jsx("li",{className:d,style:m?{listStyle:"none"}:void 0,children:l(i)})},input:({type:i,checked:d})=>i!=="checkbox"?a.jsx("input",{type:i,checked:d,readOnly:!0}):a.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
+ `)?a.jsx("pre",{className:p.codeBlock,children:a.jsx("code",{className:d,...m,children:y})}):a.jsx("code",{className:p.inlineCode,...m,children:y})}},children:e})})};function ly({label:e,title:t,ariaLabel:n,copied:s=!1,disabled:o=!1,className:l="",onClick:i,children:d}){return a.jsxs("button",{type:"button",className:`${p.taskIdBadge} ${s?p.copiedId:""} ${l}`.trim(),onClick:i,disabled:o,title:t,"aria-label":n,children:[s?a.jsx(no,{size:13}):a.jsx(tf,{size:13}),a.jsx("span",{className:p.taskIdBadgeLabel,children:d??e})]})}function Qu({copied:e,disabled:t=!1,label:n,onClick:s,title:o="Copy task reference",ariaLabel:l,className:i=""}){return a.jsx(ly,{copied:e,disabled:t,label:"",onClick:s,title:o,ariaLabel:l,className:i,children:n})}const b1=(e,t=10)=>{const n=mm[e?.toLowerCase()]||{icon:"FileCode"},s=As[n.icon]||Rk;return a.jsx(s,{size:t})},Uu=(e,t)=>{if(!e)return null;const n=t.trim();if(!n)return e;const o=Tm(n)?.match(/^(lt|t)-(\d+)$/),l=o?`${o[1]==="lt"?"l\\s*t":"t"}\\s*(?:-|\\s)?\\s*${o[2]}`:n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^${l}$`,"i"),d=e.split(new RegExp(`(${l})`,"gi"));return a.jsx(a.Fragment,{children:d.map((m,y)=>i.test(m)?a.jsx("mark",{className:p.highlight,children:m},y):m)})};function wd(e){return e.trim().replace(/\\/g,"/")}function dy(e){return e.split("?")[0].split("#")[0]}function jm(e){return typeof e=="string"?e:String(e.path||"").trim()}function uy(e){const n=dy(wd(e)).match(/\/api\/taskforce\/documents\/([^/]+)\/content$/i);if(!n?.[1])return null;try{return decodeURIComponent(n[1]).trim()||null}catch{return n[1].trim()||null}}function my(e){if(!e.includes("/api/taskforce/context-link?path="))return null;try{const n=new URL(e,window.location.origin).searchParams.get("path");return n?wd(n):null}catch{return null}}function _1(e,t){const n=(t||(typeof e=="string"?"":e.fsPath||"")).trim();if(n)return wd(n);const s=jm(e),o=my(s);return o?wd(o):null}function C1(e,t){const n=String(typeof e=="string"?"":e.assetId||"").trim();if(n)return n;const s=jm(e);return uy(s)}function A1(e,t){const n=jm(e);return uy(n)?!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(),my(n)||"",n].some(o=>{if(!o)return!1;const l=dy(wd(o)).toLowerCase();return l.endsWith(".md")||l.endsWith(".markdown")})}function x1(e,t){const n=jm(e),s=_1(e,t);if(!s||!A1(e,s))return!1;const o=C1(e),l=new CustomEvent("taskforce:open-markdown-document",{detail:{path:n,fsPath:s,...o?{assetId:o}:{},...typeof e!="string"&&e.taskId?{taskId:e.taskId}:{}},cancelable:!0});return!window.dispatchEvent(l)}const I1="I-";function py(e){return Am(I1,e)}function T1(e){return e.trim().replace(/\\/g,"/")}function fy(e){return typeof e=="string"?e:String(e.path||"").trim()}function R1(e){return/\.(png|jpe?g|webp)(\?|#|$)/i.test(e)}function j1(e){return typeof e=="string"?T1(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function N1(e,t){if(typeof e=="string")return!1;const n=String(e.assetId||"").trim(),s=fy(e);return!!(n&&s&&R1(s))}function P1(e,t){if(!N1(e))return!1;const n=e,s=String(t?.taskId||n.taskId||"").trim(),o=String(t?.taskReferenceLabel||"").trim(),l=String(n.assetId||"").trim(),i=py(n),d=fy(e),m=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...s?{taskId:s}:{},...o?{taskReferenceLabel:o}:{},assetId:l,...i?{imageReferenceLabel:i}:{},path:d,displayName:j1(e)},cancelable:!0});return!window.dispatchEvent(m)}function Rh(e,t){if(!e)return null;const n=String(e.taskId||"").trim(),s=String(e.assetId||"").trim(),o=String(e.path||"").trim(),l=String(e.displayName||"").trim()||"Image attachment";if(!s||!o)return null;const i=String(e.taskReferenceLabel||"").trim(),d=n?t.find(y=>y.id===n):void 0,m=n?i||Xi(d)||n:void 0;return{...n?{taskId:n}:{},...m?{taskReferenceLabel:m}:{},assetId:s,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,path:o,displayName:l}}function hm(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t)return"";const n=t.split("/").filter(Boolean);return n[n.length-1]||""}function _f(e){const t=String(e||"").trim(),n=t.lastIndexOf(".");return n<=0?{stem:t,ext:""}:{stem:t.slice(0,n),ext:t.slice(n)}}function hy(e,t){const n=String(e||"").trim(),s=String(t||"").trim();return n?s&&n.startsWith(`${s}-`)?n.slice(s.length+1):n.replace(/^asset-[a-z0-9-]+-/i,""):""}function M1(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function jh(e,t){const{stem:n,ext:s}=_f(hm(e)),o=hy(n,t),l=M1(o||n);return l?`${l}${s}`:hm(e)||"Untitled document"}function bp(e,t){const n=String(e||"").trim();if(!n)return!0;const s=hm(n),{stem:o}=_f(s),l=String(t||"").trim();if(l&&o.toLowerCase()===l.toLowerCase())return!0;const i=hy(o,t);return i?i!==o:!0}function E1(e){const t=String(e.logicalName||"").trim();if(t&&!bp(t,e.assetId))return t;const n=String(e.displayName||"").trim();if(n&&!bp(n,e.assetId))return n;const s=String(e.title||"").trim();if(s&&!bp(s,e.assetId))return s;const o=String(e.originalFilename||"").trim();if(o)return jh(o,e.assetId);const l=String(e.fsPath||"").trim();return l?jh(l,e.assetId):"Untitled document"}function D1(e){return E1(e)}function L1(e){const t=D1(e),n=String(e.originalFilename||e.fsPath||"").trim(),s=_f(hm(n)).ext;return s?t.toLowerCase().endsWith(s.toLowerCase())?t:`${t}${s}`:t}const B1="_taxonomyDropdown_tt12a_1",W1="_taxonomyDropdownActive_tt12a_6",F1="_taxonomyDropdownButton_tt12a_11",O1="_taxonomyDropdownOpen_tt12a_50",$1="_taxonomyDropdownButtonContent_tt12a_56",U1="_taxonomyDropdownIcon_tt12a_64",z1="_taxonomyDropdownLabel_tt12a_72",H1="_taxonomyDropdownChevron_tt12a_81",G1="_taxonomyDropdownChevronOpen_tt12a_87",V1="_taxonomyDropdownPanel_tt12a_91",q1="_taxonomyDropdownPanelPortal_tt12a_110",K1="_taxonomyDropdownOption_tt12a_129",Z1="_taxonomyDropdownOptionHighlighted_tt12a_157",Y1="_taxonomyDropdownOptionSelected_tt12a_163",yr={taxonomyDropdown:B1,taxonomyDropdownActive:W1,taxonomyDropdownButton:F1,taxonomyDropdownOpen:O1,taxonomyDropdownButtonContent:$1,taxonomyDropdownIcon:U1,taxonomyDropdownLabel:z1,taxonomyDropdownChevron:H1,taxonomyDropdownChevronOpen:G1,taxonomyDropdownPanel:V1,taxonomyDropdownPanelPortal:q1,taxonomyDropdownOption:K1,taxonomyDropdownOptionHighlighted:Z1,taxonomyDropdownOptionSelected:Y1};function id({value:e,options:t,onChange:n,placeholder:s="Select...",required:o=!1,disabled:l=!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,C]=r.useState(-1),[D,q]=r.useState({}),B=r.useRef(null),X=r.useRef(null),me=r.useRef(null),ke=t.find(Y=>String(Y.value)===String(e));r.useEffect(()=>{if(!v)return;const Y=P=>{const H=P.target,ue=!!B.current?.contains(H),ye=!!me.current?.contains(H);!ue&&!ye&&(_(!1),C(-1))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[v]),r.useEffect(()=>{if(!v)C(-1);else{const Y=t.findIndex(P=>String(P.value)===String(e));C(Y>=0?Y:0)}},[v,t,e]),r.useEffect(()=>{if(!v||!h)return;const Y=()=>{const P=X.current;if(!P)return;const H=P.getBoundingClientRect(),ue=Math.max(g||0,H.width),ye=Math.max(8,H.right-ue),V=H.bottom;q({position:"fixed",top:V,left:ye,minWidth:ue,zIndex:2e3})};return Y(),window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0)}},[v,h,g]);const le=()=>{l||_(!v)},O=Y=>{n(Y.value),_(!1),X.current?.focus()},A=Y=>{if(!l)switch(Y.key){case"Enter":case" ":Y.preventDefault(),v?I>=0&&O(t[I]):_(!0);break;case"Escape":Y.preventDefault(),_(!1),X.current?.focus();break;case"ArrowDown":Y.preventDefault(),v?C(P=>P<t.length-1?P+1:0):_(!0);break;case"ArrowUp":Y.preventDefault(),v?C(P=>P>0?P-1:t.length-1):_(!0);break;case"Home":Y.preventDefault(),v&&C(0);break;case"End":Y.preventDefault(),v&&C(t.length-1);break;case"Tab":_(!1);break}},de=(Y,P)=>{const H=Y.icon&&As[Y.icon]?As[Y.icon]:Ji,ue=Y.color?Dn(Y.color):"var(--text-secondary)",ye=P?.hideLabel===!0;return a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`taxonomyDropdownIcon ${yr.taxonomyDropdownIcon}`,style:{color:ue},children:a.jsx(H,{size:16})}),!ye&&a.jsx("span",{className:`taxonomyDropdownLabel ${yr.taxonomyDropdownLabel}`,children:Y.label})]})},ge=v?a.jsx("div",{ref:me,id:`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,className:`taxonomyDropdownPanel ${yr.taxonomyDropdownPanel} ${h?yr.taxonomyDropdownPanelPortal:""} ${S}`,role:"listbox","aria-labelledby":d,"aria-label":m,style:h?D:void 0,children:t.map((Y,P)=>{const H=String(Y.value)===String(e),ue=P===I;return a.jsx("div",{className:`taxonomyDropdownOption ${yr.taxonomyDropdownOption} ${H?`taxonomyDropdownOptionSelected ${yr.taxonomyDropdownOptionSelected}`:""} ${ue?`taxonomyDropdownOptionHighlighted ${yr.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":H,onClick:()=>O(Y),onMouseEnter:()=>C(P),style:(()=>{const ye=Y.color,V=Dn(ye),Me=!V||V.startsWith("var("),_e=Me?"#8b5cf6":V,re=Me?"20":"30",oe=Me?"05":"10";return{"--option-color":V||"var(--text-primary)","--option-border":`${_e}${re}`,"--option-bg":`${_e}${oe}`}})(),children:de(Y)},String(Y.value))})}):null;return a.jsxs("div",{ref:B,className:`taxonomyDropdown ${yr.taxonomyDropdown} ${v?`taxonomyDropdownActive ${yr.taxonomyDropdownActive}`:""} ${i}`,children:[a.jsxs("button",{ref:X,type:"button",className:`taxonomyDropdownButton ${yr.taxonomyDropdownButton} ${v?`taxonomyDropdownOpen ${yr.taxonomyDropdownOpen}`:""}`,onClick:le,onKeyDown:A,disabled:l,role:"combobox","aria-haspopup":"listbox","aria-expanded":v,"aria-controls":`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,"aria-labelledby":d,"aria-label":m,style:(()=>{if(!ke)return{};const Y=ke.color,P=Dn(Y),H=!P||P.startsWith("var("),ue=H?"#8b5cf6":P,ye=H?"30":"50",V=H?"05":"10";return{"--field-color":P||"var(--text-primary)","--field-border":`${ue}${ye}`,"--field-bg":`${ue}${V}`}})(),children:[a.jsx("span",{className:`taxonomyDropdownButtonContent ${yr.taxonomyDropdownButtonContent}`,children:ke?de(ke,{hideLabel:y}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`taxonomyDropdownIcon ${yr.taxonomyDropdownIcon}`,children:a.jsx(Ji,{size:16})}),a.jsx("span",{className:`taxonomyDropdownLabel ${yr.taxonomyDropdownLabel}`,children:s})]})}),!k&&a.jsx(nl,{size:16,className:`taxonomyDropdownChevron ${yr.taxonomyDropdownChevron} ${v?`taxonomyDropdownChevronOpen ${yr.taxonomyDropdownChevronOpen}`:""}`})]}),h?ge?Yi.createPortal(ge,document.body):null:ge]})}function gy({task:e,disabled:t=!1,actionDisabled:n,statusDisabled:s,compressed:o=!1,shortLabels:l=!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=n??t,_=s??t,I=Yc.map(C=>({...C,label:(o||l)&&C.shortLabel||C.label}));return a.jsxs("div",{className:`${p.statusActionsGroup} ${o?p.statusActionsGroupCompact:""}`,children:[g==="archive"&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.archiveTaskBtn}`,onClick:()=>e&&!v&&m?.(e),disabled:v,title:"Archive Now","aria-label":"Archive task",children:a.jsx(jk,{size:o?12:16})}),g==="unarchive"&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.archiveTaskBtn}`,onClick:()=>e&&!v&&y?.(e),disabled:v,title:"Unarchive task","aria-label":"Unarchive task",children:a.jsx(gd,{size:o?12:16})}),a.jsx("div",{className:`${p.statusSelectWrap} ${p.statusTaxonomyDropdownWrap}`,children:a.jsx(id,{value:S,options:I,disabled:_||!e,ariaLabel:"Status",hideSelectedLabel:!i,hideChevron:!i,className:`${p.statusTaxonomyDropdown} ${o?p.statusTaxonomyDropdownCompact:""} ${i?"":p.statusTaxonomyDropdownIconOnly}`,panelClassName:i?"":p.statusTaxonomyDropdownIconOnlyPanel,portalPanel:!i,panelMinWidth:i?void 0:144,onChange:C=>{e&&d?.(e,C)}})})]})}function J1(e,t,n){const s=typeof e=="string"?e.trim():"";if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;const o=Number(t),l=Number.isFinite(o)&&o>0?String(Math.floor(o)):typeof n=="string"&&n.trim().length>0?n.trim():"";if(!l)return s;const[i,d=""]=s.split("#"),m=i.includes("?")?"&":"?";return`${i}${m}v=${encodeURIComponent(l)}${d?`#${d}`:""}`}function Q1(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 X1(e){return e==="task"?"Task":e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function ar(e,t,n){const s=n?.(t,e);if(typeof s=="string")return s;if(e==null||e==="")return"none";if(Array.isArray(e)){const o=e.map(l=>ar(l,t,n)).filter(Boolean);return o.length>0?o.join(", "):"none"}return typeof e=="object"?"updated":t==="status"?X1(String(e)):String(e)}function Nh(e){return Array.isArray(e)?e.map((t,n)=>{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:n}}):[]}function eM(e){const t=Nh(e?.from),n=Nh(e?.to),s=new Map(t.map(i=>[i.id||i.title,i])),o=new Map(n.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===n.length&&t.every(i=>o.has(i.id||i.title))&&t.some((d,m)=>{const y=n[m];return(d.id||d.title)!==(y?.id||y?.title)})?"Checklist reordered":"Checklist updated"}function Cf(e){return e.split(/[?#]/,1)[0]||e}function Ph(e){const t=Cf(e).replace(/\\/g,"/"),n=t.split("/").filter(Boolean);return n[n.length-1]||t}function tM(e){return/\.(png|jpe?g|webp|gif)$/i.test(Cf(e))}function aM(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(Cf(e))}function Mh(e){return Array.isArray(e)?e.flatMap((t,n)=>{const s=t&&typeof t=="object"?t:null,o=typeof t=="string"?t:String(s?.path||"").trim(),l=String(s?.fsPath||"").trim(),i=String(s?.assetId||"").trim(),d=String(s?.referenceLabel||"").trim(),m=[s?.displayName,s?.originalFilename,s?.caption,d,l?Ph(l):"",o?Ph(o):""].map(h=>String(h||"").trim()).find(Boolean)||`Attachment ${n+1}`,y=i||l||o||`${m}:${n}`,k=[o,l,String(s?.originalFilename||"").trim(),String(s?.displayName||"").trim(),d].filter(Boolean),S=k.some(h=>tM(h))?"image":d.startsWith("D-")||k.some(h=>aM(h))?"document":"attachment";return[{key:y,label:m,kind:S}]}):[]}function nM(e,t){return t===1?e:e==="image"?"images":e==="document"?"documents":"attachments"}function zu(e){if(e.length===0)return"attachments";const t=e.reduce((s,o)=>(s[o.kind]+=1,s),{image:0,document:0,attachment:0}),n=Object.entries(t).filter(([,s])=>s>0).map(([s,o])=>o===1?s:`${o} ${nM(s,o)}`);return n.length===1?n[0]:e.length<=3&&n.length<=2?n.join(" and "):`${e.length} attachments`}function Gi(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function rM(e){const t=Mh(e?.from),n=Mh(e?.to),s=new Map(t.map(m=>[m.key,m])),o=new Map(n.map(m=>[m.key,m])),l=n.filter(m=>!s.has(m.key)),i=t.filter(m=>!o.has(m.key));if(l.length===1&&i.length===0)return`${Gi(l[0].kind)} attached: ${l[0].label}`;if(i.length===1&&l.length===0)return`${Gi(i[0].kind)} removed: ${i[0].label}`;if(l.length>0&&i.length===0)return`${Gi(zu(l))} attached`;if(i.length>0&&l.length===0)return`${Gi(zu(i))} removed`;if(l.length===1&&i.length===1)return`${Gi(l[0].kind)} replaced: ${i[0].label} -> ${l[0].label}`;if(l.length>0||i.length>0)return`${Gi(zu(l))} attached, ${zu(i)} removed`;const d=n.filter(m=>{const y=s.get(m.key);return y&&y.label!==m.label});if(d.length===1&&t.length===1&&n.length===1){const m=s.get(d[0].key);return`${Gi(d[0].kind)} renamed: ${m?.label||"Attachment"} -> ${d[0].label}`}return"Attachment details updated"}function gm(e,t,n){if(e==="checklistItems")return eM(t);if(e==="attachments")return rM(t);const s=Q1(e);if(e==="title")return`${s}: updated`;if(e==="description"){const o=ar(t?.from,e,n)!=="none",l=ar(t?.to,e,n)!=="none";return!o&&l?`${s}: added`:o&&!l?`${s}: cleared`:`${s}: updated`}return`${s}: ${ar(t?.from,e,n)} -> ${ar(t?.to,e,n)}`}function yy(e,t){const n=e.details?.changes||{},s=Object.keys(n);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"&&n.status)return`Status changed: ${ar(n.status.from,"status",t)} -> ${ar(n.status.to,"status",t)}`;if(e.action==="task-schedule-changed")return n.scheduledDate?`Scheduled date changed: ${ar(n.scheduledDate.from,"scheduledDate",t)} -> ${ar(n.scheduledDate.to,"scheduledDate",t)}`:n.dueDate?`Due date changed: ${ar(n.dueDate.from,"dueDate",t)} -> ${ar(n.dueDate.to,"dueDate",t)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&n.workstreamId)return`Workstream changed: ${ar(n.workstreamId.from,"workstreamId",t)} -> ${ar(n.workstreamId.to,"workstreamId",t)}`;if(e.action==="task-relationship-changed"&&n.initiativeId)return`Initiative changed: ${ar(n.initiativeId.from,"initiativeId",t)} -> ${ar(n.initiativeId.to,"initiativeId",t)}`;if(e.action==="task-attachments-changed")return n.attachments?gm("attachments",n.attachments,t):"Attachments updated";if(s.length===1){const o=s[0],l=n[o];return gm(o,l,t)}return s.length>1?`${s.length} fields updated`:"Task updated"}function qO(e,t){if(e.taskId||e.entityType==="task")return yy(e,t);const n=e.details?.changes||{},s=Object.keys(n),o=e.entityType==="initiative"?"Initiative":"Workstream",l=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"?l?`Task added: ${l}`:"Task added":e.action==="workstream-task-removed"?l?`Task removed: ${l}`:"Task removed":e.action==="workstream-relationship-changed"&&n.initiativeId?`Initiative changed: ${ar(n.initiativeId.from,"initiativeId",t)} -> ${ar(n.initiativeId.to,"initiativeId",t)}`:(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&n.attachments?gm("attachments",n.attachments,t):s.length===1?gm(s[0],n[s[0]],t):s.length>1?`${s.length} fields updated`:e.action==="initiative-updated"||e.action==="workstream-updated"?`${o} updated`:`${o} activity updated`}function ym(e){const t=Date.parse(String(e.timestamp||""));return Number.isFinite(t)?t:null}function sM(e){const t=e.details?.changes||{},n=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":n.length===1?n[0]:null}function KO(e){if(e.taskId||e.entityType==="task")return sM(e);const t=e.details?.changes||{},n=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":n.length===1?n[0]:null}function ky(e){const t=new Map,n=new Set,s=o=>{if(o.type==="event"&&o.event.action==="task-comment-added")return;const l=o.type==="comment"?`comment:${String(o.comment.id||o.id).replace(/^comment:/,"")}`:`event:${String(o.event.id||o.id).replace(/^event:/,"")}`;t.set(l,{...o,id:l}),o.type==="comment"&&n.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 l=String(o.id||"").trim();!l||n.has(l)||s({id:`comment:${l}`,type:"comment",timestamp:o.timestamp,comment:o})}),[...t.values()].sort((o,l)=>{const i=ym(o),d=ym(l);return i!==null&&d!==null&&i!==d?i-d:i!==null&&d===null?-1:i===null&&d!==null?1:String(o.id||"").localeCompare(String(l.id||""))})}function Af(e){return ky(e)}function oM(e){const t=Af(e);return t.length===0?null:[...t].sort((n,s)=>{const o=ym(n),l=ym(s);return o!==null&&l!==null&&o!==l?l-o:o!==null&&l===null?-1:o===null&&l!==null?1:String(s.id||"").localeCompare(String(n.id||""))})[0]||null}function iM(e,t){return e?e.type==="comment"?e.comment.text:yy(e.event,t):""}const{MessageSquare:cM,User:lM,Bot:dM,Gauge:uM,ClipboardList:mM,HelpCircle:pM,File:fM}=As,hM=({task:e,searchQuery:t="",copiedId:n=null,taxonomies:s=[],types:o=[],priorities:l=[],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:C,onToggleComplete:D,onToggleCancel:q,onSetStatus:B,onArchiveTask:X,onUnarchive:me,onDelete:ke,deleteActionTitle:le,onOpenTaskById:O,compressed:A=!1,showStatusLabel:de=!0})=>{const ge=Ng(e),Y=ge.label||(ge.isProvisional?"Pending":""),P=ge.isProvisional,H=!!ge.label,ue=um(m)||m?.id||"",ye=ry(y)||y?.id||"",V=l.find(ee=>String(ee.value)===String(e.priority)),Me=V?V.label.toLowerCase().replace(/\s+/g,"-"):String(e.priority),_e=i.find(ee=>ee.value===e.category||ee.label===e.category),re=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),oe=Number.isFinite(re)?Math.max(1,Math.min(5,Math.round(re))):3,Ie={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},Ee={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},je=Ie[oe],Pe=`var(--complexity-${Ee[oe]})`,K=Dv(e.priority,Me),x=!!p[`priorityItem_${K}`],b=cm(e.assignee),R=ud(e.assignee,d),F=Ue.useMemo(()=>{const ee=String(e.assignee||"").trim();return d.find(ze=>String(ze.value||"").trim()===ee)||null},[d,e.assignee]),Q=b!=="unassigned"&&typeof F?.avatarUrl=="string"?J1(F.avatarUrl,F.avatarRevision,F.avatarUpdatedAt):"",M=b==="agent"?"var(--color-violet-500, #8b5cf6)":b==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",$=Ue.useMemo(()=>oM(e),[e]),be=h||(e.isDeleted?"deleted":S?"archived":null),U=be!==null,se=Ue.useCallback((ee,ze)=>{const ft=String(ze||"").trim();if(ft){if(ee==="assignee")return ud(ft,d);if(ee==="workstreamId"&&ft===m?.id)return ue||m.id;if(ee==="initiativeId"&&ft===y?.id)return ye||y.id}},[d,ye,y,m,ue]),pe=Ue.useMemo(()=>iM($,se),[se,$]),z=Ue.useMemo(()=>Af(e).length,[e]),ne=[Qt.taskItem,e.status==="on-hold"?Qt.onHold:"",e.status==="in-progress"?Qt.inProgress:"",e.status==="review"?Qt.readyForReview:"",e.status==="done"?Qt.completed:"",e.status==="cancelled"?Qt.cancelled:"",g?Qt.taskItemRecentlyChanged:"",p[`priorityItem_${K}`]||"",k?Qt.kanbanCardOverlay:"",S?Qt.archived:"",A?Qt.compressed:""].filter(Boolean).join(" "),ie=Dn(V?.color),Re=o.find(ee=>ee.value===e.type),Te=Dn(Re?.color)||ub(e.type),De=ee=>{const ze=typeof ee=="string"?ee:ee.path,ft=typeof ee=="string"?"":(ee.fsPath||"").trim(),it=typeof ee=="string"?"":(ee.displayName||"").trim(),Et=typeof ee=="string"?"":(ee.originalFilename||"").trim(),ht=typeof ee=="string"?"":(ee.caption||"").trim();return[ft,Et,it,ht,ze].some(Dt=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(Dt))},Oe=ee=>{const ze=typeof ee=="string"?ee:ee.path,ft=ze.includes("/api/taskforce/documents/"),it=typeof ee=="string"?"":(ee.displayName||"").trim();if(ft&&typeof ee!="string")return L1({displayName:ee.displayName,originalFilename:ee.originalFilename,fsPath:ee.fsPath,assetId:ee.assetId||null});const Et=typeof ee=="string"?"":(ee.caption||"").trim();if(Et)return Et;if(it)return it;const ht=typeof ee=="string"?"":(ee.originalFilename||"").trim();return ht||ze.split("?")[0].split("#")[0].split("/").pop()||"Context file"},vt=ee=>{const ze=typeof ee=="string"?ee:ee.path,ft=typeof ee=="string"?"":(ee.fsPath||"").trim(),it=typeof ee=="string"?"":(ee.caption||"").trim(),Et=typeof ee=="string"?"":(ee.originalFilename||"").trim(),ht=[];if(ft&&ht.push(ft),Et&&ht.push(Et),it&&ht.push(it),ze.includes("/api/taskforce/context-link?path="))try{const Dt=new URL(ze,"http://localhost").searchParams.get("path");Dt&&ht.push(Dt)}catch{}ht.push(ze);for(const Ot of ht){const We=Ot.split("?")[0].split("#")[0].split("/").pop()||"",tt=We.lastIndexOf(".");if(tt<=0||tt===We.length-1)continue;const Fe=We.slice(tt+1);if(Fe)return Fe.slice(0,5).toUpperCase()}return"FILE"},st={"--task-change-glow-color":ie||`var(--priority-${K})`,...ie?{borderLeftColor:ie,[`--priority-${K}`]:ie}:{},...!x&&ie?{borderLeft:`4px solid ${ie}`}:{}},kt=ee=>ee.replace(/\b\w/g,ze=>ze.toUpperCase()),Ye=Cd(s,[e]),Ct=e.checklistItems||[],dt=Ct.length,Qe=dt>0?Ct.filter(ee=>ee.isCompleted).length:0,Rt=(ee,ze)=>{ee.stopPropagation(),_?.(ee,ze)};return a.jsxs("div",{className:ne,onClick:()=>v?.(e),style:st,"data-task-card":"true",children:[a.jsxs("div",{className:Qt.taskHeader,children:[a.jsxs("div",{className:Qt.taskReferenceCluster,children:[y?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:Qt.taskReferenceText,children:ye}),a.jsx("span",{className:Qt.taskReferenceDivider,children:"/"})]}):null,m?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:Qt.taskReferenceText,children:ue}),a.jsx("span",{className:Qt.taskReferenceDivider,children:"/"})]}):null,Y?a.jsx(Qu,{copied:H&&n===ge.label,onClick:ee=>Rt(ee,ge.label),disabled:!H,title:H?"Copy task reference":"Task reference pending sync",className:S?Qt.archiveBadge:"",label:Uu(Y,t)}):null,P?a.jsx("span",{className:p.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),a.jsx("div",{className:Qt.taskActions,onClick:ee=>ee.stopPropagation(),children:U?me||ke?a.jsxs(a.Fragment,{children:[me&&a.jsx("button",{type:"button",className:p.actionBtn,onClick:()=>me(e.id),title:be==="deleted"?"Restore deleted task":"Restore archived task",children:a.jsx(gd,{size:16})}),ke&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.deleteBtn}`,onClick:()=>ke(e.id),title:le||(be==="deleted"?"Delete Permanently":"Move to Trash"),children:a.jsx(_m,{size:16})})]}):null:a.jsx(gy,{task:e,compressed:A,shortLabels:!0,showLabel:de,onSetStatus:(ee,ze)=>{if(B){B(ee,ze);return}if(ze==="in-progress"){I?.(ee);return}if(ze==="review"){C?.(ee);return}if(ze==="done"){D?.(ee);return}ze==="cancelled"&&q?.(ee)},onArchiveTask:X})})]}),a.jsxs("div",{className:Qt.taskContent,children:[U&&a.jsx("div",{className:`${Qt.taskMeta} ${Qt.taskMetaCompact}`}),a.jsxs("div",{children:[a.jsxs("div",{className:Qt.taskTitle,style:A?{fontSize:"13px",lineHeight:"1.4"}:{},children:[be==="archived"&&"✓ ",be==="deleted"&&"Deleted: ",Uu(e.title,t)]}),e.description&&!U&&!A&&a.jsx("div",{className:Qt.taskDescription,children:a.jsx(cy,{onTaskIdClick:O,children:e.description})})]}),e.attachments&&e.attachments.length>0&&!U&&!A&&a.jsxs("div",{className:Qt.attachmentThumbnails,children:[a.jsx("div",{className:Qt.attachmentImageRow,children:(e.attachments||[]).map((ee,ze)=>{const ft=typeof ee=="string"?ee:ee.path;return De(ee)?a.jsx("div",{className:Qt.attachmentThumbnail,onClick:it=>{it.stopPropagation(),!P1(typeof ee=="string"?{path:ft}:ee,{taskId:e.id,taskReferenceLabel:Y})&&window.open(ft,"_blank")},children:a.jsx("img",{src:ft,alt:`Attachment ${ze}`})},ze):null})}),a.jsx("div",{className:Qt.attachmentDocumentList,children:(e.attachments||[]).map((ee,ze)=>{const ft=typeof ee=="string"?ee:ee.path,it=typeof ee=="string"?void 0:ee.fsPath,Et=Oe(ee);if(De(ee))return null;const ht=vt(ee);return a.jsxs("button",{type:"button",className:Qt.contextDocThumb,onClick:Ot=>{Ot.stopPropagation();const Dt=typeof ee=="string"?{path:ee,taskId:e.id}:{...ee,taskId:e.id};x1(Dt,it)||window.open(ft,"_blank")},title:Et,style:{"--context-doc-accent":mb(ht)},children:[a.jsxs("span",{className:Qt.contextDocMain,children:[a.jsx("span",{className:Qt.contextDocIcon,"aria-hidden":"true",children:a.jsx(fM,{size:13})}),a.jsx("span",{className:Qt.contextDocText,children:a.jsx("span",{className:Qt.contextDocName,children:Et})})]}),a.jsx("span",{className:Qt.contextDocType,children:ht})]},ze)})})]}),e.status==="cancelled"&&e.canceledReason&&!A&&a.jsxs("div",{className:Qt.taskCancellationReason,children:[a.jsx("strong",{children:"Cancellation Reason:"})," ",Uu(e.canceledReason,t)]}),pe&&!U&&!A&&a.jsxs("div",{className:Qt.taskLatestComment,children:[a.jsx("strong",{children:"Latest Activity:"})," ",Uu(pe.length>120?pe.substring(0,120)+"...":pe,t)]}),!U&&Ye.length>0&&!A&&a.jsx("div",{className:`${Qt.taskSpecialists} ${Qt.taxonomiesList}`,children:Ye.map(ee=>{const ze=e.taxonomies?.[ee.id];return ze?(Array.isArray(ze)?ze:[ze]).map(it=>{const Et=ee.options.find(tt=>tt.value===it);if(!Et)return null;const ht=As[Et.icon||"Layers"]||Ep,Ot=Dn(Et.color)||"var(--text-primary)",Dt=ee.status==="retired"?`${ee.label} (Retired)`:ee.label,We=Et.status==="retired"?`${Et.label} (Retired)`:Et.label;return a.jsx("span",{className:p.specialistBadge,style:{borderColor:`${Ot}50`,backgroundColor:`${Ot}15`,color:Ot},title:`${Dt}: ${kt(We)}`,children:a.jsx(ht,{size:10})},`${ee.id}-${it}`)}):null})}),a.jsx("div",{className:Qt.taskMeta,children:U?a.jsx("span",{children:e.category}):a.jsx(a.Fragment,{children:a.jsxs("div",{className:Qt.taskMetaRow,style:A?{marginBottom:0}:void 0,children:[a.jsxs("div",{className:Qt.taskMetaBadgeGroup,children:[(()=>{const ee=Dn(_e?.color),ze=_e?.icon||"Folder",ft=As[ze]||Po;return a.jsx("span",{className:p.metaBadge,title:kt(e.category),style:{color:ee||"var(--text-secondary)",backgroundColor:ee?`${ee}15`:"var(--bg-tertiary)",borderColor:ee?`${ee}40`:"transparent"},children:a.jsx(ft,{size:14})})})(),a.jsx("span",{className:`${p.metaBadge} ${p[`type_${e.type}`]||""}`,title:kt(e.type||Vr),style:{color:`var(--type-color, ${Te})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${Te}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${Te}), transparent 75%)`},children:Re?.icon?(()=>{const ee=As[Re.icon]||pM;return a.jsx(ee,{size:14})})():b1(e.type,14)}),V&&a.jsx("span",{className:p.metaBadge,style:{color:ie||"var(--text-secondary)",backgroundColor:ie?`${ie}15`:"var(--bg-tertiary)",borderColor:ie?`${ie}40`:"var(--border-color)"},title:`${V.label}`,children:(()=>{const ee=V.icon||"AlertCircle",ze=As[ee]||Nk;return a.jsx(ze,{size:14})})()}),z>0&&a.jsxs("span",{className:p.metaBadge,title:`${z} activity items`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[a.jsx(cM,{size:14}),a.jsx("span",{children:z})]}),dt>0&&a.jsxs("span",{className:p.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:[a.jsx(mM,{size:14}),a.jsx("span",{children:`${Qe}/${dt}`})]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsxs("span",{className:p.metaBadge,title:`AI-estimated complexity: ${je} (${oe}/5)`,style:{color:Pe,backgroundColor:`color-mix(in srgb, ${Pe}, transparent 88%)`,borderColor:`color-mix(in srgb, ${Pe}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[a.jsx(uM,{size:14}),!A&&a.jsx("span",{children:je})]}),a.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":M},children:Q?a.jsx("img",{src:Q,alt:"",className:Qt.assigneeAvatarImage}):b==="agent"?a.jsx(dM,{size:A?18:20}):b==="member"?a.jsx(lM,{size:A?18:20}):null})]})]})})})]})]})},bd=Ue.memo(hM),km="168px";function vy(){return a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:qe("standalone.filtersCaps")})}function Ki({label:e,options:t,selected:n,onChange:s,variant:o="label"}){return a.jsx(qi,{label:e,options:t,selected:n,onChange:s,variant:o,containerStyle:{flex:`0 0 ${km}`,maxWidth:km}})}function Sy({onClick:e}){return a.jsxs("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[a.jsx(nc,{size:12})," ",qe("standalone.clearFilters")]})}function Eh({label:e,options:t,selected:n,onChange:s,allLabel:o,title:l}){const[i,d]=Ue.useState(!1),m=Ue.useRef(null),y=t.find(h=>h.value===n),k=y?.selectedLabel||y?.label||o;Ue.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 a.jsxs("div",{className:p.filterContainer,ref:m,style:{flex:`0 0 ${km}`,maxWidth:km},children:[a.jsxs("button",{type:"button",className:`${p.filterButton} ${n?p.filterActive:""}`,onClick:()=>d(h=>!h),title:l||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":i,children:[a.jsx("span",{children:k}),a.jsx(nl,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&a.jsxs("div",{className:`${p.filterDropdown} ${p.appScrollbar} tf-scrollbar`,role:"listbox","aria-label":e,children:[a.jsxs("button",{type:"button",className:p.filterOption,onClick:()=>S(""),"aria-selected":!n,children:[a.jsx(no,{size:14,style:{opacity:n?0:1}}),a.jsx("span",{style:{fontWeight:n?500:600},children:o})]}),a.jsx("div",{className:p.filterDivider}),t.map(h=>{const g=h.value===n;return a.jsxs("button",{type:"button",className:p.filterOption,onClick:()=>S(h.value),"aria-selected":g,children:[a.jsx(no,{size:14,style:{opacity:g?1:0}}),a.jsx("span",{style:{fontWeight:g?600:500},children:h.label})]},h.value)})]})]})}function wy({scope:e,onScopeChange:t,className:n,labelClassName:s}){return a.jsxs("div",{className:n,children:[a.jsx("span",{className:s,children:"Scope"}),a.jsx("div",{className:p.taskScopeTabs,role:"tablist","aria-label":"Task scope",children:[{value:"open",label:"Open"},{value:"archived",label:"Archived"},{value:"deleted",label:"Deleted"}].map(o=>{const l=e===o.value;return a.jsx("button",{type:"button",className:`${p.taskScopeTab} ${l?p.taskScopeTabActive:""}`,onClick:()=>t(o.value),role:"tab","aria-selected":l,"aria-pressed":l,title:`Show ${o.label.toLowerCase()} tasks`,children:o.label},o.value)})})]})}function by({onClick:e,disabled:t=!1,className:n,title:s="Permanently delete all deleted tasks",children:o="Delete All Permanently"}){return a.jsxs("button",{type:"button",className:n,onClick:e,disabled:t,title:s,children:[a.jsx(_m,{size:14}),o]})}const{Search:Dh,ClipboardList:gM,ChevronRight:yM,ChevronDown:kM,Folder:vM,Archive:SM,RotateCcw:wM,X:bM,Plus:_M,ArrowUpDown:CM,Trash2:AM}=As,_y=r.forwardRef((e,t)=>{const{tasks:n,archivedTasks:s,categories:o,types:l,priorities:i,taxonomyDisplayLabels:d,assigneeOptions:m=[],workstreams:y=[],initiatives:k=[],searchQuery:S,filterCategories:h,filterTypes:g,filterPriorities:v,filterStatus:_,filterAssignees:I=[],filterTaxonomies:C,sortBy:D,sortOrder:q,showArchive:B,taskScope:X,collapsedCategories:me,loadingTasks:ke,filteredTasks:le,filteredArchive:O,groupedTasks:A,filteredDeletedTasks:de=[],groupedDeletedTasks:ge={},copiedId:Y,recentlyChangedTaskIds:P=[],showTaskCardStatusLabel:H=!0,onSearchChange:ue,onFilterCategoriesChange:ye,onFilterTypesChange:V,onFilterPrioritiesChange:Me,onFilterStatusChange:_e,onFilterAssigneesChange:re,onTaxonomyFilterChange:oe,onSortByChange:Ie,onSortOrderChange:Ee,onShowArchiveChange:je,onTaskScopeChange:Pe,onClearFilters:K,onToggleCategory:x,onEditTask:b,onOpenTaskById:R,onCopyId:F,onToggleInProgress:Q,onToggleReview:M,onToggleComplete:$,onToggleCancel:be,onSetStatus:U,onArchiveTask:se,onBulkArchive:pe,onUnarchive:z,onDelete:ne,onDeleteAllDeleted:ie,onFetchArchive:Re,onAddTaskToCategory:Te,supplementalTasks:De=[],taxonomies:Oe}=e,vt=new Set(P),st=Ue.useMemo(()=>new Map(y.map(te=>[te.id,te])),[y]),kt=Ue.useMemo(()=>new Map(k.map(te=>[te.id,te])),[k]),Ye=Ue.useCallback(te=>{const Le=te.workstreamId&&st.get(te.workstreamId)||null,At=Le?.initiativeId&&kt.get(Le.initiativeId)||null;return{taskWorkstream:Le,taskInitiative:At}},[kt,st]),Ct=[...n,...s,...De],dt=!!Pe,Qe=Pe,Rt=X??(B?"archived":"open"),ee=dt?Rt==="archived"?O:Rt==="deleted"?de:le:le,ze=dt?Rt==="archived"?{Archived:O}:Rt==="deleted"?ge:A:A,ft=dt?Rt==="deleted"?"deleted":Rt==="archived"?"archived":null:null,it=Tm(S),Et=S?it?`No task found for ${it.toUpperCase()}`:qe("taskList.noMatchingTasks"):Rt==="archived"?"No archived tasks found.":Rt==="deleted"?"No deleted tasks found.":qe("taskList.noActiveTasks"),ht=o.filter(te=>!te.disabled),Ot=o.filter(te=>te.disabled&&Ct.some(Le=>Le.category===te.value)),Dt=[...ht,...Ot.filter(te=>!ht.some(Le=>Le.value===te.value))].map(te=>({value:te.value,label:te.disabled?`${te.label} (Legacy)`:te.label})),We=l.filter(te=>te.status!=="retired"),tt=l.filter(te=>te.status==="retired"&&Ct.some(Le=>Le.type===te.value)),Fe=[...We,...tt.filter(te=>!We.some(Le=>Le.value===te.value))].map(te=>({value:te.value,label:te.status==="retired"?`${te.label} (Retired)`:te.label})),St=Cd(Oe,Ct).filter(te=>te.filterEnabled!==!1).map(te=>({...te,options:bf(te,Ct)})),ot=Ue.useMemo(()=>[{value:"created",label:qe("taskList.sortCreated")},{value:"updated",label:qe("taskList.sortUpdated")},{value:"priority",label:qe("taskList.sortPriority")},...iy(Oe,Ct)],[Ct,qe,Oe]);return a.jsxs("div",{className:p.viewTab,ref:t,children:[a.jsxs("div",{className:p.filterBar,children:[a.jsxs("div",{className:p.searchContainer,children:[a.jsx(Dh,{size:16,className:p.searchIcon}),a.jsx("input",{type:"text",className:p.searchInput,placeholder:qe("taskList.searchPlaceholder"),value:S,onChange:te=>ue(te.target.value)}),S&&a.jsx("button",{className:p.clearSearchBtn,onClick:()=>ue(""),title:qe("taskList.clearSearchTitle"),children:a.jsx(bM,{size:14})})]}),a.jsxs("div",{className:p.filterRow,children:[a.jsx(qi,{label:d?.category||qe("taskList.categoryLabel"),options:Dt,selected:h,onChange:ye,variant:"value"}),a.jsx(qi,{label:d?.type||qe("taskList.typeLabel"),options:Fe,selected:g,onChange:V,variant:"value"})]}),a.jsxs("div",{className:p.filterRow,children:[a.jsx(qi,{label:d?.priority||qe("taskList.priorityLabel"),options:i,selected:v,onChange:Me,variant:"value"}),a.jsx(qi,{label:qe("taskList.statusLabel"),options:ao,selected:_,onChange:_e,variant:"value"}),a.jsx(qi,{label:qe("taskList.assigneeLabel"),options:m,selected:I,onChange:te=>re?.(te),variant:"value"})]}),St.map(te=>a.jsx(qi,{label:te.status==="retired"?`${te.label} (Retired)`:te.label,options:te.options.map(Le=>({...Le,label:Le.status==="retired"?`${Le.label} (Retired)`:Le.label})),selected:C[te.id]||[],onChange:Le=>oe(te.id,Le),variant:"value"},te.id)),a.jsxs("div",{className:p.filterRow,children:[a.jsxs("div",{className:p.sortLabel,children:[a.jsx(CM,{size:14,style:{marginRight:"4px"}})," ",qe("taskList.sortByLabel")]}),a.jsx("select",{value:D,onChange:te=>Ie(te.target.value),className:`${p.filterSelect} ${p.filterSelectSort} `,children:ot.map(te=>a.jsx("option",{value:te.value,children:te.label},te.value))}),a.jsx("button",{className:`${p.resetFiltersBtn} ${p.sortDirectionBtnWidget}`,onClick:Ee,title:qe(q==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:q==="desc"?a.jsx(cg,{size:14}):a.jsx(lg,{size:14})}),a.jsx("button",{className:p.resetFiltersBtn,onClick:K,title:qe("taskList.resetFiltersTitle"),children:a.jsx(wM,{size:14})})]}),a.jsxs("div",{className:`${p.filterRow} ${p.archiveRow} `,children:[Rt==="open"?a.jsxs("button",{className:`${p.bulkArchiveBtn} ${n.some(te=>te.status==="done"||te.status==="cancelled")?"":p.disabledBtn} `,onClick:()=>n.some(te=>te.status==="done"||te.status==="cancelled")&&pe(),disabled:!n.some(te=>te.status==="done"||te.status==="cancelled"),title:n.some(te=>te.status==="done"||te.status==="cancelled")?qe("taskList.archiveAllTitle"):qe("taskList.noTasksToArchiveTitle"),children:[a.jsx(SM,{size:12}),a.jsx("span",{children:qe("taskList.archiveFinished")})]}):Rt==="deleted"&&ie?a.jsx(by,{className:`${p.bulkArchiveBtn} ${p.taskToolbarAction} ${p.bulkDeleteBtn} ${de.length===0?p.disabledBtn:""}`,onClick:()=>de.length>0&&ie(),disabled:de.length===0,title:de.length>0?"Empty trash":"Trash is already empty",children:"Empty Trash"}):a.jsx("div",{}),dt?a.jsx(wy,{scope:Rt,onScopeChange:te=>{Qe?.(te),te==="archived"?(je(!0),Re()):B&&je(!1)},className:`${p.archiveToggle} ${p.taskScopeToggle}`}):a.jsxs("label",{className:p.archiveToggle,children:[a.jsx("input",{type:"checkbox","aria-label":"Archived",checked:B,onChange:te=>{je(te.target.checked),te.target.checked&&Re()}}),a.jsx("span",{children:"Include Archive"})]})]})]}),ke&&n.length===0?a.jsx("div",{className:p.loading,children:a.jsx(kr,{size:24,className:p.spinner})}):ee.length===0&&!ke?a.jsxs("div",{className:p.emptyState,children:[S?a.jsx(Dh,{size:48}):Rt==="deleted"?a.jsx(AM,{size:48}):a.jsx(gM,{size:48}),a.jsx("p",{children:Et})]}):a.jsx("div",{className:p.taskList,style:{opacity:ke?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(ze).map(([te,Le])=>{if(Le.length===0)return null;const At=me[te];return a.jsxs("div",{className:p.categoryGroup,children:[a.jsx("div",{className:p.categoryHeader,onClick:()=>x(te),children:a.jsxs("div",{className:p.categoryTitle,children:[At?a.jsx(yM,{size:16}):a.jsx(kM,{size:16}),(()=>{const jt=o.find($t=>$t.label===te),Wt=jt?.icon&&tc[jt.icon]?tc[jt.icon]:vM,Ge=Dn(jt?.color)||"var(--color-purple, #8b5cf6)";return a.jsx(Wt,{size:16,className:p.categoryTitleIcon,style:{color:Ge}})})(),te,a.jsxs("span",{className:p.categoryCount,children:["(",Le.length,")"]}),Te&&a.jsx("button",{className:p.kanbanQuickAdd,onClick:jt=>{jt.stopPropagation(),Te(te)},title:qe("taskList.addTaskToCategoryTitle",{category:te}),style:{marginLeft:"auto"},disabled:ft!==null,children:a.jsx(_M,{size:14})})]})}),!At&&a.jsx("div",{className:p.categoryItems,children:Le.map(jt=>(()=>{const{taskWorkstream:Wt,taskInitiative:Ge}=Ye(jt);return a.jsx(bd,{task:jt,taskWorkstream:Wt,taskInitiative:Ge,searchQuery:S,copiedId:Y,taxonomies:Oe,types:l,priorities:i,assigneeOptions:m,onClick:b,onOpenTaskById:R,onCopyId:F,onToggleInProgress:Q,onToggleReview:M,onToggleComplete:$,onToggleCancel:be,onSetStatus:U,onArchiveTask:se,onUnarchive:ft?z:void 0,onDelete:ft?ne:void 0,categories:o,isRecentlyChanged:vt.has(jt.id),readOnlyMode:ft,showStatusLabel:H},jt.id)})())})]},te)})}),!dt&&B&&O.length>0&&a.jsxs("div",{className:p.archiveList,children:[a.jsx("div",{className:p.archiveHeader,children:"Archived"}),O.map(te=>(()=>{const{taskWorkstream:Le,taskInitiative:At}=Ye(te);return a.jsx(bd,{task:te,taskWorkstream:Le,taskInitiative:At,searchQuery:S,copiedId:Y,isArchived:!0,types:l,assigneeOptions:m,onClick:b,onCopyId:F,onSetStatus:U,onUnarchive:z,onDelete:ne,deleteActionTitle:"Delete Permanently",categories:o,showStatusLabel:H},te.id)})())]})]})});_y.displayName="TaskList";const xM="_formNotice_inuex_1",IM="_assigneeIndicator_inuex_12",TM="_assigneeIndicatorAgent_inuex_20",RM="_assigneeIndicatorUser_inuex_24",jM="_assigneeIndicatorUnassigned_inuex_28",NM="_markdownPreview_inuex_32",PM="_error_inuex_83",MM="_keyboardHint_inuex_92",EM="_taskFormLifecycle_inuex_110",DM="_taskFormMetaDivider_inuex_115",LM="_taskFormMetaGrid_inuex_122",BM="_compactMetaSection_inuex_128",WM="_createWorkstreamRow_inuex_134",FM="_createWorkstreamDropdown_inuex_140",OM="_compactMetaGrid_inuex_145",$M="_compactMetaField_inuex_151",UM="_compactMetaFieldHint_inuex_165",zM="_formFieldsetReset_inuex_169",HM="_formLayout_inuex_176",GM="_formLayoutWithSidebar_inuex_183",VM="_formMainColumn_inuex_191",qM="_activitySidebar_inuex_198",KM="_activitySidebarHeader_inuex_208",ZM="_activitySidebarTitle_inuex_215",YM="_activitySidebarCount_inuex_224",JM="_taskFormDateRow_inuex_246",QM="_taskFormDateLabel_inuex_253",XM="_taskFormDateValue_inuex_261",eE="_taskFormMetaStack_inuex_269",tE="_taskFormMetaActor_inuex_275",aE="_taskFormDateWarning_inuex_287",nE="_taskFormDateError_inuex_293",rE="_helpHeader_inuex_299",sE="_helpClose_inuex_310",oE="_markdownHelp_inuex_324",iE="_helpGrid_inuex_333",cE="_helpGridItem_inuex_339",lE="_settingsHint_inuex_351",dE="_sectionBlock_inuex_357",uE="_softSectionSurface_inuex_367",mE="_stackedList_inuex_374",pE="_stackedListSpaced_inuex_379",fE="_checklistRow_inuex_383",hE="_checklistRowDragging_inuex_392",gE="_checklistHandleBtn_inuex_396",yE="_checklistCheckboxBtn_inuex_419",kE="_checklistCheckboxBtnChecked_inuex_439",vE="_checklistItemText_inuex_444",SE="_checklistItemTextCompleted_inuex_450",wE="_checklistRemoveBtn_inuex_455",bE="_specialistChip_inuex_522",_E="_specialistChipActive_inuex_545",CE="_commentPanel_inuex_626",AE="_activitySidebarPanel_inuex_635",xE="_commentThread_inuex_643",IE="_emptyComments_inuex_663",TE="_activityLoadingThread_inuex_673",RE="_activitySkeletonItem_inuex_677",jE="_activitySkeletonMeta_inuex_683",NE="_activitySkeletonBody_inuex_684",PE="_comment_inuex_626",ME="_commentAi_inuex_740",EE="_commentUser_inuex_744",DE="_commentHeader_inuex_748",LE="_commentAuthor_inuex_772",BE="_commentTime_inuex_780",WE="_commentText_inuex_784",FE="_commentInputArea_inuex_844",OE="_commentInput_inuex_844",$E="_sendCommentBtn_inuex_876",UE="_taxonomyFieldsGrid_inuex_903",zE="_markdownPreviewContainer_inuex_910",HE="_descriptionSurface_inuex_915",Xe={formNotice:xM,assigneeIndicator:IM,assigneeIndicatorAgent:TM,assigneeIndicatorUser:RM,assigneeIndicatorUnassigned:jM,markdownPreview:NM,error:PM,keyboardHint:MM,taskFormLifecycle:EM,taskFormMetaDivider:DM,taskFormMetaGrid:LM,compactMetaSection:BM,createWorkstreamRow:WM,createWorkstreamDropdown:FM,compactMetaGrid:OM,compactMetaField:$M,compactMetaFieldHint:UM,formFieldsetReset:zM,formLayout:HM,formLayoutWithSidebar:GM,formMainColumn:VM,activitySidebar:qM,activitySidebarHeader:KM,activitySidebarTitle:ZM,activitySidebarCount:YM,taskFormDateRow:JM,taskFormDateLabel:QM,taskFormDateValue:XM,taskFormMetaStack:eE,taskFormMetaActor:tE,taskFormDateWarning:aE,taskFormDateError:nE,helpHeader:rE,helpClose:sE,markdownHelp:oE,helpGrid:iE,helpGridItem:cE,settingsHint:lE,sectionBlock:dE,softSectionSurface:uE,stackedList:mE,stackedListSpaced:pE,checklistRow:fE,checklistRowDragging:hE,checklistHandleBtn:gE,checklistCheckboxBtn:yE,checklistCheckboxBtnChecked:kE,checklistItemText:vE,checklistItemTextCompleted:SE,checklistRemoveBtn:wE,specialistChip:bE,specialistChipActive:_E,commentPanel:CE,activitySidebarPanel:AE,commentThread:xE,emptyComments:IE,activityLoadingThread:TE,activitySkeletonItem:RE,activitySkeletonMeta:jE,activitySkeletonBody:NE,comment:PE,commentAi:ME,commentUser:EE,commentHeader:DE,commentAuthor:LE,commentTime:BE,commentText:WE,commentInputArea:FE,commentInput:OE,sendCommentBtn:$E,taxonomyFieldsGrid:UE,markdownPreviewContainer:zE,descriptionSurface:HE};function _p({label:e,value:t,options:n,onChange:s,type:o="priority",hideLabel:l=!1,showSelectedLabel:i=!0}){const d=n.find(m=>String(m.value)===String(t));return a.jsxs("div",{className:p.field,children:[!l&&a.jsxs("div",{className:p.labelRow,children:[a.jsx("label",{className:p.label,children:e}),i&&d&&a.jsx("span",{className:p.levelLabel,style:{color:Dn(d.color)||(o==="priority"?`var(--priority-${t})`:o==="complexity"?`var(--complexity-${t})`:"var(--text-secondary)"),backgroundColor:(Dn(d.color)?`${Dn(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})]}),a.jsx("div",{className:p.levelSelect,children:n.map((m,y)=>{const k=n.findIndex(g=>String(g.value)===String(t)),S=y<=k,h=String(m.value)===String(t);return a.jsx("button",{type:"button",className:`${p.levelOption} ${S?p.levelOptionFilled:""} ${S?p[`levelOption_${o}_${m.value}`]:""} ${h?p.levelOptionSelected:""}`,onClick:()=>s(m.value),title:m.label,style:{opacity:S?1:.15,backgroundColor:S?Dn(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 Lh=new Map;function GE(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t}function VE(e,t){const n=Object.entries(t).sort(([s],[o])=>s.localeCompare(o));return JSON.stringify([e,n])}function vm(e,t,n){const s=GE(e);if(!s)return"";const o=n??Dg(),l=VE(o,t);let i=Lh.get(l);return i||(i=new Intl.DateTimeFormat(o,t),Lh.set(l,i)),i.format(s)}const qE=Ue.lazy(()=>xs(()=>import("./EntityActivityTimeline-BlS7DhA4.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),KE=Ue.lazy(()=>xs(()=>import("./TaskContextUpload-zuro5gDT.js"),__vite__mapDeps([7,1,8,9,2,3,4,5])).then(e=>({default:e.TaskContextUpload})));function ZE({count:e}){const t=Math.max(2,Math.min(e||3,4));return a.jsx("div",{className:`${Xe.commentThread} ${Xe.activityLoadingThread}`.trim(),"aria-busy":"true","aria-live":"polite","aria-label":"Loading activity",children:Array.from({length:t},(n,s)=>a.jsxs("div",{className:Xe.activitySkeletonItem,children:[a.jsx("div",{className:Xe.activitySkeletonMeta}),a.jsx("div",{className:Xe.activitySkeletonBody})]},s))})}function YE({id:e,item:t,onToggle:n,onRemove:s}){const{attributes:o,listeners:l,setNodeRef:i,transform:d,transition:m,isDragging:y}=wg({id:e}),k={transform:rf.Transform.toString(d),transition:m,opacity:y?.88:1};return a.jsxs("div",{ref:i,style:k,className:`${Xe.checklistRow} ${y?Xe.checklistRowDragging:""}`.trim(),children:[a.jsx("button",{type:"button",className:Xe.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...o,...l,children:a.jsx(Mk,{size:14})}),a.jsx("button",{type:"button",className:`${Xe.checklistCheckboxBtn} ${t.isCompleted?Xe.checklistCheckboxBtnChecked:""}`.trim(),onClick:n,title:t.isCompleted?"Mark incomplete":"Mark complete","aria-label":t.isCompleted?"Mark checklist item incomplete":"Mark checklist item complete",children:t.isCompleted?a.jsx(no,{size:14,strokeWidth:2.1}):null}),a.jsx("span",{className:`${Xe.checklistItemText} ${t.isCompleted?Xe.checklistItemTextCompleted:""}`.trim(),children:t.title}),a.jsx("button",{type:"button",className:Xe.checklistRemoveBtn,onClick:s,title:"Remove checklist item","aria-label":"Remove checklist item",children:a.jsx(nc,{size:15,strokeWidth:1.9})})]})}function Cy(e){const{editingTaskId:t,error:n,title:s,description:o,category:l,type:i,priority:d,complexity:m,manualComplexityEnabled:y=!1,assignee:k,scheduledDate:S,dueDate:h,workstreamInput:g="",checklistItems:v,comments:_,newCommentText:I,contextFiles:C,currentWorkspaceId:D,apiBaseUrl:q,descriptionFocused:B,showMarkdownHelp:X,showChecklist:me=!1,checklistEnabled:ke=!0,formTaxonomies:le,onTaxonomyChange:O,onOpenSettings:A,categories:de,types:ge,priorities:Y,taxonomyDisplayLabels:P,assigneeOptions:H,taxonomies:ue,workstreams:ye=[],initiatives:V=[],copiedId:Me,onTitleChange:_e,onDescriptionChange:re,onCategoryChange:oe,onTypeChange:Ie,onPriorityChange:Ee,onComplexityChange:je,onAssigneeChange:Pe,onScheduledDateChange:K,onDueDateChange:x,onWorkstreamInputChange:b=()=>{},onChecklistItemsChange:R,onNewCommentTextChange:F,onDescriptionFocusedChange:Q,onShowMarkdownHelpChange:M,onShowChecklistChange:$=()=>{},onSubmit:be,onAddComment:U,onAddContextFile:se,onRemoveContextFile:pe,onUpdateContextCaption:z,onCopyId:ne,onToggleInProgress:ie,onToggleReview:Re,onToggleComplete:Te,onToggleCancel:De,onSetStatus:Oe,onArchiveTask:vt,onUnarchive:st,onOpenTaskById:kt,currentTask:Ye,commentsEndRef:Ct}=e,dt=Xi(Ye),Qe=Ue.useMemo(()=>nb(ue,le),[ue,le]),Rt=Ue.useMemo(()=>{const he=de.find(wt=>wt.value===Qc),rt={value:Qc,label:he?.label||Cm,icon:he?.icon||"HelpCircle",color:he?.color||"var(--text-secondary)"},Ae=de.find(wt=>wt.value===l),pt=de.filter(wt=>!wt.disabled||wt.value===Ae?.value).filter(wt=>wt.value!==Qc).map(wt=>({value:wt.value,label:wt.disabled?`${wt.label} (Legacy)`:wt.label,icon:wt.icon,color:wt.color}));return[rt,...pt]},[de,l]),ee=Ue.useMemo(()=>{const he=ge.find(Ae=>Ae.value===i);return ge.filter(Ae=>Ae.status!=="retired"||Ae.value===he?.value).map(Ae=>({value:Ae.value,label:Ae.status==="retired"?`${Ae.label} (Retired)`:Ae.label,icon:Ae.icon||"Box",color:Ae.color||"violet-500"}))},[ge,i]),ze=he=>he&&vm(he,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,ft=ze(Ye?.createdAt),it=ze(Ye?.updatedAt||Ye?.createdAt),Et=ze(Ye?.completedAt),ht=Ue.useMemo(()=>{const he=new Date,rt=he.getFullYear(),Ae=String(he.getMonth()+1).padStart(2,"0"),Nt=String(he.getDate()).padStart(2,"0");return`${rt}-${Ae}-${Nt}`},[]),Ot=!!(h&&S&&h<S),Dt=!!(h&&h<ht&&(!Ye||Ye.status!=="done"&&Ye.status!=="cancelled")),We=v.filter(he=>he.isCompleted).length,[tt,Fe]=Ue.useState(""),[Ze,St]=Ue.useState(!1),ot=!!Ye?.isArchived,te=!!Ye?.isDeleted,Le=Ue.useMemo(()=>ye.map(he=>{const rt=um(he);return{value:rt||he.id,label:rt?`${rt} · ${he.title}`:he.title,icon:"Folder",color:"var(--text-secondary)"}}),[ye]),At=Ue.useMemo(()=>Le.some(he=>String(he.value)===String(g||"").trim()),[g,Le]);Ue.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 jt=ot||te,Wt=Ue.useRef(null),Ge=gg(Lp(Sg,{activationConstraint:{distance:6}}));Ue.useLayoutEffect(()=>{const he=Wt.current;if(!he)return;const rt=()=>{he.scrollTop=0;const Nt=he.parentElement;Nt&&(typeof Nt.scrollTo=="function"?Nt.scrollTo({top:0,left:0,behavior:"auto"}):Nt.scrollTop=0)};rt();const Ae=window.requestAnimationFrame(rt);return()=>window.cancelAnimationFrame(Ae)},[t,Ye?.id]);const $t=()=>{const he=tt.trim();if(!he)return;const rt=new Date().toISOString();R([...v,{id:`checklist-draft-${rt}-${v.length}`,taskId:t||"",title:he,isCompleted:!1,order:v.length,createdAt:rt,updatedAt:rt}]),Fe("")},yt=Ue.useCallback(he=>{const{active:rt,over:Ae}=he;if(!Ae||rt.id===Ae.id)return;const Nt=v.findIndex(ya=>ya.id===rt.id),pt=v.findIndex(ya=>ya.id===Ae.id);if(Nt<0||pt<0)return;const wt=new Date().toISOString(),Ca=sv(v,Nt,pt).map((ya,ia)=>({...ya,order:ia,updatedAt:wt}));R(Ca)},[v,R]),E=he=>{const rt=String(he||"").trim(),Ae=he.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!Ae||Ae==="ai"||rt.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${Ae.split(" ").map(pt=>pt.charAt(0).toUpperCase()+pt.slice(1)).join(" ")}`},c=lS(H,k),J=cm(k),we=ud(k,c),xe=Ue.useMemo(()=>new Map(c.map(he=>[String(he.value),he])),[c]),Ke=xe.get(String(k||"unassigned")),Je=Ye?.assigneeActor?.color||Ke?.color,Ne=Ue.useMemo(()=>{const he=[Ye?.assigneeActor,Ye?.createdByActor].filter(Boolean);return new Map(he.map(rt=>[String(rt.id),rt]))},[Ye?.assigneeActor,Ye?.createdByActor]),zt=Ue.useMemo(()=>new Map(ye.map(he=>[he.id,um(he)||he.id])),[ye]),Jt=Ue.useMemo(()=>new Map(V.map(he=>[he.id,ry(he)||he.id])),[V]),Pt=Ue.useMemo(()=>Af({activity:Ye?.activity,comments:_}),[_,Ye?.activity]),Ft=(he,rt)=>{const Ae=String(rt||"").trim();if(Ae){if(he==="assignee")return ud(Ae,c);if(he==="workstreamId")return zt.get(Ae);if(he==="initiativeId")return Jt.get(Ae)}},Lt=Ue.useCallback((he,rt,Ae)=>{if(Ae&&Ae.trim())return Ae.trim();const Nt=String(he||"").trim();if(!Nt)return rt==="ai"?"AI Agent":qe("taskForm.you");const pt=Ne.get(Nt);if(pt?.label)return pt.label;const wt=xe.get(Nt)||xe.get(Nt.toLowerCase());return wt?.label?wt.label:rt==="ai"?E(Nt):ud(Nt,c)||Nt},[Ne,xe,E,c]),Ht=Ue.useCallback(({actorId:he,actorType:rt,actorProfile:Ae,fallbackKind:Nt})=>{const pt=String(he||"").trim(),wt=pt.toLowerCase(),Ca=Ne.get(pt),ya=xe.get(pt)||xe.get(wt),ia=Ae||Ca||ya||null,ca=rt==="system"?"system":rt==="ai"||ia?.kind==="ai"?"agent":rt==="human"||ia?.kind==="human"?"member":ya?.kind==="agent"?"agent":ya?.kind==="member"?"member":Nt||(wt===""||wt==="user"||wt==="human"?"member":"agent"),Oa=ca==="system"?"System":Lt(pt,ca==="agent"?"ai":"human",ia?.label||null),gt=ia?.color,rr=String(ia?.icon||(ca==="agent"?"Bot":ca==="member"?"User":"ClipboardList")),ua=tc[rr]||(ca==="agent"?am:ca==="member"?ii:dg);return{kind:ca,label:Oa,color:gt,ActorIcon:ua}},[Ne,xe,Lt]),ra=Ue.useMemo(()=>{const he=Pt[Pt.length-1];if(!he)return null;if(he.type==="comment"){const Ae=he.comment;return Lt(Ae.author,Ae.actor?.kind==="ai"?"ai":Ae.actor?.kind==="human"?"human":null,Ae.actor?.label||null)}const rt=he.event;return Lt(rt.actor,rt.actorType,rt.actorProfile?.label||null)},[Lt,Pt]),Vt=Ue.useMemo(()=>{if(!Ye?.completedAt)return null;for(const rt of Pt){if(rt.type!=="event")continue;const Ae=rt.event,Nt=Ae.details?.changes?.status?.to;if(Nt==="done"||Nt==="cancelled")return Lt(Ae.actor,Ae.actorType,Ae.actorProfile?.label||null)}return ra},[Ye?.completedAt,ra,Lt,Pt]),Ga=Ye?.createdByActor?.label||Lt(Ye?.createdBy||null,Ye?.createdByActor?.kind==="ai"?"ai":Ye?.createdByActor?.kind==="human"?"human":null,Ye?.createdByActor?.label||null),Va=ra,qa=Pt.length;Ue.useLayoutEffect(()=>{if(!t)return;const he=Ct.current;if(!he)return;const rt=he.parentElement,Ae=()=>{if(typeof he.scrollIntoView=="function"){he.scrollIntoView({block:"end"});return}rt&&(rt.scrollTop=rt.scrollHeight)};Ae();const Nt=window.requestAnimationFrame(Ae);return()=>window.cancelAnimationFrame(Nt)},[qa,Ct,Ye?.id,t]);const cn=t?a.jsxs("aside",{className:Xe.activitySidebar,"aria-label":qe("taskForm.commentsSectionTitle"),children:[a.jsxs("div",{className:Xe.activitySidebarHeader,children:[a.jsx("h2",{className:Xe.activitySidebarTitle,children:qe("taskForm.commentsSectionTitle")}),a.jsx("span",{className:Xe.activitySidebarCount,children:qa})]}),a.jsxs("div",{className:`${Xe.commentPanel} ${Xe.activitySidebarPanel}`.trim(),children:[a.jsx(Ue.Suspense,{fallback:a.jsx(ZE,{count:qa}),children:a.jsx(qE,{activity:Ye?.activity,comments:_,formatFieldValue:Ft,resolveActorPresentation:Ht,onOpenTaskById:kt,emptyMessage:qe("taskForm.noComments"),listClassName:Xe.commentThread,emptyClassName:Xe.emptyComments,endRef:Ct})}),a.jsxs("div",{className:Xe.commentInputArea,children:[a.jsx("textarea",{className:Xe.commentInput,placeholder:qe("taskForm.commentPlaceholder"),value:I,onChange:he=>F(he.target.value),onKeyDown:he=>{he.key==="Enter"&&!he.shiftKey&&(he.preventDefault(),U())},rows:4}),a.jsx("button",{type:"button",className:Xe.sendCommentBtn,onClick:U,disabled:!I.trim(),"aria-label":"Send comment",title:"Send comment",children:a.jsx(Pk,{size:16})})]})]})]}):null;return a.jsxs("form",{ref:Wt,onSubmit:be,className:`${p.form} ${p.appScrollbar} tf-scrollbar`,children:[n&&a.jsx("div",{className:Xe.error,children:n}),jt&&a.jsx("div",{className:`${Xe.formNotice} tf-text-helper`,children:te?"Deleted tasks are read-only. Restore the task to make changes.":"Archived tasks are read-only. Unarchive the task to make changes."}),a.jsxs("fieldset",{disabled:jt,className:`${Xe.formFieldsetReset} ${t?Xe.formLayoutWithSidebar:Xe.formLayout}`.trim(),children:[a.jsxs("div",{className:Xe.formMainColumn,children:[a.jsxs("div",{className:p.field,children:[a.jsxs("div",{className:p.labelRow,children:[a.jsx("label",{className:p.label,children:"Title"}),k&&a.jsx("span",{title:`Assigned to: ${we}`,className:[Xe.assigneeIndicator,J==="agent"?Xe.assigneeIndicatorAgent:J==="member"?Xe.assigneeIndicatorUser:Xe.assigneeIndicatorUnassigned].join(" "),style:Je?{color:Je}:void 0,children:J==="agent"?a.jsx(am,{size:20}):J==="member"?a.jsx(ii,{size:20}):a.jsx(Ji,{size:20})})]}),a.jsx("input",{type:"text",value:s,onChange:he=>_e(he.target.value),placeholder:"What needs to be done?",className:p.input,required:!0,maxLength:255,autoFocus:!0})]}),a.jsxs("div",{className:p.field,children:[a.jsxs("div",{className:p.labelRow,children:[a.jsx("label",{className:p.label,children:"Description"}),a.jsx("button",{type:"button",className:p.helpLink,onClick:()=>M(!X),title:"Markdown Help",tabIndex:-1,children:a.jsx(Ji,{size:14})})]}),X&&a.jsxs("div",{className:Xe.markdownHelp,children:[a.jsxs("div",{className:Xe.helpHeader,children:[a.jsx("span",{children:"Markdown Guide"}),a.jsx("button",{onClick:()=>M(!1),className:Xe.helpClose,children:a.jsx(nc,{size:12})})]}),a.jsxs("div",{className:Xe.helpGrid,children:[a.jsx("div",{children:a.jsx("code",{children:"**bold**"})}),a.jsx("div",{children:a.jsx("code",{children:"_italic_"})}),a.jsx("div",{children:a.jsx("code",{children:"- list"})}),a.jsx("div",{children:a.jsx("code",{children:"1. list"})}),a.jsx("div",{className:Xe.helpGridItem,children:a.jsx("code",{children:"`inline code`"})}),a.jsxs("div",{className:Xe.helpGridItem,children:[a.jsx("code",{children:"```"}),a.jsx("br",{}),a.jsx("code",{children:"code block"}),a.jsx("br",{}),a.jsx("code",{children:"```"})]}),a.jsx("div",{children:a.jsx("code",{children:"[link](url)"})})]})]}),B||!o?a.jsx("textarea",{className:`${p.textarea} ${Xe.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",value:o,onChange:he=>re(he.target.value),onFocus:()=>Q(!0),onBlur:()=>Q(!1),rows:9,autoFocus:B}):a.jsx("div",{className:`${p.textarea} ${Xe.descriptionSurface} ${Xe.markdownPreview} ${Xe.markdownPreviewContainer}`,onClick:()=>Q(!0),children:a.jsx(cy,{onTaskIdClick:kt,children:o})})]}),a.jsxs("div",{className:Xe.compactMetaSection,children:[a.jsxs("div",{className:Xe.compactMetaGrid,children:[a.jsxs("div",{className:`${p.field} ${Xe.compactMetaField}`,children:[a.jsx("label",{id:"category-label",className:p.label,children:P?.category||"Category"}),a.jsx(id,{value:l,options:Rt,onChange:he=>oe(String(he)),required:!0,ariaLabelledBy:"category-label"})]}),a.jsxs("div",{className:`${p.field} ${Xe.compactMetaField}`,children:[a.jsx("label",{id:"type-label",className:p.label,children:P?.type||"Type"}),a.jsx(id,{value:i,options:ee,onChange:he=>Ie(String(he)),ariaLabelledBy:"type-label"})]}),a.jsxs("div",{className:`${p.field} ${Xe.compactMetaField}`,children:[a.jsx("label",{htmlFor:"task-form-scheduled-date",className:p.label,children:qe("taskForm.scheduledLabel")}),a.jsx("input",{id:"task-form-scheduled-date",type:"date",value:S,onChange:he=>K(he.target.value),className:`${p.input} ${p.taskFormDateInput}`})]}),a.jsxs("div",{className:`${p.field} ${Xe.compactMetaField}`,children:[a.jsx("label",{id:"assignee-label",className:p.label,children:"Assigned To"}),a.jsx(id,{value:k||"unassigned",options:c,onChange:he=>Pe(String(he)),ariaLabelledBy:"assignee-label"})]}),a.jsx("div",{className:Xe.compactMetaField,children:a.jsx(_p,{label:P?.priority||"Priority",options:Y,value:d,onChange:Ee,type:"priority",showSelectedLabel:!1})}),a.jsxs("div",{className:`${p.field} ${Xe.compactMetaField}`,children:[a.jsx("label",{htmlFor:"task-form-due-date",className:p.label,children:qe("taskForm.dueLabel")}),a.jsx("input",{id:"task-form-due-date",type:"date",value:h,onChange:he=>x(he.target.value),className:`${p.input} ${p.taskFormDateInput}`}),Ot&&a.jsx("span",{className:`${Xe.taskFormDateWarning} ${Xe.compactMetaFieldHint}`,children:qe("taskForm.dueBeforeScheduled")}),Dt&&a.jsx("span",{className:`${Xe.taskFormDateError} ${Xe.compactMetaFieldHint}`,children:qe("taskForm.overdue")})]}),y&&a.jsx("div",{className:Xe.compactMetaField,children:a.jsx(_p,{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:je,type:"general"})})]}),!t&&a.jsxs("div",{className:Xe.createWorkstreamRow,children:[a.jsx("label",{className:p.label,children:"Attach to workstream"}),a.jsxs("div",{className:p.pathInputGroup,children:[Ze?a.jsx("input",{type:"text",className:p.input,value:g,onChange:he=>b(he.target.value),placeholder:"Type a workstream name or reference","aria-label":"Attach to workstream"}):a.jsx(id,{value:g,options:Le,onChange:he=>b(String(he)),placeholder:"Select workstream...",ariaLabel:"Attach to workstream",className:Xe.createWorkstreamDropdown}),a.jsx("button",{type:"button",className:p.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:a.jsx(ro,{size:14})})]})]})]}),a.jsxs("div",{className:Xe.sectionBlock,children:[a.jsx("div",{className:Xe.taxonomyFieldsGrid,children:Qe.map(he=>{if(he.id==="approach"&&he.isSystem)return null;const rt=le[he.id],Ae=Array.isArray(rt)?rt.map(pt=>String(pt)):rt!=null&&rt!==""?[String(rt)]:[],Nt=he.options.filter(pt=>pt.status!=="retired"||Ae.includes(String(pt.value)));return a.jsxs("div",{className:p.field,children:[a.jsx("label",{className:p.label,children:he.label}),he.description&&a.jsx("div",{className:`${Xe.settingsHint} tf-text-helper`,children:he.description}),he.widgetType==="level"?a.jsx(_p,{label:he.label,options:Nt.map(pt=>({...pt,label:pt.status==="retired"?`${pt.label} (Retired)`:pt.label})),value:le[he.id]||"",onChange:pt=>O(he.id,pt),type:"general",hideLabel:!0}):he.multiSelect?a.jsx("div",{className:`${p.dropdownList} ${Xe.softSectionSurface}`,children:Nt.map(pt=>{const wt=String(pt.value),Ca=Ae.includes(wt);return a.jsxs("button",{type:"button",className:`${Xe.specialistChip} ${Ca?Xe.specialistChipActive:""}`,onClick:()=>{const ya=Ca?Ae.filter(ia=>ia!==wt):[...Ae,wt];O(he.id,ya)},title:Ca?"Click to remove":"Click to add",children:[Ca&&a.jsx(no,{size:12}),pt.status==="retired"?`${pt.label} (Retired)`:pt.label]},wt)})}):a.jsxs("div",{className:p.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=he.options.find(ya=>String(ya.value)===String(le[he.id])),wt=pt?.icon&&As[pt.icon]?As[pt.icon]:Ji,Ca=pt?.color||"var(--text-secondary)";return a.jsx("div",{className:p.fieldIcon,style:{color:Dn(Ca)},children:a.jsx(wt,{size:16})})})(),a.jsxs("select",{value:le[he.id]||"",onChange:pt=>O(he.id,pt.target.value),className:`${p.select} ${p.field_dynamic}`,required:he.isRequired,children:[a.jsxs("option",{value:"",children:["Select ",he.label,"..."]}),Nt.map(pt=>a.jsx("option",{value:pt.value,children:pt.status==="retired"?`${pt.label} (Retired)`:pt.label},pt.value))]})]})]},he.id)})}),ke&&a.jsxs("div",{className:p.specialistSection,children:[a.jsxs("div",{className:p.toggleHeading,onClick:()=>$(!me),title:me?"Hide checklist":"Show checklist",children:[a.jsxs("label",{className:p.label,children:["Checklist"," ",v.length>0&&`(${We}/${v.length})`]}),me?a.jsx(nl,{size:14}):a.jsx(Xc,{size:14})]}),me&&a.jsxs("div",{className:`${p.dropdownList} ${Xe.stackedList} ${Xe.stackedListSpaced}`,children:[a.jsxs("div",{className:p.pathInputGroup,children:[a.jsx("input",{type:"text",className:p.input,placeholder:"Add checklist item",value:tt,onChange:he=>Fe(he.target.value),onKeyDown:he=>{he.key==="Enter"&&(he.preventDefault(),$t())}}),a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:$t,disabled:!tt.trim(),children:"Add"})]}),v.length>0?a.jsx(yg,{sensors:Ge,collisionDetection:ov,onDragEnd:yt,children:a.jsx(kg,{items:v.map(he=>he.id),strategy:vg,children:v.map((he,rt)=>a.jsx(YE,{id:he.id||`checklist-${rt}`,item:he,onToggle:()=>{const Ae=new Date().toISOString();R(v.map((Nt,pt)=>pt===rt?{...Nt,isCompleted:!Nt.isCompleted,updatedAt:Ae}:Nt))},onRemove:()=>R(v.filter((Ae,Nt)=>Nt!==rt).map((Ae,Nt)=>({...Ae,order:Nt})))},he.id||`checklist-${rt}`))})}):a.jsx("div",{className:`${Xe.settingsHint} tf-text-helper`,children:"No checklist items yet."})]})]})]}),a.jsxs("div",{children:[a.jsx(Ue.Suspense,{fallback:null,children:a.jsx(KE,{taskId:t,taskReferenceLabel:dt,workspaceId:D,apiBaseUrl:q,contextFiles:C,onAddContextFile:se,onRemoveContextFile:pe,onUpdateContextCaption:z})}),a.jsx("div",{className:`${Xe.taskFormLifecycle} ${Xe.taskFormMetaDivider}`,children:a.jsx("div",{className:Xe.taskFormMetaGrid,children:Ye&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Xe.taskFormDateRow,children:[a.jsx("span",{className:Xe.taskFormDateLabel,children:qe("taskForm.createdLabel")}),a.jsxs("span",{className:Xe.taskFormMetaStack,children:[a.jsx("span",{className:Xe.taskFormDateValue,children:ft||qe("taskForm.emptyValue")}),a.jsx("span",{className:Xe.taskFormMetaActor,children:Ga?`by ${Ga}`:qe("taskForm.emptyValue")})]})]}),a.jsxs("div",{className:Xe.taskFormDateRow,children:[a.jsx("span",{className:Xe.taskFormDateLabel,children:qe("taskForm.updatedLabel")}),a.jsxs("span",{className:Xe.taskFormMetaStack,children:[a.jsx("span",{className:Xe.taskFormDateValue,children:it||qe("taskForm.emptyValue")}),a.jsx("span",{className:Xe.taskFormMetaActor,children:Va?`by ${Va}`:qe("taskForm.emptyValue")})]})]}),a.jsxs("div",{className:Xe.taskFormDateRow,children:[a.jsx("span",{className:Xe.taskFormDateLabel,children:qe("taskForm.completedLabel")}),a.jsxs("span",{className:Xe.taskFormMetaStack,children:[a.jsx("span",{className:Xe.taskFormDateValue,children:Et||qe("taskForm.emptyValue")}),a.jsx("span",{className:Xe.taskFormMetaActor,children:Vt?`by ${Vt}`:qe("taskForm.emptyValue")})]})]})]})})})]})]}),cn,a.jsxs("div",{className:Xe.keyboardHint,children:["Press ",a.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function Zi({ariaLabel:e,children:t,disabled:n=!1,onClick:s,title:o}){return a.jsx("button",{type:"button",className:`${p.taskIdBadge} ${p.taskHierarchyActionBtn}`,onClick:s,disabled:n,title:o,"aria-label":e,children:t})}function Ay({editingTaskId:e,loading:t,autoSaveState:n="idle",title:s,handleSubmit:o,resetForm:l,handleCopyId:i,copiedId:d,tasks:m,currentTask:y,currentTaskWorkstream:k,currentTaskInitiative:S,workstreamInput:h="",onWorkstreamInputChange:g,onSetWorkstreamForCurrentTask:v,handleToggleInProgress:_,handleToggleReview:I,handleToggleComplete:C,handleToggleCancel:D,handleSetStatus:q,handleArchiveTask:B,handleUnarchiveTask:X,handleRestoreDeletedTask:me,handlePermanentlyDeleteDeletedTask:ke}){const[le,O]=Ue.useState(!1),A=y??(e&&m.find(re=>re.id===e)||null),de=!!A?.isArchived,ge=!!A?.isDeleted,Y=Ng(A),P=Y.label||(Y.isProvisional?"Pending":""),H=Y.isProvisional,ue=!!Y.label,ye=k?um(k)||k.id:"",V=S?os(S)||S.id:"";Ue.useEffect(()=>{k&&O(!1)},[k?.id]);const Me=Ue.useCallback(()=>{h.trim()&&v?.()},[v,h]),_e=Ue.useCallback(()=>{O(!1),g?.(""),v?.(null)},[v,g]);return a.jsx("div",{className:p.stickyActionHeader,children:e?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:p.taskHierarchyHeader,children:[a.jsxs("div",{className:p.taskHierarchyBadgeRow,children:[k?a.jsx(a.Fragment,{children:a.jsx(Zi,{onClick:_e,disabled:t||de||ge,title:"Remove from workstream",ariaLabel:"Remove from workstream",children:a.jsx(Zu,{size:13})})}):null,S?a.jsxs("span",{className:p.taskHierarchySegment,children:[a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx(Qu,{copied:d===V,onClick:re=>i(re,V),disabled:t,title:"Copy initiative reference",label:V})]}):null,k?a.jsxs("span",{className:p.taskHierarchySegment,children:[a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx(Qu,{copied:d===ye,onClick:re=>i(re,ye),disabled:t,title:"Copy workstream reference",label:ye})]}):a.jsx(a.Fragment,{children:a.jsx(Zi,{onClick:()=>{g?.(""),O(re=>!re)},disabled:t||de||ge,title:"Attach to workstream",ariaLabel:"Attach to workstream",children:a.jsx(nm,{size:13})})}),P?a.jsxs("span",{className:p.taskHierarchySegment,children:[a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx(Qu,{copied:ue&&d===Y.label,onClick:re=>i(re,Y.label),disabled:t||!ue,title:ue?qe("actionHeader.copyTaskIdTitle"):"Task reference pending sync",label:P})]}):null,H?a.jsx("span",{className:p.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),le&&!k?a.jsxs("div",{className:p.taskHierarchyEditor,children:[a.jsx("input",{type:"text",className:`${p.input} ${p.taskHierarchyInput}`,value:h,onChange:re=>g?.(re.target.value),placeholder:"WS-123","aria-label":"Attach workstream reference",onKeyDown:re=>{re.key==="Enter"&&(re.preventDefault(),Me()),re.key==="Escape"&&(re.preventDefault(),g?.(""),O(!1))}}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:Me,disabled:!h.trim()||t,title:"Attach workstream","aria-label":"Attach workstream",children:a.jsx(no,{size:14})}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>{g?.(""),O(!1)},disabled:t,title:"Cancel workstream attach","aria-label":"Cancel workstream attach",children:a.jsx(nc,{size:14})})]}):null]}),a.jsx("div",{className:p.taskSaveStatusCenter,children:a.jsx("div",{className:`${p.taskSaveStatus} ${n==="error"?p.taskSaveStatusError:""}`,"aria-live":"polite",children:n==="saving"?a.jsxs(a.Fragment,{children:[a.jsx(kr,{size:14,className:p.spinner}),a.jsx("span",{children:"Saving…"})]}):n==="saved"?a.jsx("span",{children:"Saved"}):n==="error"?a.jsx("span",{children:"Save failed"}):null})}),a.jsx("div",{className:p.editActionsGroup,children:ge&&A?.deletedRecordId?a.jsxs(a.Fragment,{children:[me&&a.jsx("button",{type:"button",className:p.actionBtn,onClick:()=>me(A.deletedRecordId||""),disabled:t,title:"Restore deleted task",children:a.jsx(gd,{size:16})}),ke&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.deleteBtn}`,onClick:()=>ke(A.deletedRecordId||""),disabled:t,title:"Permanently delete deleted task",children:a.jsx(_m,{size:16})})]}):a.jsx(gy,{task:A,disabled:t,statusDisabled:t||de,archiveActionMode:de?"unarchive":"auto",onSetStatus:(re,oe)=>{if(q){q(re,oe);return}if(oe==="in-progress"){_(re);return}if(oe==="review"){I(re);return}if(oe==="done"){C(re);return}oe==="cancelled"&&D(re)},onArchiveTask:B,onUnarchiveTask:re=>X?.(re.id)})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button",onClick:l,disabled:t,className:p.secondaryHeaderBtn,title:qe("actionHeader.clearFormTitle"),children:[a.jsx(gd,{size:16}),qe("actionHeader.clear")]}),a.jsxs("button",{type:"button",onClick:re=>o(re),disabled:t||!s.trim(),className:p.primaryUpdateBtn,title:qe("actionHeader.addTaskTitle"),children:[t?a.jsx(kr,{size:16,className:p.spinner}):a.jsx(ro,{size:16}),qe("actionHeader.addTask")]})]})})}const JE="_topNoticeLayer_1m6a1_1",QE="_topNotice_1m6a1_1",XE="_topNoticeMessage_1m6a1_32",eD="_topNoticeSuccess_1m6a1_38",tD="_topNoticeError_1m6a1_44",aD="_topNoticeInfo_1m6a1_50",nD="_topNoticeDismiss_1m6a1_56",Vi={topNoticeLayer:JE,topNotice:QE,topNoticeMessage:XE,topNoticeSuccess:eD,topNoticeError:tD,topNoticeInfo:aD,topNoticeDismiss:nD};function xy({notice:e,onDismiss:t}){if(!e)return null;const n=e.tone==="error"?Vi.topNoticeError:e.tone==="success"?Vi.topNoticeSuccess:Vi.topNoticeInfo,s=e.tone==="error"?"alert":"status";return a.jsx("div",{className:Vi.topNoticeLayer,children:a.jsxs("div",{className:`${Vi.topNotice} ${n}`,role:s,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?a.jsx(yd,{size:14}):e.tone==="success"?a.jsx(no,{size:14}):a.jsx(Ek,{size:14}),a.jsx("span",{className:Vi.topNoticeMessage,children:e.message}),t&&a.jsx("button",{type:"button",className:Vi.topNoticeDismiss,onClick:t,"aria-label":"Dismiss notice",title:"Dismiss notice",children:a.jsx(nc,{size:14})})]})})}const rD=Ue.lazy(()=>xs(()=>import("./TaskSettings-CJPC2Bft.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings})));function sD(e){const{activeTab:t,setActiveTab:n,isOpen:s,setIsOpen:o,currentTheme:l,setCurrentTheme:i,saveSettings:d,pathSaved:m,keyShortcut:y,setKeyShortcut:k,jsonBackupEnabled:S,setJsonBackupEnabled:h,mcpHostRoot:g,setMcpHostRoot:v,settingsSection:_,setSettingsSection:I,projectRoot:C,projectName:D,mcpScriptPath:q,serverHostRoot:B,showFolderBrowser:X,setShowFolderBrowser:me,folders:ke,files:le,currentBrowsePath:O,fetchFolders:A,browserTarget:de,setBrowserTarget:ge,handleSelectPath:Y,handleAddPath:P,handleRemovePath:H,tasks:ue,loadingTasks:ye,archivedTasks:V,deletedTasks:Me,activeCategories:_e,activeTypes:re,priorities:oe,taxonomyDisplayLabels:Ie,approaches:Ee,taxonomies:je,searchQuery:Pe,setSearchQuery:K,filterCategories:x,setFilterCategories:b,filterTypes:R,setFilterTypes:F,filterPriorities:Q,setFilterPriorities:M,filterStatus:$,setFilterStatus:be,filterAssignees:U,setFilterAssignees:se,assigneeOptions:pe,filterTaxonomies:z,setFilterTaxonomies:ne,sortBy:ie,setSortBy:Re,sortOrder:Te,toggleSortOrder:De,showArchive:Oe,setShowArchive:vt,taskScope:st,setTaskScope:kt,clearFilters:Ye,filteredTasks:Ct,filteredArchive:dt,groupedTasks:Qe,collapsedCategories:Rt,setCollapsedCategories:ee,handleEdit:ze,handleDelete:ft,handleCopyId:it,handleToggleComplete:Et,handleToggleCancel:ht,handleToggleInProgress:Ot,handleToggleReview:Dt,handleArchiveTask:We,handleBulkArchive:tt,handleUnarchive:Fe,handleRestoreDeletedTask:Ze,handlePermanentlyDeleteDeletedTask:St,handleEmptyDeletedTasks:ot,fetchArchive:te,editingTaskId:Le,loading:At,error:jt,title:Wt,setTitle:Ge,description:$t,setDescription:yt,checklistItems:E,setChecklistItems:c,category:J,setCategory:we,type:xe,setType:Ke,priority:Je,setPriority:Ne,complexity:zt,setComplexity:Jt,manualComplexityEnabled:Pt,checklistDropdownEnabled:Ft,showTaskCardStatusLabel:Lt,approach:Ht,setApproach:ra,assignee:Vt,setAssignee:Ga,scheduledDate:Va,setScheduledDate:qa,dueDate:cn,setDueDate:he,workstreamInput:rt,setWorkstreamInput:Ae,formTaxonomies:Nt,setFormTaxonomies:pt,comments:wt,newCommentText:Ca,setNewCommentText:ya,attachments:ia,setAttachments:ca,setAttachmentsDirty:Oa,descriptionFocused:gt,setDescriptionFocused:rr,showMarkdownHelp:ua,setShowMarkdownHelp:ta,showChecklist:wa,setShowChecklist:Kt,showComments:vr,setShowComments:Ta,handleSubmit:Qa,resetForm:Ra,handleAddComment:Zt,handleSetWorkstreamForCurrentTask:Ka,handleOpenTaskById:aa,autoSaveState:ln,unsavedModalOpen:yn,setUnsavedModalOpen:Sr,pendingNavigation:la,handleNavigation:wr,handleClose:qr,scheduleWarningPrompt:Vn,confirmScheduleWarning:kn,cancelScheduleWarning:$a,uiNotice:br,clearNotice:dn,taskReturnTrail:Ea,clearReturnToParentTask:ja,returnToPreviousTask:_r,copiedId:xt,recentlyChangedTaskIds:vn,tasksScrollRef:Sn,setTasksScrollPos:un,currentTask:Ua,currentTaskWorkstream:sr,currentTaskInitiative:Na,exportEnvironment:ka,setExportEnvironment:Ln,exportWorkflowsPath:wn,setExportWorkflowsPath:va,exportResult:Yt,exportingResource:bn,availableWorkflows:za,onExportWorkflows:Pa,availableEnvironments:Bn,handleUpdateCategory:Ma,handleRemoveCategory:Mr,handleSaveCategory:na,handleUpdateCategoryIcon:da,handleUpdateCategoryColor:Xa,handleSaveType:or,handleRemoveType:Er,handleUpdateTaxonomies:Cr,handleUpdatePriorities:Xt,pathValidation:_n,validatePaths:Cn,getCategoryPaths:Ar,commentsEndRef:xr,currentWorkspaceId:qn,settingsModel:Kn,onHeaderMouseDown:ir,isDragging:en}=e,An=r.useRef(null),[Zn,tn]=Ue.useState(0);r.useLayoutEffect(()=>{if(t==="tasks"&&Sn.current&&Zn>0){const et=setTimeout(()=>{Sn.current&&(Sn.current.scrollTop=Zn)},50);return()=>clearTimeout(et)}},[t,Zn,ue]);const cs=et=>{Re(et)},Za=()=>{wr(()=>{if(t==="add"||t==="settings"){if(t==="add"&&_r())return;t==="add"&&Ea.length>0&&ja(),t==="add"&&Ra(),n("tasks")}else e.onClose?e.onClose():qr()})},Kr=()=>{Sr(!1),la?(t==="add"&&Ra(),la()):n("tasks")},Dr=async()=>{await Qa({preventDefault:()=>{}}),Sr(!1),la&&la()},xn=(et,Bt)=>{pt(Da=>({...Da,[et]:Bt})),et==="approach"&&typeof Bt=="string"&&ra(Bt)},cr=r.useCallback(et=>{Ra(),we(et),wr(()=>{n("add")})},[Ra,we,n,wr]),Wn=Ue.useMemo(()=>Me.map(et=>({...et.taskSnapshot,isDeleted:!0,deletedRecordId:et.id})),[Me]),mn=Ue.useMemo(()=>new globalThis.Map(Me.map(et=>[et.taskId,et])),[Me]),lr=Ue.useMemo(()=>{const et=Rm(Pe),Bt={categories:_e,types:re,priorities:oe,assigneeOptions:pe,taxonomies:je},Da=_e.every(Gt=>x.includes(Gt.value)),Aa=re.every(Gt=>R.includes(Gt.value)),Sa=Array.from(new Set(Q.map(Gt=>Number(Gt)).filter(Gt=>Number.isFinite(Gt)))),Yn=oe.map(Gt=>Number(Gt.value)).filter(Gt=>Number.isFinite(Gt)).every(Gt=>Sa.includes(Gt)),Fn=["task","in-progress","review","done","cancelled","on-hold"].every(Gt=>$.includes(Gt)),On=pe.length>0&&pe.every(Gt=>U.includes(Gt.value)),Tn=Cd(je,Wn);return Wn.filter(Gt=>{const $n=pm(Gt,et,Bt),pn=Da||x.includes(Gt.category),La=Yn||Sa.includes(sm(Gt.priority)),Lr=Aa||R.includes(Gt.type||Vr),Br=Fn||$.includes(Gt.status),dr=On||U.includes(Gt.assignee||"unassigned"),ur=Object.entries(z).every(([Fs,nn])=>{const fn=Tn.find(W=>W.id===Fs);if(!fn||bf(fn,Wn).every(W=>nn.includes(W.value)))return!0;const mr=Gt.taxonomies?.[Fs];return mr?Array.isArray(mr)?mr.some(W=>nn.includes(W)):nn.includes(mr):nn.includes("")});return $n&&pn&&La&&Lr&&Br&&dr&&ur}).sort((Gt,$n)=>fm(Gt,$n,ie,Te,je))},[_e,re,V,pe,Wn,U,x,Q,$,z,R,oe,Pe,ie,Te,je,ue]),Zr=Ue.useMemo(()=>{const et={};return lr.forEach(Bt=>{const Aa=_e.find(Sa=>Sa.value===Bt.category||Sa.label===Bt.category)?.label||Bt.category||"General";et[Aa]||(et[Aa]=[]),et[Aa].push(Bt)}),et},[_e,lr]),ls=st==="archived"?dt.length:st==="deleted"?lr.length:Ct.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{ref:An,className:`${Tt.modal} ${p.coreModal} ${t==="settings"?Tt.settingsViewModal:""}`,"data-theme":l,children:[a.jsxs("div",{className:"tf-modal-header",onMouseDown:ir,style:{cursor:ir?en?"grabbing":"grab":"default"},children:[a.jsxs("div",{className:`tf-modal-title ${ea.headerTitleWidget}`,children:["Taskforce",D&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.projectSlash,children:"/"}),a.jsx("span",{className:p.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:D})]}),a.jsx("span",{className:p.taskCountBadge,title:`${st.charAt(0).toUpperCase()+st.slice(1)} tasks`,children:ls})]}),a.jsxs("div",{className:Tt.headerActions,children:[t==="tasks"&&a.jsx(a.Fragment,{children:a.jsx("button",{className:"tf-control-icon",onClick:()=>{wr(()=>{Ra(),n("add")})},title:"Add New Task",children:a.jsx(ro,{size:18})})}),a.jsx("button",{className:`tf-control-icon ${t==="settings"?"tf-control-icon-active":""}`,onClick:()=>{t!=="settings"&&wr(()=>{n("settings")})},title:"Settings",children:a.jsx(af,{size:18})}),a.jsx("button",{className:"tf-control-icon",onClick:Za,title:t==="tasks"?"Close":"Back to Tasks",children:t==="tasks"?a.jsx(nc,{size:20}):a.jsx(Dk,{size:20})})]})]}),a.jsx(xy,{notice:br,onDismiss:dn}),t==="add"&&a.jsx(Ay,{editingTaskId:Le,loading:At,autoSaveState:ln,title:Wt,currentTask:Ua,currentTaskWorkstream:sr,currentTaskInitiative:Na,workstreamInput:rt,onWorkstreamInputChange:Ae,onSetWorkstreamForCurrentTask:Ka,handleSubmit:Qa,resetForm:Ra,handleCopyId:it,copiedId:xt,tasks:ue,handleToggleInProgress:Ot,handleToggleReview:Dt,handleToggleComplete:Et,handleToggleCancel:ht,handleArchiveTask:We,handleUnarchiveTask:et=>{if(Ua?.isDeleted){const Bt=mn.get(et);Bt&&Ze(Bt.id);return}Fe(et)},handleRestoreDeletedTask:et=>{Ze(et)},handlePermanentlyDeleteDeletedTask:et=>{St(et)}}),t==="tasks"&&a.jsx(_y,{ref:Sn,tasks:ue,archivedTasks:V,categories:_e,types:re,priorities:oe,taxonomyDisplayLabels:Ie,taxonomies:je,searchQuery:Pe,filterCategories:x,filterTypes:R,filterPriorities:Q,filterStatus:$,filterAssignees:U,assigneeOptions:pe,filterTaxonomies:z,sortBy:ie,sortOrder:Te,showArchive:Oe,taskScope:st,collapsedCategories:Rt,loadingTasks:ye,filteredTasks:Ct,filteredArchive:dt,groupedTasks:Qe,filteredDeletedTasks:lr,groupedDeletedTasks:Zr,copiedId:xt,recentlyChangedTaskIds:vn,showTaskCardStatusLabel:Lt,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:K,onFilterCategoriesChange:et=>b(et),onFilterTypesChange:et=>F(et),onFilterPrioritiesChange:M,onFilterStatusChange:be,onFilterAssigneesChange:et=>se(et),onTaxonomyFilterChange:(et,Bt)=>ne(Da=>({...Da,[et]:Bt})),onSortByChange:cs,onSortOrderChange:De,onShowArchiveChange:vt,onTaskScopeChange:kt,onClearFilters:Ye,onToggleCategory:et=>ee(Bt=>({...Bt,[et]:!Bt[et]})),onEditTask:ze,onOpenTaskById:aa,onCopyId:it,onToggleInProgress:Ot,onToggleReview:Dt,onToggleComplete:Et,onToggleCancel:ht,onArchiveTask:We,onBulkArchive:tt,onUnarchive:et=>{const Bt=mn.get(et);if(Bt){Ze(Bt.id);return}Fe(et)},onDelete:et=>{const Bt=mn.get(et);if(Bt){St(Bt.id);return}ft(et)},onDeleteAllDeleted:()=>{ot()},onFetchArchive:te,onAddTaskToCategory:cr,supplementalTasks:Wn}),t==="add"&&a.jsx(Cy,{editingTaskId:Le,error:jt,title:Wt,description:$t,checklistItems:E,category:J,type:xe,priority:Je,complexity:zt,manualComplexityEnabled:Pt,approach:Ht,assignee:Vt,scheduledDate:Va,dueDate:cn,workstreamInput:rt,formTaxonomies:Nt,onTaxonomyChange:xn,taxonomies:je,comments:wt,newCommentText:Ca,contextFiles:ia,currentWorkspaceId:qn,apiBaseUrl:"",descriptionFocused:gt,showMarkdownHelp:ua,showChecklist:wa,checklistEnabled:Ft,showComments:vr,categories:_e,types:re,priorities:oe,taxonomyDisplayLabels:Ie,assigneeOptions:pe,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:xt,onTitleChange:Ge,onDescriptionChange:yt,onChecklistItemsChange:c,onCategoryChange:we,onTypeChange:Ke,onPriorityChange:Ne,onComplexityChange:Jt,onApproachChange:et=>{ra(et),pt(Bt=>({...Bt,approach:et}))},onAssigneeChange:Ga,onScheduledDateChange:qa,onDueDateChange:he,onWorkstreamInputChange:Ae,onNewCommentTextChange:ya,onDescriptionFocusedChange:rr,onShowMarkdownHelpChange:ta,onShowChecklistChange:Kt,onShowCommentsChange:Ta,onOpenSettings:et=>{wr(()=>{I(et),n("settings")})},onSubmit:Qa,commentsEndRef:xr,onAddComment:()=>Zt(Ca),onOpenTaskById:aa,onAddContextFile:et=>{Oa(!0),ca(Bt=>[...Bt,et])},onRemoveContextFile:async et=>{Oa(!0),ca(Bt=>Bt.filter((Da,Aa)=>Aa!==et))},onUpdateContextCaption:(et,Bt)=>{Oa(!0),ca(Da=>Da.map((Aa,Sa)=>Sa!==et?Aa:typeof Aa=="string"?{path:Aa,caption:Bt,timestamp:new Date().toISOString()}:{...Aa,caption:Bt}))},onCopyId:it,onToggleInProgress:Ot,onToggleReview:Dt,onToggleComplete:Et,onToggleCancel:ht,onArchiveTask:We,onUnarchive:et=>{if(Ua?.isDeleted){const Bt=mn.get(et);Bt&&Ze(Bt.id);return}Fe(et)},currentTask:Ua}),t==="settings"&&a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(rD,{settingsModel:Kn,onSectionChange:I})})]}),X&&Yi.createPortal(a.jsx("div",{className:Ia.overlay,children:a.jsxs("div",{className:Ia.browser,children:[a.jsxs("div",{className:Ia.header,children:[a.jsxs("div",{className:Ia.pathInfo,children:[a.jsx(Po,{size:14}),a.jsx("span",{children:O||"Project Root"})]}),a.jsxs("div",{className:Ia.actions,children:[O&&a.jsx("button",{className:p.helpLink,onClick:()=>{const et=O.split("/").filter(Boolean);et.pop(),A(et.length?et.join("/")+"/":"")},children:"Back"}),a.jsx("button",{className:p.helpLink,onClick:()=>me(!1),children:"Close"})]})]}),a.jsxs("div",{className:Ia.list,children:[de&&typeof de=="object"&&a.jsxs("div",{className:`${Ia.item} ${Ia.itemCurrent}`,onClick:()=>Y(O),children:[a.jsx(no,{size:14})," Select Current: ./",O||"(root)"]}),ke.map(et=>a.jsxs("div",{className:Ia.item,onClick:()=>A(O+et+"/"),children:[a.jsx(Po,{size:14})," ",et,"/"]},et)),le.map(et=>a.jsxs("div",{className:`${Ia.item} ${Ia.itemFile}`,onClick:()=>Y(O+et),children:[a.jsx(Dp,{size:14})," ",et]},et)),ke.length===0&&le.length===0&&a.jsx("div",{className:`${Ia.item} ${Ia.empty}`,children:"No items found"})]})]})}),document.body),yn&&a.jsx("div",{className:`${Tt.overlay} ${Tt.unsavedOverlay}`,children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${Tt.modal} ${Tt.unsavedModal}`,"data-theme":l,children:[a.jsx("div",{className:`tf-modal-header ${Tt.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${Tt.unsavedTitle}`,children:[a.jsx(yd,{size:20}),"Unsaved Changes"]})}),a.jsx("div",{className:`${Tt.form} ${Tt.unsavedContent}`,children:a.jsx("p",{className:Tt.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),a.jsxs("div",{className:`${Tt.formActions} ${Tt.unsavedActions}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:()=>Sr(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),a.jsx("button",{className:p.destructiveBtn,onClick:Kr,title:"Discard unsaved changes and leave",children:"Discard"}),a.jsxs("button",{className:p.submitBtn,onClick:Dr,disabled:At,title:"Save changes and leave",children:[At?a.jsx(kr,{size:16,className:p.spinner}):a.jsx(ug,{size:16}),"Save"]})]})]})}),Vn&&a.jsx("div",{className:`${Tt.overlay} ${Tt.unsavedOverlay}`,children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${Tt.modal} ${Tt.unsavedModal}`,"data-theme":l,children:[a.jsx("div",{className:`tf-modal-header ${Tt.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${Tt.unsavedTitle}`,children:[a.jsx(yd,{size:20}),"Date Warning"]})}),a.jsxs("div",{className:`${Tt.form} ${Tt.unsavedContent}`,children:[a.jsx("p",{className:Tt.unsavedText,children:"Due date is before scheduled date."}),a.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",Vn.dueDate," · Scheduled: ",Vn.scheduledDate]})]}),a.jsxs("div",{className:`${Tt.formActions} ${Tt.unsavedActions}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:$a,children:"Go Back"}),a.jsx("button",{className:p.submitBtn,onClick:kn,children:"Save Anyway"})]})]})})]})}const oD="_accountMenuWrap_1mocf_1",iD="_avatarBtn_1mocf_5",cD="_avatarBadge_1mocf_9",lD="_avatarImage_1mocf_24",dD="_avatarIcon_1mocf_30",uD="_accountMenu_1mocf_1",mD="_accountMenuItem_1mocf_48",pD="_accountMenuItemActive_1mocf_68",fD="_accountMenuSection_1mocf_73",hD="_accountMenuSectionLabel_1mocf_79",gD="_accountMenuMeta_1mocf_88",yD="_accountMenuHint_1mocf_93",kD="_accountIdentityEmail_1mocf_99",vD="_accountIdentityBlock_1mocf_104",SD="_accountIdentityMetaLine_1mocf_109",wD="_accountIdentityMetaAction_1mocf_116",bD="_accountIdentityMetaValue_1mocf_125",_D="_accountIdentityMetaLabel_1mocf_130",CD="_accountMenuError_1mocf_159",AD="_accountHubCard_1mocf_165",xD="_profileAvatarEditor_1mocf_172",ID="_profileEditLayout_1mocf_178",TD="_profileFieldStack_1mocf_185",RD="_profileFieldLabel_1mocf_191",mt={accountMenuWrap:oD,avatarBtn:iD,avatarBadge:cD,avatarImage:lD,avatarIcon:dD,accountMenu:uD,accountMenuItem:mD,accountMenuItemActive:pD,accountMenuSection:fD,accountMenuSectionLabel:hD,accountMenuMeta:gD,accountMenuHint:yD,accountIdentityEmail:kD,accountIdentityBlock:vD,accountIdentityMetaLine:SD,accountIdentityMetaAction:wD,accountIdentityMetaValue:bD,accountIdentityMetaLabel:_D,accountMenuError:CD,accountHubCard:AD,profileAvatarEditor:xD,profileEditLayout:ID,profileFieldStack:TD,profileFieldLabel:RD},jD="_authBlockedBanner_1virb_1",ND="_loginView_1virb_10",PD="_loginCard_1virb_20",MD="_loginCloseBtn_1virb_34",ED="_loginLogo_1virb_56",DD="_authBrandRow_1virb_62",LD="_setupHeaderRow_1virb_68",BD="_runtimeIconBadge_1virb_75",WD="_loginTitle_1virb_94",FD="_loginTitleAccent_1virb_105",OD="_loginSubtitle_1virb_109",$D="_loginError_1virb_115",UD="_loginField_1virb_121",zD="_loginFieldLabel_1virb_126",HD="_loginInput_1virb_133",GD="_loginPrimaryBtn_1virb_149",VD="_authPrimaryActions_1virb_154",qD="_registerConsent_1virb_159",KD="_registerConsentLink_1virb_167",ZD="_authModeSwitch_1virb_177",YD="_authModeSwitchLink_1virb_184",JD="_authModeLinks_1virb_199",QD="_authSecondaryActions_1virb_207",XD="_authModeLink_1virb_199",eL="_optionGrid_1virb_236",tL="_optionGroup_1virb_242",aL="_optionRow_1virb_247",nL="_inlineHint_1virb_254",rL="_actionRowEnd_1virb_260",sL="_oauthProviders_1virb_267",oL="_oauthDivider_1virb_274",iL="_oauthButtons_1virb_290",cL="_oauthButton_1virb_290",fe={authBlockedBanner:jD,loginView:ND,loginCard:PD,loginCloseBtn:MD,loginLogo:ED,authBrandRow:DD,setupHeaderRow:LD,runtimeIconBadge:BD,loginTitle:WD,loginTitleAccent:FD,loginSubtitle:OD,loginError:$D,loginField:UD,loginFieldLabel:zD,loginInput:HD,loginPrimaryBtn:GD,authPrimaryActions:VD,registerConsent:qD,registerConsentLink:KD,authModeSwitch:ZD,authModeSwitchLink:YD,authModeLinks:JD,authSecondaryActions:QD,authModeLink:XD,optionGrid:eL,optionGroup:tL,optionRow:aL,inlineHint:nL,actionRowEnd:rL,oauthProviders:sL,oauthDivider:oL,oauthButtons:iL,oauthButton:cL};function lL(e={x:0,y:0}){const[t,n]=r.useState(e),[s,o]=r.useState(!1),[l,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-l.x,_=g.clientY-l.y;_<-d&&(_=-d),n({x:v,y:_})}},[s,l,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:n}}function Ws({isOpen:e,onClose:t,title:n,children:s,footer:o,size:l="md",theme:i=rm,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}=lL();if(r.useEffect(()=>{const D=q=>{q.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 C={sm:Tt.modalSizeSm,md:Tt.modalSizeMd,mdWide:Tt.modalSizeMdWide,lg:Tt.modalSizeLg,xl:Tt.modalSizeXl,full:Tt.modalSizeFull};return Yi.createPortal(a.jsx("div",{className:`${Tt.overlay} ${d||""} ${Tt.overlayHighZ}`,ref:h,onClick:D=>{S&&D.target===h.current&&t()},children:a.jsxs("div",{ref:I,className:`tf-surface-modal tf-modal-shell ${Tt.modal} tf-scrollbar-scope ${C[l]} ${y?Tt.draggableModal:""} ${k?Tt.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:[a.jsxs("div",{className:`tf-modal-header ${y?Tt.draggableHeader:""}`,onMouseDown:y?_:void 0,style:{cursor:y?v?"grabbing":"grab":"default"},children:[a.jsx("div",{className:"tf-modal-title",children:n}),a.jsxs("div",{className:Tt.headerActions,children:[m,a.jsx("button",{className:"tf-control-icon",onClick:t,title:"Close",children:a.jsx(nc,{size:20})})]})]}),a.jsx("div",{className:Tt.modalContent,children:s}),o&&a.jsx("div",{className:`${Tt.formActions} ${Tt.modalFooter}`,children:o})]})}),document.body)}const dL="_modalBody_1t87j_1",uL="_mutedText_1t87j_5",mL="_sectionText_1t87j_10",pL="_sectionTextSpaced_1t87j_15",fL="_sectionTextTop_1t87j_20",hL="_errorText_1t87j_25",gL="_inlineFieldLabel_1t87j_29",yL="_wrapRow_1t87j_35",kL="_actionRowEnd_1t87j_42",vL="_modalActionsEnd_1t87j_50",SL="_helpIntro_1t87j_56",wL="_supportEmailRow_1t87j_61",bL="_supportEmailAddress_1t87j_68",_L="_supportEmailBtn_1t87j_80",CL="_supportPanel_1t87j_86",AL="_supportPanelHeader_1t87j_92",xL="_supportRouteList_1t87j_104",IL="_supportRouteBtn_1t87j_110",TL="_memberRow_1t87j_114",RL="_memberTitle_1t87j_120",jL="_memberActions_1t87j_124",NL="_selectRole_1t87j_131",PL="_selectPermission_1t87j_135",ML="_inviteRow_1t87j_139",EL="_listHeading_1t87j_143",DL="_auditList_1t87j_148",LL="_auditPager_1t87j_154",BL="_labelFixed_1t87j_161",lt={modalBody:dL,mutedText:uL,sectionText:mL,sectionTextSpaced:pL,sectionTextTop:fL,errorText:hL,inlineFieldLabel:gL,wrapRow:yL,actionRowEnd:kL,modalActionsEnd:vL,helpIntro:SL,supportEmailRow:wL,supportEmailAddress:bL,supportEmailBtn:_L,supportPanel:CL,supportPanelHeader:AL,supportRouteList:xL,supportRouteBtn:IL,memberRow:TL,memberTitle:RL,memberActions:jL,selectRole:NL,selectPermission:PL,inviteRow:ML,listHeading:EL,auditList:DL,auditPager:LL,labelFixed:BL};function WL({isOpen:e,theme:t,onClose:n,onConfirm:s}){return a.jsx(Ws,{isOpen:e,onClose:n,title:"New Workspace",size:"sm",theme:t,draggable:!0,footer:a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:p.cancelBtn,onClick:n,children:"Cancel"}),a.jsx("button",{type:"button",className:p.submitBtn,onClick:s,children:"Start Setup"})]}),children:a.jsx("div",{className:`${Tt.form} ${lt.modalBody}`,children:a.jsx("p",{className:lt.sectionText,children:"Create and configure a new workspace."})})})}const FL=new Set(["active","trialing","grace"]),Bh={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."},Hu={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 ac(e){return String(e||"").trim()}function Iy(e){return ac(e).toLowerCase()}function OL(e){return ac(e).toLowerCase()}function $L(e){return!!(ac(e?.stripeCustomerId)||ac(e?.stripeSubscriptionId))}function UL(e){const t=ac(e?.trialEnd||e?.effectiveUntil);if(t){const n=new Date(t);if(!Number.isNaN(n.getTime()))return n.getTime()<=Date.now()?"Your trial end date has passed. Billing status is updating.":`Your trial is active through ${n.toLocaleString()}.`}return"Your trial is active. Continue to Taskforce or manage billing anytime."}function zL(e){return FL.has(Iy(e))}function Kp(e,t){const n=Iy(e?.entitlementState),s=OL(e?.gate||t),o=ac(e?.billingConflictCode).toUpperCase(),l=ac(e?.message),i=zL(n),d=$L(e);return o==="CHECKOUT_SESSION_EXPIRED"?{entitlementState:n||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:Bh.CHECKOUT_SESSION_EXPIRED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:o==="CHECKOUT_SESSION_SUPERSEDED"?{entitlementState:n||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:Bh.CHECKOUT_SESSION_SUPERSEDED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:n==="trialing"?{entitlementState:n,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:UL(e),primaryAction:d?"manage_billing":"none",primaryLabel:d?"Manage Billing":null,showManageBilling:d,markCurrentPlan:!0}:i?{entitlementState:n||null,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:l||null,primaryAction:"none",primaryLabel:null,showManageBilling:d,markCurrentPlan:!0}:n==="suspended"?{entitlementState:n,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}:n==="canceled"?{entitlementState:n,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}:n==="pending_plan_selection"||e?.planSelectionRequired===!0||s==="plan_selection_required"?{entitlementState:n||"pending_plan_selection",gate:s||"plan_selection_required",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:l||Hu.planSelectionRequired,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:n==="checkout_pending"||s==="checkout_pending"?{entitlementState:n||"checkout_pending",gate:s||"checkout_pending",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:l||Hu.checkoutPending,primaryAction:"open_plans",primaryLabel:"Open Plans",showManageBilling:d,markCurrentPlan:!1}:s==="misconfigured"?{entitlementState:n||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Hu.misconfigured,primaryAction:"none",primaryLabel:null,showManageBilling:!1,markCurrentPlan:!1}:s==="missing_entitlement"?{entitlementState:n||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Hu.missingEntitlement,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:{entitlementState:n||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:l?"error":"info",message:l||null,primaryAction:"none",primaryLabel:null,showManageBilling:d,markCurrentPlan:!1}}const Zp=12,HL=new Set(["12345678","123456789","1234567890","admin123","changeme","letmein","letmein123","password","password1","password12","password123","password1234","qwerty","qwerty123","welcome","welcome123"]),GL=e=>String(e||"").trim().toLowerCase().replace(/[^a-z0-9]/g,"");function VL(e){const t=new Set,n=String(e?.email||"").trim().toLowerCase(),s=String(e?.displayName||"").trim().toLowerCase();if(n.includes("@")){const o=n.split("@")[0]||"",l=o.replace(/[^a-z0-9]/g,"");l.length>=4&&t.add(l);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 Ty(){return[`Use at least ${Zp} characters.`,"Avoid common passwords or obvious patterns.","Do not include your email or display name."]}function Ry(e,t){const n=String(e||"");if(!n)return{ok:!1,code:"PASSWORD_REQUIRED",message:"Password is required."};if(n.length<Zp)return{ok:!1,code:"PASSWORD_TOO_SHORT",message:`Password must be at least ${Zp} characters.`};const s=GL(n);return HL.has(s)?{ok:!1,code:"PASSWORD_TOO_COMMON",message:"Choose a less common password."}:VL(t).some(l=>s.includes(l))?{ok:!1,code:"PASSWORD_CONTAINS_PERSONAL_INFO",message:"Password cannot contain your email or display name."}:{ok:!0}}function qL({isOpen:e,theme:t,runtimeMode:n,authRequiredForApi:s,isAuthenticated:o,hasAuthIdentity:l,authIdentityLabel:i,billingLoading:d,billingError:m,billingActionError:y,billingNotice:k,billingActionBusy:S,billingIntervalChoice:h,accountProfileSummary:g,currentWorkspaceId:v,canOpenTeamManagement:_,canManageWorkspaceSync:I,workspaceCloudSyncEnabled:C,syncStatusLabel:D,workspaceSyncError:q,syncControlBusy:B,cloudAuthEnabled:X,availableAuthProviders:me,onFetchLoginMethods:ke,onUnlinkLoginMethod:le,onAddPassword:O,onLinkProvider:A,onClose:de,onOpenWorkspaceAudit:ge,onBillingIntervalChange:Y,onRefreshBilling:P,onUpdateInterval:H,onManageBilling:ue,onStartCheckout:ye,onToggleWorkspaceSync:V,onOpenHelp:Me}){const _e=Kp(g),re=Ty(),oe=_e.message,Ie=_e.primaryLabel||"Start Checkout",Ee=String(g?.planName||g?.planId||"n/a").trim()||"n/a",je=()=>{if(_e.primaryAction==="manage_billing"){ue();return}ye()},[Pe,K]=r.useState([]),[x,b]=r.useState(!1),[R,F]=r.useState(null),[Q,M]=r.useState(null),[$,be]=r.useState(null),[U,se]=r.useState(!1),[pe,z]=r.useState(""),[ne,ie]=r.useState(!1),[Re,Te]=r.useState(null),[De,Oe]=r.useState(!1);r.useEffect(()=>{!e||!o||!X||(b(!0),F(null),ke().then(Qe=>{b(!1),Qe.success&&Qe.methods?K(Qe.methods):F(Qe.error||"Failed to load login methods.")}))},[e,o,X,ke]);const vt=async Qe=>{M(Qe),be(null);const Rt=await le(Qe);M(null),Rt.success?K(ee=>ee.filter(ze=>ze.provider!==Qe)):be(Rt.error||"Unlink failed.")},st=async()=>{const Qe=Ry(pe);if(!Qe.ok){Te(Qe.message||"Password does not meet the password policy.");return}ie(!0),Te(null);const Rt=await O(pe);if(ie(!1),!Rt.success)Te(Rt.error||"Failed to add password.");else{Oe(!0),z(""),se(!1);const ee=await ke();ee.success&&ee.methods&&K(ee.methods)}},kt={password:"Email & Password",google:"Google",github:"GitHub",apple:"Apple"},Ye=new Set(Pe.map(Qe=>Qe.provider)),Ct=Ye.has("password"),dt=me.filter(Qe=>Qe!=="password"&&!Ye.has(Qe));return a.jsx(Ws,{isOpen:e,onClose:de,title:"Account Hub",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${Tt.form} ${lt.modalBody}`,children:[a.jsx("p",{className:lt.mutedText,children:"Manage sign in, profile, and workspace controls from one place."}),a.jsxs("div",{className:mt.accountHubCard,children:[a.jsx("strong",{children:"Authentication"}),a.jsx("p",{className:lt.sectionText,children:n==="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."}),a.jsx("p",{className:lt.sectionTextSpaced,children:o?l?a.jsxs(a.Fragment,{children:["Signed in as ",a.jsx("span",{className:mt.accountIdentityEmail,children:i})]}):"Signed in":"Signed in as: not signed in"}),n==="cloud"&&s&&!o&&a.jsx("p",{className:lt.sectionTextTop,children:"Use the `/login` screen to sign in."})]}),o&&X&&a.jsxs("div",{className:mt.accountHubCard,children:[a.jsx("strong",{children:"Login Methods"}),x&&a.jsx("p",{className:lt.sectionText,children:"Loading..."}),R&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:R}),$&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:$}),De&&a.jsx("p",{className:lt.sectionText,style:{color:"var(--color-success, #4ade80)"},children:"Password login added."}),!x&&Pe.length>0&&a.jsx("div",{style:{marginTop:8,display:"grid",gap:6},children:Pe.map(Qe=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[a.jsxs("span",{className:lt.sectionText,children:[a.jsx("strong",{children:kt[Qe.provider]||Qe.provider}),Qe.providerEmail?a.jsxs(a.Fragment,{children:[" · ",a.jsx("span",{className:mt.accountMenuMeta,children:Qe.providerEmail})]}):null]}),Pe.length>1&&a.jsx("button",{className:p.cancelBtn,style:{fontSize:11,padding:"2px 8px"},disabled:Q===Qe.provider,onClick:()=>vt(Qe.provider),children:Q===Qe.provider?"Removing…":"Remove"})]},Qe.provider))}),!x&&!Ct&&!U&&a.jsx("div",{className:lt.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,onClick:()=>{se(!0),Oe(!1),Te(null)},children:"Add Password Login"})}),U&&a.jsxs("div",{style:{marginTop:10,display:"grid",gap:6},children:[a.jsxs("label",{className:mt.accountMenuMeta,style:{display:"block"},children:["New password",a.jsx("input",{type:"password",className:p.input,placeholder:"Use 12+ characters",value:pe,onChange:Qe=>z(Qe.target.value),disabled:ne,style:{marginTop:4,display:"block",width:"100%"},autoComplete:"new-password"})]}),a.jsx("p",{className:mt.accountMenuMeta,style:{margin:0},children:re.join(" ")}),Re&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:Re}),a.jsxs("div",{className:lt.actionRowEnd,children:[a.jsx("button",{className:p.cancelBtn,onClick:()=>{se(!1),z(""),Te(null)},disabled:ne,children:"Cancel"}),a.jsx("button",{className:p.submitBtn,onClick:st,disabled:ne||!pe,children:ne?"Saving…":"Save Password"})]})]}),!x&&dt.length>0&&a.jsxs("div",{style:{marginTop:10},children:[a.jsx("p",{className:mt.accountMenuMeta,style:{marginBottom:6},children:"Link another account:"}),a.jsx("div",{className:fe.oauthButtons,children:dt.map(Qe=>a.jsx("button",{className:fe.oauthButton,onClick:()=>A(Qe),children:kt[Qe]||Qe},Qe))})]})]}),a.jsxs("div",{className:mt.accountHubCard,children:[a.jsx("strong",{children:"Profile & Account"}),a.jsx("p",{className:lt.sectionText,children:"Profile editing and account preferences will live here."})]}),a.jsxs("div",{className:mt.accountHubCard,children:[a.jsx("strong",{children:"Billing"}),o?n!=="cloud"?a.jsx("p",{className:lt.sectionText,children:"Billing remains cloud-backed in local runtime and uses your connected cloud account."}):a.jsxs(a.Fragment,{children:[d&&a.jsx("p",{className:lt.sectionTextSpaced,children:"Loading billing status..."}),m&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:m}),y&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:y}),k&&a.jsx("p",{className:lt.errorText,children:k}),oe&&a.jsx("p",{className:lt.sectionText,children:oe}),a.jsxs("p",{className:lt.sectionTextSpaced,children:["Plan: ",a.jsx("code",{children:Ee})," · ","Entitlement: ",a.jsx("code",{children:String(g?.entitlementState||"n/a")})]}),a.jsxs("p",{className:lt.sectionText,children:["Stripe status: ",a.jsx("code",{children:String(g?.stripeStatus||"n/a")}),g?.effectiveUntil?` · Effective until ${new Date(g.effectiveUntil).toLocaleString()}`:""]}),a.jsx("div",{className:lt.wrapRow,children:a.jsxs("label",{className:`${mt.accountMenuMeta} ${lt.inlineFieldLabel}`,children:["Interval",a.jsxs("select",{className:p.input,value:h,onChange:Qe=>Y(Qe.target.value==="year"?"year":"month"),disabled:S,children:[a.jsx("option",{value:"month",children:"Monthly"}),a.jsx("option",{value:"year",children:"Yearly"})]})]})}),a.jsxs("div",{className:lt.actionRowEnd,children:[a.jsx("button",{className:p.cancelBtn,onClick:P,disabled:S||d,children:"Refresh Billing"}),a.jsx("button",{className:p.cancelBtn,onClick:H,disabled:S||!g?.stripeSubscriptionId,children:"Update Interval"}),a.jsx("button",{className:p.cancelBtn,onClick:ue,disabled:S||!g?.stripeCustomerId,children:"Manage Billing"}),a.jsx("button",{className:p.submitBtn,onClick:je,disabled:S||_e.primaryAction==="manage_billing"&&!g?.stripeCustomerId,children:S?"Working...":Ie})]})]}):a.jsx("p",{className:lt.sectionText,children:"Sign in to manage subscription billing."})]}),a.jsxs("div",{className:mt.accountHubCard,children:[a.jsx("strong",{children:"Workspace Audit Log"}),a.jsx("p",{className:lt.sectionText,children:"Audit entries are workspace-scoped for the active workspace, not global account history."}),a.jsxs("p",{className:lt.sectionText,children:["Active workspace: ",a.jsx("code",{children:v})]}),a.jsx("div",{className:lt.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,onClick:ge,disabled:!_,children:"Open Workspace Audit"})})]}),a.jsxs("div",{className:mt.accountHubCard,children:[a.jsx("strong",{children:"Workspace Cloud Sync"}),a.jsx("p",{className:lt.sectionText,children:I?C?`Enabled · ${D}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),q&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:q}),a.jsx("div",{className:lt.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,disabled:!I||B,onClick:()=>V(!C),children:C?"Disable Sync":"Enable Sync"})})]}),a.jsxs("div",{className:`${Tt.formActions} ${lt.modalActionsEnd}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:Me,children:"Help & Support"}),a.jsx("button",{className:p.submitBtn,onClick:de,children:"Close"})]})]})})}var Wh=(e,t,n,s,o,l)=>{if(l===0)e.rect(t,n,s,o);else{let i=s-l,d=o-l;e.translate(t,n),e.arc(l,l,l,Math.PI,Math.PI*1.5),e.lineTo(i,0),e.arc(i,l,l,Math.PI*1.5,Math.PI*2),e.lineTo(s,d),e.arc(i,d,l,Math.PI*2,Math.PI*.5),e.lineTo(l,o),e.arc(l,d,l,Math.PI*.5,Math.PI),e.closePath(),e.translate(-t,-n)}},KL=(e,t,n,s,o,l)=>{e.fillStyle=l;let i=s/3,d=o/3;e.fillRect(t,n,1,o),e.fillRect(i+t,n,1,o),e.fillRect(i*2+t,n,1,o),e.fillRect(i*3+t,n,1,o),e.fillRect(i*4+t,n,1,o),e.fillRect(t,n,s,1),e.fillRect(t,d+n,s,1),e.fillRect(t,d*2+n,s,1),e.fillRect(t,d*3+n,s,1),e.fillRect(t,d*4+n,s,1)},ZL=e=>!!e.match(/^\s*data:([a-z]+\/[a-z]+(;[a-z-]+=[a-z-]+)?)?(;base64)?,[a-z0-9!$&',()*+;=\-._~:@/?%\s]*\s*$/i),jy=(e,t)=>new Promise((n,s)=>{let o=new Image;o.addEventListener("load",()=>n(o)),o.addEventListener("error",s),!ZL(e)&&t&&(o.crossOrigin=t),o.src=e}),YL=e=>new Promise((t,n)=>{let s=new FileReader;s.addEventListener("load",o=>{try{if(!o?.target?.result)throw Error("No image data");t(jy(o.target.result))}catch(l){n(l)}}),s.readAsDataURL(e)}),JL=typeof File<"u",Fh=e=>Math.PI/180*e,Oh={x:.5,y:.5},QL=class{constructor(e){this.imageState=Oh,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:n,border:s}=this.config,o={width:0,height:0},[l,i]=this.getBorders(s);return this.isVertical()?(o.width=t,o.height=e):(o.width=e,o.height=t),o.width+=l*2,o.height+=i*2,{canvas:o,rotate:n,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},n=1/this.config.scale*this.getXScale(),s=1/this.config.scale*this.getYScale(),o={x:t.x-n/2,y:t.y-s/2,width:n,height:s},l=0,i=1-o.width,d=0,m=1-o.height;return(this.config.disableBoundaryChecks||n>1||s>1)&&(l=-o.width,i=1,d=-o.height,m=1),{...o,x:Math.max(l,Math.min(o.x,i)),y:Math.max(d,Math.min(o.y,m))}}getInitialSize(e,t){let n,s,o=this.getDimensions();return o.height/o.width>t/e?(n=o.height,s=n/t*e):(s=o.width,n=s/e*t),{height:n,width:s}}async loadImage(e){let t;if(JL&&e instanceof File)t=await YL(e);else if(typeof e=="string")t=await jy(e,this.config.crossOrigin);else throw Error("Invalid image source");let n={...this.getInitialSize(t.width,t.height),resource:t,x:.5,y:.5};return this.imageState=n,n}clearImage(){this.imageState=Oh}calculatePosition(e=this.imageState,t){let[n,s]=this.getBorders(t);if(!e.width||!e.height)throw Error("Image dimension is unknown.");let o=this.getCroppingRect(),l=e.width*this.config.scale,i=e.height*this.config.scale,d=-o.x*l,m=-o.y*i;return this.isVertical()?(d+=s,m+=n):(d+=n,m+=s),{x:d,y:m,height:i,width:l}}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,n=this.getDimensions(),[s,o]=this.getBorders(n.border),l=n.canvas.height,i=n.canvas.width;t=Math.max(t,0),t=Math.min(t,i/2-s,l/2-o),e.beginPath(),Wh(e,s,o,i-s*2,l-o*2,t),e.rect(i,0,-i,l),e.fill("evenodd"),this.config.borderColor&&(e.strokeStyle="rgba("+this.config.borderColor.slice(0,4).join(",")+")",e.lineWidth=1,e.beginPath(),Wh(e,s+.5,o+.5,i-s*2-1,l-o*2-1,t),e.stroke()),this.config.showGrid&&KL(e,s,o,i-s*2,l-o*2,this.config.gridColor),e.restore()}paintImage(e,t,n,s=this.pixelRatio){if(!t.resource)return;let o=this.calculatePosition(t,n);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 n=document.createElement("canvas");this.isVertical()?(n.width=Math.round(e.height),n.height=Math.round(e.width)):(n.width=Math.round(e.width),n.height=Math.round(e.height));let s=n.getContext("2d");if(!s)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return s.translate(n.width/2,n.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(n.width/2),-(n.height/2)),this.isVertical()&&s.translate((n.width-n.height)/2,(n.height-n.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,n.width,n.height)),s.drawImage(t.resource,-e.x,-e.y),n}getImageScaledToCanvas(){let e=this.getDimensions(),t=this.imageState,n=document.createElement("canvas");if(this.isVertical()?(n.width=e.height,n.height=e.width):(n.width=e.width,n.height=e.height),!t.resource)return n;let s=n.getContext("2d");if(!s)return n;let o=this.calculatePosition(t,0);return s.save(),s.translate(n.width/2,n.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(n.width/2),-(n.height/2)),this.isVertical()&&s.translate((n.width-n.height)/2,(n.height-n.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,n.width,n.height)),s.drawImage(t.resource,o.x,o.y,o.width,o.height),s.restore(),n}calculateDragPosition(e,t,n,s){let o=n-e,l=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(Fh(k)),h=Math.sin(Fh(k)),g=m+o*S+l*h,v=y+-o*h+l*S,_=1/this.config.scale*this.getXScale(),I=1/this.config.scale*this.getYScale();return{x:g/i+_/2,y:v/d+I/2}}},$h=()=>{},XL=()=>{let e=!1;try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",$h,t),window.removeEventListener("test",$h,t)}catch{e=!1}return e},Ny=r.forwardRef((e,t)=>{let{scale:n=1,rotate:s=0,border:o=25,borderRadius:l=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:C,onLoadStart:D,onLoadFailure:q,onLoadSuccess:B,onImageReady:X,onImageChange:me,onMouseUp:ke,onMouseMove:le,onPositionChange:O,borderColor:A,style:de}=e,ge=r.useRef(null),Y=r.useRef(new QL({width:i,height:d,border:o,borderRadius:l,scale:n,rotate:s,color:m,backgroundColor:I,borderColor:A,showGrid:y,gridColor:k,disableBoundaryChecks:S,disableHiDPIScaling:h,disableCanvasRotation:g,crossOrigin:C})),P=r.useRef(!1),H=r.useRef(void 0),ue=r.useRef(void 0),[ye,V]=r.useState(!1),[Me,_e]=r.useState(!1),[re,oe]=r.useState(Y.current.getImageState()),Ie=r.useRef(ke);Ie.current=ke;let Ee=r.useRef(le);Ee.current=le;let je=r.useRef(O);je.current=O,r.useEffect(()=>{Y.current.updateConfig({width:i,height:d,border:o,borderRadius:l,scale:n,rotate:s,color:m,backgroundColor:I,borderColor:A,showGrid:y,gridColor:k,disableBoundaryChecks:S,disableHiDPIScaling:h,disableCanvasRotation:g,crossOrigin:C})},[i,d,o,l,n,s,m,I,A,y,k,S,h,g,C]);let Pe=r.useCallback(()=>{if(!ge.current)throw Error("No canvas found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return ge.current},[]),K=r.useCallback(()=>{let se=Pe().getContext("2d");if(!se)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return se},[Pe]),x=r.useCallback(async se=>{_e(!0),D?.();try{let pe=await Y.current.loadImage(se);P.current=!1,V(!1),oe(pe),X?.(),B?.(pe)}catch{q?.()}finally{_e(!1)}},[D,X,B,q]),b=r.useCallback(()=>{let se=Pe();K().clearRect(0,0,se.width,se.height),Y.current.clearImage(),oe(Y.current.getImageState())},[Pe,K]),R=r.useCallback(()=>{let se=K(),pe=Pe();se.clearRect(0,0,pe.width,pe.height),Y.current.paint(se),Y.current.paintImage(se,re,o)},[K,Pe,re,o,i,d,l,n,s,m,I,A,y,k,S,h,g,C]),F=r.useCallback(se=>{se.preventDefault(),P.current=!0,H.current=void 0,ue.current=void 0,V(!0)},[]),Q=r.useCallback(()=>{P.current=!0,H.current=void 0,ue.current=void 0,V(!0)},[]);r.useImperativeHandle(t,()=>({getImage:()=>Y.current.getImage(),getImageScaledToCanvas:()=>Y.current.getImageScaledToCanvas(),getCroppingRect:()=>Y.current.getCroppingRect()}),[]),r.useEffect(()=>{let se=K();v&&x(v),Y.current.paint(se);let pe=ie=>{if(!P.current)return;ie.cancelable&&ie.preventDefault();let Re="targetTouches"in ie?ie.targetTouches[0].pageX:ie.clientX,Te="targetTouches"in ie?ie.targetTouches[0].pageY:ie.clientY,De=H.current,Oe=ue.current;if(H.current=Re,ue.current=Te,De!==void 0&&Oe!==void 0){let vt=Y.current.getImageState();if(vt.width&&vt.height){let st=Y.current.calculateDragPosition(Re,Te,De,Oe);je.current?.(st);let kt={...vt,...st};Y.current.setImageState(kt),oe(kt)}}Ee.current?.(ie)},z=()=>{P.current&&(P.current=!1,V(!1),Ie.current?.())},ne=XL()?{passive:!1}:!1;return document.addEventListener("mousemove",pe,ne),document.addEventListener("mouseup",z,ne),document.addEventListener("touchmove",pe,ne),document.addEventListener("touchend",z,ne),()=>{document.removeEventListener("mousemove",pe,!1),document.removeEventListener("mouseup",z,!1),document.removeEventListener("touchmove",pe,!1),document.removeEventListener("touchend",z,!1)}},[]),r.useEffect(()=>{v?x(v):!v&&re.x!==.5&&re.y!==.5&&b()},[v,i,d,I]),r.useEffect(()=>{R()},[R]),r.useEffect(()=>{if(!Me)return;let se=ge.current;if(!se)return;let pe=se.getContext("2d");if(!pe)return;let z,ne=performance.now(),ie=Re=>{let Te=(Re-ne)/1e3,De=.03+Math.sin(Te*2.5)*.02+.02;pe.save(),pe.clearRect(0,0,se.width,se.height),pe.fillStyle=`rgba(255,255,255,${De})`,pe.fillRect(0,0,se.width,se.height),pe.restore(),z=requestAnimationFrame(ie)};return z=requestAnimationFrame(ie),()=>cancelAnimationFrame(z)},[Me]);let M=r.useRef({image:v,width:i,height:d,position:_,scale:n,rotate:s,imageX:re.x,imageY:re.y});r.useEffect(()=>{let se=M.current;(se.image!==v||se.width!==i||se.height!==d||se.position!==_||se.scale!==n||se.rotate!==s||se.imageX!==re.x||se.imageY!==re.y)&&(me?.(),M.current={image:v,width:i,height:d,position:_,scale:n,rotate:s,imageX:re.x,imageY:re.y})},[v,i,d,_,n,s,re.x,re.y,me]);let $=Y.current.getDimensions(),be=Y.current.getPixelRatio(),U={width:$.canvas.width,height:$.canvas.height,cursor:ye?"grabbing":"grab",touchAction:"none",maxWidth:"none",maxHeight:"none"};return Ue.createElement("canvas",{width:$.canvas.width*be,height:$.canvas.height*be,onMouseDown:F,onTouchStart:Q,style:{...U,...de},ref:ge})});Ny.displayName="AvatarEditor";const eB="_avatarManagerBody_1bfwv_1",tB="_editorPanel_1bfwv_7",aB="_editorFrame_1bfwv_13",nB="_gifPreviewImage_1bfwv_21",rB="_emptyPreview_1bfwv_28",sB="_controlPanel_1bfwv_41",oB="_zoomField_1bfwv_47",iB="_zoomSlider_1bfwv_52",cB="_actionGrid_1bfwv_57",lB="_fileInput_1bfwv_63",dB="_messageStack_1bfwv_67",Ls={avatarManagerBody:eB,editorPanel:tB,editorFrame:aB,gifPreviewImage:nB,emptyPreview:rB,controlPanel:sB,zoomField:oB,zoomSlider:iB,actionGrid:cB,fileInput:lB,messageStack:dB},Cp=512,uB=48,Gu=512;function Uh(e,t,n){return new Promise(s=>{e.toBlob(s,t,n)})}function mB(e,t){const n=String(e).trim()||"avatar",s=n.lastIndexOf(".");return s<=0?`${n}${t}`:`${n.slice(0,s)}${t}`}async function pB(e,t){const n=e.getImageScaledToCanvas(),s=document.createElement("canvas");s.width=Gu,s.height=Gu;const o=s.getContext("2d");if(!o)throw new Error("Image editing requires a 2D canvas context.");o.drawImage(n,0,0,Gu,Gu);const i=await Uh(s,"image/webp",.9)||await Uh(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],mB(t,m),{type:d,lastModified:Date.now()})}function fB({isOpen:e,theme:t,title:n="Edit Photo",currentImageUrl:s,editorImageUrl:o="",fallbackInitial:l,accept:i,busy:d,hasPendingImage:m,canRemove:y,error:k,notice:S,onClose:h,onApplyImage:g,onRemoveImage:v,onDiscardPendingImage:_}){const I=r.useRef(null),C=r.useRef(null),[D,q]=r.useState(null),[B,X]=r.useState(""),[me,ke]=r.useState(1.1),[le,O]=r.useState(null),[A,de]=r.useState(null);r.useEffect(()=>{e||(q(null),X(""),ke(1.1),O(null),de(null))},[e]),r.useEffect(()=>{if(!D){X("");return}const re=URL.createObjectURL(D);return X(re),()=>URL.revokeObjectURL(re)},[D]);const ge=B||o||s,Y=D?.name||"avatar",P=String(l||"").trim().charAt(0).toUpperCase(),H=le||k,ue=A||S,ye=r.useCallback(re=>{if(O(null),de(null),!!re){if(!re.type.startsWith("image/")){O("Profile photo must be an image file.");return}re.type==="image/gif"&&de("Animated GIFs will upload without repositioning."),q(re),ke(1.1)}},[]),V=r.useCallback(async()=>{O(null);const re=I.current;if(D?.type==="image/gif"){await g(D)&&h();return}if(!re||!ge){O("Choose a profile photo first.");return}try{const oe=await pB(re,Y);await g(oe,D)&&h()}catch(oe){O(oe instanceof Error?oe.message:"Unable to prepare profile photo.")}},[ge,g,h,D,Y]),Me=D?.type==="image/gif"||!!ge,_e=r.useMemo(()=>a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:p.secondaryButton,onClick:h,disabled:d,children:"Cancel"}),a.jsx("button",{type:"button",className:p.primaryUpdateBtn,onClick:()=>{V()},disabled:d||!Me,children:d?"Applying...":"Apply Photo"})]}),[d,Me,V,h]);return a.jsx(Ws,{isOpen:e,onClose:h,title:n,size:"md",theme:t,draggable:!0,footer:_e,children:a.jsxs("div",{className:Ls.avatarManagerBody,children:[a.jsxs("div",{className:Ls.editorPanel,children:[a.jsx("div",{className:`tf-surface-inset ${Ls.editorFrame}`,children:D?.type==="image/gif"&&B?a.jsx("img",{src:B,alt:"",className:Ls.gifPreviewImage}):ge?a.jsx(Ny,{ref:I,image:ge,width:Cp,height:Cp,border:uB,borderRadius:Cp/2,scale:me,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}):a.jsx("div",{className:Ls.emptyPreview,"aria-hidden":"true",children:P})}),a.jsxs("div",{className:Ls.controlPanel,children:[a.jsx("input",{ref:C,type:"file","aria-label":"Choose profile photo",accept:i,className:Ls.fileInput,onChange:re=>ye(re.target.files?.[0]||null),disabled:d}),a.jsxs("div",{className:Ls.actionGrid,children:[a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>C.current?.click(),disabled:d,children:[a.jsx(Lk,{size:16}),"Choose"]}),m&&_&&a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:_,disabled:d,children:[a.jsx(gd,{size:16}),"Discard"]}),y&&v&&a.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",onClick:v,disabled:d,children:[a.jsx(_m,{size:16}),"Remove"]})]}),a.jsxs("label",{className:`tf-field-stack ${Ls.zoomField}`,children:[a.jsx("span",{className:"tf-field-label",children:"Zoom"}),a.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:me,onChange:re=>ke(Number(re.target.value)),className:Ls.zoomSlider,disabled:d||!ge||D?.type==="image/gif"})]})]})]}),(H||ue)&&a.jsxs("div",{className:Ls.messageStack,children:[H&&a.jsx("p",{className:"tf-text-error",children:H}),ue&&!H&&a.jsx("p",{className:"tf-text-helper",children:ue})]})]})})}const hB="_editableAvatarButton_1ga39_1",gB="_editableAvatarImage_1ga39_47",yB="_editableAvatarFallback_1ga39_54",kB="_editableAvatarBadge_1ga39_65",Vu={editableAvatarButton:hB,editableAvatarImage:gB,editableAvatarFallback:yB,editableAvatarBadge:kB};function vB({label:e,imageUrl:t,fallback:n,accentColor:s,size:o=52,width:l,height:i,radius:d,editBadgeSize:m,editIconSize:y=16,disabled:k=!1,className:S="",onClick:h}){const g=String(t||"").trim(),v=l??o,_=i??o,I=typeof d=="number"?`${d}px`:d,C=typeof m=="number"?`${m}px`:m;return a.jsxs("button",{type:"button",className:`${Vu.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}:{},...C?{"--editable-avatar-badge-size":C}:{},...s?{"--editable-avatar-accent":s}:{}},children:[g?a.jsx("img",{src:g,alt:"",className:Vu.editableAvatarImage}):a.jsx("span",{className:Vu.editableAvatarFallback,children:n}),a.jsx("span",{className:Vu.editableAvatarBadge,"aria-hidden":"true",children:a.jsx(Bk,{size:y})})]})}function SB({isOpen:e,theme:t,onClose:n,onSave:s,displayName:o,email:l,avatarDisplayUrl:i,accountBadgeInitial:d,saveBusy:m,avatarBusy:y,saveError:k,saveNotice:S,onDisplayNameChange:h,onOpenAvatarManager:g}){return a.jsx(Ws,{isOpen:e,onClose:n,title:"Edit Profile",size:"sm",theme:t,draggable:!0,footer:a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:p.secondaryButton,onClick:n,disabled:m||y,children:"Cancel"}),a.jsx("button",{type:"button",className:p.primaryUpdateBtn,onClick:s,disabled:m||y||!o.trim(),children:m?"Saving...":"Save Profile"})]}),children:a.jsxs("div",{className:`${Tt.form} ${lt.modalBody}`,children:[a.jsxs("div",{className:mt.profileEditLayout,children:[a.jsx("div",{className:mt.profileAvatarEditor,children:a.jsx(vB,{label:"Edit profile photo",imageUrl:i,fallback:d,disabled:m||y,onClick:g})}),a.jsxs("div",{className:mt.profileFieldStack,children:[a.jsxs("label",{className:mt.profileFieldLabel,children:[a.jsx("span",{children:"Display name"}),a.jsx("input",{className:p.input,type:"text",value:o,onChange:v=>h(v.target.value),placeholder:"Display name",disabled:m})]}),a.jsxs("label",{className:mt.profileFieldLabel,children:[a.jsx("span",{children:"Email"}),a.jsx("input",{className:p.input,type:"email",value:l,readOnly:!0,disabled:!0})]})]})]}),k&&a.jsx("p",{className:`${fe.loginError} ${lt.errorText}`,children:k}),S&&!k&&a.jsx("p",{className:lt.errorText,children:S})]})})}const Yp="support@taskforcehq.ai";function qu(e){return String(e||"").trim()}function wB(e={}){const t=qu(e.workspaceName),n=qu(e.workspaceId),s=qu(e.accountLabel),o=qu(e.runtimeMode),l=[t?`Workspace: ${t}`:"",n?`Workspace ID: ${n}`:"",s?`Account: ${s}`:"",o?`Runtime: ${o}`:""].filter(Boolean),i=["Hi Taskforce team,","","I need help with:","",l.length>0?"Context:":"",...l,(l.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:${Yp}?${d.toString()}`}function bB({isOpen:e,theme:t,onClose:n,onOpenSettings:s,onOpenAccountHub:o,supportMailtoHref:l}){const[i,d]=r.useState("idle"),m=async()=>{try{await navigator.clipboard.writeText(Yp),d("copied"),window.setTimeout(()=>d("idle"),1600)}catch{d("failed"),window.setTimeout(()=>d("idle"),2200)}};return a.jsx(Ws,{isOpen:e,onClose:n,title:"Help & Support",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${Tt.form} ${lt.modalBody}`,children:[a.jsxs("div",{className:lt.helpIntro,children:[a.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."}),a.jsxs("div",{className:lt.supportEmailRow,children:[a.jsx("code",{className:lt.supportEmailAddress,children:Yp}),a.jsxs("button",{className:`${p.submitBtn} ${lt.supportEmailBtn}`,onClick:()=>{m()},type:"button",children:[i==="copied"?a.jsx(no,{size:16}):a.jsx(tf,{size:16}),i==="copied"?"Copied":i==="failed"?"Copy Failed":"Copy Email"]})]}),a.jsxs("a",{className:`${p.cancelBtn} ${lt.supportEmailBtn}`,href:l,children:[a.jsx(mg,{size:16}),"Open Email App"]})]}),a.jsxs("div",{className:`${lt.supportPanel} tf-surface-panel`,children:[a.jsxs("div",{className:lt.supportPanelHeader,children:[a.jsx(Wk,{size:16}),a.jsxs("div",{children:[a.jsx("h3",{className:"tf-heading-card",children:"Before you email"}),a.jsx("p",{className:"tf-text-secondary",children:"These are the fastest places to check for common workspace, account, and setup issues."})]})]}),a.jsxs("div",{className:lt.supportRouteList,children:[a.jsxs("button",{className:`${p.cancelBtn} ${lt.supportRouteBtn}`,onClick:s,children:[a.jsx(af,{size:15}),"Open Settings"]}),o&&a.jsxs("button",{className:`${p.cancelBtn} ${lt.supportRouteBtn}`,onClick:o,children:[a.jsx(Fk,{size:15}),"Open Account Hub"]})]})]}),a.jsx("div",{className:`${Tt.formActions} ${lt.modalActionsEnd}`,children:a.jsx("button",{className:p.cancelBtn,onClick:n,children:"Close"})})]})})}function _B({prompt:e,theme:t,onClose:n,onConfirm:s}){return a.jsx(Ws,{isOpen:!!e,onClose:n,title:"Date Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:a.jsxs("div",{className:`${p.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[a.jsx("p",{className:"tf-text-body",children:"Due date is before scheduled date."}),e&&a.jsxs("p",{className:"tf-text-helper",children:["Due: ",e.dueDate," · Scheduled: ",e.scheduledDate]}),a.jsxs("div",{className:p.formActions,children:[a.jsx("button",{className:p.cancelBtn,onClick:n,children:"Go Back"}),a.jsx("button",{className:p.submitBtn,onClick:s,children:"Save Anyway"})]})]})})}function CB({isOpen:e,theme:t,onClose:n,onConfirm:s}){return a.jsx(Ws,{isOpen:e,onClose:n,title:"Cloud Sync Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:a.jsxs("div",{className:`${p.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[a.jsx("p",{className:"tf-text-body",children:"Turning on cloud sync can renumber task, document, and image references to match the cloud workspace."}),a.jsxs("p",{className:"tf-text-helper",children:["Labels like ",a.jsx("code",{children:"T-12"}),", ",a.jsx("code",{children:"D-4"}),", and ",a.jsx("code",{children:"IMG-2"})," may change. Plain file attachments are not renumbered."]}),a.jsxs("div",{className:p.formActions,children:[a.jsx("button",{className:p.cancelBtn,onClick:n,children:"Go Back"}),a.jsx("button",{className:p.submitBtn,onClick:s,children:"Enable Sync Anyway"})]})]})})}const AB="_syncStatusModal_4pd1g_1",xB="_syncStatusTop_4pd1g_6",IB="_syncStatusMetaHeader_4pd1g_15",TB="_syncStatusHeaderInfo_4pd1g_22",RB="_syncToggle_4pd1g_43",jB="_syncStatusBadge_4pd1g_47",NB="_syncToggleControl_4pd1g_75",PB="_syncToggleControlEnabled_4pd1g_91",MB="_syncToggleControlDisabled_4pd1g_98",EB="_syncToggleControlBusy_4pd1g_102",DB="_syncToggleControlBlocked_4pd1g_107",LB="_syncToggleInput_4pd1g_112",BB="_syncToggleState_4pd1g_125",WB="_syncToggleStateOn_4pd1g_136",FB="_syncToggleStateOff_4pd1g_141",OB="_syncToggleThumb_4pd1g_146",$B="_syncStatusSummaryValue_4pd1g_173",UB="_syncStatusSummaryCompact_4pd1g_180",zB="_syncStatusRepairBanner_4pd1g_190",HB="_syncStatusRepairHeader_4pd1g_200",GB="_syncStatusRepairBadge_4pd1g_207",VB="_syncStatusRepairMeta_4pd1g_216",qB="_syncStatusRepairText_4pd1g_223",KB="_syncStatusLabel_4pd1g_257",ZB="_syncStatusSectionHeader_4pd1g_265",YB="_syncStatusCompactGrid_4pd1g_278",JB="_syncStatusCompactItem_4pd1g_284",QB="_syncStatusValue_4pd1g_295",XB="_syncStatusValueError_4pd1g_325",eW="_syncStatusActions_4pd1g_329",tW="_syncStatusPanel_4pd1g_336",aW="_syncStatusPanelHeader_4pd1g_346",nW="_syncStatusPanelMeta_4pd1g_353",rW="_syncStatusEventsList_4pd1g_375",sW="_syncStatusEventItem_4pd1g_384",oW="_syncStatusEventItemError_4pd1g_391",iW="_syncStatusEventItemMuted_4pd1g_396",cW="_syncStatusEventLine_4pd1g_401",lW="_syncStatusSecondaryActions_4pd1g_411",dW="_syncStatusPrimaryActions_4pd1g_425",uW="_syncStatusPrimaryActionSlot_4pd1g_432",mW="_syncStatusActionPlaceholder_4pd1g_440",nt={syncStatusModal:AB,syncStatusTop:xB,syncStatusMetaHeader:IB,syncStatusHeaderInfo:TB,syncToggle:RB,syncStatusBadge:jB,syncToggleControl:NB,syncToggleControlEnabled:PB,syncToggleControlDisabled:MB,syncToggleControlBusy:EB,syncToggleControlBlocked:DB,syncToggleInput:LB,syncToggleState:BB,syncToggleStateOn:WB,syncToggleStateOff:FB,syncToggleThumb:OB,syncStatusSummaryValue:$B,syncStatusSummaryCompact:UB,syncStatusRepairBanner:zB,syncStatusRepairHeader:HB,syncStatusRepairBadge:GB,syncStatusRepairMeta:VB,syncStatusRepairText:qB,syncStatusLabel:KB,syncStatusSectionHeader:ZB,syncStatusCompactGrid:YB,syncStatusCompactItem:JB,syncStatusValue:QB,syncStatusValueError:XB,syncStatusActions:eW,syncStatusPanel:tW,syncStatusPanelHeader:aW,syncStatusPanelMeta:nW,syncStatusEventsList:rW,syncStatusEventItem:sW,syncStatusEventItemError:oW,syncStatusEventItemMuted:iW,syncStatusEventLine:cW,syncStatusSecondaryActions:lW,syncStatusPrimaryActions:dW,syncStatusPrimaryActionSlot:uW,syncStatusActionPlaceholder:mW};function pW({isOpen:e,theme:t,currentWorkspaceLabel:n,syncStatusMeta:s,workspaceCloudSyncEnabled:o,syncControlBusy:l,canManageWorkspaceSync:i,workspaceSyncSummary:d,workspaceSyncRecommendedAction:m,workspaceSyncRepairBusy:y,referenceMismatchCount:k,syncStageLabel:S,workspaceSyncPendingChanges:h,formattedLastSyncTime:g,formattedLastPullTime:v,formattedLastPushTime:_,syncLastError:I,workspaceSyncDiagnostics:C,activeReferenceMismatchSummaries:D,syncDiagnosticsSummary:q,syncEventRows:B,syncEventsListRef:X,workspaceSyncRepairQueued:me,workspaceSyncBusy:ke,workspaceSyncCopied:le,runtimeMode:O,isAuthenticated:A,onClose:de,onToggleWorkspaceSync:ge,onRepairSync:Y,onCopyReport:P,onOpenLogin:H,onRetrySync:ue}){return a.jsx(Ws,{isOpen:e,onClose:de,title:"Sync Manager",size:"mdWide",theme:t,draggable:!0,children:a.jsxs("div",{className:`${Tt.form} ${nt.syncStatusModal}`,style:{gap:"10px"},children:[a.jsxs("div",{className:nt.syncStatusTop,children:[a.jsx("div",{className:nt.syncStatusHeaderInfo,children:a.jsxs("div",{className:nt.syncStatusMetaHeader,children:[a.jsx("div",{className:nt.syncStatusBadge,style:{borderColor:s.border,background:s.background,color:s.color},children:s.label}),a.jsxs("span",{className:nt.syncStatusLabel,children:["Workspace: ",a.jsx("code",{children:n})]})]})}),a.jsx("label",{className:nt.syncToggle,children:a.jsxs("span",{className:[nt.syncToggleControl,o?nt.syncToggleControlEnabled:nt.syncToggleControlDisabled,l?nt.syncToggleControlBusy:"",i?"":nt.syncToggleControlBlocked].filter(Boolean).join(" "),children:[a.jsx("input",{className:nt.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:o,disabled:!i||l,onChange:ye=>ge(ye.target.checked)}),a.jsx("span",{className:`${nt.syncToggleState} ${nt.syncToggleStateOn}`,children:"On"}),a.jsx("span",{className:`${nt.syncToggleState} ${nt.syncToggleStateOff}`,children:"Off"}),a.jsx("span",{className:nt.syncToggleThumb})]})})]}),a.jsxs("div",{className:nt.syncStatusSummaryCompact,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Health"}),a.jsx("span",{className:nt.syncStatusSummaryValue,children:d})]}),a.jsxs("div",{className:nt.syncStatusSummaryCompact,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Next Step"}),a.jsx("span",{className:nt.syncStatusSummaryValue,children:m})]}),y&&a.jsxs("div",{className:nt.syncStatusRepairBanner,children:[a.jsxs("div",{className:nt.syncStatusRepairHeader,children:[a.jsxs("div",{className:nt.syncStatusRepairBadge,children:[a.jsx(kr,{size:13,className:p.spinner}),a.jsx("span",{children:"Repair In Progress"})]}),a.jsx("span",{className:nt.syncStatusRepairMeta,children:"Advanced recovery mode"})]}),a.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."})]}),a.jsx("div",{className:nt.syncStatusSectionHeader,children:a.jsx("span",{className:nt.syncStatusLabel,children:"Current Session"})}),a.jsxs("div",{className:nt.syncStatusCompactGrid,children:[a.jsxs("div",{className:nt.syncStatusCompactItem,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Stage"}),a.jsx("span",{className:nt.syncStatusValue,children:S})]}),a.jsxs("div",{className:nt.syncStatusCompactItem,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Local Changes"}),a.jsx("span",{className:nt.syncStatusValue,children:h})]}),a.jsxs("div",{className:nt.syncStatusCompactItem,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Last Successful"}),a.jsx("span",{className:nt.syncStatusValue,children:g})]})]}),a.jsx("div",{className:nt.syncStatusSectionHeader,children:a.jsx("span",{className:nt.syncStatusLabel,children:"Activity"})}),a.jsxs("div",{className:nt.syncStatusCompactGrid,children:[a.jsxs("div",{className:nt.syncStatusCompactItem,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Last Pull"}),a.jsx("span",{className:nt.syncStatusValue,children:v})]}),a.jsxs("div",{className:nt.syncStatusCompactItem,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Last Push"}),a.jsx("span",{className:nt.syncStatusValue,children:_})]})]}),I!=="None"&&a.jsxs("div",{className:nt.syncStatusPanel,style:{background:"rgba(239, 68, 68, 0.05)",borderColor:"rgba(239, 68, 68, 0.2)"},children:[a.jsxs("div",{className:nt.syncStatusSectionHeader,style:{marginTop:0},children:[a.jsx(yd,{size:12,color:"#fda4af"}),a.jsxs("span",{className:nt.syncStatusLabel,style:{color:"#fda4af"},children:["Last Error (",C.lastErrorAt?new Date(C.lastErrorAt).toLocaleTimeString():"Recent",")"]})]}),a.jsx("span",{className:`${nt.syncStatusValue} ${nt.syncStatusValueError}`,children:I})]}),k>0&&a.jsxs("div",{className:nt.syncStatusPanel,style:{background:"rgba(250, 204, 21, 0.08)",borderColor:"rgba(250, 204, 21, 0.22)"},children:[a.jsxs("div",{className:nt.syncStatusPanelHeader,children:[a.jsx("span",{className:nt.syncStatusLabel,style:{color:"#fde68a"},children:"Identifier Integrity"}),a.jsxs("span",{className:nt.syncStatusPanelMeta,children:[k," mismatch",k===1?"":"es"," detected"]})]}),a.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&&a.jsx("div",{style:{marginTop:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:D.map(ye=>a.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:[a.jsx("span",{className:nt.syncStatusValue,style:{fontSize:"12px",wordBreak:"break-all"},children:ye.pathLabel}),ye.refsLabel?a.jsx("span",{className:nt.syncStatusPanelMeta,children:ye.refsLabel}):null]},ye.key))})]}),a.jsxs("div",{className:nt.syncStatusPanel,children:[a.jsxs("div",{className:nt.syncStatusPanelHeader,children:[a.jsx("span",{className:nt.syncStatusLabel,children:"Local Sync Diagnostics"}),a.jsx("span",{className:nt.syncStatusPanelMeta,style:{fontSize:"10px"},children:"AI profiles & metadata"})]}),a.jsx("div",{className:nt.syncStatusCompactGrid,style:{gridTemplateColumns:"repeat(2, 1fr)"},children:q.map(ye=>a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"8px"},children:[a.jsx("span",{className:nt.syncStatusLabel,style:{fontSize:"9px",textTransform:"capitalize"},children:ye.label}),a.jsx("span",{className:nt.syncStatusValue,style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:ye.value})]},ye.label))})]}),a.jsxs("div",{className:nt.syncStatusPanel,children:[a.jsx("div",{className:nt.syncStatusPanelHeader,children:a.jsx("span",{className:nt.syncStatusLabel,children:"Recent Events"})}),a.jsx("div",{ref:X,className:nt.syncStatusEventsList,style:{height:"120px"},children:B.map(ye=>a.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:a.jsx("span",{className:nt.syncStatusEventLine,style:{fontSize:"11px"},children:ye.text})},ye.key))})]}),a.jsxs("div",{className:`${Tt.formActions} ${nt.syncStatusActions}`,children:[a.jsxs("div",{className:nt.syncStatusSecondaryActions,children:[a.jsx("button",{className:p.cancelBtn,onClick:Y,disabled:y,title:y?"Repair is running now.":me?"Repair is queued and will start when the current sync finishes.":ke?"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?a.jsxs(a.Fragment,{children:[a.jsx(kr,{size:14,className:p.spinner}),a.jsx("span",{style:{marginLeft:"6px"},children:"Repairing..."})]}):me?"Repair Queued":"Repair"}),a.jsxs("button",{className:p.cancelBtn,onClick:P,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[a.jsx(tf,{size:14}),a.jsx("span",{style:{marginLeft:"6px"},children:le?"Copied":"Copy Report"})]})]}),a.jsxs("div",{className:nt.syncStatusPrimaryActions,children:[a.jsx("div",{className:nt.syncStatusPrimaryActionSlot,children:O==="local"&&!A?a.jsx("button",{className:p.submitBtn,onClick:H,children:"Sign In / Register"}):a.jsx("div",{className:nt.syncStatusActionPlaceholder,"aria-hidden":"true"})}),a.jsx("div",{className:nt.syncStatusPrimaryActionSlot,children:a.jsx("button",{className:p.submitBtn,onClick:ue,disabled:ke,children:ke?a.jsxs(a.Fragment,{children:[a.jsx(kr,{size:14,className:p.spinner}),"Syncing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Ok,{size:14}),"Sync"]})})})]})]})]})})}function fW({isOpen:e,theme:t,teamPlanMode:n,teamMgmtError:s,teamManagementTab:o,teamUsersLoading:l,teamUsers:i,teamActionBusyUserId:d,teamInviteFeedback:m,teamInviteEmail:y,teamInviteRole:k,teamInvitePermissionMode:S,teamInviteBusy:h,pendingInvites:g,teamAuditLoading:v,teamAuditEvents:_,teamAuditPage:I,teamAuditPages:C,teamAuditHasMore:D,onClose:q,onOpenMembersTab:B,onOpenInvitesTab:X,onOpenAuditTab:me,onMemberRoleChange:ke,onMemberPermissionChange:le,onToggleMemberDisabled:O,onRevokeInvite:A,onRemoveMember:de,onInviteEmailChange:ge,onInviteRoleChange:Y,onInvitePermissionModeChange:P,onSubmitInvite:H,onLoadAuditPrevious:ue,onLoadAuditNext:ye}){return a.jsx(Ws,{isOpen:e,onClose:q,title:"Team Management",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${Tt.form} ${lt.modalBody}`,children:[n==="personal"&&a.jsx("p",{className:fe.loginError,children:"Team management is only available in TEAM accounts."}),s&&a.jsx("p",{className:fe.loginError,children:s}),a.jsxs("div",{className:`${p.settingsTabs} tf-scrollbar tf-scrollbar--track-transparent tf-scrollbar--compact`,children:[a.jsx("button",{className:`${p.settingsTabBtn} ${o==="members"?p.settingsTabBtnActive:""}`,onClick:B,children:"Members"}),a.jsx("button",{className:`${p.settingsTabBtn} ${o==="invites"?p.settingsTabBtnActive:""}`,onClick:X,children:"Invites"}),a.jsx("button",{className:`${p.settingsTabBtn} ${o==="audit"?p.settingsTabBtnActive:""}`,onClick:me,children:"Audit Log"})]}),o==="members"&&a.jsxs("div",{className:mt.accountHubCard,children:[l&&a.jsx("p",{className:lt.mutedText,children:"Loading members..."}),!l&&i.length===0&&a.jsx("p",{className:lt.mutedText,children:"No users found."}),!l&&i.map(V=>a.jsxs("div",{className:lt.memberRow,children:[a.jsx("div",{className:lt.memberTitle,children:V.displayName||V.email}),a.jsxs("div",{className:mt.accountMenuMeta,children:[V.email," · ",V.status,V.disabled?" · deactivated":""]}),a.jsxs("div",{className:lt.memberActions,children:[a.jsxs("select",{className:`${p.input} ${lt.selectRole}`,value:V.role,onChange:Me=>ke(V.userId,Me.target.value),disabled:d===V.userId,children:[a.jsx("option",{value:"owner",children:"Owner"}),a.jsx("option",{value:"admin",children:"Admin"}),a.jsx("option",{value:"member",children:"Member"})]}),V.role==="member"&&a.jsxs("select",{className:`${p.input} ${lt.selectPermission}`,value:V.permissionMode,onChange:Me=>le(V.userId,Me.target.value),disabled:d===V.userId,children:[a.jsx("option",{value:"read-write",children:"Read / Write"}),a.jsx("option",{value:"read-only",children:"Read Only"})]}),a.jsx("button",{className:p.cancelBtn,disabled:d===V.userId,onClick:()=>O(V.userId,!V.disabled),children:V.disabled?"Reactivate":"Deactivate"}),V.status==="invited"&&a.jsx("button",{className:p.cancelBtn,disabled:d===V.userId,onClick:()=>A(V.userId),children:"Revoke Invite"}),a.jsx("button",{className:p.cancelBtn,disabled:d===V.userId,onClick:()=>de(V.userId),children:"Remove"})]})]},V.userId))]}),o==="invites"&&a.jsxs("div",{className:mt.accountHubCard,children:[m&&a.jsx("p",{className:lt.sectionText,children:m}),a.jsxs("div",{className:p.pathInputGroup,children:[a.jsx("label",{className:`${p.label} ${lt.labelFixed}`,children:"Email"}),a.jsx("input",{className:p.input,value:y,onChange:V=>ge(V.target.value),placeholder:"name@company.com"})]}),a.jsxs("div",{className:p.pathInputGroup,children:[a.jsx("label",{className:`${p.label} ${lt.labelFixed}`,children:"Role"}),a.jsxs("select",{className:`${p.input} ${lt.selectRole}`,value:k,onChange:V=>Y(V.target.value==="admin"?"admin":"member"),children:[a.jsx("option",{value:"member",children:"Member"}),a.jsx("option",{value:"admin",children:"Admin"})]}),k==="member"&&a.jsxs("select",{className:`${p.input} ${lt.selectPermission}`,value:S,onChange:V=>P(V.target.value==="read-only"?"read-only":"read-write"),children:[a.jsx("option",{value:"read-write",children:"Read / Write"}),a.jsx("option",{value:"read-only",children:"Read Only"})]}),a.jsx("button",{className:p.submitBtn,disabled:h||!y.trim()||n!=="team",onClick:H,children:h?"Sending...":"Send Invite"})]}),a.jsxs("div",{className:lt.inviteRow,children:[a.jsx("div",{className:lt.listHeading,children:"Pending Invites"}),g.length===0&&a.jsx("p",{className:lt.mutedText,children:"No pending invites."}),g.map(V=>a.jsxs("div",{className:lt.memberRow,children:[a.jsx("div",{className:lt.memberTitle,children:V.displayName||V.email}),a.jsxs("div",{className:mt.accountMenuMeta,children:[V.email," · ",V.role]})]},V.userId))]})]}),o==="audit"&&a.jsxs("div",{className:mt.accountHubCard,children:[v&&a.jsx("p",{className:lt.mutedText,children:"Loading audit entries..."}),!v&&_.length===0&&a.jsx("p",{className:lt.mutedText,children:"No audit events for this workspace."}),!v&&a.jsx("div",{className:lt.auditList,children:_.map(V=>a.jsxs("div",{className:lt.memberRow,children:[a.jsx("div",{className:mt.accountMenuMeta,children:new Date(V.createdAt).toLocaleString()}),a.jsx("div",{className:lt.memberTitle,children:V.action}),a.jsxs("div",{className:mt.accountMenuMeta,children:[V.actorUserId," (",V.actorRole,")"]})]},V.id))}),a.jsxs("div",{className:lt.auditPager,children:[a.jsx("button",{className:p.cancelBtn,disabled:v||I===0,onClick:ue,children:"Previous"}),a.jsxs("span",{className:mt.accountMenuMeta,children:["Page ",I+1," of ",C]}),a.jsx("button",{className:p.cancelBtn,disabled:v||!D||I+1>=C,onClick:ye,children:"Next"})]})]}),a.jsx("div",{className:`${Tt.formActions} ${lt.modalActionsEnd}`,children:a.jsx("button",{className:p.cancelBtn,onClick:q,children:"Close"})})]})})}const Py=e=>{const t=e.status||"task";return t==="done"||t==="cancelled"?"completed":t},hW=(e,t,n)=>{if(Py(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=n,o):(t==="cancelled"&&(o.status="cancelled"),o)},gW=({targetTasks:e,overTaskId:t,isBelowOverItem:n})=>{if(!t)return e.length;const s=e.findIndex(o=>o.id===t);return s<0?e.length:s+(n?1:0)},My=(e,t=new Map)=>{const n=new Map(t);return e.forEach((s,o)=>{n.set(s.id,{...n.get(s.id)||{},orderInDay:o})}),n},xf=e=>Array.from(e.entries()).map(([t,n])=>({taskId:t,updates:n})),Ey=({sourceColumnId:e,targetColumnId:t,sourceTasks:n,updates:s})=>!e||e===t?s:My(n,s),yW=({activeTask:e,sourceColumnId:t,targetTasks:n,sourceTasks:s,insertAt:o})=>{const l=[...n];l.splice(o,0,e);let i=new Map;return l.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=Ey({sourceColumnId:t,targetColumnId:"backlog",sourceTasks:s,updates:i}),xf(i)},kW=({activeTask:e,targetTasks:t,insertAt:n})=>{const s=[...t];return s.splice(n,0,e),xf(My(s))},vW=({activeTask:e,sourceColumnId:t,targetColumnId:n,targetTasks:s,sourceTasks:o,insertAt:l,scheduledDate:i,scheduledWeekKey:d})=>{const m=[...s];m.splice(l,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=Ey({sourceColumnId:t,targetColumnId:n,sourceTasks:o,updates:y}),xf(y)},SW=({activeTask:e,sourceColumnId:t,targetColumnId:n,targetTasks:s,sourceTasks:o,overTaskId:l,isBelowOverItem:i,scheduleDates:d,parseToIsoWeekKey:m,todayDate:y})=>{const k=["mon","tue","wed","thu","fri","sat","sun"];if(!(n==="backlog"||n==="expired"||k.includes(n)))return null;const h=gW({targetTasks:s,overTaskId:l,isBelowOverItem:i});if(n==="expired")return t!=="expired"?null:{kind:"updates",updates:kW({activeTask:e,targetTasks:s,insertAt:h})};if(n==="backlog")return{kind:"updates",updates:yW({activeTask:e,sourceColumnId:t,targetTasks:s,sourceTasks:o,insertAt:h})};if(!k.includes(n))return null;const g=d[n];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:vW({activeTask:e,sourceColumnId:t,targetColumnId:n,targetTasks:s,sourceTasks:o,insertAt:h,scheduledDate:g,scheduledWeekKey:m(g)}),selectedDate:g}:null},Xu="expired::";function wW({tasks:e,columns:t,groupBy:n,searchQuery:s,copiedId:o,taxonomies:l,types:i,priorities:d,approaches:m,assigneeOptions:y=[],onUpdateTask:k,onTaskClick:S,onOpenTaskById:h,onCopyId:g,onToggleInProgress:v,onToggleReview:_,onToggleComplete:I,onToggleCancel:C,onSetStatus:D,onArchiveTask:q,onUnarchive:B,onDelete:X,allTasks:me=[],onAddTaskToColumn:ke,emptyColumnMode:le="show",filterCategories:O=[],filterTypes:A=[],filterPriorities:de=[],filterStatus:ge=[],filterAssignees:Y=[],filtersReady:P=!0,scheduleFilteredTaskIds:H,categories:ue=[],compressed:ye=!1,readOnlyMode:V=null,recentlyChangedTaskIds:Me=[],scheduleDates:_e,onScheduleDaySelected:re,persistedScrollLeft:oe,onScrollLeftChange:Ie,sortBy:Ee="created",sortOrder:je="desc",planningDropTargets:Pe=null,onAssignTaskToWorkstream:K,onAssignWorkstreamToInitiative:x,showTaskCardStatusLabel:b=!0,workstreams:R=[],initiatives:F=[]}){const[Q,M]=r.useState(null),[$,be]=r.useState(!1),[U,se]=r.useState(!1),pe=r.useMemo(()=>new Set(Me),[Me]),z=r.useMemo(()=>new Map(R.map(E=>[E.id,E])),[R]),ne=r.useMemo(()=>new Map(F.map(E=>[E.id,E])),[F]),ie=r.useCallback(E=>{const c=E.workstreamId&&z.get(E.workstreamId)||null,J=c?.initiativeId&&ne.get(c.initiativeId)||null;return{taskWorkstream:c,taskInitiative:J}},[ne,z]),Re=r.useMemo(()=>new Set(e.map(E=>E.id)),[e]),Te=r.useCallback(E=>E.startsWith(Xu)?E.slice(Xu.length):E,[]),De=r.useCallback(E=>Re.has(Te(E)),[Re,Te]),Oe=r.useMemo(()=>new Set(H||[]),[H]),vt=r.useRef(null),st=r.useCallback(E=>{const c=E?.data?.current||{},J=String(E?.id||"");let we=String(c.taskId||""),xe=String(c.workstreamId||"");!we&&J&&De(J)&&(we=Te(J)),!xe&&J.startsWith("planning-workstream:")&&(xe=J.slice(20));let Ke=String(c.type||"");return Ke||(we?Ke="task-card":xe&&(Ke="planning-workstream")),{activeId:J,type:Ke,taskId:we,workstreamId:xe}},[Te,De]),kt=gg(Lp(Sg,{activationConstraint:{distance:10}}),Lp(dv,{coordinateGetter:lv})),Ye=Py,Ct=r.useMemo(()=>{const E=new Date,c=E.getFullYear(),J=String(E.getMonth()+1).padStart(2,"0"),we=String(E.getDate()).padStart(2,"0");return`${c}-${J}-${we}`},[]),dt=r.useMemo(()=>{const E=we=>{const xe=we.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!xe)return null;const Ke=new Date(Date.UTC(Number(xe[1]),Number(xe[2])-1,Number(xe[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 we=new Date,xe=we.getDay(),Ke=xe===0?-6:1-xe,Je=new Date(we);Je.setDate(we.getDate()+Ke);const Ne=Pt=>{const Ft=Pt.getFullYear(),Lt=String(Pt.getMonth()+1).padStart(2,"0"),Ht=String(Pt.getDate()).padStart(2,"0");return`${Ft}-${Lt}-${Ht}`},zt={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((Pt,Ft)=>{const Lt=new Date(Je);Lt.setDate(Je.getDate()+Ft),zt[Pt]=Ne(Lt)}),zt})(),..._e||{}},parseToIsoWeekKey:E}},[_e]),Qe=E=>{const c=E.scheduledDate||null;return c?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(c)||"__offweek":"backlog"},Rt=r.useMemo(()=>{if(n==="schedule")return[];const E=new Set(t.map(xe=>String(xe.value))),c=new Set(t.map(xe=>xe.label)),J=[],we=xe=>{const Ke=n==="status"?Ye(xe):xe[n],Je=String(Ke??"");if(!Je||E.has(Je)||c.has(Je))return null;if(n==="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(n==="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(n==="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(n==="complexity")return{value:Number.isFinite(Number(Je))?Number(Je):Je,label:Je,icon:"Gauge"};if(n==="status")return{value:Je,label:Je,icon:"Circle"};if(n==="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 xe of e){const Ke=we(xe);Ke&&(J.push(Ke),E.add(String(Ke.value)),c.add(Ke.label))}return J},[y,ue,n,t,d,e,i]),ee=r.useMemo(()=>[...t,...Rt],[Rt,t]),ze=r.useMemo(()=>{const E=new Map;for(const c of ee)E.set(String(c.value),c),E.has(c.label)||E.set(c.label,c);return E},[ee]),ft=r.useMemo(()=>{const E={};return ee.forEach(J=>{E[String(J.value)]=0}),(me.length>0?me:e).forEach(J=>{let we="";if(n==="status")we=Ye(J);else if(n==="schedule")we=Qe(J);else{const Ke=J[n];we=String(Ke??"")}const xe=ze.get(we);if(xe&&E[String(xe.value)]++,n==="schedule"){const Ke=J.status==="done"||J.status==="cancelled";J.scheduledDate&&!Ke&&J.scheduledDate<Ct&&ze.has("expired")&&(E.expired=(E.expired||0)+1)}}),E},[me,e,ee,n,ze,Ct]),it=r.useMemo(()=>{const E={};if(ee.forEach(c=>{E[String(c.value)]=[]}),e.forEach(c=>{let J="";if(n==="status")J=Ye(c);else if(n==="schedule")J=Qe(c);else{const xe=c[n];J=String(xe??"")}const we=ze.get(J);if(we){if(n==="schedule"&&String(we.value)==="backlog"&&!Oe.has(c.id))return;E[String(we.value)].push(c)}if(n==="schedule"){const xe=c.status==="done"||c.status==="cancelled";c.scheduledDate&&!xe&&c.scheduledDate<Ct&&E.expired&&E.expired.push(c)}}),n==="schedule"){const c=(we,xe)=>{const Ke=typeof we.orderInDay=="number"?we.orderInDay:Number.MAX_SAFE_INTEGER,Je=typeof xe.orderInDay=="number"?xe.orderInDay:Number.MAX_SAFE_INTEGER;return Ke!==Je?Ke-Je:String(we.createdAt||"").localeCompare(String(xe.createdAt||""))},J=(we,xe)=>fm(we,xe,Ee,je,l);Object.keys(E).forEach(we=>{if(we==="backlog"||we==="expired"){E[we].sort(J);return}E[we].sort(c)})}return E},[e,me,ee,n,ze,Oe,Ct,Ee,je]),Et=Q?Te(Q):null,ht=Et?e.find(E=>E.id===Et):null,Ot=r.useRef(null),Dt=r.useRef(null),We=r.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),tt=r.useRef(-1),Fe=(E,c)=>P?n==="category"?!O.includes(String(E)):n==="type"?!A.includes(String(E)):n==="priority"?!de.some(J=>Number(J)===Number(E)):n==="status"?String(E)==="completed"?!ge.includes("done")&&!ge.includes("cancelled"):!ge.includes(String(E)):n==="assignee"?!Y.includes(String(E)):!1:!1,Ze=r.useMemo(()=>{let we=0;return ee.forEach((xe,Ke)=>{const Je=it[String(xe.value)]||[],Ne=Fe(xe.value,xe.label),zt=n!=="schedule"&&le==="hide"&&Je.length===0;if(Ne||zt)return;const Jt=le==="collapse"&&Je.length===0;we+=Jt?72:320,we+=4}),we},[ee,it,le,n,O,A,de,ge,Y,P]),St=r.useCallback(E=>{if(!Ie)return;const c=Math.max(0,Math.round(E));c!==tt.current&&(tt.current=c,Ie(c))},[Ie]);r.useEffect(()=>{const E=Ot.current,c=Dt.current;if(!E||!c)return;let J=!1,we=!1;const xe=()=>{!E||we||(J=!0,E.scrollLeft=c.scrollLeft,St(c.scrollLeft),setTimeout(()=>J=!1,0))},Ke=()=>{!c||J||(we=!0,c.scrollLeft=E.scrollLeft,St(E.scrollLeft),setTimeout(()=>we=!1,0))};return c.addEventListener("scroll",xe),E.addEventListener("scroll",Ke),()=>{c.removeEventListener("scroll",xe),E.removeEventListener("scroll",Ke)}},[St]);const ot=r.useRef(!1);r.useEffect(()=>{if(ot.current)return;if(typeof oe!="number"||!Number.isFinite(oe)){ot.current=!0;return}const E=Ot.current,c=Dt.current;if(!E||!c)return;const J=Math.max(0,E.scrollWidth-E.clientWidth),we=Math.min(Math.max(0,oe),J);E.scrollLeft=we,c.scrollLeft=we,ot.current=!0},[oe,Ze]),r.useEffect(()=>{const E=()=>{const c=Ot.current;if(!c){se(!1);return}se(c.scrollWidth>c.clientWidth+4)};return E(),window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E)}},[Ze,ee.length,it]),r.useEffect(()=>{const E=J=>{const we=We.current;if(we.pointerId===null||we.pointerId!==J.pointerId)return;const xe=J.clientX-we.startX,Ke=J.clientY-we.startY;if(!we.didPan){if(Math.abs(xe)<7||Math.abs(xe)<Math.abs(Ke))return;we.didPan=!0,be(!0),document.body.style.userSelect="none"}const Je=we.startScrollLeft-xe;Ot.current&&(Ot.current.scrollLeft=Je),Dt.current&&(Dt.current.scrollLeft=Je),J.preventDefault()},c=()=>{const J=We.current;J.pointerId!==null&&(J.pointerId=null,J.didPan=!1,$&&(be(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",E),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c),()=>{window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),document.body.style.userSelect=""}},[$]);const te=E=>{!U||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=Ot.current?.scrollLeft||0,We.current.didPan=!1)},Le=E=>{M(E.active.id)},At=E=>{const c=st(E.active),J=String(E.over?.data?.current?.type||"");c.type==="task-card"&&J.startsWith("planning-")?vt.current=`${String(E.over?.id||"")}:${J}`:vt.current&&(vt.current=null)},jt=E=>{const{active:c,over:J}=E;vt.current=null,M(null);const we=st(c),xe=we.type,Ke=String(J?.data?.current?.type||""),Je=we.taskId,Ne=we.workstreamId,zt=String(J?.data?.current?.workstreamId||""),Jt=String(J?.data?.current?.initiativeId||"");if(xe==="task-card"&&Ke==="planning-workstream-target"&&Je&&zt){K?.(Je,zt);return}if(xe==="planning-workstream"){if(Ke==="planning-initiative-target"&&Ne&&Jt){x?.(Ne,Jt);return}return}const Pt=String(c.id),Ft=J?String(J.id):null,Lt=Te(Pt);Ft&&Te(Ft);const Ht=e.find(he=>he.id===Lt);if(!Ht||!Ft)return;const ra=Wt(Pt),Ga=String(c?.data?.current?.sortable?.containerId||"")||ra,qa=String(J?.data?.current?.sortable?.containerId||"")||Wt(Ft);if(!qa)return;const cn=ze.get(qa)||ee.find(he=>String(he.value)===qa||he.label===qa);if(cn){if(n==="schedule"){const Ae=String(cn.value),Nt=Ft&&De(Ft)?Te(Ft):null,pt=J?.rect,Ca=c.rect.current.translated||c.rect.current.initial,ya=!!(pt&&Ca&&Ca.top+Ca.height/2>pt.top+pt.height/2),ia=(it[Ae]||[]).filter(gt=>gt.id!==Lt),ca=(it[String(Ga)]||[]).filter(gt=>gt.id!==Lt),Oa=SW({activeTask:Ht,sourceColumnId:Ga,targetColumnId:Ae,targetTasks:ia,sourceTasks:ca,overTaskId:Nt,isBelowOverItem:ya,scheduleDates:dt.dates,parseToIsoWeekKey:dt.parseToIsoWeekKey,todayDate:Ct});if(!Oa)return;if(Oa.kind==="blocked"){window.alert(Oa.reason);return}Oa.updates.forEach(({taskId:gt,updates:rr})=>k(gt,rr)),Oa.selectedDate&&re?.(Oa.selectedDate);return}let he=cn.value;if(n==="status"){const Ae=String(he),Nt=hW(Ht,Ae,new Date().toISOString());Nt&&k(Ht.id,Nt);return}(n==="priority"||n==="complexity")&&(he=Number(he));const rt=Ht[n];if(String(rt??"")!==String(he??"")){const Ae={[n]:he};k(Ht.id,Ae)}}},Wt=E=>{if(ze.has(E)){const we=ze.get(E);return we?String(we.value):E}if(n==="schedule"&&E.startsWith(Xu))return"expired";const c=Te(E),J=e.find(we=>we.id===c);if(J){let we="";n==="status"?we=Ye(J):n==="schedule"?we=Qe(J):we=String(J[n]??"");const xe=ze.get(we);return xe?String(xe.value):null}return null},Ge={sideEffects:uv({styles:{active:{opacity:"0"}}})},$t=E=>{try{const c=cv(E);if(c.length>0){const J=c.find(zt=>String(zt.id).startsWith("planning-"));if(J)return[J];const we=E.pointerCoordinates;if(!we)return[c[0]];const xe=c.filter(zt=>{const Jt=String(zt.id);return De(Jt)&&Jt!==Q});if(xe.length===0){const Jt=c.filter(Lt=>{const Ht=String(Lt.id);return!De(Ht)}).find(Lt=>!!Wt(String(Lt.id)))||null,Pt=Jt?Wt(String(Jt.id)):null,Ft=(E.droppableContainers||[]).filter(Lt=>{const Ht=String(Lt.id);return!De(Ht)||Ht===Q?!1:Pt?Wt(Ht)===Pt:!0});if(Ft.length>0){const Lt=Qf({...E,droppableContainers:Ft});if(Lt.length>0)return[Lt[0]]}return Jt?[Jt]:[c[0]]}const Ke=xe;let Je=Ke[0],Ne=Number.POSITIVE_INFINITY;for(const zt of Ke){const Jt=E.droppableRects?.get(zt.id);if(!Jt)continue;const Pt=Jt.left+Jt.width/2,Ft=Jt.top+Jt.height/2,Lt=we.x-Pt,Ht=we.y-Ft,ra=Lt*Lt+Ht*Ht;ra<Ne&&(Ne=ra,Je=zt)}return[Je]}return Qf(E)}catch(c){return console.error("[TaskKanban] collision detection error",c),[]}},yt={searchQuery:s,copiedId:o,taxonomies:l,types:i,priorities:d,approaches:m,assigneeOptions:y,onCopyId:g,onToggleInProgress:v,onToggleReview:_,onToggleComplete:I,onToggleCancel:C,onSetStatus:D,onArchiveTask:q,onUnarchive:B,onDelete:X,onOpenTaskById:h,categories:ue,readOnlyMode:V,changedTaskIdSet:pe,resolveTaskHierarchy:ie,groupBy:n,showStatusLabel:b};return a.jsxs(yg,{sensors:kt,collisionDetection:$t,onDragStart:Le,onDragOver:At,onDragEnd:jt,onDragCancel:E=>{vt.current=null,M(null)},children:[Pe,a.jsxs("div",{className:p.kanbanWrapper,children:[a.jsx("div",{ref:Dt,className:`${p.kanbanTopScroll} tf-scrollbar`,children:a.jsx("div",{className:p.kanbanTopScrollSpacer,style:{width:`${Ze}px`}})}),a.jsx("div",{className:p.kanbanContainer,ref:Ot,children:ee.map(E=>{const c=it[String(E.value)]||[],J=Fe(E.value,E.label),we=n!=="schedule"&&le==="hide"&&c.length===0,xe=n==="schedule",Ke=xe&&ee.some(Ht=>String(Ht.value)==="backlog"),Je=xe&&String(E.value)==="backlog",Ne=xe&&String(E.value)==="expired",zt=it.backlog||[],Pt=le==="collapse"&&zt.length===0?72:320,Ft=Je?0:Ne?Ke?Pt+4:0:void 0,Lt=Je?6:Ne?5:void 0;return J||we?null:a.jsx(bW,{id:String(E.value),title:E.label,color:E.color,icon:E.icon,tasks:c,activeId:Q,activeTaskId:Et,totalCount:ft[String(E.value)],onAddTask:()=>ke?.(n,E.value),onTaskClick:S,commonCardProps:yt,collapseEmpty:le==="collapse",compressed:ye,onHeaderPointerDown:te,isHeaderPanning:$,headerPanEnabled:U,stickyLeft:Ft,stickyZIndex:Lt,isPast:!!E.isPast,isSelected:!!E.isSelected,isWeekend:!!E.isWeekend,disableSorting:!1,scheduleDate:n==="schedule"?dt.dates[String(E.value)]:void 0,onScheduleDaySelected:re},String(E.value))})})]}),Yi.createPortal(a.jsx(iv,{dropAnimation:Ge,children:ht?(()=>{const{taskWorkstream:E,taskInitiative:c}=ie(ht);return a.jsx(bd,{task:ht,taskWorkstream:E,taskInitiative:c,isOverlay:!0,...yt,isArchived:ht.isArchived,categories:ue,compressed:ye,isRecentlyChanged:pe.has(ht.id)})})():null}),document.body)]})}function bW({id:e,title:t,color:n,icon:s,tasks:o,activeId:l=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:C,isPast:D=!1,isSelected:q=!1,isWeekend:B=!1,disableSorting:X=!1,scheduleDate:me,onScheduleDaySelected:ke}){const{setNodeRef:le}=sf({id:e,data:{type:"Column"}}),O=S&&o.length===0,A=i?o.filter(H=>H.id!==i):o,de=typeof I=="number",ge=r.useRef(null),Y=H=>e==="expired"?`${Xu}${H}`:H,P=H=>{if(!me||!ke)return;const ue=H.target;ue&&(ue.closest('[data-task-card="true"]')||ue.closest(`.${p.kanbanCardWrapper}`)||ke(me))};return a.jsxs("div",{ref:le,className:`${p.kanbanColumn} ${O?p.kanbanColumnCollapsed:""} ${de?p.kanbanColumnSticky:""} ${D?p.kanbanColumnPast:""} ${q?p.kanbanColumnSelectedDay:""} ${B?p.kanbanColumnWeekend:""}`,style:de?{left:`${I}px`,zIndex:C??4}:void 0,onClick:P,children:[a.jsxs("div",{className:`${p.kanbanHeader} ${_?p.kanbanHeaderDraggable:""} ${v?p.kanbanHeaderPanning:""}`,style:{borderTopColor:Dn(n)||"var(--color-purple)"},onPointerDown:g,children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const H=s&&tc[s]?tc[s]:Po,ue=Dn(n)||"var(--color-purple)";return a.jsx(H,{size:16,style:{color:ue}})})(),!O&&a.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!O||d>0)&&a.jsx("span",{className:p.kanbanCount,children:O?d:`${o.length} / ${d}`}),!k.readOnlyMode&&a.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:a.jsx(ro,{size:14})})]})]}),a.jsx("div",{className:p.kanbanDroppable,children:a.jsx("div",{className:`${p.kanbanDroppableScroll} ${p.appScrollbar} tf-scrollbar`,ref:ge,children:X?A.map(H=>a.jsx("div",{className:p.kanbanCardWrapper,children:(()=>{const{taskWorkstream:ue,taskInitiative:ye}=k.resolveTaskHierarchy?.(H)||{};return a.jsx(bd,{task:H,taskWorkstream:ue,taskInitiative:ye,onClick:y,...k,isArchived:H.isArchived,readOnlyMode:k.readOnlyMode||null,compressed:h,isRecentlyChanged:!1})})()},H.id)):a.jsx(kg,{id:e,items:A.map(H=>Y(H.id)),strategy:vg,children:A.map(H=>a.jsx(_W,{sortableId:Y(H.id),task:H,onClick:y,commonCardProps:k,compressed:h,isRecentlyChanged:k.changedTaskIdSet?.has(H.id)},Y(H.id)))})})})]})}function _W({sortableId:e,task:t,onClick:n,commonCardProps:s,compressed:o,isRecentlyChanged:l=!1}){const i=!!s?.readOnlyMode,{attributes:d,listeners:m,setNodeRef:y,transform:k,transition:S,isDragging:h}=wg({id:e,disabled:i,data:{type:"task-card",taskId:t.id}}),g={transform:rf.Transform.toString(k),transition:S,opacity:h?0:1,pointerEvents:h?"none":"auto"},v=s?.groupBy==="schedule",_=!v&&l;return a.jsx("div",{ref:y,style:g,...i?{}:d,...i?{}:m,className:`${p.kanbanCardWrapper} ${_?p.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:I,taskInitiative:C}=s.resolveTaskHierarchy?.(t)||{};return a.jsx(bd,{task:t,taskWorkstream:I,taskInitiative:C,onClick:n,...s,isArchived:t.isArchived,readOnlyMode:s?.readOnlyMode||null,compressed:o,isRecentlyChanged:v?!1:l})})()})}function CW(e,t,n){const s=String(t);if(e==="category"){const o=n.categories.find(l=>String(l.value)===s||l.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=n.approaches.find(l=>String(l.value)===s||l.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 AW(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 xW(e){const t=e.runtimeMode==="local"&&e.isAuthenticated;if(t){const n=AW(e.retryBlockedReason||e.pullBlockedReason||e.pushBlockedReason||null);return{actionable:t,status:e.workspaceSyncStatus,syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:n?.summary||e.workspaceSyncSummary,recommendedAction:n?.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 Sm(e,t){return e==="deleted"?!1:e==="archived"?t:!t}function IW(e,t,n){const s=t.filter(d=>Sm(n,!!d.isArchived)),o=n==="deleted"?[]:e.filter(d=>Sm(n,!!d.isArchived)).map(d=>({...d,workstreams:s.filter(m=>m.initiativeId===d.id)})),l=s.filter(d=>!d.initiativeId),i=[...o.flatMap(d=>d.workstreams),...l];return{initiatives:o,standaloneWorkstreams:l,visibleWorkstreams:i,initiativeById:new Map(o.map(d=>[d.id,d])),workstreamById:new Map(i.map(d=>[d.id,d]))}}function Dy(e){return typeof e.occurredAt=="string"&&e.occurredAt.trim().length>0?e.occurredAt:"unknown-time"}function TW(e){return typeof e.eventType=="string"&&e.eventType.trim().length>0?e.eventType.trim():"sync"}function RW(e){const t=Im(e.details),n=t?t.source:null;return typeof n=="string"?n.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 Hh(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 jW(e){const t=Dy(e),n=Im(e.details),s=RW(e);return s==="retry.blocked"?`${t} manual retry blocked: ${zh(n?.reason)} during ${Hh(n?.phase)}`:s==="repair.started"?`${t} manual repair started: ${Hh(n?.repairPhase)} selected`:s==="repair.blocked"?`${t} manual repair blocked: ${zh(n?.reason)}`:null}function al(e,t=0){const n=String(e.id??"").trim();return n?`id:${n}`:[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(),yw(e.details),String(t)].join("|")}function NW(e,t,n=15){const s=new Map;for(const[o,l]of e.entries())s.set(al(l,o),l);for(const[o,l]of t.entries())s.set(al(l,o),l);return Array.from(s.values()).sort((o,l)=>String(l.occurredAt||"").localeCompare(String(o.occurredAt||""))).slice(0,Math.max(1,n))}function PW(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(al(e[n],n)!==al(t[n],n))return!1;return!0}function Ly(e){const t=jW(e);if(t)return t;const n=Dy(e),s=TW(e),o=e.status==="error"?"failed":"succeeded",l=Number(e.changeCount),i=Number.isFinite(l)?` (${Math.max(0,Math.floor(l))} change${Math.floor(l)===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`${n} ${s} ${o}${i}${m}${k}${S}`}function Jp(e){if(!e)return"Never";const t=new Date(e);return Number.isNaN(t.getTime())?"Never":t.toLocaleString()}function MW(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 By(e,t,n){if(t)return"Repairing";if(n&&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 EW(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:Jp(e.aiProfileSnapshotLastFetchAt)},{label:"AI snapshot fetch error",value:e.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:e.aiProfileSnapshotLastSkipReason||"None"}]}function DW({syncRecentEvents:e,syncRecentEventsError:t,syncRecentEventsLoading:n}){return n&&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:al(s,o),text:Ly(s),tone:s.status==="error"?"error":"default"}))}function Wy(e){const t=[];for(const n of e){if(String(n.errorMessage||"").toLowerCase().includes("reference number mismatch")){t.push(n);continue}if(String(n.status||"").toLowerCase()==="success")break}return t}function LW(e){return Wy(e).length}function BW(e){return Wy(e).map((t,n)=>{const s=t.details&&typeof t.details=="object"?t.details:null,o=String(s?.path||"").trim(),l=String(s?.referenceLabel||"").trim(),i=String(s?.taskTitle||s?.existingTaskTitle||"").trim(),d=Number(s?.existingReferenceNumber),m=Number(s?.incomingReferenceNumber),y=o||i||l||`Mismatch ${n+1}`,k=Number.isFinite(d)||Number.isFinite(m)?`Existing ${Number.isFinite(d)?d:"?"} vs incoming ${Number.isFinite(m)?m:"?"}`:l?`Both claimed ${l}`:null;return{key:al(t,n),pathLabel:y,refsLabel:k}})}function WW({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:n,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:l,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: ${n}`,`Recommended action: ${s}`,`Last successful sync: ${o}`,`Last pull from cloud: ${l}`,`Last push to cloud: ${i}`,`Last error at: ${Jp(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: ${Jp(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(_=>Ly(_));return[...g,"","Recent sync events",...v.length>0?v:["No recent sync events recorded."]].join(`
5
+ `)}const Gh="/api/taskforce/account/profile-summary",FW=9e4,qc=new Map;function Ku(){return typeof performance<"u"?performance.now():Date.now()}function Fy(e,t){const n=String(e||"").trim();if(!n)return"";const s=String(t||"").trim();return s?`${n}::${s}`:n}function Vh(e,t){qc.delete(Fy(e,t?.identityKey))}async function OW(e,t){const n=String(e||"").trim(),s=Fy(e,t?.identityKey);if(!s||!n)return null;const o=t?.force===!0,l=Date.now(),i=qc.get(s);if(!o&&i?.payload!==void 0&&l-i.fetchedAt<FW)return Ut("account_profile_summary_cache_hit",{url:n,cacheKey:s,ageMs:l-i.fetchedAt}),i.payload;if(!o&&i?.promise)return Ut("account_profile_summary_request_reused",{url:n,cacheKey:s}),i.promise;const d=Ku(),m=(async()=>{const y=await fetch(n,{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 qc.set(s,{payload:S,fetchedAt:Date.now(),promise:null}),Ut("account_profile_summary_loaded",{url:n,cacheKey:s,durationMs:Math.round(Ku()-d),fromCache:!1}),S})().catch(y=>{const k=i?.payload??null;if(k)return qc.set(s,{payload:k,fetchedAt:i?.fetchedAt??Date.now(),promise:null}),Ut("account_profile_summary_failed",{url:n,cacheKey:s,durationMs:Math.round(Ku()-d),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!0}),k;throw qc.delete(s),Ut("account_profile_summary_failed",{url:n,cacheKey:s,durationMs:Math.round(Ku()-d),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!1}),y});return qc.set(s,{payload:i?.payload??null,fetchedAt:i?.fetchedAt??0,promise:m}),m}const $W=1024,UW=5*1024*1024,zW=[.9,.82,.74,.66,.58],HW=[.9,.82,.74,.66,.58],GW=[1,.85,.7,.55,.4],VW=new Set(["image/png","image/jpeg","image/webp"]);function qW(e,t){const n=document.createElement("canvas");return n.width=Math.max(1,Math.round(e)),n.height=Math.max(1,Math.round(t)),n}async function KW(e){const t=URL.createObjectURL(e);try{const n=await new Promise((s,o)=>{const l=new Image;l.onload=()=>s(l),l.onerror=()=>o(new Error("Failed to load image.")),l.src=t});return{width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,source:n}}finally{URL.revokeObjectURL(t)}}async function ZW(e){const t=qW(e.width,e.height),n=t.getContext("2d");if(!n)throw new Error("Image optimization requires a 2D canvas context.");return n.drawImage(e.image.source,0,0,t.width,t.height),await new Promise((s,o)=>{t.toBlob(l=>{if(l){s(l);return}o(new Error("Failed to encode resized image."))},e.type,e.quality)})}const YW={loadImage:KW,renderToBlob:ZW};function qh(e,t){return e==="image/png"?".png":e==="image/jpeg"?".jpg":e==="image/webp"?".webp":(t.includes(".")?t.slice(t.lastIndexOf(".")):"")||".img"}function Kh(e,t){const n=String(e||"").trim();if(!n)return`avatar${t}`;const s=n.lastIndexOf(".");return s<=0?`${n}${t}`:`${n.slice(0,s)}${t}`}function JW(e){const t=e==="image/jpeg"?"image/jpeg":"image/webp";return Array.from(new Set([t,"image/webp","image/jpeg"]))}function QW(e){return e==="image/webp"?zW:e==="image/jpeg"?HW:[void 0]}async function XW(e,t,n=YW){const s=Number.isFinite(t?.maxBytes)&&(t?.maxBytes||0)>0?Math.floor(t?.maxBytes):UW,o=Number.isFinite(t?.maxDimension)&&(t?.maxDimension||0)>0?Math.floor(t?.maxDimension):$W;if(e.size<=s)return{file:e,optimized:!1,exceededLimit:!1};if(!VW.has(e.type))return{file:e,optimized:!1,exceededLimit:!0};const l=await n.loadImage(e),i=Math.max(l.width,l.height,1),d=Math.min(1,o/i);let m=null;for(const k of GW){const S=Math.min(1,d*k),h=Math.max(1,Math.round(l.width*S)),g=Math.max(1,Math.round(l.height*S));for(const v of JW(e.type))for(const _ of QW(v)){const I=await n.renderToBlob({image:l,width:h,height:g,type:v,quality:_});if((!m||I.size<m.size)&&(m=I),I.size<=s)return{file:new File([I],Kh(e.name,qh(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],Kh(e.name,qh(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 Qp="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Oy="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Zh="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function e4({projectName:e,currentWorkspaceId:t,brandLabel:n="TaskForce",brandHomeLabel:s="Go to Kanban",onBrandClick:o,runtimeMode:l="local",theme:i=rm,meta:d,actions:m}){const y=Tg(i)?Oy:Qp,k=String(e||"").trim(),S=String(t||"").trim(),h=S.toLowerCase(),g=!!(k&&(l!=="cloud"||h&&h!=="default")),v=()=>{if(!S||typeof navigator>"u")return;const C=navigator.clipboard;C?.writeText&&C.writeText(S).catch(()=>{})},_=C=>{C.key!=="Enter"&&C.key!==" "||(C.preventDefault(),v())},I=a.jsxs(a.Fragment,{children:[a.jsx("img",{src:y,alt:"Taskforce Logo",className:p.brandIcon,onError:C=>{const D=C.currentTarget;D.src!==Zh?D.src=Zh:D.style.display="none"}}),a.jsx("span",{children:n}),l==="cloud"&&a.jsx("span",{className:p.brandCloudSuffix,children:"HQ"})]});return a.jsxs("div",{className:`${p.header} ${ea.standaloneHeader}`,children:[a.jsxs("div",{className:`${p.headerTitle} ${ea.standaloneTitle}`,children:[o?a.jsx("button",{type:"button",className:p.brandHomeButton,onClick:o,title:s,"aria-label":s,children:I}):a.jsx("span",{className:p.brandHomeStatic,children:I}),g&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.projectSlash,children:"/"}),a.jsx("span",{className:p.projectName,title:S?`Workspace ID: ${S}`:void 0,role:S?"button":void 0,tabIndex:S?0:void 0,onClick:v,onMouseDown:C=>C.preventDefault(),onKeyDown:_,children:k})]}),d]}),a.jsx("div",{className:p.headerActions,style:{gap:"16px"},children:m})]})}function t4({value:e,placeholder:t,active:n=!1,onChange:s,onClear:o,clearTitle:l}){return a.jsxs("div",{className:p.searchContainer,style:{width:"240px"},children:[a.jsx($k,{size:16,className:p.searchIcon}),a.jsx("input",{type:"text",className:`${p.searchInput} ${n?p.searchActive:""}`,placeholder:t,value:e,onChange:i=>s(i.target.value)}),e&&o&&a.jsx("button",{className:p.clearSearchBtn,onClick:o,title:l,children:a.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function Yh({label:e,value:t,options:n,onChange:s,trailingAction:o,width:l}){return a.jsxs("div",{className:p.groupByContainer,style:l?{width:l}:void 0,children:[a.jsx("span",{className:p.groupByLabel,children:e}),a.jsx("select",{className:`${p.select} ${p.groupBySelect}`,value:t,onChange:i=>s(i.target.value),children:n.map(i=>a.jsx("option",{value:i.value,children:i.label},String(i.value)))}),o]})}function Ap({actions:e}){return a.jsx(a.Fragment,{children:e.map(t=>a.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 Jh(){return a.jsx("div",{className:p.headerDivider})}function a4({icon:e,label:t,onClick:n,disabled:s=!1}){return a.jsxs("button",{className:p.primaryUpdateBtn,onClick:n,disabled:s,children:[e," ",t]})}function If({children:e}){return a.jsx("div",{className:p.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 n4(){return a.jsx(If,{children:a.jsx("div",{"aria-hidden":"true",style:{minHeight:"32px",flex:1}})})}function r4({categoryFilterOptions:e,typeFilterOptions:t,priorities:n,taxonomyDisplayLabels:s,filterCategories:o,setFilterCategories:l,filterTypes:i,setFilterTypes:d,filterPriorities:m,setFilterPriorities:y,filterStatus:k,setFilterStatus:S,filterAssignees:h,setFilterAssignees:g,assigneeOptions:v,initiativeFilterOptions:_=[],selectedInitiativeId:I="",setSelectedInitiativeId:C=()=>{},workstreamFilterOptions:D=[],selectedWorkstreamId:q="",setSelectedWorkstreamId:B=()=>{},taskScope:X,setTaskScope:me,showArchive:ke,setShowArchive:le,fetchArchive:O,onDeleteAllDeleted:A,clearFilters:de}){return a.jsxs(a.Fragment,{children:[a.jsx(vy,{}),a.jsx(Ki,{label:s?.category||qe("standalone.categoryLabel"),options:e,selected:o,onChange:ge=>l(ge),variant:"value"}),a.jsx(Ki,{label:s?.type||qe("standalone.typeLabel"),options:t,selected:i,onChange:ge=>d(ge),variant:"value"}),a.jsx(Ki,{label:s?.priority||qe("standalone.priorityLabel"),options:n,selected:m,onChange:ge=>y(ge),variant:"value"}),a.jsx(Ki,{label:qe("standalone.statusLabel"),options:ao,selected:k,onChange:ge=>S(ge),variant:"value"}),a.jsx(Ki,{label:qe("standalone.assigneeLabel"),options:v,selected:h,onChange:ge=>g(ge),variant:"value"}),a.jsx("div",{className:p.headerDivider,style:{height:"16px",margin:"0 8px"}}),a.jsx(Eh,{label:"Initiative",options:_,selected:I,onChange:C,allLabel:"All Initiatives",title:"Filter by initiative"}),a.jsx(Eh,{label:"Workstream",options:D,selected:q,onChange:B,allLabel:"All Workstreams",title:"Filter by workstream"}),a.jsx(wy,{scope:X,onScopeChange:ge=>{me(ge),ge==="archived"?(le(!0),O()):ke&&le(!1)},className:p.groupByContainer,labelClassName:p.groupByLabel}),a.jsx("div",{style:{flex:1}}),X==="deleted"&&A&&a.jsx(by,{onClick:A,className:`${p.bulkArchiveBtn} ${p.taskToolbarAction} ${p.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),a.jsx(Sy,{onClick:de})]})}function s4(e){return a.jsx(If,{children:a.jsx(r4,{...e})})}const em=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],tm=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function o4({typeFilters:e,setTypeFilters:t,attachmentFilters:n,setAttachmentFilters:s,clearFilters:o}){return a.jsxs(If,{children:[a.jsx(vy,{}),a.jsx(Ki,{label:"Attachment",options:tm,selected:n,onChange:l=>s(l),variant:"value"}),a.jsx(Ki,{label:"Type",options:em,selected:e,onChange:l=>t(l),variant:"value"}),a.jsx("div",{style:{flex:1}}),a.jsx(Sy,{onClick:o})]})}const i4="_drawerBody_ljth8_1",c4="_paneShell_ljth8_9",l4="_collapsedPaneShell_ljth8_18",d4="_collapsedPaneHeader_ljth8_27",u4="_collapsedPaneLabel_ljth8_39",m4="_treePane_ljth8_49",p4="_treePaneSplit_ljth8_59",f4="_detailPane_ljth8_63",h4="_paneHeader_ljth8_73",g4="_paneHeaderLabel_ljth8_87",y4="_paneContent_ljth8_96",k4="_sectionTitle_ljth8_105",v4="_sectionHeaderRow_ljth8_113",S4="_headerActionGroup_ljth8_120",w4="_toggleActive_ljth8_127",b4="_sectionGroup_ljth8_133",_4="_treeList_ljth8_158",C4="_treeChildren_ljth8_164",A4="_treeRow_ljth8_172",x4="_treeRowDetailOpen_ljth8_184",I4="_treeRowDropReady_ljth8_190",T4="_treeRowDropActive_ljth8_194",R4="_treeRowDropMode_ljth8_200",j4="_treeChevron_ljth8_200",N4="_rowButton_ljth8_201",P4="_detailsButton_ljth8_202",M4="_treeRowDragging_ljth8_206",E4="_treeChevronPlaceholder_ljth8_230",D4="_rowContent_ljth8_252",L4="_rowTopRow_ljth8_262",B4="_referenceBadgeButton_ljth8_271",W4="_referenceBadgeStatic_ljth8_277",F4="_rowTitle_ljth8_298",O4="_rowMeta_ljth8_312",$4="_detailsButtonActive_ljth8_340",U4="_emptyPanel_ljth8_347",z4="_emptyPanelTitle_ljth8_356",H4="_emptyPanelText_ljth8_362",G4="_sectionNote_ljth8_368",V4="_detailHero_ljth8_375",q4="_detailReferenceRow_ljth8_382",K4="_detailTitle_ljth8_389",Z4="_detailDescription_ljth8_396",Y4="_detailActionRow_ljth8_407",J4="_metricGrid_ljth8_414",Q4="_metricCard_ljth8_421",X4="_editorCard_ljth8_426",eF="_editorField_ljth8_433",tF="_editorLabel_ljth8_439",aF="_editorHint_ljth8_445",nF="_editorActions_ljth8_450",rF="_metricValue_ljth8_456",sF="_metricLabel_ljth8_463",oF="_progressTrack_ljth8_470",iF="_progressFill_ljth8_478",cF="_listCard_ljth8_484",lF="_activityTimelineList_ljth8_493",dF="_activityTimelineEmpty_ljth8_502",uF="_deferredPanelFallback_ljth8_506",mF="_sectionDropReady_ljth8_532",pF="_sectionDropActive_ljth8_537",fF="_sectionDropMode_ljth8_543",hF="_attachReferenceRow_ljth8_547",gF="_attachReferenceInput_ljth8_554",yF="_listItem_ljth8_559",kF="_listItemButton_ljth8_568",vF="_detailCardButton_ljth8_577",SF="_listItemText_ljth8_582",wF="_listItemTitle_ljth8_597",bF="_listItemMeta_ljth8_611",_F="_detailChildCard_ljth8_616",CF="_detailChildCardArchived_ljth8_628",AF="_detailChildCardTopRow_ljth8_633",xF="_detailChildReferenceRow_ljth8_642",IF="_taskStatusIcon_ljth8_649",Ce={drawerBody:i4,paneShell:c4,collapsedPaneShell:l4,collapsedPaneHeader:d4,collapsedPaneLabel:u4,treePane:m4,treePaneSplit:p4,detailPane:f4,paneHeader:h4,paneHeaderLabel:g4,paneContent:y4,sectionTitle:k4,sectionHeaderRow:v4,headerActionGroup:S4,toggleActive:w4,sectionGroup:b4,treeList:_4,treeChildren:C4,treeRow:A4,treeRowDetailOpen:x4,treeRowDropReady:I4,treeRowDropActive:T4,treeRowDropMode:R4,treeChevron:j4,rowButton:N4,detailsButton:P4,treeRowDragging:M4,treeChevronPlaceholder:E4,rowContent:D4,rowTopRow:L4,referenceBadgeButton:B4,referenceBadgeStatic:W4,rowTitle:F4,rowMeta:O4,detailsButtonActive:$4,emptyPanel:U4,emptyPanelTitle:z4,emptyPanelText:H4,sectionNote:G4,detailHero:V4,detailReferenceRow:q4,detailTitle:K4,detailDescription:Z4,detailActionRow:Y4,metricGrid:J4,metricCard:Q4,editorCard:X4,editorField:eF,editorLabel:tF,editorHint:aF,editorActions:nF,metricValue:rF,metricLabel:sF,progressTrack:oF,progressFill:iF,listCard:cF,activityTimelineList:lF,activityTimelineEmpty:dF,deferredPanelFallback:uF,sectionDropReady:mF,sectionDropActive:pF,sectionDropMode:fF,attachReferenceRow:hF,attachReferenceInput:gF,listItem:yF,listItemButton:kF,detailCardButton:vF,listItemText:SF,listItemTitle:wF,listItemMeta:bF,detailChildCard:_F,detailChildCardArchived:CF,detailChildCardTopRow:AF,detailChildReferenceRow:xF,taskStatusIcon:IF},TF="_header_c26na_1",RF="_title_c26na_31",jF="_icon_c26na_40",xp={header:TF,title:RF,icon:jF};function NF({label:e,count:t,showZeroCount:n=!1,expanded:s,expandedTitle:o,collapsedTitle:l,onToggle:i,className:d=""}){const m=typeof t=="number"&&(n||t>0),y=s?nl:Xc;return a.jsxs("button",{type:"button",className:`${xp.header} ${d}`.trim(),onClick:i,"aria-expanded":s,title:s?o:l,children:[a.jsxs("span",{className:xp.title,children:[e,m?` (${t})`:""]}),a.jsx(y,{className:xp.icon,size:14,"aria-hidden":"true"})]})}const PF=Ue.lazy(()=>xs(()=>import("./EntityActivityTimeline-BlS7DhA4.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),MF=Ue.lazy(()=>xs(()=>import("./ContextAttachmentManager-AmEny3eI.js"),__vite__mapDeps([8,1,9,2,3,4,5])).then(e=>({default:e.ContextAttachmentManager}))),cd=332,to=392,Ip=56;function $y(e,t,n,s,o){return(e?Ip:cd)+(t?n?Ip:to:0)+(s?o?Ip:to:0)}function EF(e,t){const n=String(t||"").trim(),s=new Map;for(const o of e){const l=String(o?.value||"").trim();if(!l||l==="unassigned"||typeof o.archivedAt=="string"&&o.archivedAt.trim().length>0)continue;const i=String(o.label||l).trim()||l,d=String(o.kind||"").trim().toLowerCase(),m=String(o.username||"").trim().toLowerCase(),y=d==="agent"?`agent:${m||i.toLowerCase()}`:`value:${l}`;(!s.has(y)||l===n)&&s.set(y,{...o,value:l,label:i})}return Array.from(s.values()).sort((o,l)=>o.label.localeCompare(l.label,void 0,{sensitivity:"base"}))}function Tp(e){return e?e.split(/[-_\s]+/g).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):"No status"}function ld({label:e,entityType:t,interactive:n=!0}){const[s,o]=Ue.useState(!1),l=Ue.useCallback(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),window.setTimeout(()=>o(!1),1200)}catch{o(!1)}},[e]);return n?a.jsx(ly,{copied:s,label:e,onClick:l,title:`Copy ${t} reference`,ariaLabel:s?`Copied ${t} reference`:`Copy ${t} reference`,className:Ce.referenceBadgeButton,children:e}):a.jsx("span",{className:`${p.taskIdBadge} ${Ce.referenceBadgeStatic}`.trim(),children:a.jsx("span",{children:e})})}function Rp({rowId:e,rowType:t,referenceLabel:n,title:s,meta:o,active:l,detailOpen:i=!1,canExpand:d=!1,expanded:m=!1,onToggleExpand:y,onToggleScope:k,onToggleDetails:S}){const{active:h}=bg(),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:C,isOver:D}=sf({id:`${I}:${e}`,data:t==="workstream"?{type:I,workstreamId:e}:{type:I,initiativeId:e}}),q=t==="workstream",{attributes:B,listeners:X,setNodeRef:me,transform:ke,isDragging:le}=mv({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!q}),O=q&&ke?{transform:rf.Translate.toString(ke)}:void 0,A=v||_;return a.jsxs("div",{ref:C,style:O,className:`${Ce.treeRow} ${i?Ce.treeRowDetailOpen:""} ${A?Ce.treeRowDropReady:""} ${D?Ce.treeRowDropActive:""} ${le?Ce.treeRowDragging:""} ${A?Ce.treeRowDropMode:""}`,children:[d?a.jsx("button",{type:"button",className:Ce.treeChevron,onClick:y,title:m?"Collapse workstreams":"Expand workstreams",children:m?a.jsx(nl,{size:15}):a.jsx(Xc,{size:15})}):a.jsx("span",{className:`${Ce.treeChevron} ${Ce.treeChevronPlaceholder}`,"aria-hidden":"true"}),a.jsxs("div",{className:Ce.rowContent,children:[a.jsxs("div",{className:Ce.rowTopRow,children:[n?a.jsx(ld,{label:n,entityType:t}):a.jsx("span",{"aria-hidden":"true"}),a.jsx("button",{type:"button",className:`${Ce.detailsButton} ${l?Ce.detailsButtonActive:""}`,onClick:k,title:l?"Clear board scope":"Scope board to this item",children:a.jsx(fg,{size:14})})]}),a.jsxs("button",{type:"button",ref:q?me:void 0,className:Ce.rowButton,onClick:S,...q?B:{},...q?X:{},children:[a.jsx("span",{className:Ce.rowTitle,children:s}),a.jsx("span",{className:Ce.rowMeta,children:o})]})]})]})}function jp({label:e,onExpand:t}){return a.jsx("div",{className:`${Ce.paneShell} ${Ce.collapsedPaneShell}`.trim(),children:a.jsxs("div",{className:Ce.collapsedPaneHeader,children:[a.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:`Expand ${e}`,children:a.jsx(Xc,{size:16})}),a.jsx("span",{className:Ce.collapsedPaneLabel,children:e})]})})}function Qh(){return a.jsxs("div",{className:Ce.deferredPanelFallback,"aria-hidden":"true",children:[a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{})]})}function DF({initiatives:e,standaloneWorkstreams:t,allStandaloneWorkstreams:n=t,activeInitiativeId:s,activeWorkstreamId:o,expandedInitiativeIds:l,detail:i,secondaryPane:d,onCreateInitiative:m,onCreateWorkstream:y,onToggleInitiative:k,onSelectInitiative:S,onSelectWorkstream:h,onOpenInitiativeDetails:g,onOpenWorkstreamDetails:v}){const[_,I]=Ue.useState(!1),C=Ue.useCallback(B=>{if(!_)return B.workstreams;const X=new Set(B.workstreams.map(ke=>ke.id)),me=(B.allWorkstreams||[]).filter(ke=>!!ke.isArchived&&!X.has(ke.id));return[...B.workstreams,...me]},[_]),D=Ue.useMemo(()=>{if(!_)return t;const B=new Set(t.map(me=>me.id)),X=n.filter(me=>!!me.isArchived&&!B.has(me.id));return[...t,...X]},[n,_,t]),q=Ue.useMemo(()=>{const B=e.reduce((me,ke)=>me+(ke.allWorkstreams||[]).filter(le=>!!le.isArchived).length,0),X=n.filter(me=>!!me.isArchived).length;return B+X},[n,e]);return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ce.sectionGroup,children:[a.jsxs("div",{className:Ce.sectionHeaderRow,children:[a.jsx("div",{className:Ce.sectionTitle,children:"Initiatives"}),a.jsxs("div",{className:Ce.headerActionGroup,children:[q>0?a.jsx("button",{type:"button",className:`tf-control-icon ${_?Ce.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(B=>!B),children:_?a.jsx(nf,{size:15}):a.jsx(pg,{size:15})}):null,a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create initiative","aria-label":"Create initiative",onClick:m,children:a.jsx(ro,{size:15})})]})]}),a.jsx("div",{className:Ce.treeList,children:e.length===0?a.jsxs("div",{className:Ce.emptyPanel,children:[a.jsx("div",{className:Ce.emptyPanelTitle,children:"No initiatives yet"}),a.jsxs("div",{className:Ce.emptyPanelText,children:["Initiatives give larger efforts a clear home without crowding the task board. Use the ",a.jsx("code",{children:"+"})," action above to create the first one."]})]}):e.map(B=>{const X=l.has(B.id),me=C(B),ke=B.workstreamCount||0,le=me.filter(de=>!!de.isArchived).length,A=`${_&&le>0?`${ke} workstreams + ${le} archived`:`${ke} workstreams`} • ${B.taskCount} tasks${B.isArchived?" • archived":""}`;return a.jsxs("div",{children:[a.jsx(Rp,{rowId:B.id,rowType:"initiative",referenceLabel:os(B),title:B.title,meta:A,active:s===B.id&&!o,detailOpen:i?.type==="initiative"&&i.item.id===B.id,canExpand:me.length>0,expanded:X,onToggleExpand:()=>k(B.id),onToggleScope:()=>S(B.id),onToggleDetails:()=>{if(i?.type==="initiative"&&i.item.id===B.id){g("");return}g(B.id)}}),X&&me.length>0&&a.jsx("div",{className:Ce.treeChildren,children:me.map(de=>a.jsx(Rp,{rowId:de.id,rowType:"workstream",referenceLabel:Eo(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,B.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))})]},B.id)})})]}),a.jsxs("div",{className:Ce.sectionGroup,children:[a.jsxs("div",{className:Ce.sectionHeaderRow,children:[a.jsx("div",{className:Ce.sectionTitle,children:"Workstreams"}),a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:y,children:a.jsx(ro,{size:15})})]}),a.jsx("div",{className:Ce.treeList,children:D.length===0?a.jsxs("div",{className:Ce.emptyPanel,children:[a.jsx("div",{className:Ce.emptyPanelTitle,children:"No standalone workstreams yet"}),a.jsxs("div",{className:Ce.emptyPanelText,children:["Smaller projects can still use workstreams without needing initiative-level structure. Use the ",a.jsx("code",{children:"+"})," action above to add one."]})]}):D.map(B=>a.jsx(Rp,{rowId:B.id,rowType:"workstream",referenceLabel:Eo(B),title:B.title,meta:`${B.taskCount} tasks • ${B.progressPercent}% complete${B.isArchived?" • archived":""}`,active:o===B.id,detailOpen:i?.type==="workstream"&&i.item.id===B.id||d?.kind==="detail"&&d.detail.item.id===B.id,onToggleScope:()=>h(B.id,null),onToggleDetails:()=>{if(i?.type==="workstream"&&i.item.id===B.id){v("");return}v(B.id)}},B.id))})]})]})}function Xh({detail:e,currentWorkspaceId:t,onOpenNestedWorkstreamDetails:n,onEdit:s,onArchive:o,onUnarchive:l,onCreateTaskInWorkstream:i,onCreateWorkstreamInInitiative:d,onOpenTaskById:m,onRemoveTaskFromWorkstream:y,onAssignInitiativeToWorkstream:k,onAttachTaskToWorkstreamByReference:S,onAttachWorkstreamToInitiativeByReference:h,onAddPlanningContextFile:g,onRemovePlanningContextFile:v,onUpdatePlanningContextCaption:_,parentInitiative:I=null,assigneeOptions:C}){const[D,q]=Ue.useState(""),[B,X]=Ue.useState(!1),[me,ke]=Ue.useState(!0),{active:le}=bg(),O=String(le?.data?.current?.type||""),A=e.type==="workstream"&&O==="task-card",de=e.type==="initiative"&&O==="planning-workstream",ge=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:Y,isOver:P}=sf({id:`${ge}:detail:${e.item.id}`,data:e.type==="initiative"?{type:ge,initiativeId:e.item.id}:{type:ge,workstreamId:e.item.id}}),H=e.type==="initiative"?"Workstreams":"Tasks",ue=Ue.useMemo(()=>{if(e.type!=="initiative")return[];const M=new Set(e.item.workstreams.map(be=>be.id)),$=(e.item.allWorkstreams||[]).filter(be=>!!be.isArchived&&!M.has(be.id));return[...e.item.workstreams,...$]},[e.item,e.type]),ye=Ue.useMemo(()=>e.type!=="workstream"?[]:e.item.tasks||[],[e.item,e.type]),V=e.type==="initiative"?ue.filter(M=>!!M.isArchived).length:ye.filter(M=>!!M.isArchived).length,Me=B?ue:ue.filter(M=>!M.isArchived),_e=B?ye:ye.filter(M=>!M.isArchived),re=e.type==="initiative"?"Initiative":"Workstream",oe=e.type==="initiative"?os(e.item):Eo(e.item);Ue.useEffect(()=>{q(""),X(!1),ke(!0)},[e.item.id,e.type]);const Ie=Ue.useCallback(()=>{const M=D.trim();M&&(e.type==="initiative"?h?.(e.item.id,M):S?.(e.item.id,M),q(""))},[D,e.item.id,e.type,S,h]),Ee=e.type==="initiative"?"Attach workstream to initiative":"Attach task to workstream",je=e.type==="initiative"?"archived workstreams":"archived tasks",Pe=e.type==="workstream"&&I?os(I):"",K=Ue.useMemo(()=>{const M=new Map;for(const $ of C){const be=String($.value||"").trim();be&&(M.set(be,$),M.set(be.toLowerCase(),$))}return M},[C]),x=Ue.useCallback((M,$,be)=>{if(be&&be.trim())return be.trim();const U=String(M||"").trim();if(!U)return $==="ai"?"AI Agent":"You";const se=K.get(U)||K.get(U.toLowerCase());return se?.label?se.label:U},[K]),b=Ue.useCallback(M=>{const $=String(M.actorId||"").trim(),be=K.get($)||K.get($.toLowerCase()),U=M.actorProfile||be||null,se=M.actorType==="system"?"system":M.actorType==="ai"||U?.kind==="ai"||be?.kind==="agent"?"agent":M.actorType==="human"||U?.kind==="human"||be?.kind==="member"?"member":M.fallbackKind||"member",pe=String(U&&"icon"in U&&U.icon?U.icon:se==="agent"?"Bot":se==="member"?"User":"ClipboardList"),z=tc[pe]||(se==="agent"?am:se==="member"?ii:dg);return{kind:se,label:se==="system"?"System":x($,se==="agent"?"ai":"human",U&&"label"in U&&U.label||null),color:U&&"color"in U&&U.color||void 0,ActorIcon:z}},[K,x]),R=Ue.useCallback((M,$)=>{const be=String($||"").trim();if(be){if(M==="ownerId")return K.get(be)?.label||K.get(be.toLowerCase())?.label||be;if(M==="initiativeId"&&I&&be===I.id)return os(I)||I.title}},[K,I]),Q=Ue.useMemo(()=>ky({activity:e.item.activity,comments:e.item.comments}),[e.item.activity,e.item.comments]).length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ce.detailHero,children:[oe?a.jsxs("div",{className:Ce.detailReferenceRow,children:[e.type==="workstream"?a.jsxs(a.Fragment,{children:[a.jsx(Zi,{onClick:M=>{if(M.stopPropagation(),Pe){k?.(e.item.id,null);return}s()},title:Pe?"Remove from initiative":"Attach to initiative",ariaLabel:Pe?"Remove from initiative":"Attach to initiative",children:Pe?a.jsx(Zu,{size:13}):a.jsx(nm,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),Pe?a.jsxs(a.Fragment,{children:[a.jsx(ld,{label:Pe,entityType:"initiative"}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}):null]}):null,a.jsx(ld,{label:oe,entityType:e.type})]}):null,a.jsx("h3",{className:Ce.detailTitle,children:e.item.title}),a.jsx("p",{className:Ce.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.")}),a.jsx("div",{className:Ce.progressTrack,"aria-label":`${e.item.progressPercent}% complete`,children:a.jsx("div",{className:Ce.progressFill,style:{width:`${e.item.progressPercent}%`}})}),a.jsxs("div",{className:Ce.detailActionRow,children:[a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:s,children:a.jsxs("span",{children:["Edit ",re]})}),e.item.isArchived?a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:l,children:a.jsx("span",{children:"Unarchive"})}):a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:o,children:a.jsx("span",{children:"Archive"})})]})]}),a.jsxs("div",{className:Ce.metricGrid,children:[a.jsxs("div",{className:Ce.metricCard,children:[a.jsx("span",{className:Ce.metricValue,children:e.item.taskCount}),a.jsx("span",{className:Ce.metricLabel,children:"Tasks in scope"})]}),a.jsxs("div",{className:Ce.metricCard,children:[a.jsx("span",{className:Ce.metricValue,children:e.item.completedTaskCount}),a.jsx("span",{className:Ce.metricLabel,children:"Done / terminal"})]}),a.jsxs("div",{className:Ce.metricCard,children:[a.jsx("span",{className:Ce.metricValue,children:e.item.ownerLabel||"Unassigned"}),a.jsx("span",{className:Ce.metricLabel,children:"Owner"})]}),a.jsxs("div",{className:Ce.metricCard,children:[a.jsx("span",{className:Ce.metricValue,children:(e.item.commentCount||0)+(e.item.attachmentCount||0)}),a.jsx("span",{className:Ce.metricLabel,children:"Context items"})]})]}),a.jsxs("div",{ref:Y,className:`${Ce.listCard} ${A||de?Ce.sectionDropReady:""} ${P?Ce.sectionDropActive:""} ${A||de?Ce.sectionDropMode:""}`.trim(),children:[a.jsxs("div",{className:Ce.sectionHeaderRow,children:[a.jsx("div",{className:Ce.sectionTitle,children:H}),a.jsxs("div",{className:Ce.headerActionGroup,children:[V>0?a.jsx("button",{type:"button",className:`tf-control-icon ${B?Ce.toggleActive:""}`.trim(),title:B?`Hide ${je}`:`Show ${je}`,"aria-label":B?`Hide ${je}`:`Show ${je}`,"aria-pressed":B,onClick:()=>X(M=>!M),children:B?a.jsx(nf,{size:15}):a.jsx(pg,{size:15})}):null,e.type==="initiative"?a.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:a.jsx(ro,{size:15})}):a.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:a.jsx(ro,{size:15})})]})]}),a.jsxs("div",{className:Ce.attachReferenceRow,children:[a.jsx(Zi,{onClick:M=>{M.stopPropagation(),Ie()},disabled:!D.trim(),title:Ee,ariaLabel:Ee,children:a.jsx(nm,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx("input",{type:"text",className:`${p.input} ${Ce.attachReferenceInput}`.trim(),placeholder:e.type==="initiative"?"Paste workstream reference (e.g. WS-123)":"Paste task reference (e.g. T-123)",value:D,onChange:M=>q(M.target.value),onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),Ie())}})]}),e.type==="initiative"?Me.length>0?Me.map(M=>{const $=Eo(M),be=()=>n?.(M.id);return a.jsx("div",{className:`${Ce.listItemButton} ${Ce.detailCardButton}`.trim(),children:a.jsxs("div",{className:`${Ce.listItem} ${Ce.detailChildCard} ${M.isArchived?Ce.detailChildCardArchived:""}`.trim(),children:[a.jsx("div",{className:Ce.detailChildCardTopRow,children:a.jsxs("div",{className:Ce.detailChildReferenceRow,children:[a.jsx(Zi,{onClick:U=>{U.stopPropagation(),k?.(M.id,null)},title:"Remove from initiative",ariaLabel:"Remove from initiative",children:a.jsx(Zu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),$?a.jsx(ld,{label:$,entityType:"workstream"}):a.jsx("span",{"aria-hidden":"true"})]})}),a.jsxs("div",{role:"button",tabIndex:0,className:Ce.listItemText,onClick:be,onKeyDown:U=>{U.key!=="Enter"&&U.key!==" "||(U.preventDefault(),be())},children:[a.jsx("span",{className:Ce.listItemTitle,children:M.title}),a.jsxs("span",{className:Ce.listItemMeta,children:[M.taskCount," tasks • ",M.progressPercent,"% complete",M.isArchived?" • archived":""]})]})]})},M.id)}):a.jsxs("div",{className:Ce.emptyPanel,children:[a.jsx("div",{className:Ce.emptyPanelTitle,children:"No workstreams yet"}),a.jsx("div",{className:Ce.emptyPanelText,children:"Add the first workstream to break the initiative into clearer lanes of execution."})]}):_e.length>0?[..._e].sort((M,$)=>{const be=pd(M.status).value==="done",U=pd($.status).value==="done";return be===U?0:be?1:-1}).map(M=>{const $=M.referenceNumber?`T-${M.referenceNumber}`:"",be=pd(M.status),U=tc[be.icon||"Square"],se=Dn(be.color)||"var(--text-secondary)",pe=()=>m?.(M.id),z=`${Tp(M.status)}${M.isArchived?" • archived":""}`;return a.jsx("div",{className:`${Ce.listItemButton} ${Ce.detailCardButton}`.trim(),children:a.jsxs("div",{className:`${Ce.listItem} ${Ce.detailChildCard} ${M.isArchived?Ce.detailChildCardArchived:""}`.trim(),children:[a.jsxs("div",{className:Ce.detailChildCardTopRow,children:[a.jsxs("div",{className:Ce.detailChildReferenceRow,children:[a.jsx(Zi,{onClick:ne=>{ne.stopPropagation(),y?.(M.id,e.item.id)},title:"Remove from workstream",ariaLabel:"Remove from workstream",children:a.jsx(Zu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),$?a.jsx(ld,{label:$,entityType:"task"}):a.jsx("span",{"aria-hidden":"true"})]}),a.jsx("span",{className:Ce.taskStatusIcon,style:{color:se},"aria-label":be.shortLabel||Tp(M.status),title:be.shortLabel||Tp(M.status),children:U?a.jsx(U,{size:18,strokeWidth:2.4}):null})]}),a.jsxs("div",{role:"button",tabIndex:0,className:Ce.listItemText,onClick:pe,onKeyDown:ne=>{ne.key!=="Enter"&&ne.key!==" "||(ne.preventDefault(),pe())},children:[a.jsx("span",{className:Ce.listItemTitle,children:M.title}),a.jsx("span",{className:Ce.listItemMeta,children:z})]})]})},M.id)}):a.jsxs("div",{className:Ce.sectionNote,children:["No tasks are linked to this workstream yet. Use the ",a.jsx("code",{children:"+"})," action above to add the first one."]})]}),a.jsx("div",{className:Ce.listCard,children:a.jsx(Ue.Suspense,{fallback:a.jsx(Qh,{}),children:a.jsx(MF,{ownerType:e.type,ownerId:e.item.id,ownerReferenceLabel:oe,workspaceId:t,attachments:e.item.attachments||[],onAddAttachment:M=>g?.(e.type,e.item.id,M),onRemoveAttachment:M=>v?.(e.type,e.item.id,M),onUpdateAttachmentCaption:(M,$)=>_?.(e.type,e.item.id,M,$)})})}),a.jsxs("div",{className:Ce.listCard,children:[a.jsx(NF,{label:"Recent Activity",count:Q,showZeroCount:!0,expanded:me,expandedTitle:"Hide recent activity",collapsedTitle:"Show recent activity",onToggle:()=>ke(M=>!M)}),me?a.jsx(Ue.Suspense,{fallback:a.jsx(Qh,{}),children:a.jsx(PF,{activity:e.item.activity,comments:e.item.comments,formatFieldValue:R,resolveActorPresentation:b,onOpenTaskById:m,emptyMessage:`No ${e.type} activity yet.`,listClassName:Ce.activityTimelineList,emptyClassName:Ce.activityTimelineEmpty})}):null]})]})}function eg({editor:e,draftTitle:t,draftDescription:n,draftOwner:s,draftInitiativeId:o,assigneeOptions:l,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 ${_}`,C=Ue.useMemo(()=>EF(l,s),[l,s]),D=Ue.useCallback(B=>{B.preventDefault(),h()},[h]),q=Ue.useCallback(()=>{e.mode!=="edit"||e.entityType!=="workstream"||v?.(e.targetId)},[e,v]);return a.jsxs("form",{className:Ce.editorCard,onSubmit:D,children:[a.jsxs("div",{className:Ce.editorField,children:[a.jsx("label",{className:Ce.editorLabel,children:"Title"}),a.jsx("input",{className:p.input,disabled:g,value:t,onChange:B=>d(B.target.value),placeholder:e.entityType==="initiative"?"Q3 Product Launch":"Content Production"})]}),a.jsxs("div",{className:Ce.editorField,children:[a.jsx("label",{className:Ce.editorLabel,children:"Description"}),a.jsx("textarea",{className:p.textarea,disabled:g,value:n,onChange:B=>m(B.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"&&a.jsxs("div",{className:Ce.editorField,children:[a.jsx("label",{className:Ce.editorLabel,children:"Initiative"}),i&&a.jsxs("div",{className:Ce.editorHint,children:["Current: ",i.title]}),a.jsxs("div",{className:Ce.attachReferenceRow,children:[e.mode==="edit"&&a.jsxs(a.Fragment,{children:[a.jsx(Zi,{onClick:B=>{B.stopPropagation(),q()},disabled:g||!o.trim(),title:"Attach workstream to initiative",ariaLabel:"Attach workstream to initiative",children:a.jsx(nm,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}),a.jsx("input",{type:"text",className:`${p.input} ${Ce.attachReferenceInput}`.trim(),disabled:g,placeholder:"Paste initiative reference (e.g. IN-123)",value:o,onChange:B=>k(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),q())}})]})]}),a.jsxs("div",{className:Ce.editorField,children:[a.jsx("label",{className:Ce.editorLabel,children:"Owner"}),a.jsxs("select",{className:`${p.select} ${p.groupBySelect}`,disabled:g,value:s,onChange:B=>y(B.target.value),children:[a.jsx("option",{value:"",children:"Unassigned"}),C.map(B=>a.jsx("option",{value:B.value,children:B.label},B.value))]})]}),a.jsxs("div",{className:Ce.editorActions,children:[a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:S,disabled:g,children:"Cancel"}),a.jsx("button",{type:"submit",className:p.primaryUpdateBtn,disabled:g,children:I})]})]})}function LF({open:e,leftOffset:t=0,initiatives:n,standaloneWorkstreams:s,allStandaloneWorkstreams:o,activeInitiativeId:l,activeWorkstreamId:i,expandedInitiativeIds:d,detail:m,editor:y,secondaryPane:k,currentWorkspaceId:S,assigneeOptions:h,draftInitiativeSummary:g,draftTitle:v,draftDescription:_,draftOwner:I,draftInitiativeId:C,onChangeDraftTitle:D,onChangeDraftDescription:q,onChangeDraftOwner:B,onChangeDraftInitiativeId:X,onCollapseTreePane:me,onExpandTreePane:ke,onCollapsePrimaryPane:le,onExpandPrimaryPane:O,onCollapseSecondaryPane:A,onExpandSecondaryPane:de,onBackFromSecondary:ge,treeCollapsed:Y,primaryCollapsed:P,secondaryCollapsed:H,onCancelEditor:ue,onSubmitEditor:ye,isSubmittingEditor:V,onCreateInitiative:Me,onCreateWorkstream:_e,onToggleInitiative:re,onSelectInitiative:oe,onSelectWorkstream:Ie,onOpenInitiativeDetails:Ee,onOpenWorkstreamDetails:je,onOpenNestedWorkstreamDetails:Pe,onEditInitiative:K,onEditWorkstream:x,onArchiveInitiative:b,onUnarchiveInitiative:R,onArchiveWorkstream:F,onUnarchiveWorkstream:Q,onCreateTaskInWorkstream:M,onCreateWorkstreamInInitiative:$,onAssignInitiativeToWorkstream:be,onOpenTaskById:U,onRemoveTaskFromWorkstream:se,onAttachTaskToWorkstreamByReference:pe,onAttachWorkstreamToInitiativeByReference:z,onAddPlanningContextFile:ne,onRemovePlanningContextFile:ie,onUpdatePlanningContextCaption:Re}){const Te=!!(m||y),De=!!k,Oe=$y(Y,Te,P,De,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=Ue.useCallback(Ye=>{const Ct=String(Ye.initiativeId||"").trim();return Ct&&n.find(dt=>dt.id===Ct)||null},[n]);return a.jsx("aside",{style:{position:"absolute",top:0,left:e?`${t}px`:`${t-Oe-24}px`,bottom:0,width:`${Oe}px`,minWidth:`${Oe}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:a.jsxs("div",{className:Ce.drawerBody,children:[Y?a.jsx(jp,{label:"Planning",onExpand:ke}):a.jsxs("div",{className:`${Ce.paneShell} ${p.appScrollbar} tf-scrollbar ${Ce.treePane} ${Te&&!P?Ce.treePaneSplit:""}`.trim(),style:{flex:`0 0 ${cd}px`,width:`${cd}px`,minWidth:`${cd}px`,maxWidth:`${cd}px`},children:[a.jsxs("div",{className:Ce.paneHeader,children:[a.jsx("span",{className:Ce.paneHeaderLabel,children:"Planning"}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:me,children:a.jsx(Mo,{size:16})})]}),a.jsx("div",{className:Ce.paneContent,children:a.jsx(DF,{initiatives:n,standaloneWorkstreams:s,allStandaloneWorkstreams:o,activeInitiativeId:l,activeWorkstreamId:i,expandedInitiativeIds:d,detail:m,secondaryPane:k,onCreateInitiative:Me,onCreateWorkstream:_e,onToggleInitiative:re,onSelectInitiative:oe,onSelectWorkstream:Ie,onOpenInitiativeDetails:Ee,onOpenWorkstreamDetails:je})})]}),Te&&(P?a.jsx(jp,{label:vt,onExpand:O}):a.jsxs("div",{className:`${Ce.paneShell} ${p.appScrollbar} tf-scrollbar ${Ce.detailPane}`.trim(),style:{flex:`0 0 ${to}px`,width:`${to}px`,minWidth:`${to}px`,maxWidth:`${to}px`},children:[a.jsxs("div",{className:Ce.paneHeader,children:[a.jsx("span",{className:Ce.paneHeaderLabel,children:vt}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:le,children:a.jsx(Mo,{size:16})})]}),a.jsx("div",{className:Ce.paneContent,children:y?a.jsx(eg,{editor:y,draftTitle:v,draftDescription:_,draftOwner:I,draftInitiativeId:C,assigneeOptions:h,draftInitiativeSummary:g,onChangeDraftTitle:D,onChangeDraftDescription:q,onChangeDraftOwner:B,onChangeDraftInitiativeId:X,onCancel:ue,onSubmit:ye,isSubmitting:V,onAssignInitiativeToWorkstream:be}):m?a.jsx(Xh,{detail:m,currentWorkspaceId:S,assigneeOptions:h,onOpenNestedWorkstreamDetails:m.type==="initiative"?Pe:void 0,onCreateTaskInWorkstream:m.type==="workstream"?M:void 0,onCreateWorkstreamInInitiative:m.type==="initiative"?$:void 0,onOpenTaskById:m.type==="workstream"?U:void 0,onRemoveTaskFromWorkstream:m.type==="workstream"?se:void 0,onAssignInitiativeToWorkstream:be,onAttachTaskToWorkstreamByReference:m.type==="workstream"?pe:void 0,onAttachWorkstreamToInitiativeByReference:m.type==="initiative"?z:void 0,parentInitiative:m.type==="workstream"?kt(m.item):null,onEdit:()=>m.type==="initiative"?K(m.item.id):x(m.item.id),onArchive:()=>m.type==="initiative"?b(m.item.id):F(m.item.id),onUnarchive:()=>m.type==="initiative"?R(m.item.id):Q(m.item.id),onAddPlanningContextFile:ne,onRemovePlanningContextFile:ie,onUpdatePlanningContextCaption:Re}):null})]})),De&&(H?a.jsx(jp,{label:st,onExpand:de}):a.jsxs("div",{className:`${Ce.paneShell} ${p.appScrollbar} tf-scrollbar ${Ce.detailPane}`.trim(),style:{flex:`0 0 ${to}px`,width:`${to}px`,minWidth:`${to}px`,maxWidth:`${to}px`},children:[a.jsxs("div",{className:Ce.paneHeader,children:[a.jsx("span",{className:Ce.paneHeaderLabel,children:st}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:A,children:a.jsx(Mo,{size:16})})]}),a.jsx("div",{className:Ce.paneContent,children:k?.kind==="editor"?a.jsx(eg,{editor:k.editor,draftTitle:v,draftDescription:_,draftOwner:I,draftInitiativeId:C,assigneeOptions:h,draftInitiativeSummary:g,onChangeDraftTitle:D,onChangeDraftDescription:q,onChangeDraftOwner:B,onChangeDraftInitiativeId:X,onCancel:ge,onSubmit:ye,isSubmitting:V,onAssignInitiativeToWorkstream:be}):k?a.jsx(Xh,{detail:k.detail,currentWorkspaceId:S,assigneeOptions:h,onCreateTaskInWorkstream:M,onOpenTaskById:U,onRemoveTaskFromWorkstream:se,onAssignInitiativeToWorkstream:be,onAttachTaskToWorkstreamByReference:pe,parentInitiative:kt(k.detail.item),onEdit:()=>x(k.detail.item.id),onArchive:()=>F(k.detail.item.id),onUnarchive:()=>Q(k.detail.item.id),onAddPlanningContextFile:ne,onRemovePlanningContextFile:ie,onUpdatePlanningContextCaption:Re}):null})]}))]})})}const BF={"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"}},fd="annotated_attachments.workspace_access",hd="documents.workspace_access",wm="workflows.workspace_access",bm="agents.workspace_access",tg="initiatives.workspace_access",WF=Object.entries(BF).reduce((e,[t,n])=>(e[t]={key:t,enabled:!!n.enabled,description:String(n.description||""),owner:String(n.owner||""),removalMilestone:String(n.removalMilestone||"")},e),{});function FF(e){const t=String(e||"").trim();return t&&WF[t]||null}function OF(e){const t=FF(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 ad(e){return OF(e.featureKey)}const $F=["tasks","docs","annotate","workflows","agents"];function UF(e){const t=e?.featureAccess||{},n={tasks:{id:"tasks",label:"Tasks",featureKey:null,enabled:!0,fallbackModuleId:"tasks"},docs:{id:"docs",label:"Documents",featureKey:hd,enabled:t[hd]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:"Image Notes",featureKey:fd,enabled:t[fd]?.allowed??!1,fallbackModuleId:"tasks"},workflows:{id:"workflows",label:"Workflows",featureKey:wm,enabled:t[wm]?.allowed??!1,fallbackModuleId:"tasks"},agents:{id:"agents",label:"Agents",featureKey:bm,enabled:t[bm]?.allowed??!1,fallbackModuleId:"tasks"}};return $F.map(s=>n[s])}function zF(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 ag(e,t){const n=t.find(s=>s.id===e);return n?n.enabled?n.id:n.fallbackModuleId:"tasks"}const HF="_weekLabel_vet2o_1",GF="_sectionTitle_vet2o_6",VF="_calendarHeader_vet2o_11",qF="_monthLabel_vet2o_18",KF="_weekdayGrid_vet2o_23",ZF="_weekdayLabel_vet2o_30",YF="_calendarGrid_vet2o_36",JF="_calendarDay_vet2o_42",QF="_calendarDayDot_vet2o_55",XF="_jumpRow_vet2o_67",eO="_displaySection_vet2o_73",tO="_toggleLabel_vet2o_79",aO="_expiredSummary_vet2o_87",nO="_actionButton_vet2o_95",Hn={weekLabel:HF,sectionTitle:GF,calendarHeader:VF,monthLabel:qF,weekdayGrid:KF,weekdayLabel:ZF,calendarGrid:YF,calendarDay:JF,calendarDayDot:QF,jumpRow:XF,displaySection:eO,toggleLabel:tO,expiredSummary:aO,actionButton:nO},ng=["mon","tue","wed","thu","fri","sat","sun"],rO={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function Jc(e){const t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${s}`}function dd(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(n.getTime())?null:n}function Xp(e,t){const n=e.getDay(),s=t==="sunday"?-n:n===0?-6:1-n,o=new Date(e);return o.setHours(0,0,0,0),o.setDate(o.getDate()+s),o}function sO(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 Uy(e,t){const n=new Date(e);return n.setDate(e.getDate()+t),n}function oO(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))),s=n.getUTCDay()||7;n.setUTCDate(n.getUTCDate()+4-s);const o=new Date(Date.UTC(n.getUTCFullYear(),0,1)),l=Math.ceil(((n.getTime()-o.getTime())/864e5+1)/7);return`${n.getUTCFullYear()}-W${String(l).padStart(2,"0")}`}const ef=320;function iO({open:e,onClose:t,scheduleSelectedDate:n,setScheduleSelectedDate:s,scheduleCalendarMonth:o,setScheduleCalendarMonth:l,scheduleShowWeekends:i,setScheduleShowWeekends:d,scheduleShowBacklog:m,setScheduleShowBacklog:y,scheduleOnlyExpired:k,setScheduleOnlyExpired:S,expiredScheduledCount:h,overdueDueCount:g,expiredLeafCandidates:v,expiredRecoveryCandidates:_,onMoveExpiredToSelectedWeek:I,onMoveExpiredToBacklog:C,scheduleBulkBusy:D,globalWeekStartsOn:q,resolvedLocale:B,todayDateOnly:X,scheduleBaseTasks:me,scheduleWeekStart:ke,scheduleWeekLabel:le}){const O=Ue.useMemo(()=>{const[P,H]=o.split("-"),ue=Number(P),ye=Number(H);if(!Number.isInteger(ue)||!Number.isInteger(ye)||ye<1||ye>12){const V=dd(n)||new Date;return new Date(V.getFullYear(),V.getMonth(),1)}return new Date(ue,ye-1,1)},[o,n]),A=Ue.useMemo(()=>vm(O,{month:"long",year:"numeric"},B),[O,B]),de=Ue.useMemo(()=>{const P=Xp(O,q);return Array.from({length:42},(H,ue)=>Uy(P,ue))},[O,q]),ge=Ue.useMemo(()=>{const P=new Map;for(const H of me){const ue=H.scheduledDate||"";if(!ue)continue;const V=!(H.status==="done"||H.status==="cancelled")&&ue<X,Me=P.get(ue);Me?(Me.count+=1,V&&(Me.hasExpired=!0)):P.set(ue,{count:1,hasExpired:V})}return P},[me,X]),Y=Ue.useMemo(()=>q==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[q]);return a.jsxs("aside",{className:`${p.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:`${ef}px`,minWidth:`${ef}px`},children:[a.jsxs("div",{className:"tf-sidebar-header",children:[a.jsxs("div",{className:"tf-sidebar-title",children:[a.jsx(Uk,{size:16}),a.jsx("span",{children:"Schedule Controls"})]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:"Hide Schedule Sidebar",children:a.jsx(Xc,{size:16})})]}),a.jsxs("div",{className:Hn.weekLabel,children:["Week of ",le]}),a.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[a.jsxs("div",{className:Hn.calendarHeader,children:[a.jsx("button",{className:"tf-control-icon",onClick:()=>{const P=new Date(O);P.setMonth(O.getMonth()-1),l(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:a.jsx(Mo,{size:14})}),a.jsx("div",{className:Hn.monthLabel,children:A}),a.jsx("button",{className:"tf-control-icon",onClick:()=>{const P=new Date(O);P.setMonth(O.getMonth()+1),l(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:a.jsx(Xc,{size:14})})]}),a.jsx("div",{className:Hn.weekdayGrid,children:Y.map(P=>a.jsx("div",{className:Hn.weekdayLabel,children:P},P))}),a.jsx("div",{className:Hn.calendarGrid,children:de.map(P=>{const H=Jc(P),ue=P.getMonth()!==O.getMonth(),ye=Xp(P,q),V=Jc(ye)===Jc(ke),Me=H===n,_e=H===X,re=H<X,oe=ge.get(H),Ie=!!oe,Ee=!!oe?.hasExpired;return a.jsxs("button",{onClick:()=>{s(H),l(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},className:Hn.calendarDay,style:{"--calendar-day-border":Me?"1px solid #2563eb":_e?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":Me?"rgba(59,130,246,0.22)":_e?"rgba(245,158,11,0.16)":V?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":ue?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":Me||_e?700:500,"--calendar-day-opacity":re?.42:1},title:`${_e?`${H} (Today)`:H}`+(Ie?` • ${oe?.count} scheduled`:"")+(Ee?" • includes expired":""),children:[P.getDate(),Ie&&a.jsx("span",{className:Hn.calendarDayDot,style:{"--calendar-dot-background":Ee?"#ef4444":"#3b82f6","--calendar-dot-opacity":ue?.6:.95}})]},H)})}),a.jsx("div",{className:Hn.jumpRow,children:a.jsx("button",{className:"tf-control-icon",onClick:()=>{const P=new Date;s(Jc(P)),l(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),a.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${Hn.displaySection}`,children:[a.jsx("div",{className:Hn.sectionTitle,children:"Display"}),a.jsxs("label",{className:Hn.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:i,onChange:P=>d(P.target.checked)}),"Show weekends"]}),a.jsxs("label",{className:Hn.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:m,onChange:P=>y(P.target.checked)}),"Show backlog"]}),a.jsxs("label",{className:Hn.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:k,onChange:P=>S(P.target.checked)}),"Only expired/overdue"]})]}),h>0&&a.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[a.jsx("div",{className:Hn.sectionTitle,children:"Expired Tasks"}),a.jsxs("div",{className:Hn.expiredSummary,children:[a.jsxs("span",{children:[h," expired"]}),a.jsxs("span",{children:[g," overdue"]})]}),a.jsx("button",{className:`tf-control-icon ${Hn.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"}),a.jsx("button",{className:`tf-control-icon ${Hn.actionButton}`,onClick:C,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 cO(e,t,n){return zy(e,t)&&n==="team"}function lO({isOpen:e,workspaceId:t,refreshKeys:n}){const[s,o]=r.useState([]),[l,i]=r.useState(!1),[d,m]=r.useState(null),y=r.useRef(null),k=r.useRef(null);r.useLayoutEffect(()=>{k.current=uO(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=dO(y.current),o(_=>{const I=_.length===0?v:NW(_,v,15);return PW(_,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,...n]),{syncRecentEvents:s,syncRecentEventsLoading:l,syncRecentEventsError:d,syncEventsListRef:y,loadRecentSyncEvents:S}}function dO(e){return e&&e.scrollTop>8?{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight}:null}function uO(e,t){if(!t||!e)return null;const n=e.scrollHeight-t.scrollHeight;return e.scrollTop=t.scrollTop+Math.max(0,n),null}function mO({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:n,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:l,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,workspaceSyncPhase:k,referenceMismatchCount:S,syncRecentEvents:h,loadRecentSyncEvents:g,pushNotice:v,resetWorkspaceSyncCursorAndPull:_,workspaceSyncBusy:I}){const[C,D]=r.useState(!1),[q,B]=r.useState(!1),[X,me]=r.useState(!1),ke=r.useCallback(async()=>{try{const A=h.length>0?h:await g(),de=WW({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:n,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:l,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:By(k,C,I),referenceMismatchCount:S,syncRecentEvents:A});await navigator.clipboard.writeText(de),me(!0),window.setTimeout(()=>{me(!1)},1800),v("Sync details copied to clipboard.","success")}catch{me(!1),v("Failed to copy sync details.","error")}},[e,l,i,o,g,v,S,y,h,t,d,k,m,s,n,I,C]),le=r.useCallback(async()=>{B(!1),D(!0);try{await _()}finally{D(!1)}},[_]),O=r.useCallback(()=>{if(!C){if(I){B(!0);return}le()}},[le,I,C]);return r.useEffect(()=>{q&&(I||C||le())},[le,I,C,q]),{workspaceSyncRepairBusy:C,workspaceSyncRepairQueued:q,workspaceSyncCopied:X,handleCopySyncDetails:ke,handleQueueOrRunRepairSync:O}}function pO({canManageWorkspaceSync:e,workspaceCloudSyncEnabled:t,saveWorkspaceCloudSyncSettings:n}){const[s,o]=r.useState(!1),[l,i]=r.useState(!1),[d,m]=r.useState(!1),[y,k]=r.useState(null),S=r.useCallback(async C=>{if(e){k(null),m(!0);try{const D=await n({enabled:C});D.success||k(D.error||(C?"Failed to enable sync.":"Failed to disable sync."))}finally{m(!1)}}},[e,n]),h=r.useCallback(async C=>{if(C&&!t){i(!0);return}await S(C)},[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:l,workspaceSyncToggleBusy:d,workspaceSyncError:y,syncControlBusy:d,openSyncStatusModal:_,closeSyncStatusModal:I,handleWorkspaceSyncToggle:h,cancelSyncEnableWarning:g,confirmSyncEnableWarning:v}}const rg=Ue.lazy(()=>xs(()=>import("./TaskSettings-CJPC2Bft.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings}))),fO=Ue.lazy(()=>xs(()=>import("./AnnotatedAttachmentWorkspace-BJLe8DFj.js"),__vite__mapDeps([12,1,2,3,4,5,13])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),hO=Ue.lazy(()=>xs(()=>import("./DocumentWorkspace-Cqdq31Ha.js"),__vite__mapDeps([14,1,2,9,3,4,5,15])).then(e=>({default:e.DocumentWorkspaceShell}))),gO=Ue.lazy(()=>xs(()=>import("./WorkflowsModule-CEEGuxsf.js"),__vite__mapDeps([16,1,2,3,4,5])).then(e=>({default:e.WorkflowsModule}))),yO=Ue.lazy(()=>xs(()=>import("./AgentsModule-7jpDeuVR.js"),__vite__mapDeps([17,1,2,3,4,5])).then(e=>({default:e.AgentsModule})));Ue.lazy(()=>xs(()=>import("./InitiativesModule-C1qfO1uZ.js"),__vite__mapDeps([18,1,2,3,4,5])).then(e=>({default:e.InitiativesModule})));const kO=Ue.lazy(()=>xs(()=>import("./PlansPage-DFt5w-0Y.js"),__vite__mapDeps([19,1,2,5,3,4,20])).then(e=>({default:e.PlansPage}))),vO="image/png,image/jpeg,image/webp,image/gif",SO=5*1024*1024,wO=e=>e;function bO(e,t){const n=xm(e);if(n)return th(n).label.toUpperCase();for(const s of t){const o=String(s||"").trim();if(!o)continue;const l=uf(o);if(l)return th(l).label.toUpperCase();let i=o.toLowerCase();try{i=new URL(o.includes("://")?o:`https://${o}`).hostname.toLowerCase()}catch{i=o.toLowerCase()}if(!(i.includes("localhost")||i.includes("127.0.0.1")||i.includes("::1")))return i.toUpperCase()}return"UNKNOWN"}function nd(){return typeof performance<"u"?performance.now():Date.now()}function _O(e){const s=_g(),o=Cg(),l=r.useMemo(()=>new URLSearchParams(o.search),[o.search]),i=String(l.get("screen")||"").trim().toLowerCase()==="plans",d=r.useCallback(u=>{const w=new URLSearchParams(o.search);w.set("screen","plans");for(const[N,ce]of Object.entries(u||{}))ce==null||String(ce).trim()===""?w.delete(N):w.set(N,String(ce));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:C,zenMode:D,setZenMode:q,filterStatus:B,setFilterStatus:X,tasks:me,handleEdit:ke,handleSubmit:le,resetForm:O,handleUpdateTask:A,editingTaskId:de,loading:ge,error:Y,title:P,setTitle:H,description:ue,setDescription:ye,checklistItems:V,setChecklistItems:Me,category:_e,setCategory:re,type:oe,setType:Ie,priority:Ee,setPriority:je,complexity:Pe,setComplexity:K,setStatus:x,approach:b,setApproach:R,assignee:F,setAssignee:Q,scheduledDate:M,setScheduledDate:$,dueDate:be,setDueDate:U,workstreamInput:se,setWorkstreamInput:pe,manualComplexityEnabled:z,checklistDropdownEnabled:ne,showTaskCardStatusLabel:ie,formTaxonomies:Re,setFormTaxonomies:Te,comments:De,newCommentText:Oe,setNewCommentText:vt,attachments:st,setAttachments:kt,setAttachmentsDirty:Ye,descriptionFocused:Ct,setDescriptionFocused:dt,showMarkdownHelp:Qe,setShowMarkdownHelp:Rt,showChecklist:ee,setShowChecklist:ze,showComments:ft,setShowComments:it,handleAddComment:Et,handleSetWorkstreamForCurrentTask:ht,handleOpenTaskById:Ot,taxonomies:Dt,activeTypes:We,priorities:tt,taxonomyDisplayLabels:Fe,approaches:Ze,copiedId:St,handleCopyId:ot,handleToggleInProgress:te,handleToggleComplete:Le,handleToggleReview:At,handleToggleCancel:jt,handleArchiveTask:Wt,handleDelete:Ge,handleUnarchive:$t,handleRestoreDeletedTask:yt,handlePermanentlyDeleteDeletedTask:E,handleEmptyDeletedTasks:c,fetchTasks:J,searchQuery:we,setSearchQuery:xe,filterCategories:Ke,setFilterCategories:Je,filterTypes:Ne,setFilterTypes:zt,filterPriorities:Jt,setFilterPriorities:Pt,filterAssignees:Ft,setFilterAssignees:Lt,hasInitedFilters:Ht,assigneeOptions:ra,taskScope:Vt,setTaskScope:Ga,sortBy:Va,setSortBy:qa,clearFilters:cn,settingsModel:he,configLoaded:rt,currentTheme:Ae,setCurrentTheme:Nt,pathSaved:pt,saveSettings:wt,keyShortcut:Ca,setKeyShortcut:ya,globalWeekStartsOn:ia,locale:ca,jsonBackupEnabled:Oa,setJsonBackupEnabled:gt,mcpHostRoot:rr,setMcpHostRoot:ua,settingsSection:ta,setSettingsSection:wa,runtimeMode:Kt,workspaceSwitchingEnabled:vr,cloudAuthConfigured:Ta,authRequiredForApi:Qa,authBlocked:Ra,isAuthenticated:Zt,authUserId:Ka,authWorkspaceId:aa,authUserEmail:ln,authUserDisplayName:yn,authUserAvatarUrl:Sr,authSessionResolved:la,realtimeSyncEnabled:wr,realtimeSyncFlagSource:qr,workspaceCloudSyncEnabled:Vn,workspaceSyncPhase:kn,workspaceSyncStatus:$a,workspaceSyncSummary:br,workspaceSyncRecommendedAction:dn,workspaceSyncBusy:Ea,workspaceSyncPendingChanges:ja,saveWorkspaceCloudSyncSettings:_r,pushNotice:xt,userGlobalSyncStatus:vn,workspaceLastSuccessfulSyncAt:Sn,workspaceLastPullAt:un,workspaceLastPushAt:Ua,workspaceLastErrorAt:sr,userGlobalSyncError:Na,workspaceLastErrorMessage:ka,retryWorkspaceCloudSync:Ln,resetWorkspaceSyncCursorAndPull:wn,getWorkspaceSyncDiagnostics:va,currentWorkspaceId:Yt,currentWorkspaceRole:bn,availableWorkspaces:za,switchWorkspace:Pa,updateCurrentUserProfile:Bn,resolveCloudAuthUrl:Ma=wO,logout:Mr,fetchLoginMethods:na,unlinkLoginMethod:da,addPasswordToAccount:Xa,beginOAuthLogin:or,beginOAuthLink:Er,availableAuthProviders:Cr,projectRoot:Xt,projectName:_n,mcpScriptPath:Cn,serverHostRoot:Ar,showFolderBrowser:xr,setShowFolderBrowser:qn,folders:Kn,files:ir,currentBrowsePath:en,fetchFolders:An,browserTarget:Zn,setBrowserTarget:tn,handleSelectPath:cs,handleAddPath:Za,handleRemovePath:Kr,handleUpdateCategory:Dr,handleRemoveCategory:xn,handleSaveCategory:cr,handleUpdateCategoryIcon:Wn,handleUpdateCategoryColor:mn,handleSaveType:lr,handleRemoveType:Zr,handleUpdateTaxonomies:ls,handleUpdatePriorities:et,pathValidation:Bt,exportEnvironment:Da,setExportEnvironment:Aa,exportWorkflowsPath:Sa,setExportWorkflowsPath:In,exportResult:Yn,exportingResource:ds,availableWorkflows:Fn,onExportWorkflows:On,fetchWorkflows:Tn,availableEnvironments:Gt,initiativeTemplates:$n,fetchInitiativeTemplates:pn,createInitiativeFromTemplate:La,uiNotice:Lr,clearNotice:Br,taskReturnTrail:dr,clearReturnToParentTask:ur,returnToPreviousTask:Fs,tasksScrollRef:nn,setTasksScrollPos:fn,commentsEndRef:so,autoSaveState:Wr,unsavedModalOpen:mr,setUnsavedModalOpen:W,pendingNavigation:$e,handleNavigation:It,currentTask:Mt,currentTaskWorkstream:Ha,currentTaskInitiative:Jn,scheduleWarningPrompt:Yr,confirmScheduleWarning:Ba,cancelScheduleWarning:Fr}=e,Wa=ca||Dg();r.useEffect(()=>{const u=String(_n||"").trim();document.title=u?`Taskforce - ${u}`:"Taskforce"},[_n]);const T=()=>{W(!1),$e?(y==="add"&&O(),$e()):(y==="add"&&O(),k("tasks"))},j=async()=>{await le({preventDefault:()=>{}}),W(!1),$e&&$e()},[at,bt]=r.useState(!1),[ve,ae]=r.useState(!1),[Rn,jn]=r.useState(!0),[hn,Os]=r.useState(!1),[Jr,Nn]=r.useState(!0),[$s,oo]=r.useState(Jc(new Date)),[Lo,us]=r.useState(()=>{const u=new Date;return`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}`}),[di,Pn]=r.useState(0),[io,ui]=r.useState(!1),[mi,pi]=r.useState(!1),[Or,Bo]=r.useState(!1),[ms,rc]=r.useState(!0),[Qr,co]=r.useState(!0),[Is,Ts]=r.useState(!0),[lo,ps]=r.useState(!1),[fi,ha]=r.useState(!1),[sc,Qn]=r.useState(!1),[sa,uo]=r.useState(""),[Xr,mo]=r.useState(""),[$r,oc]=r.useState(new Set),[Rs,pr]=r.useState(null),[Us,rn]=r.useState(null),[fs,zs]=r.useState(null),[po,Hs]=r.useState(null),[Wo,Gs]=r.useState(""),[fo,fr]=r.useState(""),[ma,an]=r.useState(""),[Xn,es]=r.useState(""),[hi,Vs]=r.useState(!1),ic=r.useRef({taskId:null,attachments:[]}),sl=r.useRef(new Map),sn=r.useRef(new Map),[ho,Fo]=r.useState(()=>em.map(u=>u.value)),[go,Oo]=r.useState(()=>tm.map(u=>u.value)),[Nm,ol]=r.useState(null),[Pm,il]=r.useState(null),[er,hs]=r.useState(null),[yo,gi]=r.useState(null),[Mm,Ad]=r.useState(0),[$o,Em]=r.useState({}),[xd,Id]=r.useState(!1),qs=r.useRef(!1),Td=r.useRef(""),cl=r.useRef(null),Rd=r.useRef(null),cc=r.useRef(new Set);r.useEffect(()=>{ic.current={taskId:de||null,attachments:st}},[de,st]);const ll=r.useCallback(u=>{const w=de||null,N=ic.current,ce=N.taskId===w?N.attachments:st,Se=u(ce);ic.current={taskId:w,attachments:Se},kt(Se),Ye(!0),w&&A(w,{attachments:Se})},[st,de,A,kt,Ye]),Uo=r.useMemo(()=>{const u={},w=String(Yt||"").trim();return Kt==="cloud"&&w&&w!=="default"&&(u["x-taskforce-workspace-id"]=w),u},[Kt,Yt]),ko=r.useMemo(()=>`${Kt}:${String(Yt||"default").trim()||"default"}`,[Kt,Yt]),lc=r.useMemo(()=>`taskforce:annotate-layout:${ko}`,[ko]),gs=r.useMemo(()=>`taskforce:task-origin-workspace-module:${ko}`,[ko]),yi=r.useMemo(()=>Kt==="cloud"?la:rt,[la,rt,Kt]),zo=r.useRef(!1),ki=r.useRef(!1),Ks=r.useCallback(u=>{const w=String(u||"").trim();if(!(!w||typeof window>"u")){zo.current=!0;try{window.sessionStorage.setItem(gs,w)}catch{}}},[gs]),Ir=r.useCallback(()=>{if(zo.current=!1,!(typeof window>"u"))try{window.sessionStorage.removeItem(gs)}catch{}},[gs]);r.useEffect(()=>{cl.current=er},[er]),r.useEffect(()=>{Rd.current=yo},[yo]);const vo=r.useMemo(()=>({[hd]:ad({featureKey:hd}),[fd]:ad({featureKey:fd}),[wm]:ad({featureKey:wm}),[bm]:ad({featureKey:bm}),[tg]:ad({featureKey:tg})}),[Kt]),js=r.useMemo(()=>UF({featureAccess:vo}),[vo]),oa=r.useMemo(()=>ag(v,js),[v,js]),Ho=vo[hd]?.allowed??!1,dc=vo[fd]?.allowed??!1,dl="Documents is not available in this build yet.",ul="Annotate is not available in this build yet.";r.useEffect(()=>{const u=w=>{const N=w,ce=N.detail?.fsPath,Se=String(N.detail?.assetId||"").trim()||null;if(!(!ce&&!Se)){if(N.preventDefault(),!Ho){xt(dl,"error");return}Ks(N.detail?.taskId),ol(ce||null),il(Se),_("docs")}};return window.addEventListener("taskforce:open-markdown-document",u),()=>{window.removeEventListener("taskforce:open-markdown-document",u)}},[Ho,dl,xt,Ks,_]),r.useEffect(()=>{oa!==v&&_(oa)},[v,oa,_]),r.useEffect(()=>{oa==="docs"&&Ho||(ol(null),il(null))},[Ho,oa]),r.useEffect(()=>{if(!(typeof window>"u"))try{const u=window.sessionStorage.getItem(lc);if(!u)return;const w=JSON.parse(u);w?.annotatedTarget&&typeof w.annotatedTarget=="object"&&hs(w.annotatedTarget),typeof w?.annotatedSessionId=="string"&&gi(w.annotatedSessionId.trim()||null)}catch{}},[lc]),r.useEffect(()=>{if(!ki.current&&!(oa!=="docs"&&oa!=="annotate")&&(ki.current=!0,!(zo.current||typeof window>"u")))try{if(!String(window.sessionStorage.getItem(gs)||"").trim())return;window.sessionStorage.removeItem(gs),_("tasks")}catch{}},[oa,_,gs]),r.useEffect(()=>{ki.current=!1,zo.current=!1},[gs]),r.useEffect(()=>{if(Td.current===ko)return;Td.current=ko,Id(!1);let u=!1;return(async()=>{try{const N=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:Uo});if(!N.ok)return;const ce=await N.json().catch(()=>({})),Se=ce?.state&&typeof ce.state=="object"?ce.state:null;if(!Se||u)return;if(typeof Se.scheduleShowWeekends=="boolean"&&ae(Se.scheduleShowWeekends),typeof Se.scheduleShowBacklog=="boolean"&&jn(Se.scheduleShowBacklog),typeof Se.scheduleOnlyExpired=="boolean"&&Os(Se.scheduleOnlyExpired),typeof Se.scheduleSidebarOpen=="boolean"&&Nn(Se.scheduleSidebarOpen),typeof Se.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(Se.scheduleSelectedDate)&&oo(Se.scheduleSelectedDate),typeof Se.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(Se.scheduleCalendarMonth)&&us(Se.scheduleCalendarMonth),typeof Se.scheduleScrollLeft=="number"&&Number.isFinite(Se.scheduleScrollLeft)&&Se.scheduleScrollLeft>=0&&Pn(Se.scheduleScrollLeft),typeof Se.showFilters=="boolean"&&ui(Se.showFilters),Array.isArray(Se.documentTypeFilters)&&Fo(Se.documentTypeFilters),Array.isArray(Se.documentAttachmentFilters)&&Oo(Se.documentAttachmentFilters),typeof Se.planningDrawerOpen=="boolean"&&Bo(Se.planningDrawerOpen),typeof Se.documentTrayOpen=="boolean"&&rc(Se.documentTrayOpen),typeof Se.imageTrayOpen=="boolean"&&co(Se.imageTrayOpen),typeof Se.agentTrayOpen=="boolean"&&Ts(Se.agentTrayOpen),typeof Se.planningTreeCollapsed=="boolean"&&ps(Se.planningTreeCollapsed),typeof Se.planningPrimaryCollapsed=="boolean"&&ha(Se.planningPrimaryCollapsed),typeof Se.planningSecondaryCollapsed=="boolean"&&Qn(Se.planningSecondaryCollapsed),Array.isArray(Se.planningExpandedInitiativeIds)&&oc(new Set(Se.planningExpandedInitiativeIds.map(qt=>String(qt||"").trim()).filter(Boolean))),Se.planningDrawerDetail&&typeof Se.planningDrawerDetail=="object"&&(Se.planningDrawerDetail.type==="initiative"||Se.planningDrawerDetail.type==="workstream")&&typeof Se.planningDrawerDetail.id=="string"){const qt=Se.planningDrawerDetail.id.trim();pr(qt?{type:Se.planningDrawerDetail.type,id:qt}:null)}else Se.planningDrawerDetail===null&&pr(null);typeof Se.planningNestedWorkstreamDetailId=="string"?rn(Se.planningNestedWorkstreamDetailId.trim()||null):Se.planningNestedWorkstreamDetailId===null&&rn(null);const ut=Se.annotatedTarget;ut&&typeof ut=="object"&&(cl.current||hs(ut)),typeof Se.annotatedSessionId=="string"&&(Rd.current||gi(Se.annotatedSessionId.trim()||null))}catch{}finally{u||Id(!0)}})(),()=>{u=!0}},[ko,Uo]),r.useEffect(()=>{if(!xd)return;const u=window.setTimeout(async()=>{try{await pf({stateKey:"layout",workspaceId:Yt,headers:Uo,patch:{scheduleShowWeekends:ve,scheduleShowBacklog:Rn,scheduleOnlyExpired:hn,scheduleSidebarOpen:Jr,scheduleSelectedDate:$s,scheduleCalendarMonth:Lo,scheduleScrollLeft:di,showFilters:io,documentTypeFilters:ho,documentAttachmentFilters:go,documentTrayOpen:ms,imageTrayOpen:Qr,agentTrayOpen:Is,planningDrawerOpen:Or,planningTreeCollapsed:lo,planningPrimaryCollapsed:fi,planningSecondaryCollapsed:sc,planningExpandedInitiativeIds:Array.from($r),planningDrawerDetail:Rs,planningNestedWorkstreamDetailId:Us,annotatedTarget:er,annotatedSessionId:yo}})}catch{}},250);return()=>window.clearTimeout(u)},[xd,ve,Rn,hn,Jr,$s,Lo,di,io,ho,go,ms,Qr,Is,Or,lo,fi,sc,$r,Rs,Us,er,yo,Uo]),r.useEffect(()=>{if(!(typeof window>"u"))try{window.sessionStorage.setItem(lc,JSON.stringify({annotatedTarget:er,annotatedSessionId:yo}))}catch{}},[lc,yo,er]),r.useEffect(()=>{h==="schedule"&&Nn(!0)},[h]);const{showArchive:So,setShowArchive:ml,fetchArchive:pl,filteredArchive:fl}=e,vi=r.useMemo(()=>fl.map(u=>({...u,isArchived:!0})),[fl]),Un=r.useMemo(()=>e.archivedTasks.map(u=>({...u,isArchived:!0})),[e.archivedTasks]),Ns=r.useMemo(()=>[...e.searchAgnosticTasks,...Un],[Un,e.searchAgnosticTasks]),jd=r.useCallback(u=>{const w=String(u||"").trim();if(!w)return"";const N=Ns.find(ce=>ce.id===w);return Xi(N)||""},[Ns]),Nd=r.useCallback(u=>{const w=String(u||"").trim();if(!w)return"";const N=String($o[w]||"").trim();if(N)return N;for(const ce of Ns)for(const Se of ce.attachments||[]){if(!Se||typeof Se!="object"||String(Se.assetId||"").trim()!==w)continue;const ut=py({referenceNumber:typeof Se.referenceNumber=="number"?Se.referenceNumber:null,referenceLabel:String(Se.referenceLabel||"").trim()||null});if(ut)return ut}return""},[Ns,$o]);r.useEffect(()=>{const u=w=>{const N=w,ce=Rh(N.detail,Ns);if(ce){if(N.preventDefault(),!dc){xt(ul,"error");return}hs(ce),gi(null),Ad(Se=>Se+1),Ks(ce.taskId),_("annotate")}};return window.addEventListener("taskforce:open-annotated-attachment",u),()=>{window.removeEventListener("taskforce:open-annotated-attachment",u)}},[Ns,dc,ul,xt,Ks,_]),r.useEffect(()=>{if(!er)return;const u=Rh(er,Ns);u&&(u.taskReferenceLabel===er.taskReferenceLabel&&u.imageReferenceLabel===er.imageReferenceLabel||hs(u))},[Ns,er]),r.useEffect(()=>{const u=cl.current,w=String(u?.assetId||"").trim();if(!w)return;const N=String($o[w]||"").trim();N&&N!==String(u?.imageReferenceLabel||"").trim()&&hs(ce=>!ce||String(ce.assetId||"").trim()!==w?ce:{...ce,imageReferenceLabel:N})},[$o,er]),r.useEffect(()=>{if(!yi)return;const w=String(er?.assetId||"").trim();if(!w||cc.current.has(w)||String($o[w]||"").trim())return;let N=!1;cc.current.add(w);const ce=String(Yt||"default").trim()||"default",Se=new URLSearchParams({workspaceId:ce});return(async()=>{try{const qt=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(w)}?${Se.toString()}`,{method:"GET",credentials:"include",headers:Uo});if(!qt.ok)return;const ga=await qt.json().catch(()=>({})),_s=String(ga?.target?.imageReferenceLabel||"").trim();if(!_s||N)return;Em(_a=>_a[w]===_s?_a:{..._a,[w]:_s})}catch{}finally{cc.current.delete(w)}})(),()=>{N=!0}},[yi,$o,Yt,er,Uo]);const zn=r.useMemo(()=>e.deletedTasks.map(u=>({...u.taskSnapshot,isDeleted:!0,deletedRecordId:u.id})),[e.deletedTasks]),Si=r.useMemo(()=>{const u=new Map;return e.deletedTasks.forEach(w=>{u.set(w.taskSnapshot.id,w)}),u},[e.deletedTasks]),wi=r.useMemo(()=>{const u=zn,w=Rm(we),N={categories:S,types:We,priorities:tt,assigneeOptions:e.assigneeOptions,taxonomies:Dt},ce=S.every(_a=>Ke.includes(_a.value)),Se=We.every(_a=>Ne.includes(_a.value)),ut=new Set(Jt.map(_a=>String(_a))),qt=tt.every(_a=>ut.has(String(_a.value))),ga=new Set(B.map(_a=>String(_a))),_s=ao.every(_a=>ga.has(String(_a.value)));return u.filter(_a=>{const op=pm(_a,w,N),ju=ce||Ke.includes(_a.category),ip=Se||Ne.includes(_a.type||Vr),cp=qt||ut.has(String(_a.priority)),Nu=_s||ga.has(String(_a.status)),lp=Ft.length===0||Ft.includes(_a.assignee||"unassigned");return op&&ju&&ip&&cp&&Nu&&lp})},[S,We,zn,Ft,Ke,Jt,B,Ne,tt,we]),bi=r.useMemo(()=>[...e.tasks,...Un,...zn],[Un,zn,e.tasks]),uc=r.useMemo(()=>{const u=S.filter(N=>!N.disabled).map(N=>({value:N.value,label:N.label})),w=S.filter(N=>N.disabled&&bi.some(ce=>ce.category===N.value)).map(N=>({value:N.value,label:`${N.label} (Legacy)`}));return[...u,...w]},[S,bi]),hl=r.useMemo(()=>{const u=We.filter(N=>N.status!=="retired").map(N=>({value:N.value,label:N.label})),w=We.filter(N=>N.status==="retired"&&bi.some(ce=>(ce.type||Vr)===N.value)).map(N=>({value:N.value,label:`${N.label} (Retired)`}));return[...u,...w]},[We,bi]),Zs=r.useMemo(()=>Vt==="archived"?vi:Vt==="deleted"?wi:So?[...e.filteredTasks,...vi]:e.filteredTasks,[vi,wi,e.filteredTasks,So,Vt]),mc=r.useMemo(()=>Vt==="open"?e.tasks.filter(u=>!u.isArchived):Zs,[Zs,e.tasks,Vt]),gl=r.useMemo(()=>new Set(Zs.map(u=>u.id)),[Zs]),_i=r.useMemo(()=>Vt==="archived"?Un:Vt==="deleted"?zn:So?[...e.tasks,...Un]:e.tasks,[Un,zn,e.tasks,So,Vt]),Ci=r.useMemo(()=>{const u=new Map;for(const w of Un)u.set(w.id,w);for(const w of zn)u.set(w.id,w);for(const w of e.tasks)u.set(w.id,w);return Array.from(u.values())},[Un,zn,e.tasks]),pc=r.useMemo(()=>{const u=new Map;return Ci.forEach(w=>u.set(w.id,w)),u},[Ci]),fc=r.useMemo(()=>{const u=new Map;ra.forEach(ce=>{u.set(String(ce.value),ce.label)});const w=String(Ka||"").trim(),N=String(yn||ln||"").trim();return w&&N&&u.set(w,N),u},[ra,yn,ln,Ka]),_t=r.useMemo(()=>{const u=Vt==="archived"?Un:Vt==="deleted"?zn:e.tasks.filter(ct=>!ct.isArchived),w=Vt==="deleted"?zn:Array.from([...e.tasks,...Un].reduce((ct,Ja)=>ct.set(Ja.id,Ja),new Map).values()),N=(ct,Ja)=>({progressPercent:ct>0?Math.round(Ja/ct*100):0,taskCount:ct,completedTaskCount:Ja}),ce=Vt==="open"&&e.planningBootstrapTaskSummaries.length>0&&(e.loadingTasks||e.tasks.length===0),Se=new Map,ut=new Map;ce?e.planningBootstrapTaskSummaries.forEach(ct=>{Se.set(ct.workstreamId,ct),ut.set(ct.workstreamId,ct.tasks||[])}):(u.forEach(ct=>{const Ja=String(ct.workstreamId||"").trim();if(!Ja)return;const gr=Se.get(Ja)||{workstreamId:Ja,taskCount:0,completedTaskCount:0,tasks:[]};gr.taskCount+=1,(ct.isArchived||ct.status==="done"||ct.status==="cancelled")&&(gr.completedTaskCount+=1),Se.set(Ja,gr)}),w.forEach(ct=>{const Ja=String(ct.workstreamId||"").trim();if(!Ja)return;const gr=ut.get(Ja)||[];gr.push({id:ct.id,referenceNumber:ct.referenceNumber??null,title:ct.title,status:ct.status||null,isArchived:!!ct.isArchived}),ut.set(Ja,gr)}));const qt=new Map,ga=new Map,_s=new Map,_a=new Map,op=ct=>{const Ja=Se.get(ct.id),gr=ut.get(ct.id)||Ja?.tasks||[],Pu={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?fc.get(String(ct.ownerId))||String(ct.ownerId):null,...N(Ja?.taskCount||0,Ja?.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:gr};if(qt.set(ct.id,gr.map(Hc=>Hc.id)),ct.initiativeId){ga.set(ct.id,ct.initiativeId);const Hc=_a.get(ct.initiativeId)||[];Hc.push(Pu),_a.set(ct.initiativeId,Hc)}return Pu},ju=e.workstreams.map(op),ip=ju.filter(ct=>Sm(Vt,!!ct.isArchived)),cp=e.initiatives.map(ct=>{const Ja=_a.get(ct.id)||[],gr=Ja.filter(Xl=>Sm(Vt,!!Xl.isArchived)),Pu=gr.reduce((Xl,dp)=>Xl+dp.taskCount,0),Hc=gr.reduce((Xl,dp)=>Xl+dp.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?fc.get(String(ct.ownerId))||String(ct.ownerId):null,...N(Pu,Hc),workstreamCount:gr.length,workstreams:gr,allWorkstreams:Ja,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:Nu,standaloneWorkstreams:lp,initiativeById:Ak,workstreamById:xk}=IW(cp,ip,Vt),Ik=ju.filter(ct=>!ct.initiativeId);return Nu.forEach(ct=>{_s.set(ct.id,ct.workstreams.flatMap(Ja=>(Ja.tasks||[]).map(gr=>gr.id)))}),{initiatives:Nu,standaloneWorkstreams:lp,allStandaloneWorkstreams:Ik,workstreamTaskIds:qt,workstreamInitiativeIds:ga,initiativeTaskIds:_s,workstreamById:xk,initiativeById:Ak}},[Un,fc,zn,e.initiatives,e.loadingTasks,e.planningBootstrapTaskSummaries,e.tasks,e.workstreams,Vt]),Pd=r.useMemo(()=>_t.initiatives.map(u=>{const w=os(u);return{value:u.id,label:w||u.title}}),[_t.initiatives]),hc=r.useMemo(()=>{const w=(sa?_t.initiativeById.get(sa)?.workstreams||[]:_t.initiatives.flatMap(ce=>ce.workstreams)).map(ce=>{const Se=Eo(ce);return{value:ce.id,label:Se||ce.title}}),N=sa?[]:_t.standaloneWorkstreams.map(ce=>{const Se=Eo(ce);return{value:ce.id,label:Se||ce.title}});return[...w,...N]},[_t.initiativeById,_t.initiatives,_t.standaloneWorkstreams,sa]),ys=r.useMemo(()=>Xr?new Set(_t.workstreamTaskIds.get(Xr)||[]):sa?new Set(_t.initiativeTaskIds.get(sa)||[]):null,[_t.initiativeTaskIds,_t.workstreamTaskIds,sa,Xr]),Go=r.useMemo(()=>{if(!Rs)return null;if(Rs.type==="initiative"){const w=_t.initiativeById.get(Rs.id);return w?{type:"initiative",item:w}:null}const u=_t.workstreamById.get(Rs.id)||_t.standaloneWorkstreams.find(w=>w.id===Rs.id);return u?{type:"workstream",item:u}:null},[Rs,_t.initiativeById,_t.standaloneWorkstreams,_t.workstreamById]),gc=r.useMemo(()=>{if(!Us)return null;const u=_t.workstreamById.get(Us)||_t.standaloneWorkstreams.find(w=>w.id===Us);return u?{type:"workstream",item:u}:null},[Us,_t.standaloneWorkstreams,_t.workstreamById]),yc=r.useMemo(()=>po?{kind:"editor",editor:po}:gc?{kind:"detail",detail:gc}:null,[gc,po]),Md=$y(lo,!!(Go||fs),fi,!!yc,sc),kc=r.useMemo(()=>{if(!Xn.trim())return null;const u=_t.initiativeById.get(Xn);return u||vp(_t.initiatives,Xn)},[Xn,_t.initiativeById,_t.initiatives]);r.useEffect(()=>{sa&&!_t.initiativeById.has(sa)&&uo(""),Xr&&!_t.workstreamById.has(Xr)&&mo("")},[_t.initiativeById,_t.workstreamById,sa,Xr]);const Tr=r.useMemo(()=>h==="schedule"?mc:Zs,[h,Zs,mc]),Ya=r.useMemo(()=>{const u=new Date,w=u.getFullYear(),N=String(u.getMonth()+1).padStart(2,"0"),ce=String(u.getDate()).padStart(2,"0");return`${w}-${N}-${ce}`},[]),Ai=r.useMemo(()=>h!=="schedule"||!hn?Tr:Tr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const N=!!u.scheduledDate&&u.scheduledDate<Ya,ce=!!u.dueDate&&u.dueDate<Ya;return N||ce}),[h,hn,Tr,Ya]),yl=r.useMemo(()=>!ys||ys.size===0?Ai:Ai.filter(u=>ys.has(u.id)),[Ai,ys]),Ed=r.useMemo(()=>!ys||ys.size===0?_i:_i.filter(u=>ys.has(u.id)),[_i,ys]),wo=r.useMemo(()=>h!=="schedule"?[]:Tr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const N=!!u.scheduledDate&&u.scheduledDate<Ya,ce=!!u.dueDate&&u.dueDate<Ya;return N||ce}),[h,Tr,Ya]),Dd=r.useMemo(()=>h!=="schedule"?0:Tr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<Ya).length,[h,Tr,Ya]),kl=r.useMemo(()=>h!=="schedule"?0:Tr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.dueDate&&u.dueDate<Ya).length,[h,Tr,Ya]),ts=String(Ka||"").trim(),Ld=r.useMemo(()=>!ts||ts==="anonymous"?0:me.filter(u=>u.status==="done"||u.status==="cancelled"?!1:String(u.assignee||"").trim()===ts).length,[ts,me]),Bd=r.useMemo(()=>!ts||ts==="anonymous"?0:me.filter(u=>u.status==="done"||u.status==="cancelled"||String(u.assignee||"").trim()!==ts?!1:!!u.dueDate&&u.dueDate<Ya).length,[ts,me,Ya]),vc=r.useMemo(()=>h!=="schedule"?[]:Tr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<Ya),[h,Tr,Ya]),xi=wo,[bo,Ii]=r.useState(!1),Sc=()=>{It(()=>{Fs()||(y==="add"&&dr.length>0&&ur(),pi(!1),y==="add"&&O(),k("tasks"))})};r.useEffect(()=>{y!=="add"&&pi(!1)},[y]);const wc=r.useCallback((u,w)=>{if(u.status!==w){if(w==="in-progress"){te(u);return}if(w==="review"){At(u);return}if(w==="done"){Le(u);return}if(w==="cancelled"){jt(u);return}A(u.id,{status:w,completedAt:null})}},[te,At,Le,jt,A]),vl=r.useCallback((u,w)=>{O();const N=CW(u,w,{categories:S,approaches:Ze});N.category&&re(N.category),N.type&&Ie(N.type),typeof N.priority=="number"&&je(N.priority),typeof N.complexity=="number"&&K(N.complexity),N.approach&&R(N.approach);const ce=N.taxonomyApproach;typeof ce=="string"&&ce.length>0&&Te(Se=>({...Se,approach:ce})),N.assignee&&Q(N.assignee),N.status&&x(N.status),N.scheduledDate&&$(N.scheduledDate),k("add")},[O,S,Ze,re,Ie,je,K,x,R,Q,$,Te,k]);Ue.useEffect(()=>{B&&!B.includes("done")&&X(u=>[...u,"done"])},[]);const[Wd,Vo]=r.useState(!1),[ks,tr]=r.useState(!1),[_o,Co]=r.useState(!1),[Sl,wl]=r.useState(!1),[Dm,bc]=r.useState(!1),[_c,Fd]=r.useState(!1),[Od,bl]=r.useState(""),[_l,Ti]=r.useState(!1),[Lm,$d]=r.useState(!1),[Bm,Ri]=r.useState("members"),[Cc,Ac]=r.useState(null),[xc,ji]=r.useState("unknown"),[Ud,Ni]=r.useState(!1),[Wm,Mn]=r.useState(null),[vs,Rr]=r.useState(null),[Ic,Tc]=r.useState(!1),[qo,Cl]=r.useState([]),[Pi,Ko]=r.useState(null),[Mi,Rc]=r.useState(""),[Ps,Ei]=r.useState("member"),[Di,jc]=r.useState("read-write"),[Nc,Al]=r.useState(!1),[zd,Zo]=r.useState(null),[Ms,Fm]=r.useState(0),[Hd,Gd]=r.useState(!1),[Om,$m]=r.useState([]),[Um,zm]=r.useState(!1),[Vd,Hm]=r.useState(1),[gn,xl]=r.useState(null),[qd,Pc]=r.useState(!1),[Mc,Il]=r.useState(null),[Kd,Li]=r.useState(!1),[Ur,zr]=r.useState(null),[Yo,Hr]=r.useState(!1),[Zd,Tl]=r.useState(null),[Ys,Bi]=r.useState("month"),[Rl,Yd]=r.useState(""),[Ss,Jo]=r.useState(""),[hr,Qo]=r.useState(null),[jl,Jd]=r.useState(!1),[Gm,Nl]=r.useState(!1),[Qd,as]=r.useState(null),[Xd,ns]=r.useState(null),eu=25,tu=r.useRef(null),Wi=r.useRef(null),Pl=r.useRef({billing:!1,teamManagement:!1}),Fi=r.useRef(null);r.useEffect(()=>{Fi.current=gn},[gn]),r.useEffect(()=>{if(!ks)return;const u=w=>{tu.current?.contains(w.target)||tr(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[ks]);const Vm=Kt==="cloud"&&vr&&Zt,Xo=Zt&&(Kt==="cloud"||Ta),Ml=Kt==="local"&&Zt,{showSyncStatusModal:El,showSyncEnableWarning:qm,workspaceSyncError:Dl,syncControlBusy:au,openSyncStatusModal:Km,closeSyncStatusModal:Ll,handleWorkspaceSyncToggle:nu,cancelSyncEnableWarning:Zm,confirmSyncEnableWarning:Ym}=pO({canManageWorkspaceSync:Ml,workspaceCloudSyncEnabled:Vn,saveWorkspaceCloudSyncSettings:_r}),Bl=r.useMemo(()=>{const u=za.find(ce=>ce.id===Yt),w=String(u?.name||"").trim();if(w)return w;if(Kt==="local"){const ce=String(_n||"").trim();if(ce)return ce}return String(Yt||"").trim()||"Workspace"},[za,Yt,_n,Kt]),Ec=zy(Xo,Cc),Ao=cO(Xo,Cc,xc),ei=String(yn||"").trim(),jr=String(Sr||"").trim(),xo=String(ln||"").trim(),Js=ei||xo,Dc=Js.length>0,ru=xo.length>0,Jm=r.useMemo(()=>wB({workspaceName:Bl,workspaceId:Yt,accountLabel:Js||xo,runtimeMode:Kt}),[xo,Js,Yt,Bl,Kt]),su=(Js||xo||"").trim(),Lc=Zt&&la&&su.length>0?su.charAt(0).toUpperCase():"",Fl=jr,ou=Zt&&la&&Fl.length>0,Ol=String(Ss||jr).trim(),Bc=String(gn?.planName||gn?.planId||"").trim(),iu=Bc.length>0,Es=String(gn?.workspaceId||aa||Yt||"").trim(),cu=Kt==="cloud"?"CLOUD":"LOCAL",$l=e.config?.apiBaseUrl||"",lu=r.useMemo(()=>bO(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]),du=Ta&&!la;r.useEffect(()=>{Sl&&(Yd(ei),Jo(jr),Qo(null),as(null),ns(null))},[jr,ei,Sl]);const Ds=r.useCallback(async u=>{const w=String(u||"").trim();if(!(!w||!Ta))try{await fetch(Ma("/api/taskforce/auth/profile/avatar/discard"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:w})})}catch{}},[Ta,Ma]),uu=r.useCallback(()=>{const u=hr;wl(!1),bc(!1),as(null),ns(null),Qo(null),Jo(jr),u&&Ds(u)},[jr,Ds,hr]),mu=r.useCallback(async u=>{if(!u||!Ta)return!1;if(!u.type.startsWith("image/"))return as("Profile photo must be an image file."),ns(null),!1;Jd(!0),as(null),ns(null);try{const w=await XW(u,{maxBytes:SO});if(w.exceededLimit){const _a=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(_a)}const N=w.file,ce=await fetch(Ma("/api/taskforce/auth/profile/avatar/init"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:N.name,mimeType:N.type,size:N.size})}),Se=await ce.json().catch(()=>({}));if(!ce.ok||!Se?.success||typeof Se?.draftId!="string"||typeof Se?.relativePath!="string")throw new Error(Se?.error||"Failed to start avatar upload.");if(!(await fetch(Ma("/api/taskforce/auth/profile/avatar/upload"),{method:"POST",headers:{"Content-Type":N.type||"application/octet-stream","x-taskforce-avatar-draft-id":Se.draftId},credentials:"include",body:N})).ok)throw new Error("Failed to upload avatar.");const qt=await fetch(Ma("/api/taskforce/auth/profile/avatar/finalize"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:Se.draftId,relativePath:Se.relativePath})}),ga=await qt.json().catch(()=>({}));if(!qt.ok||!ga?.success||typeof ga?.draftId!="string")throw new Error(ga?.error||"Failed to finalize avatar upload.");const _s=hr;return Qo(ga.draftId),Jo(typeof ga?.avatarUrl=="string"?ga.avatarUrl:""),ns(null),_s&&_s!==ga.draftId&&Ds(_s),!0}catch(w){return as(w instanceof Error?w.message:"Failed to upload profile photo."),!1}finally{Jd(!1)}},[Ta,Ds,hr,Ma]),pu=r.useCallback(()=>{if(!hr)return;const u=hr;Qo(null),Jo(jr),ns(null),as(null),Ds(u)},[jr,Ds,hr]),fu=r.useCallback(()=>{const u=hr;Qo(null),Jo(""),ns(jr?"Profile photo will be removed when you save.":null),as(null),u&&Ds(u)},[jr,Ds,hr]),hu=r.useCallback(async()=>{const u=Rl.trim();if(!u){as("Display name is required."),ns(null);return}Nl(!0),as(null),ns(null);const w=await Bn({displayName:u,avatarDraftId:hr,clearAvatar:!hr&&!Ss&&!!jr});if(!w.success){as(w.error||"Failed to update profile."),Nl(!1);return}ns("Profile updated."),Qo(null),Jo(""),Nl(!1),bc(!1),wl(!1)},[jr,hr,Ss,Rl,Bn]),rs=r.useCallback(()=>{const u={},w=String(Es||"").trim();w&&(u["x-taskforce-workspace-id"]=w);const N=Cc||bn;return(N==="owner"||N==="admin"||N==="member"||N==="read-only")&&(u["x-taskforce-workspace-role"]=N),u},[bn,Es,Cc]),Ul=r.useCallback(u=>{const w=Zt,N=Xo;Wi.current=nd(),Pl.current={billing:w,teamManagement:N},Ut("account_surface_opened",{surface:u,expectsBilling:w,expectsTeamManagement:N}),!w&&!N&&(Ut("account_surface_ready",{surface:u,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),Wi.current=null)},[Xo,Zt]),ti=r.useCallback(u=>{const w=Pl.current;if(w[u]=!1,w.billing||w.teamManagement)return;const N=Wi.current;N!==null&&(Ut("account_surface_ready",{surface:_o?"account_hub":ks?"account_menu":"closed",durationMs:Math.round(nd()-N),teamManagementVisible:Ao,billingPlanId:String(gn?.planId||"").trim()||null}),Wi.current=null)},[gn?.planId,Ao,_o,ks]),Nr=r.useCallback(async u=>{const w=Ma(Gh);if(!Zt)return xl(null),Il(null),Ac(null),ji("unknown"),Ni(!1),Mn(null),Vh(w,{identityKey:Ka}),ti("billing"),ti("teamManagement"),null;const N=nd();Pc(!0),Il(null),Ni(Xo),Mn(null);try{const ce=await OW(w,{identityKey:Ka,force:u?.force===!0}),Se=ce?.workspaceRole==="owner"||ce?.workspaceRole==="admin"||ce?.workspaceRole==="member"||ce?.workspaceRole==="read-only"?ce.workspaceRole:null,ut=ce?.teamPlanMode==="team"||ce?.teamPlanMode==="personal"?ce.teamPlanMode:"unknown";return xl(ce),Ac(Se),ji(ut),Mn(null),Ut("account_profile_summary_resolved",{durationMs:Math.round(nd()-N),planId:String(ce?.planId||"").trim()||null,gate:String(ce?.gate||"").trim()||null,teamManagementAllowed:ce?.teamManagementAllowed===!0}),ce}catch(ce){const Se=ce instanceof Error?ce.message:"Failed to load account summary.",ut=!!Fi.current;return Il(Se),ut?Mn(null):(Ac(null),ji("unknown"),Mn(Se)),Ut("account_profile_summary_failed",{durationMs:Math.round(nd()-N),error:Se,preservedSummary:ut}),Fi.current}finally{Pc(!1),Ni(!1),ti("billing"),ti("teamManagement")}},[Ka,Xo,Zt,ti,Ma]),gu=r.useCallback(u=>{xl(u);const w=u?.workspaceRole==="owner"||u?.workspaceRole==="admin"||u?.workspaceRole==="member"||u?.workspaceRole==="read-only"?u.workspaceRole:null,N=u?.teamPlanMode==="team"||u?.teamPlanMode==="personal"?u.teamPlanMode:"unknown";Ac(w),ji(N)},[]),zl=r.useMemo(()=>Kp(gn).allowReturnToApp,[gn]),Qm=r.useCallback(async()=>{const u=new URLSearchParams;u.set("screen","plans"),u.set("interval",Ys);const w=String(gn?.planId||"").trim(),N=String(gn?.planVersionId||"").trim();w&&u.set("planId",w),N&&u.set("planVersionId",N),s(`/?${u.toString()}`)},[gn?.planId,gn?.planVersionId,Ys,s]),Wc=r.useCallback(async()=>{zr(null),Tl(null),Li(!0);try{const u=await fetch(Ma("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),w=await u.json().catch(()=>({}));if(!u.ok){zr(String(w?.error||"Failed to create portal session."));return}const N=String(w?.url||"").trim();if(!N){zr("Portal session did not return a redirect URL.");return}window.location.assign(N)}catch{zr("Failed to open billing portal.")}finally{Li(!1)}},[Ma]),yu=r.useCallback(async()=>{zr(null),Tl(null),Li(!0);try{const u=String(gn?.planVersionId||"").trim();if(!u){zr("No active plan version is linked to this account.");return}const w=await fetch(Ma("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:u,interval:Ys})}),N=await w.json().catch(()=>({}));if(!w.ok){zr(String(N?.error||"Failed to update subscription interval."));return}Tl("Subscription updated."),Vh(Ma(Gh),{identityKey:Ka}),await Nr()}catch{zr("Failed to update subscription interval.")}finally{Li(!1)}},[gn?.planVersionId,Ka,Ys,Nr,Ma]);r.useEffect(()=>{!Zt||!la||Nr()},[la,Zt,Nr]),r.useEffect(()=>{!_o&&!ks||Nr()},[Nr,_o,ks]);const ai=r.useCallback(async()=>{if(Ec){Tc(!0),Rr(null);try{const u=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:rs()}),w=await u.json().catch(()=>({}));if(!u.ok){Rr(w?.error||"Failed to load workspace users.");return}const N=Array.isArray(w?.users)?w.users:[],ce={owner:0,admin:1,member:2,"read-only":3},Se=N.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}));Se.sort((ut,qt)=>{const ga=(ce[ut.role]??99)-(ce[qt.role]??99);return ga!==0?ga:(ut.displayName||ut.email).localeCompare(qt.displayName||qt.email,void 0,{sensitivity:"base"})}),Cl(Se)}catch{Rr("Failed to load workspace users.")}finally{Tc(!1)}}},[Ec,rs]),Io=r.useCallback(async u=>{if(!Ec)return;const w=Math.max(0,Math.floor(u));Gd(!0),Rr(null);try{const N=w*eu,ce=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${eu}&offset=${N}`,{method:"GET",credentials:"include",headers:rs()}),Se=await ce.json().catch(()=>({}));if(!ce.ok){Rr(Se?.error||"Failed to load workspace audit log.");return}const ut=Array.isArray(Se?.events)?Se.events:[];$m(ut.map(ga=>({id:String(ga?.id||""),action:String(ga?.action||""),actorUserId:String(ga?.actorUserId||""),actorRole:String(ga?.actorRole||""),createdAt:String(ga?.createdAt||ga?.ts||"")}))),Fm(w);const qt=Math.max(1,Number(Se?.pages||1));Hm(qt),zm(w+1<qt)}catch{Rr("Failed to load workspace audit log.")}finally{Gd(!1)}},[Ec,rs]),Fc=r.useCallback(async()=>{await Promise.all([ai(),Io(Ms)])},[ai,Io,Ms]),Oc=r.useCallback((u="login")=>{const w=`${o.pathname}${o.search}${o.hash}`,N=!w||w==="/login"||!w.startsWith("/")?"/":w;tr(!1),Co(!1),Ll(),s(`/login?mode=${u}&next=${encodeURIComponent(N)}`)},[Ll,o.hash,o.pathname,o.search,s]),Oi=r.useCallback(u=>{tr(!1),Ti(!1);const w=new URLSearchParams({step:"workspace"});u?.intent==="create-workspace"&&w.set("intent","create-workspace"),s(`/setup?${w.toString()}`,{replace:!0})},[s]),ni=r.useCallback(async()=>{if(Yo)return;if(Hr(!0),!Zt){try{m()}finally{Hr(!1)}return}const u=Fi.current;if(u&&!Kp(u).allowReturnToApp){Hr(!1);return}m(),(async()=>{try{const w=await e.continueAfterCommercialOnboarding();if(!w.success){xt(w.error||"Unable to finish onboarding.","error"),w.destination==="login"&&s("/login",{replace:!0});return}w.destination==="setup"&&Oi()}finally{Hr(!1)}})()},[Fi,m,Zt,s,Oi,Yo,e,xt]),Hl=r.useCallback(()=>{if(i){ni();return}It(()=>{Ir(),_("tasks"),Bo(!1),pr(null),rn(null),zs(null),pi(!1),y==="add"&&O(),k("tasks"),(o.pathname!=="/"||o.search)&&s("/")})},[y,Ir,It,ni,i,o.pathname,o.search,s,O,k,_]),Gl=r.useCallback(async u=>{if(!(!u||_c)){bl(""),Fd(!0);try{const w=await Pa(u);if(!w.success){if(w.code==="WORKSPACE_NOT_FOUND"||w.code==="WORKSPACE_ID_REQUIRED"){Oi();return}bl(w.error||"Failed to switch workspace.");return}await J(!0),tr(!1)}finally{Fd(!1)}}},[Pa,_c,J,Oi]),$c=r.useCallback(async()=>{tr(!1),$d(!0),Ri("members"),((await Nr())?.teamManagementAllowed??Ao)&&(await ai(),await Io(0))},[Ao,Nr,Io,ai]),To=r.useCallback(async(u,w)=>{Rr(null),Ko(u);try{const N=await w(),ce=await N.json().catch(()=>({}));if(!N.ok){Rr(ce?.error||"Team management action failed.");return}await Fc()}catch{Rr("Team management action failed.")}finally{Ko(null)}},[Fc]),Vl=r.useCallback(async()=>{const u=Mi.trim();if(u){Al(!0),Rr(null),Zo(null);try{const w=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...rs()},credentials:"include",body:JSON.stringify({workspaceId:Es,email:u,role:Ps,permissionMode:Ps==="member"?Di:"read-write"})}),N=await w.json().catch(()=>({}));if(!w.ok){Rr(N?.error||"Failed to send invite.");return}Rc(""),N?.inviteEmailSent===!1?Zo(`Invite created, but email delivery failed${N?.inviteEmailError?`: ${String(N.inviteEmailError)}`:"."}`):Zo("Invite sent."),await Fc()}catch{Rr("Failed to send invite.")}finally{Al(!1)}}},[Yt,Fc,rs,Mi,Di,Ps]),$i=r.useMemo(()=>we.trim().length>0,[we]),Xm=r.useMemo(()=>qo.filter(u=>u.status==="invited"),[qo]),ql=r.useMemo(()=>{const u=Ke.length!==S.length,w=Ne.length!==We.length,N=Jt.length!==tt.length,ce=B.length!==ao.length,Se=Ft.length!==ra.length,ut=sa.length>0,qt=Xr.length>0;return u||w||N||ce||Se||ut||qt},[S.length,We.length,ra.length,Ft.length,Ke.length,Jt.length,B.length,Ne.length,tt.length,sa,Xr]),ku=r.useMemo(()=>ho.length!==em.length||go.length!==tm.length,[go.length,ho.length]),vu=oa,Qs=r.useMemo(()=>zF(vu),[vu]),Su=r.useMemo(()=>{switch(Qs.filterBar.kind){case"task-filters":return ql;case"document-filters":return ku;default:return!1}},[ku,ql,Qs.filterBar.kind]),Kl=$i||ql,wu=Vt==="archived"?Un.length:Vt==="deleted"?zn.length:me.length,bu=Vt==="archived"?vi.length:Vt==="deleted"?wi.length:e.filteredTasks.length,ep=Kl?`${bu}/${wu}`:`${wu}`,Zl=Kl?`${Vt.charAt(0).toUpperCase()+Vt.slice(1)} tasks matching current filters`:`${Vt.charAt(0).toUpperCase()+Vt.slice(1)} tasks`,tp=Kt==="local"&&Zt,ri=r.useCallback(u=>{if(!u)return"Never";const w=new Date(u);return Number.isNaN(w.getTime())?"Never":w.toLocaleString()},[]),Yl=r.useMemo(()=>ri(Sn),[ri,Sn]),_u=r.useMemo(()=>ri(un),[ri,un]),Cu=r.useMemo(()=>ri(Ua),[ri,Ua]),Au=Dl||ka||Na||"None",ws=va(),bs=r.useMemo(()=>xW({runtimeMode:Kt,isAuthenticated:Zt,workspaceSyncStatus:$a,workspaceCloudSyncEnabled:Vn,workspaceSyncSummary:br,workspaceSyncRecommendedAction:dn,workspaceSyncError:Au,pushBlockedReason:ws.pushBlockedReason||null,pullBlockedReason:ws.pullBlockedReason||null,retryBlockedReason:ws.retryBlockedReason||null}),[Kt,Zt,$a,Vn,br,dn,Au,ws.pushBlockedReason,ws.pullBlockedReason,ws.retryBlockedReason]),xu=bs.lastError,[Iu,ap]=r.useState(bs.status),f=r.useMemo(()=>EW(ws),[ws]),{syncRecentEvents:L,syncRecentEventsLoading:G,syncRecentEventsError:Z,syncEventsListRef:He,loadRecentSyncEvents:Be}=lO({isOpen:El,workspaceId:Yt,refreshKeys:[Ua,un,sr,$a]}),Ve=bs.actionable&&$a==="syncing"&&kn==="active"&&ja===0;r.useEffect(()=>{if(!Ve){ap(bs.status);return}const u=window.setTimeout(()=>{ap(bs.status)},1200);return()=>window.clearTimeout(u)},[bs.status,Ve]);const pa=r.useMemo(()=>DW({syncRecentEvents:L,syncRecentEventsError:Z,syncRecentEventsLoading:G}),[L,Z,G]),fa=r.useMemo(()=>LW(L),[L]),Fa=r.useMemo(()=>BW(L),[L]),ba=r.useMemo(()=>MW(Iu),[Iu]),{workspaceSyncRepairBusy:En,workspaceSyncRepairQueued:Pr,workspaceSyncCopied:Jl,handleCopySyncDetails:Gy,handleQueueOrRunRepairSync:Vy}=mO({currentWorkspaceId:Yt,syncStatusLabel:ba.label,workspaceSyncSummary:bs.summary,workspaceSyncRecommendedAction:bs.recommendedAction,formattedLastSyncTime:Yl,formattedLastPullTime:_u,formattedLastPushTime:Cu,workspaceSyncDiagnostics:ws,workspaceSyncPendingChanges:ja,syncLastError:xu,workspaceSyncPhase:kn,referenceMismatchCount:fa,syncRecentEvents:L,loadRecentSyncEvents:Be,pushNotice:xt,resetWorkspaceSyncCursorAndPull:wn,workspaceSyncBusy:Ea}),qy=r.useMemo(()=>By(kn,En,Ea),[Ea,kn,En]),Tf=r.useMemo(()=>dd($s)||new Date,[$s]),Ui=r.useMemo(()=>Xp(Tf,ia),[Tf,ia]),Ro=r.useMemo(()=>{const u={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return ng.forEach(w=>{const N=sO(w,ia);u[w]=Jc(Uy(Ui,N))}),u},[Ui,ia]),Rf=r.useCallback(u=>{const w=dd(u);if(!w)return Ro.mon;const N=w.getDay();return Ro[N===1?"mon":N===2?"tue":N===3?"wed":N===4?"thu":N===5?"fri":N===6?ve?"sat":"fri":ve?"sun":"fri"]||Ro.mon},[Ro,ve]),Ky=r.useCallback(async()=>{if(!(bo||xi.length===0)){Ii(!0);try{for(const u of xi){const w=u.scheduledDate||u.dueDate||Ya,N=Rf(w);await A(u.id,{scheduledDate:N,scheduledWeekKey:oO(N),orderInDay:null})}await J(!0)}finally{Ii(!1)}}},[bo,xi,Ya,Rf,A,J]),Zy=r.useCallback(async()=>{if(!(bo||wo.length===0)){Ii(!0);try{for(const u of wo)await A(u.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await J(!0)}finally{Ii(!1)}}},[bo,wo,A,J]),Yy=r.useMemo(()=>vm(Ui,{month:"short",day:"numeric",year:"numeric"},Wa),[Ui,Wa]),jf=r.useMemo(()=>{const N=(ve?ia==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:ng:["mon","tue","wed","thu","fri"]).map(Se=>{const ut=dd(Ro[Se])||Ui,qt=Ro[Se],ga=Se==="sat"||Se==="sun";return{value:Se,label:`${rO[Se]} ${vm(ut,{month:"short",day:"numeric"},Wa)}`,color:ga?"#1e3a8a":"#3b82f6",icon:"Calendar",date:qt,isPast:qt<Ya,isSelected:qt===$s,isWeekend:ga}}),ce=vc.length>0;return[...Rn?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...ce?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...N]},[ve,Rn,Ro,Ui,vc.length,Ya,$s,ia,Wa]),Nf=r.useMemo(()=>{switch(h){case"category":return S;case"type":return(We||[]).map(u=>({...u,icon:u.icon||mm[u.value]?.icon,color:u.color||mm[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 ra.map(u=>({value:u.value,label:u.label,icon:u.icon==="HelpCircle"?"Circle":u.icon,color:u.color}));case"status":return[...ao.filter(u=>u.value!=="done"&&u.value!=="cancelled"),{value:"completed",label:"Completed",icon:pd("done").icon,color:pd("done").color}];case"schedule":return jf;default:return S}},[h,S,We,tt,Ze,ra,jf]),Jy=a.jsxs("div",{className:mt.accountMenuWrap,ref:tu,children:[a.jsx("button",{className:`tf-control-icon ${mt.avatarBtn}`,onClick:()=>{tr(u=>{const w=!u;return w?Ul("account_menu"):(Wi.current=null,Pl.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":ks,children:a.jsx("span",{className:mt.avatarBadge,"aria-hidden":"true",children:ou?a.jsx("img",{src:Fl,alt:"",className:mt.avatarImage}):Lc||a.jsx(ii,{size:14,className:mt.avatarIcon})})}),ks&&a.jsxs("div",{className:mt.accountMenu,role:"menu","aria-label":"Account menu",children:[a.jsxs("div",{className:mt.accountMenuSection,children:[a.jsx("div",{className:mt.accountMenuSectionLabel,children:"Account"}),a.jsx("div",{className:mt.accountMenuHint,children:du?"Checking sign-in status...":Zt?a.jsx(a.Fragment,{children:Dc?a.jsx(a.Fragment,{children:a.jsxs("span",{className:mt.accountIdentityBlock,children:[a.jsx("span",{className:mt.accountIdentityEmail,children:Js}),ru&&ei&&a.jsxs("span",{className:mt.accountIdentityMetaLine,children:[a.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Email"}),a.jsx("span",{className:mt.accountIdentityMetaValue,children:xo})]}),qd?a.jsxs("span",{className:mt.accountIdentityMetaLine,children:[a.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:mt.accountIdentityMetaValue,children:"Loading…"})]}):iu?a.jsxs("button",{"aria-label":`Subscription ${Bc}`,className:`${mt.accountIdentityMetaLine} ${mt.accountIdentityMetaAction}`,onClick:()=>{tr(!1),d()},type:"button",children:[a.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:mt.accountIdentityMetaValue,children:Bc})]}):Mc?a.jsxs("span",{className:mt.accountIdentityMetaLine,children:[a.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:mt.accountIdentityMetaValue,children:"Unavailable"})]}):null,a.jsxs("span",{className:mt.accountIdentityMetaLine,children:[a.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Runtime"}),a.jsx("span",{className:mt.accountIdentityMetaValue,children:cu})]}),a.jsxs("span",{className:mt.accountIdentityMetaLine,children:[a.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Environment"}),a.jsx("span",{className:mt.accountIdentityMetaValue,children:lu})]})]})}):"Signed in"}):"Not signed in"})]}),Vm&&a.jsxs("div",{className:mt.accountMenuSection,children:[a.jsx("div",{className:mt.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),za.length===0&&a.jsx("div",{className:mt.accountMenuHint,children:"No workspaces found for this account yet."}),za.map(u=>a.jsxs("button",{className:`${mt.accountMenuItem} ${u.id===Yt?mt.accountMenuItemActive:""}`,onClick:()=>Gl(u.id),role:"menuitem",disabled:_c||u.id===Yt,title:u.description||u.name,children:[a.jsx(Po,{size:15}),a.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[a.jsx("span",{children:u.name}),a.jsx("span",{className:mt.accountMenuMeta,children:u.role})]})]},u.id)),a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{bl(""),Ti(!0),tr(!1)},role:"menuitem",disabled:_c,children:[a.jsx(ro,{size:15}),"Create Workspace"]}),Od&&a.jsx("div",{className:mt.accountMenuError,children:Od})]}),Ud?a.jsx("div",{className:mt.accountMenuHint,children:"Resolving team management access..."}):Ao?a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{$c()},role:"menuitem",children:[a.jsx(zk,{size:15}),"Team Management"]}):Wm?a.jsx("div",{className:mt.accountMenuHint,children:"Team Management unavailable right now."}):null,Zt&&a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{tr(!1),wl(!0)},role:"menuitem",children:[a.jsx(ii,{size:15}),"Edit Profile"]}),a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{tr(!1),d()},role:"menuitem",children:[a.jsx(Ep,{size:15}),"Plans"]}),a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{tr(!1),Ul("account_hub"),Co(!0)},role:"menuitem",children:[a.jsx(ii,{size:15}),"Account Hub"]}),a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{tr(!1),Vo(!0)},role:"menuitem",children:[a.jsx(Ji,{size:15}),"Help & Support"]}),a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{tr(!1),Vo(!0)},role:"menuitem",children:[a.jsx(mg,{size:15}),"Contact Support"]}),Kt==="local"&&!Zt&&!du&&a.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{Oc("login")},role:"menuitem",children:[a.jsx(ii,{size:15}),"Sign In / Register"]}),Zt&&a.jsxs("button",{className:mt.accountMenuItem,onClick:async()=>{tr(!1),await Mr(),Kt==="cloud"&&s("/login",{replace:!0})},role:"menuitem",children:[a.jsx(Hk,{size:15}),"Sign Out"]})]})]}),Pf=r.useCallback(()=>{C(u=>u==="show"?"collapse":u==="collapse"?"hide":"show")},[C]),Mf=r.useCallback(()=>{O(),_("tasks"),k("add")},[O,k,_]),Qy=r.useCallback(u=>{const w=e.workstreams.find(N=>N.id===u);O(),pe(Eo(w)||u),_("tasks"),k("add")},[e.workstreams,O,k,_,pe]),Ef=r.useCallback(u=>{qs.current=!1,Vs(!1),zs(u),ha(!1),Hs(null),Qn(!1),Gs(""),fr(""),an("");const w=u.entityType==="workstream"&&sa&&_t.initiativeById.get(sa)||null;es(w?os(w):""),rn(null)},[_t.initiativeById,sa]),Df=r.useCallback((u,w)=>{qs.current=!1,Vs(!1),Hs(u),Qn(!1),Gs(""),fr(""),an("");const N=u.entityType==="workstream"&&((w?_t.initiativeById.get(w):null)||sa&&_t.initiativeById.get(sa))||null;es(N?os(N):""),rn(null)},[_t.initiativeById,sa]),np=r.useCallback(()=>{qs.current=!1,Vs(!1),zs(null),Gs(""),fr(""),an(""),es("")},[]),Lf=r.useCallback(()=>{qs.current=!1,Vs(!1),Hs(null),Gs(""),fr(""),an(""),es("")},[]),Xy=r.useCallback(async()=>{const u=po||fs;if(!u||qs.current)return;qs.current=!0,Vs(!0);const w=!!po,N=ma.trim()||null;try{if(u.entityType==="initiative")if(u.mode==="edit")await e.updateInitiative(u.targetId,{title:Wo.trim()||"Untitled Initiative",description:fo.trim()||null,ownerId:N}),pr({type:"initiative",id:u.targetId}),rn(null),xt("Initiative updated","success");else{const ce=await e.createInitiative({title:Wo.trim()||"Untitled Initiative",description:fo.trim()||null,ownerId:N});pr({type:"initiative",id:ce.id}),rn(null),xt("Initiative created","success")}else{const ce=Xn.trim(),Se=ce.length===0?null:vp(_t.initiatives,ce);if(ce.length>0&&!Se){xt("Initiative not found by that reference.","error");return}const ut={title:Wo.trim()||"Untitled Workstream",description:fo.trim()||null,ownerId:N,initiativeId:Se?.id||null};if(u.mode==="edit")await e.updateWorkstream(u.targetId,ut),w?rn(u.targetId):(pr({type:"workstream",id:u.targetId}),rn(null)),xt("Workstream updated","success");else{const qt=await e.createWorkstream(ut);w?rn(qt.id):(pr({type:"workstream",id:qt.id}),rn(null)),xt("Workstream created","success")}}w?Lf():np()}catch(ce){xt(ce instanceof Error?ce.message:"Failed to save planning item.","error")}finally{qs.current=!1,Vs(!1)}},[np,Lf,fo,Xn,ma,Wo,fs,po,_t.initiatives,e,xt]),ek=r.useCallback(u=>{oc(w=>{const N=new Set(w);return N.has(u)?N.delete(u):N.add(u),N})},[]),tk=r.useCallback(u=>{uo(w=>w===u?"":u),mo("")},[]),ak=r.useCallback((u,w)=>{mo(N=>{const ce=N===u?"":u;return uo(ce&&w||""),ce})},[]),nk=r.useCallback(u=>{zs(null),Hs(null),ha(!1),Qn(!1),pr(u?{type:"initiative",id:u}:null),rn(null)},[]),rk=r.useCallback(u=>{zs(null),Hs(null),ha(!1),Qn(!1),pr(u?{type:"workstream",id:u}:null),rn(null)},[]),sk=r.useCallback(u=>{Hs(null),Qn(!1),rn(u)},[]),rp=r.useCallback((u,w)=>{if(u==="workstream"&&w){Df({mode:"create",entityType:"workstream"},w);return}if(Ef({mode:"create",entityType:u}),u==="workstream"){const N=(w?_t.initiativeById.get(w):null)||(sa?_t.initiativeById.get(sa):null)||null;es(N?os(N):"")}},[Ef,Df,_t.initiativeById,sa]),Bf=r.useCallback((u,w)=>{if(u==="initiative"){const N=_t.initiativeById.get(w);if(!N)return;zs({mode:"edit",entityType:"initiative",targetId:w}),Gs(N.title),fr(N.description||""),an(N.ownerId?String(N.ownerId):""),es("")}else{const N=_t.workstreamById.get(w)||_t.standaloneWorkstreams.find(Se=>Se.id===w);if(!N)return;zs({mode:"edit",entityType:"workstream",targetId:w}),Gs(N.title),fr(N.description||""),an(N.ownerId?String(N.ownerId):"");const ce=N.initiativeId&&_t.initiativeById.get(N.initiativeId)||null;es(ce?os(ce):"")}rn(null)},[_t.initiativeById,_t.standaloneWorkstreams,_t.workstreamById]),Tu=r.useCallback(async(u,w)=>{const N=e.workstreams.find(qt=>qt.id===u);if(!N){xt("Workstream not found.","error");return}const ce=typeof w=="string"?w.trim():w===null?"":Xn.trim(),Se=ce.length===0?null:vp(_t.initiatives,ce);if(ce.length>0&&!Se){xt("Initiative not found by that reference.","error");return}const ut=Se?.id||null;if((N.initiativeId||null)===ut){xt(ut?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info");return}try{await e.updateWorkstream(u,{initiativeId:ut}),es(Se?os(Se):""),xt(ut?"Initiative set":"Initiative removed","success")}catch{xt("Failed to set initiative.","error")}},[Xn,_t.initiatives,e,xt]),Ru=r.useCallback(async(u,w)=>{const N=pc.get(u);if(!N){xt("Task not found.","error");return}const ce=w||null;if(_t.initiativeById.has(u)||_t.workstreamById.has(u)){xt("Only execution tasks can be moved into workstreams.","error");return}if(ce&&!_t.workstreamById.has(ce)){xt("Workstream not found.","error");return}if((N.workstreamId||null)===ce){xt(ce?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const Se=await fetch(`/api/taskforce/task/${u}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:ce})});if(!Se.ok){const ut=await Se.json().catch(()=>({}));xt(ut?.error||"Failed to set workstream.","error");return}await Se.json().catch(()=>null),await J(!0),xt(ce?"Workstream set":"Workstream removed","success")}catch{xt("Failed to set workstream.","error")}},[J,pc,_t.initiativeById,_t.workstreamById,xt]),ok=r.useCallback(async(u,w)=>{const N=w.trim();if(!N){xt("Enter a task reference.","error");return}const ce=jg(N),Se=Ci.find(ut=>ut.id===N||Xi(ut)===N||ce!==null&&ut.referenceNumber===ce);if(!Se){xt("Task not found by that reference.","error");return}await Ru(Se.id,u)},[Ru,Ci,xt]),ik=r.useCallback(async(u,w)=>{const N=w.trim();if(!N){xt("Enter a workstream reference.","error");return}const ce=_t.initiativeById.get(u);if(!ce){xt("Initiative not found.","error");return}const Se=ny(N),ut=e.workstreams.find(qt=>qt.id===N||Eo(qt)===N||Se!==null&&qt.referenceNumber===Se);if(!ut){xt("Workstream not found by that reference.","error");return}await Tu(ut.id,os(ce))},[Tu,_t.initiativeById,e.workstreams,xt]),Uc=r.useCallback((u,w)=>{const N=`${u}:${w}`,ce=sl.current.get(N);if(ce)return ce;const Se=u==="initiative"?e.initiatives.find(ut=>ut.id===w):e.workstreams.find(ut=>ut.id===w);return Array.isArray(Se?.attachments)?Se.attachments:[]},[e.initiatives,e.workstreams]),zc=r.useCallback((u,w,N)=>{const ce=`${u}:${w}`;sl.current.set(ce,N);const ut=(sn.current.get(ce)||Promise.resolve()).catch(()=>{}).then(()=>u==="initiative"?e.updateInitiative(w,{attachments:N}):e.updateWorkstream(w,{attachments:N}));sn.current.set(ce,ut),ut.catch(qt=>{xt(qt instanceof Error?qt.message:"Failed to update planning context.","error")}).finally(()=>{sn.current.get(ce)===ut&&sn.current.delete(ce)})},[e,xt]),ck=r.useCallback((u,w,N)=>{const ce=Uc(u,w);zc(u,w,[...ce,N])},[Uc,zc]),lk=r.useCallback((u,w,N)=>{const ce=Uc(u,w);zc(u,w,ce.filter((Se,ut)=>ut!==N))},[Uc,zc]),dk=r.useCallback((u,w,N,ce)=>{const ut=Uc(u,w).map((qt,ga)=>ga!==N?qt:typeof qt=="string"?{path:qt,caption:ce,timestamp:new Date().toISOString()}:{...qt,caption:ce});zc(u,w,ut)},[Uc,zc]),Wf=r.useCallback(u=>{uo(u),mo("")},[]),Ff=r.useCallback(u=>{mo(u),uo(u&&_t.workstreamInitiativeIds.get(u)||"")},[_t.workstreamInitiativeIds]),sp=r.useCallback(u=>{const w=ag(u,js);if(w!==u){const N=js.find(ce=>ce.id===u)?.label||"That module";xt(`${N} is not available in this build yet.`,"error");return}Ir(),_(w)},[Ir,xt,_,js]),Of=r.useCallback(()=>{if(oa==="tasks"&&Or){Bo(!1),pr(null),rn(null),zs(null);return}if(oa!=="tasks"){_("tasks"),Bo(!0);return}Bo(u=>!u)},[Or,oa,_]),$f=r.useCallback(()=>{if(oa!=="docs"){_("docs"),rc(!0);return}rc(u=>!u)},[oa,_]),Uf=r.useCallback(()=>{if(oa!=="annotate"){_("annotate"),co(!0);return}co(u=>!u)},[oa,_]),zf=r.useCallback(()=>{if(oa!=="agents"){_("agents"),Ts(!0);return}Ts(u=>!u)},[oa,_]),uk=r.useCallback(u=>{Ir(),_("tasks"),Ot(u)},[Ir,Ot,_]),mk=r.useCallback(u=>{Ir(),_("tasks"),Ot(u)},[Ir,Ot,_]),pk=r.useCallback((u,w)=>{hs(u),gi(w?.sessionId??null),Ad(N=>N+1),_("annotate")},[_]),fk=r.useCallback(({target:u,sessionId:w})=>{hs(N=>!N&&!u||N&&u&&N.taskId===u.taskId&&N.taskReferenceLabel===u.taskReferenceLabel&&N.assetId===u.assetId&&N.imageReferenceLabel===u.imageReferenceLabel&&N.path===u.path&&N.displayName===u.displayName?N:u),gi(N=>N===w?N:w)},[]),Hf=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")},...iy(Dt,[...e.searchAgnosticTasks,...Un])],[Un,e.searchAgnosticTasks,Dt]),Gf=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")}],[]),Vf=r.useMemo(()=>js.filter(u=>u.enabled),[js]),qf=r.useMemo(()=>[{key:"empty-columns",icon:I==="show"?a.jsx(Zf,{size:16}):I==="collapse"?a.jsx(Yf,{size:16}):a.jsx(nf,{size:16}),title:qe(I==="show"?"standalone.showEmptyColumns":I==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:Pf,active:I!=="show"},{key:"compressed-cards",icon:at?a.jsx(Gk,{size:16}):a.jsx(Vk,{size:16}),title:qe(at?"standalone.expandCards":"standalone.compressCards"),onClick:()=>bt(!at),active:at}],[at,Pf,I]),hk=r.useMemo(()=>[{key:"filter-toggle",icon:a.jsx(fg,{size:16}),title:qe("standalone.toggleFilters"),onClick:()=>ui(!io),active:io,className:Su?p.filterGlow:""}],[Su,ui,io]),gk=r.useMemo(()=>{switch(Qs.filterBar.kind){case"task-filters":return a.jsx(s4,{categoryFilterOptions:uc,typeFilterOptions:hl,priorities:tt,taxonomyDisplayLabels:Fe,filterCategories:Ke,setFilterCategories:Je,filterTypes:Ne,setFilterTypes:zt,filterPriorities:Jt,setFilterPriorities:Pt,filterStatus:B,setFilterStatus:X,filterAssignees:Ft,setFilterAssignees:Lt,assigneeOptions:ra,initiativeFilterOptions:Pd,selectedInitiativeId:sa,setSelectedInitiativeId:Wf,workstreamFilterOptions:hc,selectedWorkstreamId:Xr,setSelectedWorkstreamId:Ff,taskScope:Vt,setTaskScope:Ga,showArchive:So,setShowArchive:ml,fetchArchive:pl,onDeleteAllDeleted:()=>{const u=zn.length;u===0||!window.confirm(`Permanently delete ${u} deleted task${u===1?"":"s"}? This cannot be undone.`)||c()},clearFilters:()=>{cn(),uo(""),mo("")}});case"document-filters":return a.jsx(o4,{typeFilters:ho,setTypeFilters:Fo,attachmentFilters:go,setAttachmentFilters:Oo,clearFilters:()=>{Fo(em.map(u=>u.value)),Oo(tm.map(u=>u.value))}});default:return a.jsx(n4,{})}},[ra,uc,cn,zn.length,go,ho,Ft,Ke,Jt,B,Ne,Wf,Ff,Pd,tt,sa,Xr,Oo,Fo,Lt,Je,Pt,X,zt,uo,mo,ml,Ga,So,Vt,Fe,hl,hc,Qs.filterBar.kind,pl,c]),yk=r.useMemo(()=>[{key:"zen-toggle",icon:a.jsx(qk,{size:16,fill:D?"currentColor":"none"}),title:qe(D?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>q(),active:D}],[D,q]),kk=r.useMemo(()=>({search:a.jsx(t4,{value:we,placeholder:qe("standalone.searchPlaceholder"),active:$i,onChange:xe,onClear:()=>xe(""),clearTitle:qe("standalone.clearSearchTitle")}),sort:a.jsx(Yh,{label:a.jsxs(a.Fragment,{children:[a.jsx(Kk,{size:12})," ",qe("standalone.sortLabel")]}),value:Va,options:Hf,onChange:u=>qa(u),trailingAction:a.jsx("button",{className:`tf-control-icon ${p.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?qe("standalone.sortDirectionDescTitle"):qe("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?a.jsx(cg,{size:14}):a.jsx(lg,{size:14})})}),"divider-primary":a.jsx(Jh,{}),grouping:a.jsx(Yh,{label:a.jsxs(a.Fragment,{children:[a.jsx(Ep,{size:12})," ",qe("standalone.groupLabel")]}),value:h,options:Gf,onChange:u=>g(u)}),"divider-secondary":a.jsx(Jh,{}),"task-display-actions":a.jsx(Ap,{actions:qf})}),[h,Gf,sp,$i,e,we,g,xe,qa,Va,Hf,qf,Qs.moduleId]),vk=r.useMemo(()=>({"add-task":a.jsx(a4,{icon:a.jsx(ro,{size:16}),label:qe("standalone.addTask"),onClick:Mf}),"add-document":null}),[Mf]),Ql=r.useMemo(()=>{const u={tasks:a.jsx(ev,{size:18}),docs:a.jsx(Dp,{size:18}),annotate:a.jsx(Xk,{size:18}),workflows:a.jsx(Jf,{size:18}),agents:a.jsx(am,{size:18})},w=ea.workspaceToolButtonDisabled,N=oa==="docs"?a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${ms?ea.workspaceToolButtonActive:""}`.trim(),onClick:$f,title:ms?"Collapse document tray":"Document tray","aria-label":ms?"Collapse document tray":"Document tray",children:ms?a.jsx(Mo,{size:18}):a.jsx(Po,{size:18})}):oa==="annotate"?a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${Qr?ea.workspaceToolButtonActive:""}`.trim(),onClick:Uf,title:Qr?"Collapse image tray":"Image tray","aria-label":Qr?"Collapse image tray":"Image tray",children:Qr?a.jsx(Mo,{size:18}):a.jsx(Po,{size:18})}):oa==="agents"?a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${Is?ea.workspaceToolButtonActive:""}`.trim(),onClick:zf,title:Is?"Collapse agent tray":"MCP settings tray","aria-label":Is?"Collapse agent tray":"MCP settings tray",children:Is?a.jsx(Mo,{size:18}):a.jsx(Jk,{size:18})}):oa==="workflows"?a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${w}`.trim(),title:"Workflow tray coming soon","aria-label":"Workflow tray coming soon",disabled:!0,children:a.jsx(Jf,{size:18})}):a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${oa==="tasks"&&Or?ea.workspaceToolButtonActive:""}`.trim(),onClick:Of,title:oa==="tasks"&&Or?"Collapse planning trays":"Planning","aria-label":oa==="tasks"&&Or?"Collapse planning trays":"Planning",children:oa==="tasks"&&Or?a.jsx(Mo,{size:18}):a.jsx(Qk,{size:18})});return a.jsxs("aside",{className:ea.workspaceToolRail,"aria-label":"Workspace tools",children:[a.jsxs("div",{className:ea.workspaceToolRailMain,children:[N,a.jsx("div",{className:ea.workspaceToolRailDivider}),Vf.map(ce=>a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${oa===ce.id?ea.workspaceToolButtonActive:""}`.trim(),onClick:()=>sp(ce.id),title:ce.label,"aria-label":ce.label,children:u[ce.id]},ce.id))]}),a.jsxs("div",{className:ea.workspaceToolRailBottom,children:[a.jsx("div",{className:ea.workspaceToolRailDivider}),a.jsx("button",{type:"button",className:`${ea.workspaceToolButton} ${y==="settings"?ea.workspaceToolButtonActive:""}`.trim(),onClick:()=>{wa("general"),k("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:a.jsx(af,{size:18})})]})]})},[y,Is,ms,zf,$f,Uf,sp,Of,Qr,Or,oa,wa,k,Vf]),[Kf,Sk]=r.useState(null),wk=r.useCallback(u=>{Sk(u)},[]),bk=a.jsx(LF,{open:Or,leftOffset:56,initiatives:_t.initiatives,standaloneWorkstreams:_t.standaloneWorkstreams,allStandaloneWorkstreams:_t.allStandaloneWorkstreams,activeInitiativeId:sa,activeWorkstreamId:Xr,expandedInitiativeIds:$r,detail:Go,editor:fs,secondaryPane:yc,currentWorkspaceId:Yt,assigneeOptions:ra.map(u=>({value:String(u.value),label:u.label,kind:u.kind,username:u.username??null,archivedAt:u.archivedAt??null})),draftInitiativeSummary:kc,draftTitle:Wo,draftDescription:fo,draftOwner:ma,draftInitiativeId:Xn,onChangeDraftTitle:Gs,onChangeDraftDescription:fr,onChangeDraftOwner:an,onChangeDraftInitiativeId:es,onCollapseTreePane:()=>ps(!0),onExpandTreePane:()=>ps(!1),onCollapsePrimaryPane:()=>ha(!0),onExpandPrimaryPane:()=>ha(!1),onCollapseSecondaryPane:()=>Qn(!0),onExpandSecondaryPane:()=>Qn(!1),onBackFromSecondary:()=>{qs.current=!1,Vs(!1),Hs(null),rn(null)},treeCollapsed:lo,primaryCollapsed:fi,secondaryCollapsed:sc,onCancelEditor:np,onSubmitEditor:Xy,isSubmittingEditor:hi,onCreateInitiative:()=>rp("initiative"),onCreateWorkstream:()=>rp("workstream"),onCreateTaskInWorkstream:Qy,onCreateWorkstreamInInitiative:u=>rp("workstream",u),onAssignInitiativeToWorkstream:Tu,onOpenTaskById:Ot,onRemoveTaskFromWorkstream:u=>{Ru(u,null)},onAttachTaskToWorkstreamByReference:ok,onAttachWorkstreamToInitiativeByReference:ik,onAddPlanningContextFile:ck,onRemovePlanningContextFile:lk,onUpdatePlanningContextCaption:dk,onToggleInitiative:ek,onSelectInitiative:tk,onSelectWorkstream:ak,onOpenInitiativeDetails:nk,onOpenWorkstreamDetails:rk,onOpenNestedWorkstreamDetails:sk,onEditInitiative:u=>Bf("initiative",u),onEditWorkstream:u=>Bf("workstream",u),onArchiveInitiative:u=>{e.archiveInitiative(u).then(()=>{xt("Initiative archived","success")}).catch(w=>{xt(w instanceof Error?w.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:u=>{e.unarchiveInitiative(u).then(()=>{xt("Initiative unarchived","success")}).catch(w=>{xt(w instanceof Error?w.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:u=>{e.archiveWorkstream(u).then(()=>{xt("Workstream archived","success")}).catch(w=>{xt(w instanceof Error?w.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:u=>{e.unarchiveWorkstream(u).then(()=>{xt("Workstream unarchived","success")}).catch(w=>{xt(w instanceof Error?w.message:"Failed to unarchive workstream.","error")})}}),_k=Qs.headerSections.map(u=>{const w=kk[u];return w?a.jsx(Ue.Fragment,{children:w},u):null}).filter(Boolean),Ck=Qs.primaryAction?vk[Qs.primaryAction]:null;return a.jsxs("div",{className:`${ea.standaloneWrapper} ${D?p.zenModeEnabled:""}`,"data-theme":Ae,children:[a.jsx(e4,{projectName:_n,currentWorkspaceId:Yt,runtimeMode:Kt,theme:Ae,onBrandClick:Hl,meta:a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.taskCountBadge,title:Zl,children:ep}),ts&&ts!=="anonymous"&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:p.taskCountBadge,title:"Tasks assigned to me",children:[a.jsx(ii,{size:13,className:p.taskCountBadgeIcon,"aria-hidden":"true"}),Ld]}),a.jsxs("span",{className:`${p.taskCountBadge} ${Bd>0?p.taskCountBadgeAlert:""}`.trim(),title:"Tasks overdue",children:[a.jsx(Zk,{size:13,className:p.taskCountBadgeIcon,"aria-hidden":"true"}),Bd]})]}),tp&&a.jsx("button",{className:"tf-control-icon",onClick:Km,title:`Sync manager: ${ba.label} | Last success: ${Yl}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${ba.border}`,background:ba.background,color:ba.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:ba.icon==="off"?a.jsx(Yk,{size:16}):a.jsx(hg,{size:16})})]}),actions:a.jsxs(a.Fragment,{children:[i&&a.jsxs(a.Fragment,{children:[Zt&&gn?.stripeCustomerId&&a.jsx("button",{className:"tf-control-icon",onClick:()=>{Wc()},title:"Manage billing",disabled:Kd,children:"Manage billing"}),a.jsx("button",{className:"tf-control-icon",onClick:()=>{if(zl){ni();return}m()},title:zl?"Continue to Taskforce":"Back",disabled:Yo,children:zl?"Take Me to Taskforce":"Back"})]}),!i&&a.jsxs(a.Fragment,{children:[_k,Ck]}),a.jsx(Ap,{actions:yk}),!i&&a.jsx(Ap,{actions:hk}),Jy]})}),a.jsx(xy,{notice:Lr,onDismiss:Br}),Ra&&a.jsx("div",{className:fe.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),!i&&io&&gk,i?a.jsx("div",{className:`${ea.standalonePage} ${ea.standaloneContent} ${p.appScrollbar} tf-scrollbar`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",scrollbarGutter:"stable",background:"var(--surface-page)"},children:a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(kO,{...e,currentTheme:Ae,projectName:_n,currentWorkspaceId:Yt,authUserId:Ka,apiBaseUrl:$l,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",resolveCloudAuthUrl:Ma,embedded:!0,shellOwnsScroll:!0,onAccountProfileSummaryChange:gu,onContinueToTaskforce:ni,continueBusy:Yo})})}):oa==="docs"&&Ho?a.jsxs("div",{className:`${ea.standalonePage} ${ea.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[Ql,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(hO,{tasks:me,runtimeMode:Kt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:ho,attachmentFilters:go,onTypeFiltersChange:Fo,onAttachmentFiltersChange:Oo,documentTrayOpen:ms,onCloseDocumentTray:()=>rc(!1),requestedDocPath:Nm,requestedDocAssetId:Pm,onRequestedDocHandled:()=>{ol(null),il(null)},onBackToTask:mk,enableTaskGeneration:!0})})]}):oa==="annotate"&&dc?a.jsxs("div",{className:`${ea.standalonePage} ${ea.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[Ql,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(fO,{runtimeMode:Kt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:Yt,sessionLoadReady:yi,requestedTarget:er,requestedSessionId:yo,requestedOpenVersion:Mm,imageTrayOpen:Qr,onCloseImageTray:()=>co(!1),resolveTaskReferenceLabel:jd,resolveImageReferenceLabel:Nd,onOpenTarget:pk,onContextChange:fk,onBackToTask:uk})})]}):oa==="workflows"?a.jsxs("div",{className:`${ea.standalonePage} ${ea.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[Ql,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(gO,{availableWorkflows:Fn,availableEnvironments:Gt,exportEnvironment:Da,exportWorkflowsPath:e.exportWorkflowsPath,exportingResource:ds,exportResult:Yn,onExportEnvironmentChange:e.setExportEnvironment,onExportWorkflows:On,onRefreshWorkflows:Tn,onFetchWorkflowTemplate:e.fetchWorkflowTemplate,onFetchWorkflowOverrideNames:e.fetchWorkflowOverrideNames,onSaveWorkflowTemplateDraft:e.saveWorkflowTemplateDraft,onResetWorkflowTemplateDraft:e.resetWorkflowTemplateDraft})})]}):oa==="agents"?a.jsxs("div",{className:`${ea.standalonePage} ${ea.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[Ql,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(yO,{workspaceId:Yt,cloudAuthConfigured:Ta,authSessionResolved:la,isAuthenticated:Zt,cloudAiProfileSeatUsage:gn?.aiProfileSeatUsage??null,agentTrayOpen:Is,onCloseAgentTray:()=>Ts(!1),mcpSettingsNode:a.jsx(rg,{settingsModel:{...he,initialSection:"mcp",onOpenCloudAuth:Oc},renderMode:"mcp-only"})})})]}):a.jsxs("div",{className:`${ea.standalonePage} ${ea.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:Or?`${56+Md+6}px`:"62px",paddingRight:h==="schedule"&&Jr?`${ef}px`:0},children:[Ql,a.jsx("div",{ref:wk,style:{position:"absolute",inset:0,zIndex:35,pointerEvents:"none"}}),a.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.loadingTasks&&Ai.length>0&&a.jsx("div",{className:p.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:a.jsx(kr,{size:14,className:p.spinner})}),a.jsx(wW,{tasks:yl,allTasks:Ed,columns:Nf,groupBy:h,scheduleDates:Ro,searchQuery:we,filterCategories:Ke,filterTypes:Ne,filterPriorities:Jt,filterStatus:B,filterAssignees:Ft,filtersReady:Ht,assigneeOptions:ra,scheduleFilteredTaskIds:Array.from(gl),copiedId:St,taxonomies:Dt,types:We,priorities:tt,onUpdateTask:A,onTaskClick:u=>ke(u),onOpenTaskById:Ot,onCopyId:ot,onToggleInProgress:te,onToggleReview:At,onToggleComplete:Le,onToggleCancel:jt,onSetStatus:wc,onArchiveTask:Wt,onAddTaskToColumn:vl,showTaskCardStatusLabel:ie,onScheduleDaySelected:u=>{oo(u);const w=dd(u);w&&us(`${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:h==="schedule"?di:void 0,onScrollLeftChange:u=>{h==="schedule"&&Pn(u)},emptyColumnMode:I,categories:S,compressed:at,readOnlyMode:Vt==="deleted"?"deleted":Vt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:Va,sortOrder:e.sortOrder,planningDropTargets:Kf?Yi.createPortal(bk,Kf):null,onAssignTaskToWorkstream:Ru,onAssignWorkstreamToInitiative:Tu,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:u=>{if(Vt==="deleted"){const w=Si.get(u);if(!w)return;yt(w.id);return}$t(u)},onDelete:u=>{if(Vt==="deleted"){const w=Si.get(u);if(!w||!window.confirm("Permanently delete this task? This cannot be undone."))return;E(w.id);return}Ge(u)}},`${h}-${Nf.map(u=>String(u.value)).join("|")}-${Ro.mon}`),h==="schedule"&&!Jr&&a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{pr(null),Nn(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:a.jsx(Mo,{size:16})})]}),h==="schedule"&&a.jsx(iO,{open:Jr,onClose:()=>Nn(!1),scheduleSelectedDate:$s,setScheduleSelectedDate:oo,scheduleCalendarMonth:Lo,setScheduleCalendarMonth:us,scheduleShowWeekends:ve,setScheduleShowWeekends:ae,scheduleShowBacklog:Rn,setScheduleShowBacklog:jn,scheduleOnlyExpired:hn,setScheduleOnlyExpired:Os,expiredScheduledCount:Dd,overdueDueCount:kl,expiredLeafCandidates:xi,expiredRecoveryCandidates:wo,onMoveExpiredToSelectedWeek:Ky,onMoveExpiredToBacklog:Zy,scheduleBulkBusy:bo,globalWeekStartsOn:ia,resolvedLocale:Wa,todayDateOnly:Ya,scheduleBaseTasks:mc,scheduleWeekStart:Ui,scheduleWeekLabel:Yy})]}),a.jsxs(Ws,{isOpen:y==="add",onClose:Sc,title:de?Mt?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:mi?"full":"xl",theme:Ae,headerActions:a.jsx("button",{className:"tf-control-icon",onClick:()=>pi(u=>!u),title:mi?"Exit full screen":"Enter full screen","aria-label":mi?"Exit full screen":"Enter full screen",children:mi?a.jsx(Yf,{size:18}):a.jsx(Zf,{size:18})}),draggable:!mi,closeOnOverlayClick:!1,children:[a.jsx(Ay,{editingTaskId:de,loading:ge,autoSaveState:Wr,title:P,currentTask:Mt,currentTaskWorkstream:Ha,currentTaskInitiative:Jn,workstreamInput:se,onWorkstreamInputChange:pe,onSetWorkstreamForCurrentTask:ht,handleSubmit:le,resetForm:O,handleCopyId:ot,copiedId:St,tasks:me,handleToggleInProgress:te,handleToggleReview:At,handleToggleComplete:Le,handleToggleCancel:jt,handleSetStatus:wc,handleArchiveTask:Wt,handleUnarchiveTask:u=>{if(Mt?.isDeleted){const w=Si.get(u);if(!w)return;yt(w.id);return}$t(u)},handleRestoreDeletedTask:Mt?.deletedRecordId?u=>{yt(u)}:void 0,handlePermanentlyDeleteDeletedTask:Mt?.deletedRecordId?u=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(E(u),O(),k("tasks"))}:void 0}),a.jsx(Cy,{editingTaskId:de,error:Y,title:P,description:ue,checklistItems:V,category:_e,type:oe,priority:Ee,complexity:Pe,manualComplexityEnabled:z,approach:b,assignee:F,scheduledDate:M,dueDate:be,workstreamInput:se,formTaxonomies:Re,onTaxonomyChange:(u,w)=>Te(N=>({...N,[u]:w})),taxonomies:Dt,comments:De,newCommentText:Oe,contextFiles:st,currentWorkspaceId:Yt,apiBaseUrl:$l,descriptionFocused:Ct,showMarkdownHelp:Qe,showChecklist:ee,checklistEnabled:ne,showComments:ft,categories:S,types:We,priorities:tt,taxonomyDisplayLabels:Fe,assigneeOptions:ra,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:St,onTitleChange:H,onDescriptionChange:ye,onChecklistItemsChange:Me,onCategoryChange:re,onTypeChange:Ie,onPriorityChange:je,onComplexityChange:K,onApproachChange:u=>{R(u),Te(w=>({...w,approach:u}))},onAssigneeChange:Q,onScheduledDateChange:$,onDueDateChange:U,onWorkstreamInputChange:pe,onNewCommentTextChange:vt,onDescriptionFocusedChange:dt,onShowMarkdownHelpChange:Rt,onShowChecklistChange:ze,onShowCommentsChange:it,onOpenSettings:u=>{wa(u),k("settings")},onSubmit:le,commentsEndRef:so,onAddComment:()=>Et(Oe),onOpenTaskById:Ot,onAddContextFile:u=>{ll(w=>[...w,u])},onRemoveContextFile:async u=>{ll(w=>w.filter((N,ce)=>ce!==u))},onUpdateContextCaption:(u,w)=>{ll(N=>N.map((ce,Se)=>Se!==u?ce:typeof ce=="string"?{path:ce,caption:w,timestamp:new Date().toISOString()}:{...ce,caption:w}))},onCopyId:ot,onToggleInProgress:te,onToggleReview:At,onToggleComplete:Le,onToggleCancel:jt,onSetStatus:wc,onArchiveTask:Wt,onUnarchive:u=>{if(Mt?.isDeleted){const w=Si.get(u);if(!w)return;yt(w.id);return}$t(u)},currentTask:Mt})]}),a.jsx(Ws,{isOpen:y==="settings",onClose:Sc,title:"Settings",size:"xl",theme:Ae,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:a.jsx(kr,{size:20,className:p.spinner})}),children:a.jsx(rg,{settingsModel:{...he,onOpenCloudAuth:Oc},onSectionChange:wa})})}),a.jsx(_B,{prompt:Yr,theme:Ae,onClose:Fr,onConfirm:Ba}),a.jsx(CB,{isOpen:qm,theme:Ae,onClose:Zm,onConfirm:Ym}),a.jsx(bB,{isOpen:Wd,theme:Ae,onClose:()=>Vo(!1),supportMailtoHref:Jm,onOpenSettings:()=>{Vo(!1),k("settings"),wa("general")},onOpenAccountHub:()=>{Vo(!1),Ul("account_hub"),Co(!0)}}),a.jsx(SB,{isOpen:Sl,theme:Ae,onClose:uu,onSave:()=>{hu()},displayName:Rl,email:xo,avatarDisplayUrl:Ol,accountBadgeInitial:Lc,saveBusy:Gm,avatarBusy:jl,saveError:Qd,saveNotice:Xd,onDisplayNameChange:Yd,onOpenAvatarManager:()=>{as(null),ns(null),bc(!0)}}),a.jsx(fB,{isOpen:Dm,theme:Ae,title:"Edit Profile Photo",currentImageUrl:Ol,fallbackInitial:Lc,accept:vO,busy:jl,hasPendingImage:!!hr,canRemove:!!Ol,error:Qd,notice:Xd,onClose:()=>bc(!1),onApplyImage:mu,onRemoveImage:fu,onDiscardPendingImage:pu}),a.jsx(qL,{isOpen:_o,theme:Ae,runtimeMode:Kt,authRequiredForApi:Qa,isAuthenticated:Zt,hasAuthIdentity:Dc,authIdentityLabel:Js,billingLoading:qd,billingError:Mc,billingActionError:Ur,billingNotice:Zd,billingActionBusy:Kd,billingIntervalChoice:Ys,accountProfileSummary:gn,currentWorkspaceId:Yt,canOpenTeamManagement:Ao,canManageWorkspaceSync:Ml,workspaceCloudSyncEnabled:Vn,syncStatusLabel:ba.label,workspaceSyncError:Dl,syncControlBusy:au,cloudAuthEnabled:Ta,availableAuthProviders:Cr,onFetchLoginMethods:na,onUnlinkLoginMethod:da,onAddPassword:Xa,onLinkProvider:u=>Er(u),onClose:()=>Co(!1),onOpenWorkspaceAudit:()=>{Co(!1),$c(),Ri("audit")},onBillingIntervalChange:Bi,onRefreshBilling:()=>{Nr()},onUpdateInterval:()=>{yu()},onManageBilling:()=>{Wc()},onStartCheckout:()=>{Qm()},onToggleWorkspaceSync:u=>{nu(u)},onOpenHelp:()=>{Co(!1),Vo(!0)}}),a.jsx(fW,{isOpen:Lm,theme:Ae,teamPlanMode:xc,teamMgmtError:vs,teamManagementTab:Bm,teamUsersLoading:Ic,teamUsers:qo,teamActionBusyUserId:Pi,teamInviteFeedback:zd,teamInviteEmail:Mi,teamInviteRole:Ps,teamInvitePermissionMode:Di,teamInviteBusy:Nc,pendingInvites:Xm,teamAuditLoading:Hd,teamAuditEvents:Om,teamAuditPage:Ms,teamAuditPages:Vd,teamAuditHasMore:Um,onClose:()=>$d(!1),onOpenMembersTab:()=>{Ri("members"),ai()},onOpenInvitesTab:()=>Ri("invites"),onOpenAuditTab:()=>{Ri("audit"),Io(Ms)},onMemberRoleChange:(u,w)=>{To(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...rs()},credentials:"include",body:JSON.stringify({workspaceId:Es,role:w})}))},onMemberPermissionChange:(u,w)=>{To(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...rs()},credentials:"include",body:JSON.stringify({workspaceId:Es,mode:w})}))},onToggleMemberDisabled:(u,w)=>{To(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...rs()},credentials:"include",body:JSON.stringify({workspaceId:Es,disabled:w})}))},onRevokeInvite:u=>{To(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...rs()},credentials:"include",body:JSON.stringify({workspaceId:Es})}))},onRemoveMember:u=>{To(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}?workspaceId=${encodeURIComponent(Es)}`,{method:"DELETE",headers:rs(),credentials:"include"}))},onInviteEmailChange:Rc,onInviteRoleChange:Ei,onInvitePermissionModeChange:jc,onSubmitInvite:()=>{Vl()},onLoadAuditPrevious:()=>{Io(Ms-1)},onLoadAuditNext:()=>{Io(Ms+1)}}),a.jsx(WL,{isOpen:_l,theme:Ae,onClose:()=>Ti(!1),onConfirm:()=>Oi({intent:"create-workspace"})}),a.jsx(pW,{isOpen:El,theme:Ae,currentWorkspaceLabel:Bl,syncStatusMeta:ba,workspaceCloudSyncEnabled:Vn,syncControlBusy:au,canManageWorkspaceSync:Ml,workspaceSyncSummary:bs.summary,workspaceSyncRecommendedAction:bs.recommendedAction,workspaceSyncRepairBusy:En,referenceMismatchCount:fa,syncStageLabel:qy,workspaceSyncPendingChanges:ja,formattedLastSyncTime:Yl,formattedLastPullTime:_u,formattedLastPushTime:Cu,syncLastError:xu,workspaceSyncDiagnostics:ws,activeReferenceMismatchSummaries:Fa,syncDiagnosticsSummary:f,syncEventRows:pa,syncEventsListRef:He,workspaceSyncRepairQueued:Pr,workspaceSyncBusy:Ea,workspaceSyncCopied:Jl,runtimeMode:Kt,isAuthenticated:Zt,onClose:Ll,onToggleWorkspaceSync:u=>{nu(u)},onRepairSync:Vy,onCopyReport:()=>{Gy()},onOpenLogin:()=>{Oc("login")},onRetrySync:()=>{Ln()}}),mr&&Yi.createPortal(a.jsx("div",{className:`${Tt.overlay} ${Tt.unsavedOverlay}`,style:{zIndex:2e3},children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${Tt.modal} ${Tt.unsavedModal}`,"data-theme":Ae,children:[a.jsx("div",{className:`tf-modal-header ${Tt.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${Tt.unsavedTitle}`,children:[a.jsx(yd,{size:20}),"Unsaved Changes"]})}),a.jsx("div",{className:`${Tt.form} ${Tt.unsavedContent}`,children:a.jsx("p",{className:Tt.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),a.jsxs("div",{className:`${Tt.formActions} ${Tt.unsavedActions}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:()=>W(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),a.jsx("button",{className:p.destructiveBtn,onClick:T,title:"Discard unsaved changes and leave",children:"Discard"}),a.jsxs("button",{className:p.submitBtn,onClick:j,disabled:ge,title:"Save changes and leave",children:[ge?a.jsx(kr,{size:16,className:p.spinner}):a.jsx(ug,{size:16}),"Save"]})]})]})}),document.body),xr&&Yi.createPortal(a.jsx("div",{className:Ia.overlay,children:a.jsxs("div",{className:Ia.browser,children:[a.jsxs("div",{className:Ia.header,children:[a.jsxs("div",{className:Ia.pathInfo,children:[a.jsx(Po,{size:14}),a.jsx("span",{children:en||"Project Root"})]}),a.jsxs("div",{className:Ia.actions,children:[en&&a.jsx("button",{className:p.helpLink,onClick:()=>{const u=en.split("/").filter(Boolean);u.pop(),An(u.length?u.join("/")+"/":"")},children:"Back"}),a.jsx("button",{className:p.helpLink,onClick:()=>qn(!1),children:"Close"})]})]}),a.jsxs("div",{className:Ia.list,children:[Zn&&typeof Zn=="object"&&a.jsxs("div",{className:`${Ia.item} ${Ia.itemFile} ${Ia.itemCurrent}`,onClick:()=>cs(en),children:[a.jsx(no,{size:14})," Select Current: ./",en||"(root)"]}),Kn.map(u=>a.jsxs("div",{className:Ia.item,onClick:()=>An(en+u+"/"),children:[a.jsx(Po,{size:14})," ",u,"/"]},u)),ir.map(u=>a.jsxs("div",{className:`${Ia.item} ${Ia.itemFile}`,onClick:()=>cs(en+u),children:[a.jsx(Dp,{size:14})," ",u]},u)),Kn.length===0&&ir.length===0&&a.jsx("div",{className:`${Ia.item} ${Ia.empty}`,children:"No items found"})]})]})}),document.body)]})}function CO(e){const t=e.setupState,n=e.runtimeMode,s=e.isAuthenticated,o=!!(t&&n==="cloud"&&s&&t.globalSetupState==="missing"),l=!!(t&&n==="local"&&t.globalSetupState==="missing"),i=!!(t&&n==="cloud"&&s&&t.workspaceSetupState==="missing"),d=!!(t&&n==="local"&&t.workspaceSetupState==="missing"),m=!!(t&&(t.forceSetup||t.forceGlobalSetup||t.forceWorkspaceSetup||o||i||l||d));if(!m)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const y=!!(t&&(t.forceSetup||t.forceGlobalSetup||o||l)),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 Np="/taskforce/assets/taskforce-BxLPokNB.png";function sg(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function Pp(e){return(Array.isArray(e)?e:[]).map(t=>String(t.label||t.value||"").trim()).filter(Boolean).join(", ")}function Mp(e={}){const t=new URLSearchParams;t.set("screen","plans");for(const[n,s]of Object.entries(e)){const o=String(s||"").trim();o&&t.set(n,o)}return`/?${t.toString()}`}function og({config:e={},initialTaskId:t,onTaskCountChange:n,onHeaderMouseDown:s,isDragging:o,onClose:l,mode:i="standalone"}){const d=Cg(),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",_=Mp(),I=Mp({gate:"plan_selection_required"}),C=_g(),[D,q]=r.useState(""),[B,X]=r.useState(""),[me,ke]=r.useState(""),[le,O]=r.useState(""),[A,de]=r.useState("login"),[ge,Y]=r.useState(""),[P,H]=r.useState(!1),[ue,ye]=r.useState(null),[V,Me]=r.useState(null),[_e,re]=r.useState(null),[oe,Ie]=r.useState(!1),[Ee,je]=r.useState(""),[Pe,K]=r.useState(""),[x,b]=r.useState(null),[R,F]=r.useState(null),[Q,M]=r.useState("unknown"),[$,be]=r.useState(!1),[U,se]=r.useState([]),[pe,z]=r.useState(null),[ne,ie]=r.useState(null),[Re,Te]=r.useState(null),[De,Oe]=r.useState(!1),[vt,st]=r.useState(0),[kt,Ye]=r.useState(0),[Ct,dt]=r.useState(()=>Date.now()),[Qe,Rt]=r.useState("core"),[ee,ze]=r.useState(!1),[ft,it]=r.useState(null),[Et,ht]=r.useState(null),[Ot,Dt]=r.useState(""),[We,tt]=r.useState(""),[Fe,Ze]=r.useState("local"),[St,ot]=r.useState("details"),[te,Le]=r.useState([]),[At,jt]=r.useState(""),[Wt,Ge]=r.useState(!1),[$t,yt]=r.useState(null),[E,c]=r.useState(!1),[J,we]=r.useState(null),[xe,Ke]=r.useState(!1),Je=r.useRef(!1),Ne=r.useMemo(()=>sy(),[]),[zt,Jt]=r.useState(Ne),[Pt,Ft]=r.useState(()=>Ne.find(W=>W.isDefaultStarter)?.id||Ne[0]?.id||""),[Lt,Ht]=r.useState(()=>sg(Ne.find(W=>W.isDefaultStarter)||Ne[0]||null)),[ra,Vt]=r.useState(!1),[Ga,Va]=r.useState(null),[qa,cn]=r.useState(!1),[he,rt]=r.useState(null),[Ae,Nt]=r.useState(!1),pt=Bb({config:e,initialTaskId:t,onTaskCountChange:n,onClose:l}),{runtimeMode:wt,workspaceSwitchingEnabled:Ca,currentWorkspaceId:ya,cloudAuthConfigured:ia,authRequiredForApi:ca,authBlocked:Oa,isAuthenticated:gt,hasBetaAccess:rr,authSessionResolved:ua,setupState:ta,runtimeCapabilities:wa,refreshSetupContext:Kt,retryBootstrapChecks:vr,createWorkspace:Ta,saveWorkspaceProfile:Qa,fetchWorkspaces:Ra,applyWorkspaceSyncStateSnapshot:Zt,workspaceCloudSyncEnabled:Ka,workspaceSyncPhase:aa,workspaceSyncSetupIntent:ln,workspaceSyncSummary:yn,workspaceSyncRecommendedAction:Sr,workspaceSyncBusy:la,workspaceLastErrorMessage:wr,retryWorkspaceCloudSync:qr,settingsModel:Vn,fetchTasks:kn,bootstrapState:$a,loginWithCredentials:br,beginOAuthLogin:dn,availableAuthProviders:Ea,registerWithCredentials:ja,requestEmailVerification:_r,confirmEmailVerification:xt,requestPasswordReset:vn,confirmPasswordReset:Sn,inspectInviteAcceptance:un,acceptInviteWithToken:Ua,joinInviteWithToken:sr,authUserEmail:Na,currentTheme:ka,logout:Ln}=pt,wn=r.useCallback(async(W,$e)=>{const It=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:W,stateKey:"workspace-sync",patch:$e})}),Mt=await It.json().catch(()=>({}));if(!It.ok||Mt?.success===!1)throw new Error(Mt?.error||`Failed to configure workspace sync (${It.status})`);return Mt},[]),va=r.useMemo(()=>zt.find(W=>W.id===Pt)||zt.find(W=>W.isDefaultStarter)||zt[0]||null,[Pt,zt]);Tg(ka);const Yt=Qp,bn=r.useMemo(()=>{const W=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return W?W.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),za=wt==="cloud"||wa?.runtimeMode==="cloud",Pa=!za&&ia&&!!bn,Bn=typeof window<"u"&&/^app\./i.test(window.location.hostname),Ma=wt==="cloud"&&ca,Mr=wt==="cloud"&&Oa,na=d.pathname==="/login",da=d.pathname==="/setup",Xa=d.pathname==="/coming-soon",or="/setup?step=workspace&source=cloud&postAuth=select-cloud-workspace",Er=!za&&Fe==="cloud",Cr=Er&&Pa,Xt=r.useMemo(()=>{if(J)return J;if(ln!=="attach-cloud-import")return null;const W=String(ya||"").trim();if(!W||W.toLowerCase()==="default")return null;const $e=te.find(It=>It.id===W);return{workspaceId:W,name:$e?.name||W}},[te,ya,J,ln]),_n=!!(Xt&&ya===Xt.workspaceId),Cn=!!(Xt&&_n&&aa==="error"),Ar=!!(Xt&&_n&&Ka&&aa==="active"&&!la),xr=r.useMemo(()=>{if(!Xt)return[];const W=ee?"In progress":"Complete",$e=Cn?"Needs attention":la||aa==="attach-cloud"?"In progress":aa==="active"?"Complete":"Waiting",It=xe?"In progress":Ar?"Ready":"Waiting";return[`Connect workspace: ${W}`,`Import cloud data: ${$e}`,`Open local workspace: ${It}`]},[Xt,ee,Cn,la,aa,xe,Ar]),qn=Bn?(!gt||Oa)&&!h&&!g&&!v:(Ma&&!gt||Mr)&&!h&&!g&&!v,Kn=wt==="cloud"&&gt&&!rr&&!h&&!g&&!v,ir=wt==="cloud"&&gt&&ua&&he?.canAccessApp===!1&&he?.canAccessPlans!==!1&&!h&&!g&&!v,en=wt==="cloud"&&gt&&(!ua||!Ae),An=ia,Zn=r.useMemo(()=>{switch(A){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"}},[A]),tn=r.useMemo(()=>String(new URLSearchParams(d.search).get("step")||"").trim().toLowerCase(),[d.search]),cs=r.useMemo(()=>String(new URLSearchParams(d.search).get("intent")||"").trim().toLowerCase(),[d.search]),Za=da&&tn==="workspace"&&cs==="create-workspace",Kr=i!=="widget"&&$a.authPending&&!na&&!da&&!h&&!g&&!v&&(wt==="cloud"||Bn),Dr=r.useMemo(()=>CO({setupState:ta?{globalSetupState:ta.globalSetupState,workspaceSetupState:ta.workspaceSetupState,runtimeMode:ta.runtimeMode,workspaceId:ta.workspaceId,mode:ta.mode,forceSetup:ta.forceSetup,forceGlobalSetup:ta.forceGlobalSetup,forceWorkspaceSetup:ta.forceWorkspaceSetup}:null,runtimeMode:wt,isAuthenticated:gt}),[ta,wt,gt]),xn=Dr.setupGateActive,cr=Dr.needsGlobalSetup,Wn=Dr.needsWorkspaceSetup,mn=Dr.hasSetupReadError,lr=i!=="widget"&&$a.auth.resolved&&!qn&&!Kn&&!h&&!g&&!v&&!na&&$a.appPending&&(da||wt==="cloud"||Bn),Zr=wt==="cloud"&&oe&&!v,ls=$a.subtitle,et=Za||da&&!!Xt||da&&xn&&(mn||cr||Wn),Bt=r.useMemo(()=>Kr?"auth-bootstrap":Zr||lr?"app-bootstrap":na?"login":qn&&!na?"login-redirect":Xa&&Kn?"coming-soon":et?"guided-setup":"app",[Xa,na,Kn,qn,Zr,Kr,lr,et]),Da=r.useCallback((W,$e,It)=>{const Mt=String(W||"").trim().toLowerCase(),Ha=String($e||"").trim().toLowerCase();return!!(!Mt||Mt==="system default workspace"||Ha&&Mt===Ha)},[]);r.useEffect(()=>{const W=ta?.mode==="operations"?"operations":"core";Rt(W)},[ta?.mode]),r.useEffect(()=>{if(wt!=="cloud"||!gt){rt(null),Nt(!1);return}if(!ua){rt(null),Nt(!1);return}rt(null),Nt(!1);let W=!1;return(async()=>{try{const $e=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),It=await $e.json().catch(()=>({}));if(W)return;if(!$e.ok){rt(null),Nt(!0);return}const Mt=String(It?.gate||"").trim().toLowerCase();if(Mt!=="ok"&&Mt!=="plan_selection_required"&&Mt!=="checkout_pending"&&Mt!=="misconfigured"&&Mt!=="missing_entitlement"){rt(null),Nt(!0);return}rt({gate:Mt,canAccessApp:It?.canAccessApp===!0,canAccessPlans:It?.canAccessPlans!==!1,message:typeof It?.message=="string"?It.message:null}),Nt(!0)}catch{W||(rt(null),Nt(!0))}})(),()=>{W=!0}},[ua,gt,wt,d.pathname,d.search]),r.useEffect(()=>{if(Za){Dt(""),tt("");return}if(!ta)return;const W=String(ta.workspace?.name||"").trim(),$e=String(ta.suggestedWorkspaceName||"").trim(),It=Da(W,ta.workspaceId,ta.workspace?.description)?$e:W;Dt(It||$e||W),tt(String(ta.workspace?.description||""))},[ta?.workspace?.name,ta?.workspace?.description,ta?.suggestedWorkspaceName,ta?.workspaceId,Za,Da]),r.useEffect(()=>{if(!da||tn!=="workspace")return;if(ot("details"),Xt&&Pa){Ze("cloud"),c(!1);return}if(String(new URLSearchParams(d.search).get("source")||"").trim().toLowerCase()==="cloud"&&Pa){Ze("cloud"),c(!1);return}Ze("local")},[Xt,Pa,da,d.search,tn]);const Aa=r.useCallback(async()=>{if(!Pa||!gt){Le([]),jt("");return}Ge(!0),yt(null);try{const W=await fetch(`${bn}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),$e=await W.json().catch(()=>({}));if(!W.ok||$e?.success===!1){Le([]),jt(""),yt($e?.error||`Failed to load cloud projects (${W.status})`);return}const It=Array.isArray($e?.workspaces)?$e.workspaces.map(Mt=>({id:String(Mt?.id||"").trim(),name:String(Mt?.name||Mt?.id||"").trim(),description:typeof Mt?.description=="string"?Mt.description:null})).filter(Mt=>Mt.id.length>0):[];Le(It),jt(Mt=>Mt&&It.some(Ha=>Ha.id===Mt)?Mt:It[0]?.id||"")}catch{Le([]),jt(""),yt("Failed to load cloud projects.")}finally{Ge(!1)}},[Pa,gt,bn]);r.useEffect(()=>{Fe==="cloud"&&Aa()},[Aa,Fe]),r.useEffect(()=>{if(!da||tn!=="workspace"||Fe==="cloud")return;let W=!1;return Vt(!0),Va(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async $e=>{if(!$e.ok)throw new Error(`Failed to load setup libraries (${$e.status})`);const It=await $e.json().catch(()=>({})),Mt=Array.isArray(It?.packs)?It.packs:[];W||Mt.length===0||(Jt(Mt),Ft(Ha=>Mt.some(Jn=>Jn.id===Ha)?Ha:Mt.find(Jn=>Jn.isDefaultStarter)?.id||Mt[0]?.id||""))}).catch($e=>{W||(Jt(Ne),Va($e instanceof Error?$e.message:"Failed to load setup libraries."))}).finally(()=>{W||Vt(!1)}),()=>{W=!0}},[Ne,da,tn,Fe]),r.useEffect(()=>{Ht(sg(va))},[Pt,va]),r.useEffect(()=>{Fe==="cloud"&&ot("details")},[Fe]),r.useEffect(()=>{Cr||(we(null),Ke(!1),Je.current=!1)},[Cr]),r.useEffect(()=>{!Cn||!Xt||(ht(null),it(wr||`Failed to import "${Xt.name}" from cloud. Retry import to continue.`))},[Xt,Cn,wr]),r.useEffect(()=>{if(!Ar||!Xt||Je.current)return;let W=!1;return Je.current=!0,Ke(!0),it(null),ht(`Workspace import complete. Opening ${Xt.name}...`),(async()=>{try{if(await Kt(),await Promise.all([Ra(),kn(!0)]),W)return;await wn(Xt.workspaceId,{setupIntent:null}),Zt({enabled:Ka,phase:aa,setupIntent:null}),we(null),C("/",{replace:!0})}catch{if(W)return;ht(null),it(`Imported "${Xt.name}" but failed to finish opening it.`),Ke(!1),Je.current=!1}})(),()=>{W=!0}},[Xt,Zt,kn,Ra,Ar,C,wn,Kt]);const Sa=r.useMemo(()=>{const W=new URLSearchParams(d.search).get("next")||"/";if(W.startsWith("/"))return W==="/login"?"/":W;try{const $e=new URL(W),It=$e.hostname.toLowerCase(),Mt=It==="localhost"||It==="127.0.0.1"||It==="::1",Ha=It==="taskforcehq.ai"||It.endsWith(".taskforcehq.ai");if(($e.protocol==="http:"||$e.protocol==="https:")&&(Mt||Ha))return $e.toString()}catch{return"/"}return"/"},[d.search]),In=r.useMemo(()=>Sa.startsWith("/")?Sa:"/",[Sa]),Yn=r.useCallback((W,$e)=>{if(W){if(W.startsWith("/")){C(W,{replace:$e?.replace===!0});return}typeof window<"u"&&($e?.replace===!0?window.location.replace(W):window.location.assign(W))}},[C]),ds=r.useMemo(()=>{try{const W=new URL(In,"https://taskforce.local");return W.pathname==="/setup"&&W.searchParams.get("step")==="workspace"&&W.searchParams.get("source")==="cloud"&&W.searchParams.get("postAuth")==="select-cloud-workspace"}catch{return!1}},[In]),Fn=r.useCallback(()=>ds?or:"/setup?step=workspace",[ds]),On=S==="year"?"year":"month",Tn=r.useCallback(W=>!!(W?.planSelectionRequired||W?.checkoutPending||W?.commercialState==="pending_plan_selection"||W?.commercialState==="checkout_pending"),[]),Gt=r.useCallback(W=>W?.planSelectionRequired||W?.commercialState==="pending_plan_selection"?I:W?.checkoutPending||W?.commercialState==="checkout_pending"?Mp({gate:"checkout_pending",checkout:k?"start":null,planId:y||null,planVersionId:k||null,interval:k?On:null}):Sa,[Sa,I,On,y,k]),$n=r.useMemo(()=>{const W=String(new URLSearchParams(d.search).get("mode")||"").trim().toLowerCase();return W==="register"?An?"register":"login":W==="verify"||W==="forgot"||W==="reset"||W==="invite"?W:"login"},[An,d.search]),pn=r.useMemo(()=>String(new URLSearchParams(d.search).get("token")||"").trim(),[d.search]),La=r.useCallback(W=>{const $e=new URLSearchParams(d.search),It=W==="register"&&!An?"login":W;It==="login"?$e.delete("mode"):$e.set("mode",It);const Mt=$e.toString();C(`/login${Mt?`?${Mt}`:""}`,{replace:!0})},[An,d.search,C]);r.useEffect(()=>{na&&(de($n),$n==="verify"&&pn&&Y(pn),$n==="reset"&&pn&&je(pn),$n==="invite"&&pn&&K(pn))},[na,$n,pn]),r.useEffect(()=>{A!=="verify"&&(na&&$n==="verify"||(H(!1),ye(null),Me(null)))},[A,na,$n]),r.useEffect(()=>{A!=="register"&&O("")},[A]),r.useEffect(()=>{if(!_e||!gt||!_e.commercialOnboardingGate&&(!ua||en))return;const W=!_e.commercialOnboardingGate&&_e.workspaceSetupRequired?Fn():_e.path,$e=`${d.pathname}${d.search}${d.hash||""}`;if(W.startsWith("/")){$e!==W&&C(W,{replace:!0});return}Yn(W,{replace:!0})},[ua,en,gt,d.hash,d.pathname,d.search,C,Yn,_e,Fn]),r.useEffect(()=>{if(!oe||!ua)return;if(!gt){Ie(!1),re(null);return}if(Ae&&he?.canAccessApp===!0){q(""),X(""),ke(""),O(""),re(null),Ie(!1);return}const W=_e?.commercialOnboardingGate?_e.path:I,$e=`${d.pathname}${d.search}${d.hash||""}`;if(W.startsWith("/")){$e!==W&&C(W,{replace:!0});return}Yn(W,{replace:!0})},[he?.canAccessApp,Ae,ua,oe,gt,d.hash,d.pathname,d.search,C,Yn,_e,I]),r.useEffect(()=>{if(!_e||!gt)return;const W=!_e.commercialOnboardingGate&&_e.workspaceSetupRequired?Fn():_e.path;`${d.pathname}${d.search}${d.hash||""}`===W&&(_e.commercialOnboardingGate||(q(""),X(""),ke(""),O(""),re(null)))},[d.hash,d.pathname,d.search,gt,_e,Fn,wt]),r.useEffect(()=>{na&&(document.title=Zn)},[Zn,na]),r.useEffect(()=>{if(!na||A!=="invite"||!Pe.trim())return;let W=!0;return(async()=>{const $e=await un(Pe);if(W)if($e.success){b($e.email||null),F($e.workspaceId||null),be($e.passwordRequired===!0);const It=($e.availableMethods||[]).filter(Jn=>Jn==="google"||Jn==="github"||Jn==="apple");se($e.inviteeState==="pending_setup"?It:[]);const Mt=!!(gt&&Na&&$e.email&&Na.trim().toLowerCase()===$e.email.trim().toLowerCase()),Ha=$e.passwordRequired===!0?"new_user":Mt?"existing_user_ready":"existing_user_signed_out";M(Ha),z(Ha==="new_user"?"Create your account password to join this workspace.":Ha==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),ie(null),Te(null)}else b(null),F(null),M("invalid"),be(!1),se([]),ie(nn($e)),Te($e.code||$e.state||null)})(),()=>{W=!1}},[na,A,Pe,un,gt,Na]),r.useEffect(()=>{A==="invite"&&Q==="existing_user_signed_out"&&x&&q(W=>W.trim()?W:x)},[A,Q,x]),r.useEffect(()=>{if(!(vt>Date.now()||kt>Date.now()))return;const $e=window.setInterval(()=>dt(Date.now()),1e3);return()=>window.clearInterval($e)},[vt,kt]);const Lr=Math.max(0,Math.ceil((vt-Ct)/1e3)),Br=Math.max(0,Math.ceil((kt-Ct)/1e3)),dr=Lr>0,ur=Br>0,Fs=r.useMemo(()=>Ty(),[]),nn=W=>{const $e=W.error||"Request failed.",It=W.code||W.state;return It?`[${It}] ${$e}`:$e},fn=W=>W?.deliveryAttempted===!1?W?.intro||"If that account exists and still needs verification, we sent an email.":W?.emailSent===!1?`Verification email failed to send. ${W?.emailError||"Try Resend Verification again."}`:"Verification email resent.",so=W=>W?.deliveryAttempted===!1?"If that account exists, we sent password reset instructions.":W?.emailSent===!1?`Password reset email failed to send. ${W?.emailError||"Try again in a minute."}`:"Password reset instructions sent.";r.useEffect(()=>{if(i==="widget"||na&&De)return;const W=wt==="cloud"&&gt&&Ae&&he?.canAccessApp===!1&&he?.canAccessPlans!==!1;if($a.workspace.pending&&!W)return;if(Kn){Xa||C("/coming-soon",{replace:!0});return}if(Xa&&!Kn){C("/",{replace:!0});return}if(qn){if(!na){const It=`${d.pathname}${d.search}${d.hash}`;C(`/login?next=${encodeURIComponent(It||"/")}`,{replace:!0});return}return}else{const It=na&&A==="invite"&&Pe.trim().length>0;if(na&&gt&&!It&&(!!_e||$a.workspace.pending||A==="register"||A==="verify"||!$a.config.loaded||en))return;na&&gt&&!It&&Yn(Sa,{replace:!0})}if(!(na&&!gt||_e&&gt||na&&gt&&(A==="register"||A==="verify"||A==="invite"&&Pe.trim().length>0))&&!oe&&!v){if(ir){if(!v){const It=encodeURIComponent(String(he?.gate||"plan_selection_required"));C(`/?screen=plans&gate=${It}`,{replace:!0})}return}if(Xt){da&&tn==="workspace"&&new URLSearchParams(d.search).get("source")==="cloud"||C(or,{replace:!0});return}if(!(v&&en)&&!(v&&wt==="cloud"&&Ae&&he?.canAccessApp===!1&&he?.canAccessPlans!==!1)){if(xn){if(mn){(!da||tn!=="error")&&C("/setup?step=error",{replace:!0});return}if(cr){(!da||tn!=="global")&&C("/setup?step=global",{replace:!0});return}if(Wn){(!da||tn!=="workspace")&&C(Fn(),{replace:!0});return}da&&C("/",{replace:!0});return}da&&ta&&!Za&&C("/",{replace:!0})}}},[i,qn,Kn,ir,na,da,Xa,g,v,he,he?.gate,Ae,A,oe,en,xn,ta,mn,Za,Xt,cr,Wn,tn,$a,wt,De,gt,Ae,Pe,d.pathname,d.search,d.hash,C,In,_e,or]),r.useEffect(()=>{if(i==="widget"||wt!=="local"||!$a.config.loaded||na||da)return;const W=String(ya||"").trim().toLowerCase();(!W||W==="default")&&C("/setup?step=workspace",{replace:!0})},[i,wt,$a.config.loaded,na,da,ya,C]);const Wr=r.useCallback(async()=>{cn(!0);try{await vr()}finally{cn(!1)}},[vr]),mr=r.useCallback(async()=>{await Ln(),C("/login",{replace:!0})},[Ln,C]);if(i==="widget")return a.jsx(sD,{...pt,onHeaderMouseDown:s,isDragging:o,onClose:l});if(h){const W=new URLSearchParams(d.search);return W.set("screen","plans"),a.jsx(Xf,{to:`/?${W.toString()}${d.hash||""}`,replace:!0})}if(g){const W=new URLSearchParams(d.search);return W.set("screen","plans"),a.jsx(Xf,{to:`/?${W.toString()}${d.hash||""}`,replace:!0})}if(Bt==="auth-bootstrap")return a.jsx("div",{className:ea.standaloneWrapper,"data-theme":ka,children:a.jsx("div",{className:fe.loginView,children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:Yt,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:fe.loginSubtitle,children:"Checking your session..."})]})})});if(Bt==="app-bootstrap")return a.jsx("div",{className:ea.standaloneWrapper,"data-theme":ka,children:a.jsx("div",{className:fe.loginView,children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:Yt,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:fe.loginSubtitle,children:ls}),$a.stalled&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:fe.loginError,children:$a.error||"Startup checks timed out."}),a.jsx("button",{className:p.submitBtn,disabled:qa,onClick:Wr,children:qa?"Retrying...":"Retry checks"}),za&&a.jsx("button",{className:p.cancelBtn,disabled:qa,onClick:mr,children:"Go to sign-in"})]})]})})});if(Bt==="login")return a.jsx("div",{className:ea.standaloneWrapper,"data-theme":ka,children:a.jsx("div",{className:fe.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Np})`},children:a.jsxs("div",{className:fe.loginCard,children:[!za&&!qn&&a.jsx("button",{className:fe.loginCloseBtn,"aria-label":"Close sign in","data-testid":"auth-close-button",onClick:()=>C(In,{replace:!0}),children:"×"}),a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:Yt,alt:"Taskforce",className:fe.loginLogo}),a.jsxs("h1",{className:fe.loginTitle,children:["TASKFORCE ",a.jsx("span",{className:fe.loginTitleAccent,children:"HQ"})]})]}),a.jsxs("p",{className:fe.loginSubtitle,children:[A==="login"&&"Sign in with your account credentials.",A==="register"&&"Create your Taskforce account.",A==="verify"&&"Enter your verification token.",A==="forgot"&&"Request a password reset link.",A==="reset"&&"Set a new password using your reset token.",A==="invite"&&(Q==="existing_user_ready"?`You've been invited to join ${R||"this workspace"}.`:Q==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(A==="login"||A==="register"||A==="verify"||A==="forgot"||A==="invite"&&Q==="existing_user_signed_out")&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Email"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"email",value:D,placeholder:"Email",autoComplete:"email","data-testid":"auth-email-input",onChange:W=>q(W.target.value)})]}),A==="register"&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Display name"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:B,placeholder:"Display name",autoComplete:"nickname","data-testid":"auth-display-name-input",onChange:W=>X(W.target.value)})]}),(A==="login"||A==="register"||A==="reset"||A==="invite"&&($||Q==="existing_user_signed_out"))&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:A==="reset"?"New password":A==="invite"&&$?"Create password":"Password"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"password",value:me,placeholder:A==="reset"?"New password":A==="invite"&&$?"Create password":"Password",autoComplete:A==="register"||A==="reset"||A==="invite"&&$?"new-password":"current-password","data-testid":"auth-password-input",onChange:W=>ke(W.target.value)})]}),(A==="register"||A==="invite"&&$)&&a.jsx(a.Fragment,{children:a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Confirm password"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"password",value:le,placeholder:"Confirm password",autoComplete:"new-password","data-testid":"auth-confirm-password-input",onChange:W=>O(W.target.value)})]})}),(A==="register"||A==="invite"&&$)&&a.jsx("p",{className:fe.loginSubtitle,children:Fs.join(" ")}),A==="verify"&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Verification token"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:ge,placeholder:"Verification token",autoComplete:"one-time-code","data-testid":"auth-verification-token-input",onChange:W=>Y(W.target.value)})]}),A==="reset"&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Reset token"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:Ee,placeholder:"Reset token",autoComplete:"one-time-code","data-testid":"auth-reset-token-input",onChange:W=>je(W.target.value)})]}),A==="invite"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Invite token"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:Pe,placeholder:"Invite token","data-testid":"auth-invite-token-input",onChange:W=>K(W.target.value)})]}),x&&a.jsxs("p",{className:fe.loginSubtitle,children:["Invite for: ",a.jsx("strong",{children:x}),R?` · Workspace: ${R}`:""]})]}),pe&&a.jsx("p",{className:fe.loginSubtitle,children:pe}),ne&&a.jsx("p",{className:fe.loginError,children:ne}),A==="login"&&Re==="EMAIL_NOT_VERIFIED"&&D.trim()&&a.jsx("button",{className:fe.authModeLink,disabled:De||dr,onClick:async()=>{Oe(!0),z(null);const W=await _r(D);W.success?(st(Date.now()+3e4),La("verify"),W.verificationToken&&Y(W.verificationToken),z(fn(W)),ie(null),Te(null)):ie(nn(W)),Oe(!1)},children:dr?`Resend in ${Lr}s`:"Resend Verification Email"}),a.jsx("div",{className:fe.authPrimaryActions,role:"group","aria-label":"Primary authentication action",children:a.jsx("button",{className:`${p.submitBtn} ${fe.loginPrimaryBtn}`,disabled:De||A==="forgot"&&ur,"data-testid":"auth-submit-button",onClick:async()=>{if(Oe(!0),z(null),ie(null),Te(null),A==="register"&&!B.trim()){ie("Display name is required."),Oe(!1);return}if(A==="register"){const $e=Ry(me,{email:D,displayName:B});if(!$e.ok){ie($e.message||"Password does not meet the password policy."),Te($e.code||null),Oe(!1);return}if(me!==le){ie("Passwords do not match."),Te("PASSWORD_CONFIRMATION_MISMATCH"),Oe(!1);return}}let W={success:!1};if(A==="login"?W=await br(D,me):A==="register"?W=await ja(D,me,{displayName:B,planId:y||void 0,planVersionId:k||void 0,interval:S||void 0}):A==="verify"?W=await xt(ge):A==="forgot"?W=await vn(D):A==="reset"?W=await Sn(Ee,me):A==="invite"&&(Q==="existing_user_signed_out"?W=await br(D,me):W=$?await Ua(Pe,me):await sr(Pe)),W.success)if(A==="register"){const $e=Gt(W),It=Tn(W);W.verificationRequired?(H(!!W.workspaceSetupRequired),ye(It?String(W.commercialState||"").trim()||(W.planSelectionRequired?"pending_plan_selection":"checkout_pending"):null),Me($e),W.verificationToken&&Y(W.verificationToken),st(Date.now()+3e4),La("verify"),z(W.emailSent===!1?`Account created, but verification email failed to send. ${W.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")):(Ie(It),re({path:$e,workspaceSetupRequired:!!W.workspaceSetupRequired,commercialOnboardingGate:It}))}else if(A==="verify"){await vr();const $e=ue==="pending_plan_selection"||ue==="checkout_pending";Ie($e),re({path:V||Sa,workspaceSetupRequired:P,commercialOnboardingGate:$e})}else if(A==="forgot"){const $e=W.deliveryAttempted===!0&&W.emailSent===!1;W.resetToken&&je(W.resetToken),z(so(W)),$e||(Ye(Date.now()+3e4),La("reset"))}else if(A==="reset")La("login"),z("Password updated. Sign in with your new password.");else if(A==="invite"){if(Q==="existing_user_signed_out"){const $e=String(x||"").trim().toLowerCase(),It=D.trim().toLowerCase();if($e&&It===$e){de("invite"),M("existing_user_ready"),ke(""),O(""),z("Signed in. Review the invite details to continue."),ie(null),Te(null),Oe(!1);return}$e&&q(x||""),M("existing_user_signed_out"),ke(""),O(""),z($e?`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."),ie("Sign in with the invited account to join this workspace."),Te("INVITE_ACCOUNT_MISMATCH"),Oe(!1);return}if(W.workspaceSetupRequired){C(Fn(),{replace:!0}),Oe(!1);return}Yn(Sa,{replace:!0})}else if(A==="login"){if(Pe.trim()){de("invite"),ke(""),O(""),z("Signed in. Review the invite details to continue."),Oe(!1);return}if(W.workspaceSetupRequired){C(Fn(),{replace:!0}),Oe(!1);return}q(""),X(""),ke(""),O(""),Yn(Sa,{replace:!0})}else q(""),X(""),ke(""),O(""),Yn(Sa,{replace:!0});else{if(A==="register"&&(W.code==="SIGNUP_PLAN_NOT_ENABLED"||W.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||W.code==="SIGNUP_PLAN_VERSION_REQUIRED")){C(I,{replace:!0}),Oe(!1);return}if(ie(nn(W)),Te(W.code||null),A==="login"&&(W.code==="WORKSPACE_NOT_FOUND"||W.code==="WORKSPACE_ID_REQUIRED")){C("/setup?step=workspace",{replace:!0}),Oe(!1);return}if(A==="login"&&W.code==="EMAIL_NOT_VERIFIED"&&D.trim()){const $e=await _r(D);$e.success&&(st(Date.now()+3e4),La("verify"),$e.verificationToken&&Y($e.verificationToken),z(fn({...$e,intro:"If that account exists and still needs verification, we sent an email."})),ie(null),Te(null))}A==="register"&&W.code==="EMAIL_ALREADY_EXISTS_UNVERIFIED"&&D.trim()&&(st(Date.now()+3e4),La("verify"),W.verificationToken&&Y(W.verificationToken),z(W.emailSent===!1?`This email already has an unverified account, but verification email delivery failed. ${W.emailError||"Try Resend Verification again."}`:"This email already has an unverified account. Check your email for verification instructions."),ie(null),Te(null))}Oe(!1)},children:De?"Working...":A==="login"?"Sign In":A==="register"?"Create Account":A==="verify"?"Verify Email":A==="forgot"?ur?`Retry in ${Br}s`:"Send Reset Link":A==="reset"?"Reset Password":Q==="existing_user_signed_out"?"Sign In to Continue":$?"Create Account and Join":"Join Workspace"})}),(A==="login"||A==="register")&&Ea.length>0&&a.jsxs("div",{className:fe.oauthProviders,children:[a.jsx("div",{className:fe.oauthDivider,children:a.jsx("span",{children:"or continue with"})}),a.jsxs("div",{className:fe.oauthButtons,children:[Ea.includes("google")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:De,onClick:()=>dn("google",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with Google",children:"Google"}),Ea.includes("github")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:De,onClick:()=>dn("github",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with GitHub",children:"GitHub"}),Ea.includes("apple")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:De,onClick:()=>dn("apple",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with Apple",children:"Apple"})]})]}),A==="invite"&&Q==="new_user"&&U.length>0&&a.jsxs("div",{className:fe.oauthProviders,children:[a.jsx("div",{className:fe.oauthDivider,children:a.jsx("span",{children:"or join with"})}),a.jsxs("div",{className:fe.oauthButtons,children:[U.includes("google")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:De,onClick:()=>dn("google","/",Pe),"aria-label":"Join with Google",children:"Google"}),U.includes("github")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:De,onClick:()=>dn("github","/",Pe),"aria-label":"Join with GitHub",children:"GitHub"}),U.includes("apple")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:De,onClick:()=>dn("apple","/",Pe),"aria-label":"Join with Apple",children:"Apple"})]})]}),A==="register"&&a.jsxs("p",{className:fe.registerConsent,children:["By creating an account, you agree to the"," ",a.jsx("a",{className:fe.registerConsentLink,href:"https://taskforcehq.ai/legal/terms/",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," ","and acknowledge the"," ",a.jsx("a",{className:fe.registerConsentLink,href:"https://taskforcehq.ai/legal/privacy/",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]}),a.jsxs("div",{className:fe.authSecondaryActions,role:"group","aria-label":"Authentication navigation",children:[An&&(A==="login"||A==="register")&&a.jsxs("p",{className:fe.authModeSwitch,children:[A==="login"?"Need an account?":"Already have an account?"," ",a.jsx("button",{className:fe.authModeSwitchLink,disabled:De,"data-testid":"auth-switch-mode-button",onClick:()=>{ie(null),Te(null),z(null),La(A==="login"?"register":"login")},children:A==="login"?"Register":"Sign In"})]}),a.jsxs("div",{className:fe.authModeLinks,children:[(A==="login"||A==="register")&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:fe.authModeLink,disabled:De||ur,"data-testid":"auth-forgot-password-button",onClick:()=>{ie(null),Te(null),z(null),La("forgot")},children:ur?`Forgot Password (${Br}s)`:"Forgot Password"}),a.jsx("button",{className:fe.authModeLink,disabled:De||dr,"data-testid":"auth-resend-verification-button",onClick:()=>{ie(null),Te(null),z(null),La("verify")},children:dr?`Resend Verification (${Lr}s)`:"Resend Verification"}),a.jsx("button",{className:fe.authModeLink,disabled:De,"data-testid":"auth-accept-invite-button",onClick:()=>{ie(null),Te(null),z(null),La("invite")},children:"Accept Invite"})]}),A!=="login"&&A!=="register"&&a.jsxs(a.Fragment,{children:[A==="verify"&&a.jsx("button",{className:fe.authModeLink,disabled:De||dr||!D.trim(),"data-testid":"auth-resend-verification-button",onClick:async()=>{Oe(!0),z(null),ie(null),Te(null);const W=await _r(D);W.success?(st(Date.now()+3e4),W.verificationToken&&Y(W.verificationToken),z(fn(W))):ie(nn(W)),Oe(!1)},children:dr?`Resend Verification (${Lr}s)`:"Resend Verification"}),a.jsx("button",{className:fe.authModeLink,disabled:De,"data-testid":"auth-return-sign-in-button",onClick:()=>{ie(null),Te(null),z(null),La("login")},children:A==="verify"?"Back to Sign In":"Sign In"}),An&&A!=="verify"&&a.jsx("button",{className:fe.authModeLink,disabled:De,"data-testid":"auth-return-register-button",onClick:()=>{ie(null),Te(null),z(null),La("register")},children:"Register"}),A==="reset"&&a.jsx("button",{className:fe.authModeLink,disabled:De||ur,"data-testid":"auth-return-forgot-password-button",onClick:()=>{ie(null),Te(null),z(null),La("forgot")},children:ur?`Forgot Password (${Br}s)`:"Forgot Password"})]})]})]})]})})});if(Bt==="login-redirect")return a.jsx("div",{className:ea.standaloneWrapper,"data-theme":ka,children:a.jsx("div",{className:fe.loginView,children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:Yt,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:fe.loginSubtitle,children:"Redirecting to sign in..."})]})})});if(Bt==="coming-soon")return a.jsx("div",{className:ea.standaloneWrapper,"data-theme":ka,children:a.jsx("div",{className:fe.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Np})`},children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:Yt,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Beta Access"})]}),a.jsx("p",{className:fe.loginSubtitle,children:"You are signed in, but your account does not have beta access yet."}),a.jsx("p",{className:fe.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),a.jsx("button",{className:p.cancelBtn,onClick:async()=>{await pt.logout(),C("/login",{replace:!0})},children:"Sign Out"})]})})});if(Bt==="guided-setup"){const W=!Za&&(mn||tn==="error"),$e=!Za&&!W&&(cr||tn==="global"),It=qe(W?"setup.headingCheckFailed":$e?"setup.headingGlobalRequired":"setup.headingWorkspaceRequired"),Mt=W?qe("setup.subtitleUnreadable"):$e?qe("setup.subtitleGlobalRequired"):null,Ha="Workspace",Jn=za||Fe!=="cloud",Yr=Jn&&St==="details",Ba=Jn&&St==="library",Fr=!za&&Pa&&Yr&&!Xt,Wa=wa?.runtimeMode==="cloud"?hg:tv,T=va?Pp(va.categories):"",j=va?Pp(va.types):"",at=va?Pp(va.priorities):"",bt=ee?qe("setup.saving"):Er?Xt?Cn?"Retry Import":"Importing Workspace...":"Connect Workspace":Yr?"Continue":Ba?"Create Workspace":"Connect Workspace";return a.jsx("div",{className:ea.standaloneWrapper,"data-theme":ka,children:a.jsx("div",{className:fe.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Np})`},children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.setupHeaderRow,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:Yt,alt:"Taskforce",className:fe.loginLogo}),a.jsxs("h1",{className:fe.loginTitle,children:["TASKFORCE ",a.jsx("span",{className:fe.loginTitleAccent,children:"HQ"})]})]}),wa&&a.jsx("span",{className:fe.runtimeIconBadge,title:wa.runtimeMode==="cloud"?"Cloud runtime":"Local runtime","aria-label":wa.runtimeMode==="cloud"?"Cloud runtime":"Local runtime",children:Ue.createElement(Wa,{size:16,"aria-hidden":!0})})]}),a.jsx("p",{className:fe.loginSubtitle,children:a.jsx("strong",{children:It})}),Mt?a.jsx("p",{className:fe.loginSubtitle,children:Mt}):null,Et&&a.jsx("p",{className:fe.loginSubtitle,children:Et}),ft&&a.jsx("p",{className:fe.loginError,children:ft}),$e&&a.jsxs("div",{className:fe.optionGrid,children:[a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:Qe==="core",onChange:()=>Rt("core"),disabled:ee}),a.jsx("span",{children:qe("setup.coreModeOption",{workspaceLabel:Ha})})]}),a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:Qe==="operations",onChange:()=>Rt("operations"),disabled:ee}),a.jsx("span",{children:qe("setup.operationsModeOption")})]})]}),!W&&!$e&&a.jsxs("div",{className:fe.optionGrid,children:[Fr&&a.jsxs("div",{className:fe.optionGroup,children:[a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:Fe==="local",onChange:()=>Ze("local"),disabled:ee}),a.jsxs("span",{children:["Create new local ",Ha.toLowerCase()]})]}),a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:Fe==="cloud",onChange:()=>Ze("cloud"),disabled:ee}),a.jsxs("span",{children:["Sync existing cloud ",Ha.toLowerCase()]})]})]}),Er?a.jsxs("div",{className:fe.optionGroup,children:[!Xt&&!Pa&&a.jsx("p",{className:fe.loginError,children:"Cloud workspace sync is unavailable right now. Switch back to local setup or refresh runtime configuration."}),!Xt&&Pa&&!gt&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:fe.inlineHint,children:"Sign in to choose one of your cloud projects."}),a.jsxs("div",{className:fe.actionRowEnd,children:[a.jsx("button",{className:p.cancelBtn,disabled:ee,onClick:()=>{C(`/login?mode=login&next=${encodeURIComponent(or)}`,{replace:!0})},children:"Sign In"}),An&&a.jsx("button",{className:p.submitBtn,disabled:ee,onClick:()=>{C(`/login?mode=register&next=${encodeURIComponent(or)}`,{replace:!0})},children:"Register"})]})]}),!Xt&&Pa&&gt&&a.jsxs(a.Fragment,{children:[a.jsxs("select",{className:p.input,value:At,onChange:ve=>jt(ve.target.value),disabled:ee||Wt||te.length===0,children:[te.length===0&&a.jsx("option",{value:"",children:Wt?"Loading cloud projects...":"No cloud projects found"}),te.map(ve=>a.jsxs("option",{value:ve.id,children:[ve.name," (",ve.id,")"]},ve.id))]}),a.jsx("div",{className:fe.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,disabled:ee||Wt,onClick:()=>{Aa()},children:"Refresh Cloud Projects"})}),$t&&a.jsx("p",{className:fe.loginError,children:$t})]}),Xt&&a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:fe.inlineHint,children:['Importing "',Xt.name,'" from cloud into local.']}),a.jsx("div",{className:fe.optionGroup,children:xr.map(ve=>a.jsx("p",{className:fe.inlineHint,children:ve},ve))}),a.jsx("p",{className:fe.inlineHint,children:xe?"Finishing setup and opening your workspace.":yn||"Pulling tasks, taxonomies, and settings into local."}),!xe&&Sr&&a.jsx("p",{className:fe.inlineHint,children:Sr})]})]}):a.jsxs(a.Fragment,{children:[Yr&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:fe.loginSubtitle,children:"Workspace name"}),a.jsx("input",{className:p.input,type:"text",value:Ot,placeholder:"Workspace name",onChange:ve=>Dt(ve.target.value),disabled:ee}),a.jsx("p",{className:fe.loginSubtitle,children:"Workspace description"}),a.jsx("textarea",{className:p.textarea,value:We,placeholder:"Workspace description (optional)",onChange:ve=>tt(ve.target.value),disabled:ee,rows:4})]}),Ba&&a.jsxs("div",{className:fe.optionGroup,children:[a.jsx("p",{className:fe.loginSubtitle,children:"What are you working on?"}),a.jsxs("select",{className:p.input,value:Pt,onChange:ve=>Ft(ve.target.value),disabled:ee||ra||zt.length===0,children:[zt.length===0&&a.jsx("option",{value:"",children:ra?"Loading setup options...":"No setup options available"}),zt.map(ve=>a.jsx("option",{value:ve.id,children:ve.label},ve.id))]}),va?a.jsx(a.Fragment,{children:va.description?a.jsx("p",{className:fe.inlineHint,children:va.description}):null}):null,a.jsxs("div",{className:fe.optionGroup,children:[a.jsx("p",{className:fe.loginSubtitle,children:"Apply Setup Sections"}),a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:Lt.categories,onChange:()=>Ht(ve=>({...ve,categories:!ve.categories})),disabled:ee||!va?.categories.length}),a.jsx("span",{children:"Categories"})]}),T?a.jsx("p",{className:fe.inlineHint,children:T}):null,a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:Lt.types,onChange:()=>Ht(ve=>({...ve,types:!ve.types})),disabled:ee||!va?.types.length}),a.jsx("span",{children:"Task Types"})]}),j?a.jsx("p",{className:fe.inlineHint,children:j}):null,a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:Lt.priorities,onChange:()=>Ht(ve=>({...ve,priorities:!ve.priorities})),disabled:ee||!va?.priorities.length}),a.jsx("span",{children:"Priorities"})]}),at?a.jsx("p",{className:fe.inlineHint,children:at}):null]}),ra?a.jsx("p",{className:fe.inlineHint,children:"Loading setup options…"}):null,Ga?a.jsx("p",{className:fe.loginError,children:Ga}):null]}),!za&&Pa&&gt&&Yr&&a.jsxs("div",{className:fe.optionGroup,children:[a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:E,onChange:ve=>c(ve.target.checked),disabled:ee}),a.jsx("span",{children:"Sync to cloud after setup"})]}),a.jsx("p",{className:fe.inlineHint,children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),a.jsxs("div",{className:fe.authModeLinks,children:[Ba?a.jsx("button",{className:p.cancelBtn,onClick:()=>{it(null),ht(null),ot("details")},children:"Back"}):Za?a.jsx("button",{className:p.cancelBtn,onClick:()=>{it(null),ht(null),C("/",{replace:!0})},children:"Cancel"}):wt==="cloud"?a.jsx("button",{className:p.cancelBtn,onClick:async()=>{await pt.logout(),C("/login",{replace:!0})},children:qe("setup.signOut")}):null,$e?a.jsx("button",{className:p.submitBtn,disabled:ee||Cr&&!!Xt&&!Cn,onClick:async()=>{ze(!0),ht(null),it(null);try{const ve=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:Qe}})}),ae=await ve.json().catch(()=>({}));!ve.ok||ae?.success===!1?it(ae?.error||qe("setup.saveFailedWithStatus",{status:ve.status})):(ht(qe("setup.globalSetupSaved")),await Kt())}catch{it(qe("setup.saveFailed"))}finally{ze(!1)}},children:qe(ee?"setup.saving":"setup.saveGlobalSetup")}):W?a.jsx("button",{className:p.submitBtn,disabled:ee,onClick:Kt,children:qe("setup.retrySetupCheck")}):a.jsx("button",{className:p.submitBtn,disabled:ee||Cr&&!Xt&&!gt,onClick:async()=>{if(Cr&&Xt){if(!Cn)return;ze(!0),ht(`Retrying import for ${Xt.name}...`),it(null);try{await qr()}catch{ht(null),it(`Failed to retry import for "${Xt.name}".`)}finally{ze(!1)}return}if(Er){if(!Pa){it("Cloud workspace sync is unavailable right now."),ze(!1);return}if(!gt){it("Sign in is required before syncing a cloud project."),ze(!1);return}const ve=te.find(jn=>jn.id===At);if(!ve){it("Select a cloud project to sync."),ze(!1);return}const ae=await Qa({workspaceId:ve.id,name:ve.name||ve.id,description:ve.description||void 0});if(!ae.success){it(ae.error||qe("setup.saveWorkspaceFailed")),ze(!1);return}const Rn=String(ae.workspaceId||ve.id||"").trim();if(!Rn){it("Failed to resolve workspace id for sync setup."),ze(!1);return}try{await wn(Rn,{version:2,enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null})}catch(jn){it(jn instanceof Error?jn.message:"Failed to configure workspace sync."),ze(!1);return}Zt({enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null}),await Kt(),we({workspaceId:Rn,name:ve.name||ve.id}),Ke(!1),ht(`Importing ${ve.name||ve.id} from cloud...`),ze(!1);return}if(Yr){if(!Ot.trim()){it("Workspace name is required before continuing.");return}it(null),ht(null),ot("library");return}ze(!0),ht(null),it(null);{const ve=Za||ta?.workspaceSetupState==="missing",ae=Za||Ca&&ve,Rn=ae?await Ta(Ot,We||void 0):null,jn=ae?null:await Qa({workspaceId:ve?void 0:ta?.workspaceId,name:Ot,description:We}),hn=Rn||jn;if(hn?.success){const Os=String(Rn?.workspace?.id||jn?.workspaceId||ta?.workspaceId||"").trim();if(!Os){it("Failed to resolve workspace id for setup."),ze(!1);return}if(!!va&&(Lt.categories||Lt.types||Lt.priorities)&&va){const us=await Vn.onApplySystemTaxonomyPack({pack:va,sections:Lt,remapExistingValuesToDefault:!0,workspaceIdOverride:Os});if(!us?.success){it(us?.error||"Failed to apply setup library."),ze(!1);return}}const Nn=!!(!za&&E&&Pa&&gt),oo=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Os,stateKey:"workspace-sync",patch:{version:2,enabled:Nn,phase:Nn?"provision-local":"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),Lo=await oo.json().catch(()=>({}));if(!oo.ok||Lo?.success===!1){it(Lo?.error||`Failed to configure workspace sync (${oo.status})`),ze(!1);return}Zt({enabled:Nn,phase:Nn?"provision-local":"idle",setupIntent:null,pullCursor:null}),ht(Nn?`${Ha} setup saved. Cloud sync enabled.`:qe("setup.workspaceSetupSaved",{workspaceLabel:Ha})),Za&&(await Kt(),await kn(!0),C("/",{replace:!0}))}else{if(hn?.code==="WORKSPACE_LIMIT_REACHED"){ze(!1),C(_,{replace:!0});return}it(hn?.error||qe("setup.saveWorkspaceFailed"))}}ze(!1)},children:bt})]})]})})})}return a.jsx(_O,{...pt,onHeaderMouseDown:s,isDragging:o,onClose:l})}function AO(e){return pv()?a.jsx(og,{...e}):a.jsx(fv,{children:a.jsx(og,{...e})})}const Hy={},ig="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=ig,console.info(`[Taskforce] Build marker: ${ig}`));function xO(){if(typeof window<"u"){const t=window.location.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1")return}return mf(Hy).apiBaseUrl||void 0}function IO(e){const t=mf(Hy),n=t.cloudAuthBaseUrl;if(n)if(typeof window<"u"){const s=window.location.hostname.toLowerCase(),o=s==="localhost"||s==="127.0.0.1"||s==="::1",l="".trim().toLowerCase()==="true";if(!o&&!l)try{const i=new URL(n,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 n}catch{}else return n}else return n;if(t.baseUrl)return t.baseUrl;if(e)return e}function TO(){const e=xO(),t=IO(e);return a.jsx(hv,{children:a.jsx(AO,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:t}})})}Tk.createRoot(document.getElementById("root")).render(a.jsx(Ue.StrictMode,{children:a.jsx(TO,{})}));export{P1 as $,HO as A,fB as B,J1 as C,Qc as D,vB as E,zO as F,XW as G,zL as H,tc as I,uf as J,Kp as K,Gh as L,Ws as M,Vh as N,OW as O,GO as P,e4 as Q,ly as R,ky as S,id as T,vm as U,cy as V,KO as W,qO as X,gm as Y,NF as Z,N1 as _,Cm as a,x1 as a0,UO as a1,Am as a2,Vr as b,eS as c,xv as d,Ut as e,LO as f,Qu as g,D1 as h,ub as i,VO as j,L1 as k,sy as l,Xe as m,vS as n,em as o,Kg as p,tm as q,Dn as r,Zg as s,p as t,FO as u,BO as v,OO as w,WO as x,$O as y,MS as z};