@taskforcehq/taskforce 0.3.304 → 0.3.306

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 (383) hide show
  1. package/README.md +140 -247
  2. package/dist/Taskforce.module.css +295 -89
  3. package/dist/TaskforceCore.js +378 -111
  4. package/dist/TaskforceCore.test.js +1221 -107
  5. package/dist/assets/fonts/CourierPrime-Bold.woff2 +0 -0
  6. package/dist/assets/fonts/CourierPrime-BoldItalic.woff2 +0 -0
  7. package/dist/assets/fonts/CourierPrime-Italic.woff2 +0 -0
  8. package/dist/assets/fonts/CourierPrime-Regular.woff2 +0 -0
  9. package/dist/assets/fonts/Noir_medium.woff2 +0 -0
  10. package/dist/assets/fonts/Noir_regular.woff2 +0 -0
  11. package/dist/assets/fonts/RussoOne-Regular.woff2 +0 -0
  12. package/dist/assets/fonts/SpecialElite-Regular.woff2 +0 -0
  13. package/dist/compat/workspaceSyncCompat.js +52 -2
  14. package/dist/compat/workspaceSyncCompat.test.js +38 -1
  15. package/dist/components/context/ContextAttachmentManager.d.ts +14 -0
  16. package/dist/components/context/ContextAttachmentManager.js +549 -0
  17. package/dist/components/features/AgentsModule.d.ts +10 -1
  18. package/dist/components/features/AgentsModule.js +260 -15
  19. package/dist/components/features/AgentsModule.test.js +255 -5
  20. package/dist/components/features/DocumentIndex.d.ts +1 -1
  21. package/dist/components/features/DocumentIndex.js +1 -1
  22. package/dist/components/features/DocumentViewer.d.ts +6 -2
  23. package/dist/components/features/DocumentViewer.js +90 -10
  24. package/dist/components/features/DocumentWorkspace.d.ts +5 -22
  25. package/dist/components/features/DocumentWorkspace.js +12 -155
  26. package/dist/components/features/DocumentWorkspace.test.js +226 -6
  27. package/dist/components/features/TaskSettings.js +29 -3
  28. package/dist/components/features/TaskSettings.test.js +42 -1
  29. package/dist/components/features/documentWorkspaceModel.d.ts +24 -0
  30. package/dist/components/features/documentWorkspaceModel.js +57 -0
  31. package/dist/components/features/useDocumentWorkspaceController.d.ts +34 -0
  32. package/dist/components/features/useDocumentWorkspaceController.js +113 -0
  33. package/dist/components/task/TaskCard.js +19 -28
  34. package/dist/components/task/TaskCard.test.js +38 -3
  35. package/dist/components/task/TaskContextUpload.js +4 -526
  36. package/dist/components/task/TaskForm.d.ts +8 -8
  37. package/dist/components/task/TaskForm.js +362 -230
  38. package/dist/components/task/TaskForm.test.js +558 -381
  39. package/dist/components/task/TaskKanban.d.ts +2 -1
  40. package/dist/components/task/TaskKanban.js +96 -14
  41. package/dist/components/task/TaskKanban.test.js +36 -0
  42. package/dist/components/ui/EditableAvatarButton.d.ts +18 -0
  43. package/dist/components/ui/EditableAvatarButton.js +18 -0
  44. package/dist/components/views/PlanComparisonPage.d.ts +9 -1
  45. package/dist/components/views/PlanComparisonPage.js +70 -17
  46. package/dist/components/views/PlanComparisonPage.test.js +289 -41
  47. package/dist/components/views/PlansPage.js +239 -106
  48. package/dist/components/views/PlansPage.test.js +593 -42
  49. package/dist/components/views/StandaloneLayout.js +310 -554
  50. package/dist/components/views/panels/FilterToolbar.test.js +6 -4
  51. package/dist/components/views/panels/PlanningDrawer.d.ts +8 -1
  52. package/dist/components/views/panels/PlanningDrawer.js +18 -11
  53. package/dist/components/views/panels/PlanningDrawer.test.d.ts +1 -0
  54. package/dist/components/views/panels/PlanningDrawer.test.js +141 -0
  55. package/dist/components/views/planningScope.d.ts +20 -0
  56. package/dist/components/views/planningScope.js +25 -0
  57. package/dist/components/views/planningScope.test.d.ts +1 -0
  58. package/dist/components/views/planningScope.test.js +60 -0
  59. package/dist/components/views/standalone/modals/AccountHubModal.d.ts +27 -14
  60. package/dist/components/views/standalone/modals/AccountHubModal.js +87 -15
  61. package/dist/components/views/standalone/modals/AccountHubModal.test.js +42 -2
  62. package/dist/components/views/standalone/modals/AvatarImageManagerModal.d.ts +20 -0
  63. package/dist/components/views/standalone/modals/AvatarImageManagerModal.js +127 -0
  64. package/dist/components/views/standalone/modals/EditProfileModal.d.ts +2 -9
  65. package/dist/components/views/standalone/modals/EditProfileModal.js +3 -2
  66. package/dist/components/views/standalone/modals/SyncEnableWarningModal.d.ts +9 -0
  67. package/dist/components/views/standalone/modals/SyncEnableWarningModal.js +6 -0
  68. package/dist/components/views/standalone/modals/SyncEnableWarningModal.test.d.ts +1 -0
  69. package/dist/components/views/standalone/modals/SyncEnableWarningModal.test.js +24 -0
  70. package/dist/components/views/standalone/modals/SyncStatusModal.d.ts +2 -1
  71. package/dist/components/views/standalone/modals/SyncStatusModal.js +2 -2
  72. package/dist/config/envSchema.js +1 -1
  73. package/dist/core/AiProfileService.d.ts +45 -3
  74. package/dist/core/AiProfileService.js +774 -63
  75. package/dist/core/AiProfileService.test.js +22 -2
  76. package/dist/core/AiProfiles.test.js +761 -2
  77. package/dist/core/AttachmentLinkService.js +57 -15
  78. package/dist/core/AuthIdentityService.d.ts +107 -0
  79. package/dist/core/AuthIdentityService.js +284 -0
  80. package/dist/core/AuthTokenService.d.ts +4 -0
  81. package/dist/core/AuthTokenService.js +34 -6
  82. package/dist/core/AuthTokenService.test.d.ts +1 -0
  83. package/dist/core/AuthTokenService.test.js +78 -0
  84. package/dist/core/EntitlementsPolicy.test.js +77 -15
  85. package/dist/core/GlobalSettingsService.js +115 -6
  86. package/dist/core/PlanEntitlementService.d.ts +30 -3
  87. package/dist/core/PlanEntitlementService.js +454 -93
  88. package/dist/core/PlanFeatureCatalog.test.d.ts +1 -0
  89. package/dist/core/PlanFeatureCatalog.test.js +84 -0
  90. package/dist/core/PlanVersionPolicy.test.js +54 -28
  91. package/dist/core/PlanningEntities.test.js +52 -0
  92. package/dist/core/SignupMonetizationSettings.test.js +241 -44
  93. package/dist/core/SyncReconciliationService.js +2 -65
  94. package/dist/core/SystemAdmin.test.js +244 -88
  95. package/dist/core/TaskAttachmentsCanonical.test.js +51 -1
  96. package/dist/core/TaskTaxonomyValidation.test.js +53 -0
  97. package/dist/core/Taskforce.d.ts +228 -14
  98. package/dist/core/Taskforce.js +814 -201
  99. package/dist/core/Taskforce.listTasksSlim.test.d.ts +1 -0
  100. package/dist/core/Taskforce.listTasksSlim.test.js +91 -0
  101. package/dist/core/UserProfileAvatarDrafts.test.js +30 -3
  102. package/dist/core/WorkspaceLifecycleService.js +0 -5
  103. package/dist/core/WorkspacePermissions.test.js +25 -1
  104. package/dist/core/WorkspacePlanMode.test.js +128 -27
  105. package/dist/core/shared.d.ts +3 -1
  106. package/dist/core/shared.js +16 -1
  107. package/dist/core/types.d.ts +68 -2
  108. package/dist/hooks/auth/useTaskforceAuthBootstrap.js +26 -1
  109. package/dist/hooks/sync/auth.js +3 -1
  110. package/dist/hooks/sync/bootstrap.js +2 -0
  111. package/dist/hooks/sync/controlPlane.d.ts +37 -0
  112. package/dist/hooks/sync/controlPlane.js +78 -0
  113. package/dist/hooks/sync/controlPlane.test.d.ts +1 -0
  114. package/dist/hooks/sync/controlPlane.test.js +121 -0
  115. package/dist/hooks/sync/lifecyclePolicy.d.ts +45 -0
  116. package/dist/hooks/sync/lifecyclePolicy.js +93 -0
  117. package/dist/hooks/sync/lifecyclePolicy.test.d.ts +1 -0
  118. package/dist/hooks/sync/lifecyclePolicy.test.js +124 -0
  119. package/dist/hooks/sync/orchestratorShared.d.ts +10 -1
  120. package/dist/hooks/sync/orchestratorShared.js +68 -47
  121. package/dist/hooks/sync/orchestratorShared.test.js +50 -1
  122. package/dist/hooks/sync/pullLifecycle.d.ts +31 -0
  123. package/dist/hooks/sync/pullLifecycle.js +24 -0
  124. package/dist/hooks/sync/pullLifecycle.test.d.ts +1 -0
  125. package/dist/hooks/sync/pullLifecycle.test.js +80 -0
  126. package/dist/hooks/sync/recovery.d.ts +16 -2
  127. package/dist/hooks/sync/recovery.js +171 -53
  128. package/dist/hooks/sync/recovery.test.d.ts +1 -0
  129. package/dist/hooks/sync/recovery.test.js +292 -0
  130. package/dist/hooks/sync/transfers.d.ts +16 -3
  131. package/dist/hooks/sync/transfers.js +186 -65
  132. package/dist/hooks/sync/transfers.test.d.ts +1 -0
  133. package/dist/hooks/sync/transfers.test.js +396 -0
  134. package/dist/hooks/sync/useRecentSyncEvents.d.ts +21 -0
  135. package/dist/hooks/sync/useRecentSyncEvents.js +92 -0
  136. package/dist/hooks/sync/useRecentSyncEvents.test.d.ts +1 -0
  137. package/dist/hooks/sync/useRecentSyncEvents.test.js +124 -0
  138. package/dist/hooks/sync/useSyncStatusActions.d.ts +30 -0
  139. package/dist/hooks/sync/useSyncStatusActions.js +88 -0
  140. package/dist/hooks/sync/useSyncStatusActions.test.d.ts +1 -0
  141. package/dist/hooks/sync/useSyncStatusActions.test.js +133 -0
  142. package/dist/hooks/sync/useSyncStatusControls.d.ts +25 -0
  143. package/dist/hooks/sync/useSyncStatusControls.js +60 -0
  144. package/dist/hooks/sync/useSyncStatusControls.test.d.ts +1 -0
  145. package/dist/hooks/sync/useSyncStatusControls.test.js +88 -0
  146. package/dist/hooks/useSyncOrchestrator.aiProfiles.test.js +12 -0
  147. package/dist/hooks/useSyncOrchestrator.d.ts +16 -6
  148. package/dist/hooks/useSyncOrchestrator.js +424 -175
  149. package/dist/hooks/useSyncOrchestrator.retry-closure.test.js +487 -10
  150. package/dist/hooks/useTaskData.js +8 -3
  151. package/dist/hooks/useTaskData.test.js +45 -0
  152. package/dist/hooks/useTaskMutations.d.ts +2 -1
  153. package/dist/hooks/useTaskMutations.js +12 -1
  154. package/dist/hooks/useTaskMutations.test.js +30 -1
  155. package/dist/hooks/useTaskforce.d.ts +65 -4
  156. package/dist/hooks/useTaskforce.js +564 -243
  157. package/dist/hooks/useTaskforce.runtime-routing.test.d.ts +1 -0
  158. package/dist/hooks/useTaskforce.runtime-routing.test.js +152 -0
  159. package/dist/hooks/useTaskforce.sync-behavior.test.js +2454 -208
  160. package/dist/hooks/useWorkspaceSyncController.d.ts +4 -1
  161. package/dist/hooks/useWorkspaceSyncController.js +17 -2
  162. package/dist/hooks/useWorkspaceSyncController.test.js +1 -0
  163. package/dist/hooks/workspace/useTaskforceWorkspaceBootstrap.d.ts +16 -0
  164. package/dist/hooks/workspace/useTaskforceWorkspaceBootstrap.js +316 -35
  165. package/dist/localization/locales/en-US.d.ts +0 -1
  166. package/dist/localization/locales/en-US.js +0 -1
  167. package/dist/localization/locales/es-419.js +0 -1
  168. package/dist/localization/locales/pt-BR.js +0 -1
  169. package/dist/mcp/adminWorkspaceRegistrar.d.ts +2 -0
  170. package/dist/mcp/adminWorkspaceRegistrar.js +154 -0
  171. package/dist/mcp/collaborationRegistrar.d.ts +2 -0
  172. package/dist/mcp/collaborationRegistrar.js +71 -0
  173. package/dist/mcp/documentAssetRegistrar.d.ts +2 -0
  174. package/dist/mcp/documentAssetRegistrar.js +346 -0
  175. package/dist/mcp/runtime.d.ts +2 -0
  176. package/dist/mcp/runtime.js +2433 -3534
  177. package/dist/mcp/runtime.test.js +440 -2
  178. package/dist/mcp/taskPlanningRegistrar.d.ts +2 -0
  179. package/dist/mcp/taskPlanningRegistrar.js +418 -0
  180. package/dist/mcp/toolCatalog.d.ts +35 -0
  181. package/dist/mcp/toolCatalog.js +3 -0
  182. package/dist/migrations/taskSchemaMigrations.d.ts +1 -1
  183. package/dist/migrations/taskSchemaMigrations.js +171 -61
  184. package/dist/migrations/taskSchemaMigrations.test.js +15 -0
  185. package/dist/resources/templates/workflow-sources/workflowDocs.mjs +6 -6
  186. package/dist/resources/templates/workflows/collaborate.yaml +1 -1
  187. package/dist/resources/templates/workflows/evaluate.yaml +2 -2
  188. package/dist/resources/templates/workflows/plan.yaml +1 -1
  189. package/dist/resources/templates/workflows/review.yaml +2 -2
  190. package/dist/server/annotatedAttachmentsRoutes.test.js +3 -3
  191. package/dist/server/auth/providers/apple.d.ts +33 -0
  192. package/dist/server/auth/providers/apple.js +82 -0
  193. package/dist/server/auth/providers/appleClientSecret.d.ts +37 -0
  194. package/dist/server/auth/providers/appleClientSecret.js +65 -0
  195. package/dist/server/auth/providers/github.d.ts +26 -0
  196. package/dist/server/auth/providers/github.js +86 -0
  197. package/dist/server/auth/providers/google.d.ts +21 -0
  198. package/dist/server/auth/providers/google.js +56 -0
  199. package/dist/server/auth/providers/types.d.ts +21 -0
  200. package/dist/server/auth/providers/types.js +1 -0
  201. package/dist/server/auth.d.ts +2 -0
  202. package/dist/server/auth.js +6 -3
  203. package/dist/server/documentReviewRoutes.test.js +36 -3
  204. package/dist/server/index.cookieProxy.test.js +1 -0
  205. package/dist/server/index.d.ts +12 -0
  206. package/dist/server/index.js +120 -9
  207. package/dist/server/index.rateLimit.test.js +3 -0
  208. package/dist/server/index.test.js +106 -3
  209. package/dist/server/routes/admin.d.ts +4 -5
  210. package/dist/server/routes/admin.js +410 -80
  211. package/dist/server/routes/annotatedAttachments.d.ts +1 -1
  212. package/dist/server/routes/annotatedAttachments.js +1 -1
  213. package/dist/server/routes/auth.d.ts +16 -6
  214. package/dist/server/routes/auth.js +1015 -118
  215. package/dist/server/routes/authSupport.d.ts +30 -0
  216. package/dist/server/routes/authSupport.js +81 -0
  217. package/dist/server/routes/billing.d.ts +1 -1
  218. package/dist/server/routes/billing.js +276 -34
  219. package/dist/server/routes/billing.test.js +760 -52
  220. package/dist/server/routes/documentReviews.d.ts +1 -1
  221. package/dist/server/routes/documentReviews.js +1 -1
  222. package/dist/server/routes/documents.d.ts +5 -2
  223. package/dist/server/routes/documents.js +242 -74
  224. package/dist/server/routes/primitives.d.ts +11 -0
  225. package/dist/server/routes/primitives.js +73 -0
  226. package/dist/server/routes/resources.d.ts +1 -1
  227. package/dist/server/routes/resources.js +1 -1
  228. package/dist/server/routes/shared.d.ts +29 -3
  229. package/dist/server/routes/shared.js +69 -4
  230. package/dist/server/routes/sync.d.ts +1 -1
  231. package/dist/server/routes/sync.integration.test.js +437 -39
  232. package/dist/server/routes/sync.js +62 -606
  233. package/dist/server/routes/syncAuxRoutes.d.ts +15 -0
  234. package/dist/server/routes/syncAuxRoutes.js +91 -0
  235. package/dist/server/routes/syncAuxRoutes.test.d.ts +1 -0
  236. package/dist/server/routes/syncAuxRoutes.test.js +158 -0
  237. package/dist/server/routes/syncPullApplyRoutes.d.ts +36 -0
  238. package/dist/server/routes/syncPullApplyRoutes.js +204 -0
  239. package/dist/server/routes/syncPushRoutes.d.ts +24 -0
  240. package/dist/server/routes/syncPushRoutes.js +212 -0
  241. package/dist/server/routes/syncRouteGuards.d.ts +36 -0
  242. package/dist/server/routes/syncRouteGuards.js +67 -0
  243. package/dist/server/routes/syncRouteGuards.test.d.ts +1 -0
  244. package/dist/server/routes/syncRouteGuards.test.js +94 -0
  245. package/dist/server/routes/syncRouteTypes.d.ts +13 -0
  246. package/dist/server/routes/syncRouteTypes.js +1 -0
  247. package/dist/server/routes/syncSnapshotRoutes.d.ts +66 -0
  248. package/dist/server/routes/syncSnapshotRoutes.js +180 -0
  249. package/dist/server/routes/tasks.d.ts +1 -1
  250. package/dist/server/routes/tasks.js +44 -2
  251. package/dist/server/routes/workspaces.d.ts +1 -1
  252. package/dist/server/routes/workspaces.js +37 -6
  253. package/dist/server/routes.d.ts +2 -9
  254. package/dist/server/routes.js +136 -165
  255. package/dist/server/routes.test.js +2457 -162
  256. package/dist/services/workflowExportSnapshots.test.js +2 -0
  257. package/dist/shared/aiProfileSeatScope.d.ts +5 -0
  258. package/dist/shared/aiProfileSeatScope.js +21 -0
  259. package/dist/shared/passwordPolicy.d.ts +13 -0
  260. package/dist/shared/passwordPolicy.js +84 -0
  261. package/dist/shared/passwordPolicy.test.d.ts +1 -0
  262. package/dist/shared/passwordPolicy.test.js +34 -0
  263. package/dist/storage/workspaceAssetStore.d.ts +15 -3
  264. package/dist/storage/workspaceAssetStore.js +132 -44
  265. package/dist/storage/workspaceAssetStore.test.js +93 -6
  266. package/dist/styles/fonts.css +70 -0
  267. package/dist/sync/collaborationSyncPayload.d.ts +6 -1
  268. package/dist/sync/collaborationSyncPayload.js +17 -11
  269. package/dist/sync/collaborationSyncPayload.test.js +13 -1
  270. package/dist/sync/contentSyncState.d.ts +4 -8
  271. package/dist/sync/contentSyncState.js +33 -77
  272. package/dist/sync/syncApplyHandlers.d.ts +7 -0
  273. package/dist/sync/syncApplyHandlers.js +28 -13
  274. package/dist/sync/syncApplyHandlers.test.js +72 -3
  275. package/dist/sync/syncFieldSemantics.d.ts +12 -0
  276. package/dist/sync/syncFieldSemantics.js +55 -0
  277. package/dist/sync/syncResourceAdapters.d.ts +44 -0
  278. package/dist/sync/syncResourceAdapters.js +77 -0
  279. package/dist/sync/syncService.d.ts +6 -0
  280. package/dist/sync/syncService.js +60 -0
  281. package/dist/sync/syncService.test.js +71 -3
  282. package/dist/sync/taskSyncChangeKey.d.ts +2 -0
  283. package/dist/sync/taskSyncChangeKey.js +143 -0
  284. package/dist/sync/taskSyncPayload.js +3 -8
  285. package/dist/sync/workspacePullFeed.js +4 -3
  286. package/dist/sync/workspacePullFeed.test.js +43 -0
  287. package/dist/sync/workspaceRepair.js +5 -2
  288. package/dist/sync/workspaceSyncModel.d.ts +48 -0
  289. package/dist/sync/workspaceSyncModel.js +195 -31
  290. package/dist/sync/workspaceSyncModel.test.js +325 -12
  291. package/dist/sync/workspaceSyncState.d.ts +19 -0
  292. package/dist/sync/workspaceSyncState.js +3 -1
  293. package/dist/sync/workspaceSyncSurface.js +3 -8
  294. package/dist/types.d.ts +17 -0
  295. package/dist/ui/assets/AgentsModule-DrLawwNl.js +1 -0
  296. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-BlS-cqnl.js → AnnotatedAttachmentWorkspace-Z9_whf7F.js} +1 -1
  297. package/dist/ui/assets/CourierPrime-Bold-BuLj_dpw.woff2 +0 -0
  298. package/dist/ui/assets/CourierPrime-BoldItalic-BrK2pUkZ.woff2 +0 -0
  299. package/dist/ui/assets/CourierPrime-Italic-DFUZK5Ey.woff2 +0 -0
  300. package/dist/ui/assets/CourierPrime-Regular-BsKphzVf.woff2 +0 -0
  301. package/dist/ui/assets/DocumentWorkspace-B03MaSkw.js +252 -0
  302. package/dist/ui/assets/DocumentWorkspace-Dhdso07p.css +1 -0
  303. package/dist/ui/assets/{InitiativesModule-BjR6iBf9.js → InitiativesModule-9E6ParrY.js} +1 -1
  304. package/dist/ui/assets/Noir_medium-bxQwKGzB.woff2 +0 -0
  305. package/dist/ui/assets/Noir_regular-ojf2kxlG.woff2 +0 -0
  306. package/dist/ui/assets/PlansPage-CvfnMiWq.css +1 -0
  307. package/dist/ui/assets/PlansPage-DRXscYxH.js +1 -0
  308. package/dist/ui/assets/RussoOne-Regular-Cu_qq_qC.woff2 +0 -0
  309. package/dist/ui/assets/SpecialElite-Regular-Di6gSvAS.woff2 +0 -0
  310. package/dist/ui/assets/TaskSettings-DZX4jk7e.js +9 -0
  311. package/dist/ui/assets/{WorkflowsModule-DnFqdUME.js → WorkflowsModule-BA7jcEpH.js} +1 -1
  312. package/dist/ui/assets/index-9eT8e0Lu.css +1 -0
  313. package/dist/ui/assets/index-C6k75jr8.js +6 -0
  314. package/dist/ui/assets/{vendor-icons-I7ZwG1z_.js → vendor-icons-DuEd_65c.js} +1 -1
  315. package/dist/ui/fonts/CourierPrime-Bold.ttf +0 -0
  316. package/dist/ui/fonts/CourierPrime-Bold.woff2 +0 -0
  317. package/dist/ui/fonts/CourierPrime-BoldItalic.ttf +0 -0
  318. package/dist/ui/fonts/CourierPrime-BoldItalic.woff2 +0 -0
  319. package/dist/ui/fonts/CourierPrime-Italic.ttf +0 -0
  320. package/dist/ui/fonts/CourierPrime-Italic.woff2 +0 -0
  321. package/dist/ui/fonts/CourierPrime-Regular.ttf +0 -0
  322. package/dist/ui/fonts/CourierPrime-Regular.woff2 +0 -0
  323. package/dist/ui/fonts/Noir_medium.otf +0 -0
  324. package/dist/ui/fonts/Noir_medium.woff2 +0 -0
  325. package/dist/ui/fonts/Noir_regular.otf +0 -0
  326. package/dist/ui/fonts/Noir_regular.woff2 +0 -0
  327. package/dist/ui/fonts/RussoOne-Regular.woff2 +0 -0
  328. package/dist/ui/fonts/SpecialElite-Regular.ttf +0 -0
  329. package/dist/ui/fonts/SpecialElite-Regular.woff2 +0 -0
  330. package/dist/ui/index.html +3 -3
  331. package/dist/utils/accountProfileSummaryCache.d.ts +5 -0
  332. package/dist/utils/assignees.d.ts +2 -0
  333. package/dist/utils/assignees.js +2 -0
  334. package/dist/utils/avatarUpload.d.ts +27 -0
  335. package/dist/utils/avatarUpload.js +132 -0
  336. package/dist/utils/avatarUpload.test.d.ts +1 -0
  337. package/dist/utils/avatarUpload.test.js +40 -0
  338. package/dist/utils/bootstrapTrace.d.ts +7 -0
  339. package/dist/utils/bootstrapTrace.js +29 -0
  340. package/dist/utils/commercialLifecyclePresentation.d.ts +19 -0
  341. package/dist/utils/commercialLifecyclePresentation.js +199 -0
  342. package/dist/utils/contextAssetEvents.d.ts +2 -0
  343. package/dist/utils/syncEventDetails.d.ts +3 -0
  344. package/dist/utils/syncEventDetails.js +64 -0
  345. package/dist/utils/syncEventDetails.test.d.ts +1 -0
  346. package/dist/utils/syncEventDetails.test.js +23 -0
  347. package/dist/utils/syncEventPresentation.d.ts +15 -0
  348. package/dist/utils/syncEventPresentation.js +129 -0
  349. package/dist/utils/syncEventPresentation.test.d.ts +1 -0
  350. package/dist/utils/syncEventPresentation.test.js +64 -0
  351. package/dist/utils/syncStatusPresentation.d.ts +72 -0
  352. package/dist/utils/syncStatusPresentation.js +217 -0
  353. package/dist/utils/syncStatusPresentation.test.d.ts +1 -0
  354. package/dist/utils/syncStatusPresentation.test.js +164 -0
  355. package/dist/utils/taskActivity.d.ts +2 -0
  356. package/dist/utils/taskActivity.js +228 -22
  357. package/dist/utils/taskActivity.test.js +119 -8
  358. package/dist/utils/workspaceSyncPresentation.d.ts +4 -0
  359. package/dist/utils/workspaceSyncPresentation.js +68 -2
  360. package/dist/utils/workspaceSyncPresentation.test.js +36 -1
  361. package/package.json +10 -2
  362. package/scripts/check-cloud-mcp.mjs +83 -0
  363. package/scripts/export-sqlite-to-postgres.mjs +7 -9
  364. package/scripts/playwright-auth.sh +5 -1
  365. package/scripts/run-billing-performance-smoke.sh +24 -0
  366. package/scripts/run-e2e-realtime.sh +17 -3
  367. package/scripts/run-smoke.sh +17 -5
  368. package/scripts/run-soak.sh +17 -5
  369. package/src/resources/templates/workflow-sources/workflowDocs.mjs +6 -6
  370. package/src/resources/templates/workflows/collaborate.yaml +1 -1
  371. package/src/resources/templates/workflows/evaluate.yaml +2 -2
  372. package/src/resources/templates/workflows/plan.yaml +1 -1
  373. package/src/resources/templates/workflows/review.yaml +2 -2
  374. package/dist/ui/assets/AgentsModule-BLWVbuKP.js +0 -1
  375. package/dist/ui/assets/DocumentWorkspace-BH_6DF6x.js +0 -250
  376. package/dist/ui/assets/DocumentWorkspace-C_8T8oz-.css +0 -1
  377. package/dist/ui/assets/PlansPage-C2dd2n1X.css +0 -1
  378. package/dist/ui/assets/PlansPage-CSDQ4sLa.js +0 -1
  379. package/dist/ui/assets/RussoOne-Regular-C3BxZIj7.ttf +0 -0
  380. package/dist/ui/assets/TaskSettings-CEDy34Jo.js +0 -9
  381. package/dist/ui/assets/index-DXUdtH1B.js +0 -6
  382. package/dist/ui/assets/index-Ii0B0rTO.css +0 -1
  383. package/scripts/migrate-planning-model.ts +0 -233
@@ -0,0 +1,6 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TaskSettings-DZX4jk7e.js","assets/vendor-react-CKJs5o3c.js","assets/vendor-icons-DuEd_65c.js","assets/vendor-markdown-BUxTU7dS.js","assets/vendor-dnd-DRzYolkg.js","assets/vendor-router-BbWMxlnO.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-Z9_whf7F.js","assets/AnnotatedAttachmentWorkspace-BaS2VwIr.css","assets/DocumentWorkspace-B03MaSkw.js","assets/DocumentWorkspace-Dhdso07p.css","assets/WorkflowsModule-BA7jcEpH.js","assets/AgentsModule-DrLawwNl.js","assets/InitiativesModule-9E6ParrY.js","assets/PlansPage-DRXscYxH.js","assets/PlansPage-CvfnMiWq.css"])))=>i.map(i=>d[i]);
2
+ import{r,j as t,R as pt,a as Ii,b as Zy}from"./vendor-react-CKJs5o3c.js";import{I as us,C as Ti,a as fd,b as po,c as nd,F as Yy,A as Jy,R as cd,T as Bc,L as bp,d as Ni,e as Xy,X as Ei,f as $h,g as Uh,h as Va,i as Wc,j as Xm,k as Fc,P as Qy,D as If,l as ek,B as wp,U as _i,m as tk,S as nk,n as Cs,G as ak,o as rk,p as qh,q as sk,r as xp,s as zh,t as ok,u as ik,v as ck,w as lk,x as Mc,y as Hh,z as dk,E as Gh,H as uk,J as mk,K as pk,M as Tf,N as Nf,O as fk,Q as hk,Z as gk,V as yk,W as kk,Y as Sk,_ as vk,$ as Vh,a0 as bk,a1 as wk,a2 as xk,a3 as _k}from"./vendor-icons-DuEd_65c.js";import{M as Ck,r as Ak,a as Ik}from"./vendor-markdown-BUxTU7dS.js";import{u as Kh,a as _p,b as Tk,D as Zh,c as Nk,S as Yh,v as Jh,P as Xh,d as Qh,C as Hp,e as Rk,p as jk,f as Rf,s as Pk,K as Ek,g as hd,h as Mk,i as lm,j as Dk}from"./vendor-dnd-DRzYolkg.js";import{u as eg,a as tg,b as Lk,M as Bk,N as jf,B as Wk}from"./vendor-router-BbWMxlnO.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const i of c.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function a(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(o){if(o.ep)return;o.ep=!0;const c=a(o);fetch(o.href,c)}})();const Dc="default",dm="General",Mr="task",Fk=2,Ok=[{value:Dc,label:dm,icon:"Inbox"}],ng=[{value:Mr,label:"Task",icon:"CheckSquare",color:"blue-500"}],$k=[{value:Fk,label:"Medium",color:"blue-500",icon:"Minus"}];function Uk(){return Ok.map(e=>({...e}))}function qk(){return ng.map(e=>({...e}))}function zk(e){const n=String(e||"").trim().toLowerCase();return ng.find(a=>a.value===n)}function ag(){return $k.map(e=>({...e}))}const Hk="default",Gk=[{value:Hk,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 rg(){return Gk.map(e=>({...e}))}const Vk={categories:Uk(),types:qk(),priorities:ag(),approaches:rg(),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},Kk=["light","dawn","dark","midnight"],Ku="dark",Zk=[{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"}],Yk=new Set(Kk),Jk=new Set(Zk.filter(e=>e.family==="light").map(e=>e.id));function Xk(e){return typeof e=="string"&&Yk.has(e)}function Rc(e){if(typeof e!="string")return null;const n=e.trim().toLowerCase();return Xk(n)?n:null}function sg(e){const n=Rc(e);return n!==null&&Jk.has(n)}function Cp(e){const n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return null;const a=Math.floor(n);return a>0?a:null}function Oc(e,n){const a=Cp(typeof n=="object"&&n!==null?n.referenceNumber:n);return a?`${e}${a}`:""}function Gp(e,n){const a=String(e||"").trim(),s=String(n||"").trim();if(!a||!s)return null;const o=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=s.match(new RegExp(`^${o}(\\d+)$`,"i"));return c?Cp(c[1]):null}function gd(e,n){return n?typeof n.referenceLabel=="string"&&n.referenceLabel.trim().length>0?n.referenceLabel.trim():Oc(e,n.referenceNumber):""}const Vp="T-",Pf="LT-";function Qk(e){return Oc(Vp,e)}function og(e){return typeof e=="number"||e===null||e===void 0?Oc(Pf,e):Oc(Pf,{referenceNumber:e.localReferenceNumber??null})}function ig(e){return Gp(Vp,e)}function qs(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const n=gd(Vp,e);return n||og(e.localReferenceNumber)}function eS(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function cg(e){return{label:qs(e),isProvisional:eS(e)}}ag();const tS={low:1,medium:2,high:3,critical:4,"on-hold":1},nS={1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function aS(e){const n=String(e||"").trim().toLowerCase();return n==="blocked"||n==="on hold"||n==="on-hold"?"on-hold":n==="task"||n==="on-hold"||n==="in-progress"||n==="review"||n==="done"||n==="cancelled"?n:"task"}function Zu(e){if(typeof e=="number"&&Number.isFinite(e))return Math.max(1,Math.round(e));const n=Number(e);return Number.isFinite(n)?Math.max(1,Math.round(n)):tS[String(e||"").trim().toLowerCase()]??2}function rS(e,n){return nS[String(e)]||n}function fo(e){const n=typeof e.referenceNumber=="number"?e.referenceNumber:Number.isFinite(Number(e.referenceNumber))?Number(e.referenceNumber):null,a=typeof e.localReferenceNumber=="number"?e.localReferenceNumber:Number.isFinite(Number(e.localReferenceNumber))?Number(e.localReferenceNumber):null;return{...e,referenceNumber:n&&n>0?Math.floor(n):null,localReferenceNumber:a&&a>0?Math.floor(a):null,referenceLabel:typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0?e.referenceLabel.trim():n?Qk(n):og(a),assignee:(()=>{const s=String(e.assignee||"").trim(),o=s.toLowerCase();return o==="agent"||o==="ai"?"agent":!s||o==="user"||o==="human"||o==="unassigned"||o==="none"||o==="null"?"unassigned":s})(),category:typeof e.category=="string"?e.category:e.category?.value||"default",type:(typeof e.type=="string"?e.type:e.type?.label||"task").toLowerCase(),priority:Zu(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:aS(e.status)}}function sS(e,n,a){if(!e||typeof e!="object")return{tasks:n,archivedTasks:a};const s=fo(e),o=String(s.id||"").trim();if(!o)return{tasks:n,archivedTasks:a};const c=!!s.isArchived,i=c?{...s,isArchived:!0}:{...s,isArchived:!1},l=v=>[...v].sort((b,g)=>{const h=Date.parse(String(b.updatedAt||b.createdAt||"")),k=Date.parse(String(g.updatedAt||g.createdAt||""));if(Number.isFinite(h)&&Number.isFinite(k)&&h!==k)return k-h;if(Number.isFinite(h)!==Number.isFinite(k))return Number.isFinite(k)?1:-1;const I=Date.parse(String(g.createdAt||""))-Date.parse(String(b.createdAt||""));return Number.isFinite(I)&&I!==0?I:String(b.id).localeCompare(String(g.id))}),m=n.filter(v=>v.id!==o),y=a.filter(v=>v.id!==o);return c?y.push(i):m.push(i),{tasks:l(m),archivedTasks:l(y)}}function oS(e,n){if(!n.length||!e.length)return[];const a=new Set(n.map(o=>Number(o.value))),s=Array.from(new Set(e.map(o=>Number(o)).filter(o=>Number.isFinite(o)&&a.has(o))));return s.length>0?s:n.map(o=>Number(o.value))}function Qm(e,n){return n.some(a=>String(a)===String(e))}function iS(e,n){if(!e.length||!n.length)return e;const a=new Set(n.map(o=>o.value)),s=Array.from(new Set(e.filter(o=>a.has(o))));return s.length>0?s:n.map(o=>o.value)}const cS={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 / Tutorial",settings:"Settings",filtersCaps:"FILTERS:",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",linksLabel:"Links:",chooseLinksTitle:"Choose which linked tasks are shown",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchiveTitle:"Include archived tasks",includeArchive:"Archived",clearFilters:"Clear Filters",noTasksMatchFilters:"No tasks match current filters.",showingWithLinksHint:"Showing: {parentFilterLabel}. Switch Links to All or clear filters.",visibleActiveTasksTitle:"Visible active tasks / total active tasks",totalActiveTasksTitle:"Total active tasks"},setup:{headingCheckFailed:"Setup Check Failed",headingGlobalRequired:"Global Setup Required",headingWorkspaceRequired:"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"}},lS={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 / Tutorial",settings:"Configuracion",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",linksLabel:"Vinculos:",chooseLinksTitle:"Elige que tareas vinculadas se muestran",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchiveTitle:"Incluir tareas archivadas",includeArchive:"Incluir archivo",clearFilters:"Limpiar filtros",noTasksMatchFilters:"Ninguna tarea coincide con los filtros actuales.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Cambia Vinculos a Todas o limpia filtros.",visibleActiveTasksTitle:"Tareas activas visibles / total de tareas activas",totalActiveTasksTitle:"Total de tareas activas"},setup:{headingCheckFailed:"Fallo en verificacion de configuracion",headingGlobalRequired:"Configuracion global requerida",headingWorkspaceRequired:"Configuracion del espacio requerida",subtitleUnreadable:"Taskforce no pudo leer el estado de configuracion. Reintenta para continuar.",subtitleGlobalRequired:"Elige tu modo operativo predeterminado para continuar.",subtitleWorkspaceRequired:"Configura el perfil de tu espacio para continuar.",runtimeLabel:"Entorno",workspaceTermProject:"Proyecto",workspaceTermMission:"Mision",coreModeOption:"Modo Core: valores predeterminados de planificacion para {workspaceLabel}",operationsModeOption:"Modo Operaciones: terminologia y flujos orientados a Mision",workspaceNamePlaceholder:"Nombre de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descripcion de {workspaceLabel} (opcional)",saving:"Guardando...",saveGlobalSetup:"Guardar configuracion global",saveWorkspaceSetup:"Guardar configuracion de {workspaceLabel}",globalSetupSaved:"Configuracion global guardada.",workspaceSetupSaved:"Configuracion de {workspaceLabel} guardada.",saveFailedWithStatus:"Error al guardar la configuracion ({status})",saveFailed:"Error al guardar la configuracion.",saveWorkspaceFailed:"Error al guardar el perfil del espacio.",retrySetupCheck:"Reintentar verificacion",signOut:"Cerrar sesion"}},dS={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 / Tutorial",settings:"Configuracoes",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",linksLabel:"Vinculos:",chooseLinksTitle:"Escolha quais tarefas vinculadas sao exibidas",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchiveTitle:"Incluir tarefas arquivadas",includeArchive:"Incluir arquivo",clearFilters:"Limpar filtros",noTasksMatchFilters:"Nenhuma tarefa corresponde aos filtros atuais.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Mude Vinculos para Todas ou limpe os filtros.",visibleActiveTasksTitle:"Tarefas ativas visiveis / total de tarefas ativas",totalActiveTasksTitle:"Total de tarefas ativas"},setup:{headingCheckFailed:"Falha na verificacao da configuracao",headingGlobalRequired:"Configuracao global obrigatoria",headingWorkspaceRequired:"Configuracao do espaco obrigatoria",subtitleUnreadable:"Taskforce nao conseguiu ler o estado da configuracao. Tente novamente para continuar.",subtitleGlobalRequired:"Escolha seu modo operacional padrao para continuar.",subtitleWorkspaceRequired:"Configure o perfil do seu espaco para continuar.",runtimeLabel:"Ambiente",workspaceTermProject:"Projeto",workspaceTermMission:"Missao",coreModeOption:"Modo Core: padroes de planejamento para {workspaceLabel}",operationsModeOption:"Modo Operacoes: terminologia e fluxos orientados por Missao",workspaceNamePlaceholder:"Nome de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descricao de {workspaceLabel} (opcional)",saving:"Salvando...",saveGlobalSetup:"Salvar configuracao global",saveWorkspaceSetup:"Salvar configuracao de {workspaceLabel}",globalSetupSaved:"Configuracao global salva.",workspaceSetupSaved:"Configuracao de {workspaceLabel} salva.",saveFailedWithStatus:"Falha ao salvar configuracao ({status})",saveFailed:"Falha ao salvar configuracao.",saveWorkspaceFailed:"Falha ao salvar perfil do espaco.",retrySetupCheck:"Tentar verificacao novamente",signOut:"Sair"}},lg=["en-US","es-419","pt-BR"],Yu="en-US",ep={"en-US":cS,"es-419":lS,"pt-BR":dS},dg={en:"en-US",es:"es-419",pt:"pt-BR"};let Ri=Yu;function uS(e){return e.split(".").filter(Boolean)}function tp(e,n){let a=e;for(const s of n){if(!a||typeof a!="object")return;a=a[s]}return typeof a=="string"?a:void 0}function ug(e){if(!e)return Yu;const n=lg.find(s=>s.toLowerCase()===e.toLowerCase());if(n)return n;const a=e.split("-")[0]?.toLowerCase()||"";return dg[a]||Yu}function np(e,n){return n?e.replace(/\{([^}]+)\}/g,(a,s)=>{const o=n[s];return o==null?"":String(o)}):e}function mg(){return Ri}function mS(){return[...lg]}function pg(e){const n=ug(e);return Ri=n,n}function pS(e){const n=typeof navigator<"u"?navigator.language:null;return Ri=ug(n),Ri}function He(e,n){const a=uS(e),s=tp(ep[Ri],a);if(s)return np(s,n);const o=Ri.split("-")[0]?.toLowerCase()||"",c=dg[o];if(c&&c!==Ri){const l=tp(ep[c],a);if(l)return np(l,n)}const i=tp(ep[Yu],a);return i?np(i,n):e}const fS="default",ji="bootstrap";function hS(e){let n=2166136261;for(let a=0;a<e.length;a+=1)n^=e.charCodeAt(a),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function Kp(e){const n=String(e||"").trim().toLowerCase();return n?`${(n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${hS(n)}`:ji}function fg(e){const n=String(e||"").trim().toLowerCase();if(!n)return ji;const a=n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return a?a.slice(0,96):ji}function hg(e){const n=String(e||"").trim();return n?Kp(n):ji}function gS(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?ji:hg(e.projectRoot)}function yS(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const a=String(e.workspaceId||"").trim();return a&&!Zp(a)?Kp(`cloud-workspace:${a}`):ji}return hg(e.projectRoot)}function Zp(e){return String(e||"").trim().toLowerCase()===fS}const kS={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function SS(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function vS(e){return kS[SS(e)]}const ld={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 um(e){const n=String(e||"").trim().toLowerCase();return n==="production"||n==="staging"||n==="performance"?n:null}function bS(e){return um(e)||"production"}function Ef(e){return ld[bS(String(e||""))]}function wS(e){const n=String(e||"").trim().toLowerCase();if(!n)return null;for(const[a,s]of Object.entries(ld))if(new URL(s.appBaseUrl).hostname.toLowerCase()===n||new URL(s.mcpBaseUrl).hostname.toLowerCase()===n)return a;return null}function Yp(e){const n=String(e||"").trim();if(!n)return null;try{return wS(new URL(n).hostname)}catch{return null}}function xS(e){const n=Yp(e);return n?ld[n].mcpBaseUrl:null}function Si(e,n){return String(e[n]||"").trim()}function Mf(e,n,a){e.push(n),a?.(n)}function _S(e,n){const a=[],s=Si(e,"ENV"),o=um(s);if(o)return Mf(a,`[Taskforce compat] ENV=${s} is deprecated; set TASKFORCE_CLOUD_ENVIRONMENT=${o} instead.`,n),{cloudEnvironment:o,warnings:a};const c=[{key:"TASKFORCE_CLOUD_PROXY_BASE_URL",value:Si(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:Si(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:Si(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:Si(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:Si(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:Si(e,"TASKFORCE_BASE_URL")}];for(const i of c){if(!i.value)continue;const l=Yp(i.value);if(l)return Mf(a,`[Taskforce compat] ${i.key} is being used to infer TASKFORCE_CLOUD_ENVIRONMENT=${l}. Set TASKFORCE_CLOUD_ENVIRONMENT explicitly.`,n),{cloudEnvironment:l,warnings:a}}return{cloudEnvironment:null,warnings:a}}function $s(e,n){return String(e[n]||"").trim()}function CS(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function Tc(e){return String(e||"").trim().replace(/\/+$/,"")}function AS(e){return String(e||"").trim().replace(/\/+$/,"")}function co(...e){for(const n of e)if(String(n||"").trim())return String(n||"").trim();return""}function IS(e,n={}){const a=[],s=oe=>{a.push(oe),n.onWarning?.(oe)},o=CS($s(e,"TASKFORCE_RUNTIME_MODE")),c=um($s(e,"TASKFORCE_CLOUD_ENVIRONMENT")),i=c?{cloudEnvironment:c}:_S(e,s),l=c||i.cloudEnvironment,m=Tc(String(n.requestBaseUrl||"")),y=Tc(co($s(e,"VITE_TASKFORCE_BASE_URL"),$s(e,"TASKFORCE_BASE_URL"))),v=Tc($s(e,"VITE_TASKFORCE_API_BASE_URL")),b=Tc($s(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),g=Tc(co($s(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),$s(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),h=Tc($s(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),k=AS($s(e,"VITE_TASKFORCE_WS_BASE_URL")),I=l?ld[l].appBaseUrl:"",x=l?ld[l].mcpBaseUrl:"",A=co(h,b,v,y,I),M=co(g,x,A),B=co(m,y,v,b,A),ue=co(m,v,y,A),X=co(b,y,v,A),ce=o==="local"?co(k,m,v,y,h,b,I,A):co(m,k,ue,B,A);return{runtimeMode:o,cloudEnvironment:l,cloudBaseUrl:A,cloudMcpBaseUrl:M,baseUrl:B,apiBaseUrl:ue,cloudAuthBaseUrl:X,wsBaseUrl:ce,cloudAuthViaLocalProxy:o==="local"||!!h,warnings:a}}function Jp(e){return IS({TASKFORCE_CLOUD_ENVIRONMENT:"",VITE_TASKFORCE_BASE_URL:e.VITE_TASKFORCE_BASE_URL,VITE_TASKFORCE_API_BASE_URL:e.VITE_TASKFORCE_API_BASE_URL,VITE_TASKFORCE_CLOUD_AUTH_BASE_URL:e.VITE_TASKFORCE_CLOUD_AUTH_BASE_URL,VITE_TASKFORCE_CLOUD_MCP_BASE_URL:e.VITE_TASKFORCE_CLOUD_MCP_BASE_URL,VITE_TASKFORCE_WS_BASE_URL:e.VITE_TASKFORCE_WS_BASE_URL})}function Df(e){const n=String(e.workspaceId||"default").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"default",a=Number.isFinite(Number(e.epoch))?Math.max(0,Math.floor(Number(e.epoch))):0,s=String(e.seed||"session").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"session",o=String(e.phase||"bootstrap").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"bootstrap";return`tfb-${s}-${n}-e${a}-${o}`}function ap(e,n){const a=String(n||"").trim();if(!a)return e;const s=new Headers(e?.headers||void 0);return s.has("x-taskforce-bootstrap-trace-id")||s.set("x-taskforce-bootstrap-trace-id",a),{...e||{},headers:s}}const Ju="unassigned",gg="agent",TS="user",NS=/^[0-9a-f]{8,}$/i;function yg(e){const n=String(e||"").trim().toLowerCase();return n===gg||n==="ai"||n.startsWith("ai-profile-")}function kg(e){const n=String(e||"").trim().toLowerCase();return!n||n===Ju||n==="none"||n==="null"||n===TS}function Xu(e){return yg(e)?"agent":kg(e)?"unassigned":"member"}function RS(e){const n=String(e.displayName||"").trim(),a=String(e.email||"").trim().toLowerCase();return n||a||String(e.userId||"").trim()||"Workspace member"}function $o(){return[{value:Ju,label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)",kind:"unassigned"}]}function jS(e){const n=new Map;for(const a of e){const s=String(a.userId||"").trim();s&&n.set(s,{value:s,label:RS(a),icon:"User",color:"#22c55e",kind:"member",avatarUrl:typeof a.avatarUrl=="string"&&a.avatarUrl.trim().length>0?a.avatarUrl.trim():null})}return dd(Array.from(n.values()))}function dd(e){const n=new Map;for(const s of $o())n.set(s.value,s);for(const s of Array.isArray(e)?e:[]){const o=String(s?.value||"").trim();!o||o===Ju||o===gg||n.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})}const a=[Ju];return Array.from(n.values()).sort((s,o)=>{const c=a.indexOf(s.value),i=a.indexOf(o.value);return c>=0||i>=0?c<0?1:i<0?-1:c-i:s.label.localeCompare(o.label,void 0,{sensitivity:"base"})})}function PS(e,n){const a=String(n||"").trim();if(!a||e.some(c=>c.value===a))return e;const s=a.replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),o=s?s.split(" ").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" "):a;if(Xu(a)==="agent"){const c=String(a).toLowerCase().startsWith("ai-profile-")&&s.split(" ").every(i=>NS.test(i));return dd([...e,{value:a,label:c?"AI":o||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return Xu(a)==="member"?dd([...e,{value:a,label:o||a,icon:"User",color:"#22c55e",kind:"member"}]):e}function Sg(e){const n=Array.isArray(e)?e.filter(Boolean):[];return dd(n)}function ad(e,n){const a=String(e||"").trim(),o=Sg(n).find(c=>c.value===a);return o?o.label:yg(a)?"AI":kg(a)?"Unassigned":a||"Unassigned"}const vg="taskforce.workspaceContext.v2",ES="taskforce.uiState.app.v1",MS="taskforce.bootstrapDebug.v1",Lf=5e3,Cu=new Map;function DS(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(MS)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Ht(e,n){if(!DS())return;console.info("[Taskforce Bootstrap]",e,n&&typeof n=="object"?n:{})}function LS(e,n){const a=String(e).trim()||"default";return`${String(n).trim()||"default"}::${a}`}async function Xp(e){const n=String(e.stateKey||"default").trim()||"default",a=String(e.workspaceId||"").trim(),s=e.patch&&typeof e.patch=="object"?e.patch:{},o=JSON.stringify(s),c=LS(n,a||"default"),i=Date.now(),l=Cu.get(c);if(l&&l.serializedPatch===o){if(l.status==="success"&&e.skipIfUnchanged!==!1)return Ht("ui_state_persist_skipped",{stateKey:n,workspaceId:a||"default",reason:"unchanged"}),{skipped:!0,reason:"unchanged"};if(e.respectFailureCooldown!==!1&&l.retryAfter>i)return Ht("ui_state_persist_skipped",{stateKey:n,workspaceId:a||"default",reason:"cooldown",retryAfterMs:l.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:n,...a?{workspaceId:a}:{},patch:s})}),y=await m.json().catch(()=>({}));if(m.ok&&y?.success!==!1)return Cu.set(c,{serializedPatch:o,status:"success",retryAfter:0}),{skipped:!1,response:m,payload:y};if(Cu.set(c,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??Lf)}),Ht("ui_state_persist_failed",{stateKey:n,workspaceId:a||"default",status:m.status,error:String(y?.error||"")}),e.throwOnError)throw new Error(String(y?.error||`Failed to persist UI state (${m.status})`));return{skipped:!1,response:m,payload:y}}catch(m){if(Cu.set(c,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??Lf)}),Ht("ui_state_persist_failed",{stateKey:n,workspaceId:a||"default",error:m instanceof Error?m.message:String(m)}),e.throwOnError)throw m;return{skipped:!1,payload:null}}}function Qp(e){const n=Kp(e);return`${vg}.${n}`}function bg(e){const n=fg(e);return`${vg}.${n}`}function Ap(e){if(typeof window>"u")return"";try{const n=Qp(e),a=String(window.localStorage.getItem(n)||"").trim();if(a&&a.length<=120&&!/\s/.test(a))return a;const s=bg(e),o=String(window.localStorage.getItem(s)||"").trim();return o&&o.length<=120&&!/\s/.test(o)?(window.localStorage.setItem(n,o),o):""}catch{return""}}function BS(e,n){if(typeof window>"u")return;const a=String(e||"").trim();try{if(!a||Zp(a))return;const s=Qp(n),o=String(window.localStorage.getItem(s)||"").trim();if(!a&&o&&o.toLowerCase()!=="default")return;window.localStorage.setItem(s,a)}catch{}}function Bf(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(Qp(e)),window.localStorage.removeItem(bg(e))}catch{}}function wg(e){const n=fg(e);return`${ES}.${n}`}function Wf(e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(wg(e));if(!n)return null;const a=JSON.parse(n);return a&&typeof a=="object"?a:null}catch{return null}}function WS(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(wg(n),JSON.stringify(e))}catch{}}const Ip="taskforce.localMutationActorUserId.v1";function xg(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function FS(e){const n=String(e||"").trim().toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"}function Jl(e){if(!(typeof window>"u"))try{const n=String(e||"").trim();if(!n||n==="anonymous"){window.sessionStorage.removeItem(Ip);return}window.sessionStorage.setItem(Ip,n)}catch{}}function ef(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Ip)||"").trim()}catch{return""}}function OS(e,n){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!FS(window.location.hostname))return!1;try{return new URL(n,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function $S(e,n,a){if(!OS(e,n))return a;const s=ef();if(!s)return a;const o=new Headers(a?.headers||void 0);return o.has("x-taskforce-user-id")||o.set("x-taskforce-user-id",s),{...a,headers:o}}function US(e,n){if(!e.startsWith("/"))return e;const a=xg(n);return a?`${a}${e}`:e}async function fF(e,n,a){const s=US(e,a),o=xg(a).length>0,c=$S(e,s,n),i=typeof performance<"u"?performance.now():Date.now();try{const l=await fetch(s,c);if(!(o&&s!==e&&e.startsWith("/api/taskforce/")&&(l.status===401||l.status===403)))return l;Ht("taskforce_api_auth_fallback_retry",{path:e,primaryUrl:s,fallbackUrl:e,status:l.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)});try{const y=await fetch(e,c);return Ht("taskforce_api_auth_fallback_completed",{path:e,primaryUrl:s,fallbackUrl:e,primaryStatus:l.status,fallbackStatus:y.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),y}catch{return Ht("taskforce_api_auth_fallback_failed",{path:e,primaryUrl:s,fallbackUrl:e,status:l.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),l}}catch(l){if(!o||!e.startsWith("/"))throw l;Ht("taskforce_api_network_fallback_retry",{path:e,primaryUrl:s,fallbackUrl:e,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i),error:l instanceof Error?l.message:String(l)});const m=await fetch(e,c);return Ht("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 qS(e){const n=Number(e?.status);return Number.isFinite(n)&&n>0?Math.floor(n):0}async function zc(e){try{const n=await e,a=await n.text().catch(()=>"");let s={};if(a)try{s=JSON.parse(a)}catch{s={error:!n.ok&&n.statusText?`${n.status} ${n.statusText}`:a.slice(0,400)}}else!n.ok&&n.statusText&&(s={error:`${n.status} ${n.statusText}`});const o=n.headers.get("retry-after");let c;if(o){const i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>0)c=i*1e3;else{const l=Date.parse(o);if(Number.isFinite(l)){const m=l-Date.now();m>0&&(c=m)}}}return{ok:n.ok,status:n.status,data:s,retryAfterMs:c}}catch(n){return{ok:!1,status:qS(n),data:{}}}}async function zS(e){return zc(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function HS(e,n){return zc(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function rp(e,n){return zc(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n})}))}async function Ff(e,n){return zc(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function GS(e,n){const a=new URLSearchParams({limit:String(n.limit),workspaceId:n.workspaceId});n.cursor&&a.set("cursor",n.cursor),n.repairMode===!0&&a.set("repair","1");const s=e("/api/taskforce/sync/workspace/pull"),o=s.includes("?")?"&":"?";return zc(fetch(`${s}${o}${a.toString()}`,{method:"GET",credentials:"include"}))}async function VS(e,n){return zc(fetch(e("/api/taskforce/sync/workspace/push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({...n,...n.repairMode===!0?{repair:!0}:{}})}))}async function Tp(e,n,a){const s=JSON.stringify({workspaceId:e,changes:n,workspaceMembers:Array.isArray(a?.workspaceMembers)?a.workspaceMembers:void 0,...a?.repairMode===!0?{repair:!0}:{},bootstrapSnapshot:a?.bootstrapSnapshot?{currentAnnotatedAttachmentSessionIds:Array.isArray(a.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds)?a.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds:[]}:void 0}),o="/api/taskforce/sync/workspace/apply-local",c=[];try{const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:s});if(i.ok){const y=await i.json().catch(()=>({}));return{ok:!0,status:i.status,data:y,failures:c}}const l=await i.text().catch(()=>"");let m={};if(l)try{m=JSON.parse(l)}catch{m={error:l.slice(0,400)}}else i.statusText&&(m={error:`${i.status} ${i.statusText}`});return c.push(`${o}:${i.status}`),{ok:!1,status:i.status,data:m,failures:c}}catch{c.push(`${o}:network`)}return{ok:!1,status:0,data:{},failures:c}}const Np="V1:AESGCM:",tf="AES-GCM",KS=12;async function _g(e){const n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("Encryption key must be exactly 32 bytes (256-bit).");return crypto.subtle.importKey("raw",n,{name:tf},!1,["encrypt","decrypt"])}async function Of(e,n){if(!e)return e;const a=crypto.getRandomValues(new Uint8Array(KS)),s=await _g(n),c=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:tf,iv:a},s,c),l=Buffer.from(i).toString("base64"),m=Buffer.from(a).toString("base64");return`${Np}${m}:${l}`}async function $f(e,n){if(!e||!e.startsWith(Np))return e;const a=e.slice(Np.length),[s,o]=a.split(":");if(!s||!o)throw new Error("Malformed encrypted document payload.");const c=Buffer.from(s,"base64"),i=Buffer.from(o,"base64"),l=await _g(n);try{const m=await crypto.subtle.decrypt({name:tf,iv:c},l,i);return new TextDecoder("utf-8").decode(m)}catch(m){throw new Error(`Failed to decrypt document: ${m.message}`)}}var jc={};function Gr(e){return e&&typeof e=="object"?e:{}}function _s(e){const n=Number(e||0);return n===0||n===429||n>=500}function Uf(e,n){const a=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim();return a==="WORKSPACE_ID_ALREADY_EXISTS"||s.toLowerCase()==="workspace id already exists"?"This workspace is already linked to another cloud account. Sign in with the original account, ask the workspace owner to grant you access, or keep this workspace local-only.":s||`Workspace provisioning failed (${n})`}function ZS(e,n){if(n!==400)return!1;const a=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim().toLowerCase();return a==="WORKSPACE_ID_REQUIRED"&&s.includes("no cloud workspace is selected")}async function YS(e){if(!e.cloudAuthConfigured)return{success:!1,error:"Cloud auth endpoint is not configured."};if(e.runtimeMode!=="local")return{success:!1,error:"Workspace sync is only available in local runtime."};if(!e.isAuthenticated)return{success:!1,error:"Authentication required."};try{let n=await rp(e.resolveCloudAuthUrl,e.workspaceId);if(n.ok)return{success:!0,provisioned:!1};const a=Gr(n.data);if(n.status===401)return{success:!1,statusCode:401,transient:!1,error:String(a.error||"Authentication required for workspace sync.")};if(n.status===429)return{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,transient:!0,error:String(a.error||"Workspace sync rate limited. Please retry later.")};if(ZS(a,n.status)){const s=await Ff(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=Gr(s.data);return{success:!1,statusCode:s.status,transient:_s(s.status),retryAfterMs:s.retryAfterMs,error:Uf(o,s.status)}}if(n=await rp(e.resolveCloudAuthUrl,e.workspaceId),!n.ok){const o=Gr(n.data);return n.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:n.status===429?{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:n.status,transient:_s(n.status),error:String(o.error||`Workspace sync handshake failed (${n.status})`)}}return{success:!0,provisioned:!0}}if(n.status===409&&a.code==="WORKSPACE_ID_MISMATCH"){if(e.allowProvisionOnMismatch===!1)return{success:!1,statusCode:409,transient:!1,error:String(a.error||"Selected cloud workspace could not be attached to this local workspace.")};const s=await Ff(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=Gr(s.data);return{success:!1,statusCode:s.status,error:Uf(o,s.status)}}if(n=await rp(e.resolveCloudAuthUrl,e.workspaceId),!n.ok){const o=Gr(n.data);return n.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:n.status===429?{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:n.status,transient:_s(n.status),error:String(o.error||`Workspace sync handshake failed (${n.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:n.status,transient:_s(n.status),error:String(a.error||`Workspace sync handshake failed (${n.status})`)}}catch{return{success:!1,statusCode:0,transient:!0,error:"Failed to validate workspace sync access."}}}async function JS(e,n){const a=JSON.stringify([e,n]);try{const s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a));return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{let s=2166136261;for(let c=0;c<a.length;c+=1)s^=a.charCodeAt(c),s=Math.imul(s,16777619);const o=(s>>>0).toString(16).padStart(8,"0");return`${e}:fallback:${o}`}}async function XS(e){const n=e.payload.changes.length,a=e.payload.deleteTaskIds.size,s=await JS(e.workspaceId,e.payload.changes);let o=0,c=e.payload.changes;if(typeof process<"u"&&jc?.TASKFORCE_SYNC_KEY){const b=jc.TASKFORCE_SYNC_KEY,g=[];for(const h of c)h.op==="document-upsert"&&typeof h.content=="string"?g.push({...h,content:await Of(h.content,b)}):h.op==="asset-upsert"&&typeof h.contentBase64=="string"&&h.contentBase64.length>0?g.push({...h,contentBase64:await Of(h.contentBase64,b)}):g.push(h);c=g}const i=async()=>{const b=Date.now(),g=await VS(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,idempotencyKey:s,changes:c,repairMode:e.repairMode===!0});return o+=Date.now()-b,g};let l=await i();if(!l.ok&&(l.status===403||l.status===409)&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(l=await i()),!l.ok){const b=Gr(l.data);return{success:!1,status:l.status,error:typeof b.error=="string"?b.error:void 0,code:typeof b.code=="string"?b.code:void 0,retryAfterMs:l.retryAfterMs,transient:_s(l.status),requestMs:o,changeCount:n,deleteCount:a,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]}}const m=Gr(l.data),y=Array.isArray(m.emittedEventIds)?Array.from(new Set(m.emittedEventIds.map(b=>String(b||"").trim()).filter(Boolean))):[],v=Array.isArray(m.appliedTaskUpserts)?m.appliedTaskUpserts.map(b=>{const g=b&&typeof b=="object"?b:{},h=g.task&&typeof g.task=="object"?g.task:null,k=String(h?.id||"").trim();return!h||!k?null:{archived:g.archived===!0,task:h}}).filter(b=>!!b):[];return{success:!0,syncedAt:new Date().toISOString(),requestMs:o,changeCount:n,deleteCount:a,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:e.payload.pushedWatermarks,pushedTaskChangeKeys:e.payload.pushedTaskChangeKeys??new Map,emittedEventIds:y,appliedTaskUpserts:v}}async function QS(e){let n=e.cursor,a=!0,s=0,o=0,c=0,i=0;const l=new Set;let m=!1,y=!1,v=!1;const b=new Set,g=new Set,h=new Set;let k=null;const I=Number.isFinite(Number(e.maxPages))?Math.max(1,Math.floor(Number(e.maxPages))):20;try{for(;a&&s<I;){const x=async()=>{const oe=Date.now(),be=await GS(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:n,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0});return c+=Date.now()-oe,be};let A=await x();if(!A.ok&&A.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(A=await x()),!A.ok){const oe=Gr(A.data);return{success:!1,kind:"pull_http",status:A.status,errorCode:typeof oe.code=="string"?oe.code:void 0,error:typeof oe.error=="string"?oe.error:void 0,retryAfterMs:A.retryAfterMs,transient:_s(A.status),cursor:n,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),serverDiagnostics:null}}const M=A.data||{},B=Array.isArray(M?.changes)?M.changes:[],ue=M?.diagnostics&&typeof M.diagnostics=="object"?M.diagnostics:null;k=ue;const X=Array.isArray(M?.workspaceMembers),ce=X?M.workspaceMembers:void 0;for(const oe of B){if(oe.op==="upsert"){oe?.archived===!0||oe?.task?.isArchived===!0?y=!0:m=!0;continue}if(oe.op==="annotated-attachment-session-upsert"){const _=String(oe?.session?.id||"").trim();_&&h.add(_);continue}if(oe.op==="task-event-upsert"){v=!0;continue}if(oe.op==="document-upsert"){if(typeof oe.content=="string"&&typeof process<"u"&&jc?.TASKFORCE_SYNC_KEY)try{oe.content=await $f(oe.content,jc.TASKFORCE_SYNC_KEY)}catch{const _=String(oe.path||"").trim();_&&b.add(_)}continue}if(oe.op==="asset-upsert"){if(typeof oe.contentBase64=="string"&&typeof process<"u"&&jc?.TASKFORCE_SYNC_KEY)try{oe.contentBase64=await $f(oe.contentBase64,jc.TASKFORCE_SYNC_KEY)}catch{const _=String(oe.path||"").trim();_&&b.add(_)}continue}if(oe.op!=="delete")continue;const be=String(oe.taskId||"").trim();be&&l.add(be)}if(e.onPagePulled&&e.onPagePulled(),B.length>0||X){const oe=Date.now(),be=await Tp(e.workspaceId,B,{...X?{workspaceMembers:ce}:{},repairMode:e.repairMode===!0}),_=be.failures;if(!be.ok){i+=Date.now()-oe;const Q=Gr(be.data);if(_.some(P=>P.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:_,cursor:n,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),serverDiagnostics:ue};const H=_.some(P=>{if(P.endsWith(":network"))return!0;const U=P.split(":").pop()||"",se=Number.parseInt(U,10);return Number.isFinite(se)&&(se===429||se>=500)});return{success:!1,kind:"apply_all_candidates",status:be.status||void 0,transient:H,error:String(Q.error||"").trim()||void 0,failures:_,hasTransientApplyFailure:H,cursor:n,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(g),serverDiagnostics:k}}const J=Gr(be.data);if(J.success===!1)return i+=Date.now()-oe,{success:!1,kind:"apply_payload",transient:!1,error:String(J.error||"Workspace sync apply failed."),cursor:n,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(g),serverDiagnostics:k};if(i+=Date.now()-oe,o+=B.length,Array.isArray(J.emittedEventIds))for(const Q of J.emittedEventIds)g.add(String(Q));e.onChangesApplied&&e.onChangesApplied(B.length)}M&&"nextCursor"in M&&(M.nextCursor===null||typeof M.nextCursor=="string")&&(n=M.nextCursor),a=!!M?.hasMore,s+=1}if(e.bootstrap){const x=Date.now(),A=await Tp(e.workspaceId,[],{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(h)}}),M=A.failures;if(!A.ok){i+=Date.now()-x;const B=Gr(A.data);if(M.some(ce=>ce.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:M,cursor:n,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(g),serverDiagnostics:k};const X=M.some(ce=>{if(ce.endsWith(":network"))return!0;const oe=ce.split(":").pop()||"",be=Number.parseInt(oe,10);return Number.isFinite(be)&&(be===429||be>=500)});return{success:!1,kind:"apply_all_candidates",status:A.status||void 0,transient:X,error:String(B.error||"").trim()||void 0,failures:M,hasTransientApplyFailure:X,cursor:n,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(g),serverDiagnostics:k}}i+=Date.now()-x}return{success:!0,syncedAt:new Date().toISOString(),cursor:n||null,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(g),serverDiagnostics:k}}catch(x){return{success:!1,kind:"exception",status:0,transient:!0,error:String(x?.message||x||"Workspace sync pull failed unexpectedly."),cursor:n||null,pages:s,appliedChanges:o,pullRequestMs:c,applyMs:i,pulledDeleteTaskIds:l,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:v,documentDecryptFailures:Array.from(b),emittedEventIds:Array.from(g),serverDiagnostics:null}}}async function ev(e){const n=await zS(e.resolveCloudAuthUrl);if(!n.ok){const g=Number(n.status||0);return{success:!1,error:`Sync pull failed (${n.status})`,statusCode:n.status,retryAfterMs:n.retryAfterMs,transient:_s(g)}}const a=Gr(n.data),s=a.settings&&typeof a.settings=="object"?a.settings:{},o=typeof a.updatedAt=="string"&&a.updatedAt.trim().length>0?a.updatedAt.trim():null,c=e.getLocalUpdatedAt(e.userId),i=c?Date.parse(c):NaN,l=o?Date.parse(o):NaN;if(!c&&e.preferCloudOnFirstSync&&Number.isFinite(l))return await e.applyRemoteSettings(s),{success:!0,mode:"pulled",updatedAt:o};if(Number.isFinite(l)&&(!Number.isFinite(i)||l>i))return await e.applyRemoteSettings(s),{success:!0,mode:"pulled",updatedAt:o};const m=c||new Date().toISOString(),y=await HS(e.resolveCloudAuthUrl,{settings:e.buildLocalSettings(),updatedAt:m});if(!y.ok){const g=Number(y.status||0);return{success:!1,error:`Sync push failed (${y.status})`,statusCode:y.status,retryAfterMs:y.retryAfterMs,transient:_s(g)}}const v=Gr(y.data);return{success:!0,mode:"pushed",updatedAt:typeof v.updatedAt=="string"&&v.updatedAt.trim().length>0?v.updatedAt.trim():m}}function tv(e){const n=Math.max(1,Math.floor(Number(e)||1)),a=Math.min(12e4,1500*2**Math.max(0,n-1)),s=Math.floor(a*(.15*Math.random()));return a+s}const nv=["chat_app","ide","coding_tool","agent","other"],hF=["chat_app","ide","coding_tool","agent","other","unclassified"],av={chat_app:"Chat app",ide:"IDE",coding_tool:"Coding tool",agent:"Agent",other:"Other"},rv={chat_app:"Chat Apps",ide:"IDEs",coding_tool:"Coding Tools",agent:"Agents",other:"Other",unclassified:"Unclassified"};function sv(e){return typeof e=="string"&&nv.includes(e)}function Cg(e){if(typeof e!="string")return null;const n=e.trim();return sv(n)?n:null}function gF(e){return av[e]}function yF(e){return e??"unclassified"}function kF(e){return rv[e]}const ov=["cloud_metered","local_unmetered"],iv={cloud_metered:"Cloud MCP",local_unmetered:"Local MCP"};function cv(e){return typeof e=="string"&&ov.includes(e)}function Ag(e){if(typeof e!="string")return null;const n=e.trim();return cv(n)?n:null}function SF(e){return iv[e]}function Oo(e){if(e==null)return;const n=String(e).trim();return n.length>0?n:void 0}function ca(e){if(e==null)return null;const n=String(e).trim();return n.length>0?n:null}function ud(e){return Oo(e)}function Qu(e){return ca(e)}function ds(e){return ca(e)}function $c(e){const n=ca(e);return n&&n.startsWith("/api/taskforce/context/")?n:null}function Au(e){return Oo(e)}function Iu(e){if(e!==void 0)return ca(e)}function lv(e){return typeof e=="boolean"?e:void 0}function Tu(e,n){if(e===void 0)return;if(e===null||e==="")return n?.nullable?null:void 0;const a=typeof e=="number"?e:Number(e);if(!Number.isFinite(a))return n?.nullable?null:void 0;const s=Math.floor(a);return Number.isFinite(n?.min)&&s<Number(n?.min)?n?.nullable?null:void 0:s}function dv(e){if(!e||typeof e!="object"||Array.isArray(e))return;const a=Object.entries(e).reduce((s,[o,c])=>Array.isArray(c)?(s[o]=c.map(i=>String(i??"")),s):(c==null||(s[o]=String(c)),s),{});return Object.keys(a).length>0?a:{}}function uv(e){return Array.isArray(e)?e:void 0}function mv(e){return Array.isArray(e)?e:void 0}function pv(e){return Array.isArray(e)?e:void 0}function Ig(e){const n=e&&typeof e=="object"?e:{};return{id:String(n.id||"").trim(),title:String(n.title||"").trim(),description:n.description===void 0?void 0:n.description||null,status:String(n.status||"task").trim()||"task",priority:Tu(n.priority,{min:1})??void 0,complexity:Tu(n.complexity,{min:1,nullable:!0}),type:String(n.type||"").trim(),category:String(n.category||"").trim(),approach:Au(n.approach),canceledReason:n.canceledReason===void 0?void 0:n.canceledReason||null,createdAt:String(n.createdAt||"").trim(),updatedAt:Au(n.updatedAt),completedAt:n.completedAt===void 0?void 0:n.completedAt||null,isArchived:lv(n.isArchived),taxonomies:dv(n.taxonomies),createdBy:Au(n.createdBy),assignee:Au(n.assignee),scheduledDate:Iu(n.scheduledDate),dueDate:Iu(n.dueDate),scheduledWeekKey:Iu(n.scheduledWeekKey),orderInDay:Tu(n.orderInDay,{min:0,nullable:!0}),workstreamId:Iu(n.workstreamId),referenceNumber:Tu(n.referenceNumber,{min:1,nullable:!0}),comments:uv(n.comments),attachments:mv(n.attachments),checklistItems:pv(n.checklistItems)}}function fv(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const n=Object.entries(e).filter(([s])=>String(s||"").trim().length>0).sort(([s],[o])=>s.localeCompare(o)),a={};for(const[s,o]of n){if(Array.isArray(o)){a[s]=o.map(c=>String(c??"")).sort((c,i)=>c.localeCompare(i));continue}o!=null&&(a[s]=String(o))}return a}function hv(e){return Array.isArray(e)?e.map(n=>{const a=n&&typeof n=="object"?n:{};return{id:String(a.id||"").trim(),title:String(a.title||"").trim(),isCompleted:!!a.isCompleted,order:a.order===void 0||a.order===null?"":String(a.order)}}).sort((n,a)=>{const s=Number.parseInt(n.order,10),o=Number.parseInt(a.order,10);return Number.isFinite(s)&&Number.isFinite(o)&&s!==o?s-o:n.title!==a.title?n.title.localeCompare(a.title):n.id.localeCompare(a.id)}):[]}function gv(e){return Array.isArray(e)?e.map(n=>{const a=n&&typeof n=="object"?n:null;return{id:String(a?.id||"").trim(),author:String(a?.author||"").trim(),submittedAuthor:Oo(a?.submittedAuthor)||"",text:String(a?.text||""),timestamp:ds(a?.timestamp)||"",actor:a?.actor??null}}).sort((n,a)=>n.timestamp!==a.timestamp?n.timestamp.localeCompare(a.timestamp):n.id!==a.id?n.id.localeCompare(a.id):n.author!==a.author?n.author.localeCompare(a.author):n.text.localeCompare(a.text)):[]}function yv(e){return Array.isArray(e)?e.map(n=>{if(typeof n=="string")return{path:n.trim(),fsPath:"",caption:"",displayName:"",originalFilename:"",assetId:"",referenceNumber:"",taskId:"",timestamp:""};const a=n&&typeof n=="object"?n:null;return{path:String(a?.path||"").trim(),fsPath:Oo(a?.fsPath)||"",caption:Oo(a?.caption)||"",displayName:Oo(a?.displayName)||"",originalFilename:Oo(a?.originalFilename)||"",assetId:ud(a?.assetId)||"",referenceNumber:a?.referenceNumber===void 0||a.referenceNumber===null?"":String(a.referenceNumber),taskId:Qu(a?.taskId)||"",timestamp:ds(a?.timestamp)||""}}).sort((n,a)=>n.path!==a.path?n.path.localeCompare(a.path):n.assetId!==a.assetId?n.assetId.localeCompare(a.assetId):n.timestamp!==a.timestamp?n.timestamp.localeCompare(a.timestamp):JSON.stringify(n).localeCompare(JSON.stringify(a))):[]}function kv(e,n){const a=Ig(e);return JSON.stringify({id:a.id,title:a.title,description:ca(a.description)||"",category:a.category,type:a.type,priority:a.priority===void 0||a.priority===null?"":String(a.priority),complexity:a.complexity===void 0||a.complexity===null?"":String(a.complexity),status:a.status,approach:Oo(a.approach)||"",canceledReason:ca(a.canceledReason)||"",createdAt:a.createdAt,completedAt:ds(a.completedAt)||"",taxonomies:fv(a.taxonomies),createdBy:ud(a.createdBy)||"",assignee:ud(a.assignee)||"",scheduledDate:ca(a.scheduledDate)||"",dueDate:ca(a.dueDate)||"",scheduledWeekKey:ca(a.scheduledWeekKey)||"",orderInDay:a.orderInDay===void 0||a.orderInDay===null?"":String(a.orderInDay),workstreamId:Qu(a.workstreamId)||"",referenceNumber:a.referenceNumber===void 0||a.referenceNumber===null?"":String(a.referenceNumber),comments:gv(a.comments),attachments:yv(a.attachments),checklistItems:hv(a.checklistItems),isArchived:n?"1":"0"})}function Sv(...e){return e.reduce((n,a)=>{const s=ds(a)||"";return n?s&&s>n?s:n:s},"")}function vv(e){const n=e||{};return Sv(n.createdAt,n.updatedAt,n.lastActiveAt,n.archivedAt,n.rosterStateUpdatedAt)}function bv(e){const n=e||{};return JSON.stringify({id:String(n.id||"").trim(),workspaceId:String(n.workspaceId||"").trim(),profileToken:String(n.profileToken||"").trim(),name:String(n.name||"").trim(),username:String(n.username||"").trim(),icon:String(n.icon||"Bot").trim()||"Bot",color:String(n.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:$c(n.avatarUrl)||"",avatarSourceUrl:$c(n.avatarSourceUrl)||"",description:ca(n.description)||"",role:ca(n.role)||"",provider:ca(n.provider)||"",model:ca(n.model)||"",surfaceType:ca(n.surfaceType)||"",seatScope:ca(n.seatScope)||"",providerMetadata:n.providerMetadata&&typeof n.providerMetadata=="object"&&!Array.isArray(n.providerMetadata)?n.providerMetadata:null,archivedAt:ds(n.archivedAt)||"",archivedBy:ud(n.archivedBy)||"",archivedReason:ca(n.archivedReason)||"",mergedIntoProfileId:ud(n.mergedIntoProfileId)||"",rosterStateUpdatedAt:ds(n.rosterStateUpdatedAt)||"",createdAt:ds(n.createdAt)||"",updatedAt:ds(n.updatedAt)||"",lastActiveAt:ds(n.lastActiveAt)||""})}const ls={kind:"task",getId:e=>String(e?.id||"").trim(),getWatermark:e=>String(e?.updatedAt||e?.createdAt||"").trim(),getChangeKey:e=>kv(e,!!e?.isArchived)},rd={kind:"ai-profile",getId:e=>String(e?.id||"").trim(),getWatermark:e=>vv(e),getChangeKey:e=>bv(e)};function qf(e,n,a){const s=e.getId(n);if(!s)return!1;const o=e.getChangeKey(n),c=a?.watermarks;if(!c||c.size===0||!c.has(s))return!0;const l=a?.changeKeys?.get(s);return typeof l=="string"?l!==o:(c.get(s)||"")!==o}function zf(e){return Ig(e)}function Hf(e,n){const a=e??n;return new Set(Array.from(a).map(s=>String(s||"").trim()).filter(s=>s.length>0))}function wv(e){return[...e].sort((n,a)=>{const s=String(n?.createdAt||"").trim(),o=String(a?.createdAt||"").trim(),c=s.localeCompare(o);return c!==0?c:String(n?.id||"").trim().localeCompare(String(a?.id||"").trim())})}function Gf(e){return[...e].sort((n,a)=>{const s=String(n?.id||"").trim(),o=String(a?.id||"").trim();return s.localeCompare(o)})}function xv(e){const n=new Date().toISOString(),a=new Set(Array.from(e.pendingDeletedTaskIds).map(d=>String(d||"").trim()).filter(d=>d.length>0)),s=new Map(Array.from(e.pendingDeletedTaskWatermarks||new Map).map(([d,Me])=>[String(d||"").trim(),String(Me||"").trim()]).filter(([d,Me])=>d.length>0&&Number.isFinite(Date.parse(Me)))),o=e.lastPushedWatermarks,c=e.lastPushedTaskChangeKeys,i=(d,Me)=>(d?.referenceNumber===void 0||d?.referenceNumber===null)&&Number.isFinite(Number(d?.localReferenceNumber))?!0:qf(ls,{...d,isArchived:Me},{watermarks:o,changeKeys:c}),l=Gf(e.tasks||[]),m=Gf(e.archivedTasks||[]),y=new Map,v=new Map,b=new Map,g=new Map,h=l.filter(d=>!a.has(String(d?.id||"").trim())&&i(d,!1)).map(d=>{const Me=String(d?.id||"").trim(),We=ls.getWatermark(d),Qe=ls.getChangeKey({...d,isArchived:!1});return Me&&(b.set(Me,We),g.set(Me,Qe)),{op:"upsert",archived:!1,task:zf(d)}}),k=m.filter(d=>!a.has(String(d?.id||"").trim())&&i(d,!0)).map(d=>{const Me=String(d?.id||"").trim(),We=ls.getWatermark(d),Qe=ls.getChangeKey({...d,isArchived:!0});return Me&&(b.set(Me,We),g.set(Me,Qe)),{op:"upsert",archived:!0,task:zf(d)}}),I=new Set;for(const d of e.tasks||[]){const Me=String(d?.id||"").trim();Me&&(I.add(Me),y.set(Me,ls.getWatermark(d)),v.set(Me,ls.getChangeKey({...d,isArchived:!1})))}for(const d of e.archivedTasks||[]){const Me=String(d?.id||"").trim();Me&&(I.add(Me),y.set(Me,ls.getWatermark(d)),v.set(Me,ls.getChangeKey({...d,isArchived:!0})))}const x=Array.from(e.lastPushedTaskIds).filter(d=>!I.has(d)).map(d=>({op:"delete",taskId:d,deletedAt:s.get(d)||n})),A=Array.from(a).map(d=>({op:"delete",taskId:d,deletedAt:s.get(d)||n})),M=new Set([...x.map(d=>String(d.taskId)),...A.map(d=>String(d.taskId))]),B=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),ue=new Map((Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),X=e.lastPushedInitiativeWatermarks,ce=!X||X.size===0,oe=(Array.isArray(e.initiatives)?e.initiatives:[]).map(d=>({op:"initiative-upsert",initiative:{id:String(d?.id||"").trim(),referenceNumber:Number.isFinite(Number(d?.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,referenceLabel:typeof d?.referenceLabel=="string"&&d.referenceLabel.trim().length>0?d.referenceLabel.trim():void 0,title:String(d?.title||"").trim(),description:typeof d?.description=="string"?d.description:null,ownerId:typeof d?.ownerId=="string"&&d.ownerId.trim().length>0?d.ownerId.trim():null,createdAt:String(d?.createdAt||"").trim(),updatedAt:String(d?.updatedAt||d?.createdAt||"").trim(),order:Number.isFinite(Number(d?.order))?Math.floor(Number(d.order)):null,isArchived:!!d?.isArchived}})).filter(d=>d.initiative.id.length>0).filter(d=>ce?!0:X.get(d.initiative.id)!==d.initiative.updatedAt),be=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),_=new Map((Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),J=e.lastPushedWorkstreamWatermarks,Q=!J||J.size===0,ie=(Array.isArray(e.workstreams)?e.workstreams:[]).map(d=>({op:"workstream-upsert",workstream:{id:String(d?.id||"").trim(),referenceNumber:Number.isFinite(Number(d?.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,referenceLabel:typeof d?.referenceLabel=="string"&&d.referenceLabel.trim().length>0?d.referenceLabel.trim():void 0,initiativeId:typeof d?.initiativeId=="string"&&d.initiativeId.trim().length>0?d.initiativeId.trim():null,title:String(d?.title||"").trim(),description:typeof d?.description=="string"?d.description:null,ownerId:typeof d?.ownerId=="string"&&d.ownerId.trim().length>0?d.ownerId.trim():null,createdAt:String(d?.createdAt||"").trim(),updatedAt:String(d?.updatedAt||d?.createdAt||"").trim(),order:Number.isFinite(Number(d?.order))?Math.floor(Number(d.order)):null,isArchived:!!d?.isArchived}})).filter(d=>d.workstream.id.length>0).filter(d=>Q?!0:J.get(d.workstream.id)!==d.workstream.updatedAt),H=new Set((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),P=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>[String(d?.id||"").trim(),rd.getWatermark(d)]).filter(([d])=>d.length>0)),U=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>[String(d?.id||"").trim(),rd.getChangeKey(d)]).filter(([d])=>d.length>0)),se=e.lastPushedAiProfileWatermarks,he=e.lastPushedAiProfileChangeKeys,V=!se||se.size===0,Ce=(Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(d=>({op:"ai-profile-upsert",profile:{id:String(d.id||"").trim(),workspaceId:String(d.workspaceId||"").trim(),profileToken:String(d.profileToken||"").trim(),name:String(d.name||"").trim(),username:String(d.username||"").trim(),icon:String(d.icon||"Bot").trim()||"Bot",color:String(d.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:$c(d.avatarUrl),avatarSourceUrl:$c(d.avatarSourceUrl),description:typeof d.description=="string"&&d.description.trim()||null,role:typeof d.role=="string"&&d.role.trim()||null,provider:typeof d.provider=="string"&&d.provider.trim()||null,model:typeof d.model=="string"&&d.model.trim()||null,surfaceType:Cg(d.surfaceType),seatScope:Ag(d.seatScope),providerMetadata:d.providerMetadata&&typeof d.providerMetadata=="object"&&!Array.isArray(d.providerMetadata)?d.providerMetadata:null,archivedAt:typeof d.archivedAt=="string"&&d.archivedAt.trim().length>0?d.archivedAt.trim():null,archivedBy:typeof d.archivedBy=="string"&&d.archivedBy.trim().length>0?d.archivedBy.trim():null,archivedReason:typeof d.archivedReason=="string"&&d.archivedReason.trim()||null,mergedIntoProfileId:typeof d.mergedIntoProfileId=="string"&&d.mergedIntoProfileId.trim().length>0?d.mergedIntoProfileId.trim():null,rosterStateUpdatedAt:typeof d.rosterStateUpdatedAt=="string"&&d.rosterStateUpdatedAt.trim().length>0?d.rosterStateUpdatedAt.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),lastActiveAt:typeof d.lastActiveAt=="string"&&d.lastActiveAt.trim().length>0?d.lastActiveAt.trim():null}})).filter(d=>d.profile.id.length>0&&d.profile.workspaceId.length>0).filter(d=>V?!0:qf(rd,d.profile,{watermarks:se,changeKeys:he})),Se=Hf(e.currentDocumentPaths,(Array.isArray(e.documents)?e.documents:[]).map(d=>String(d?.path||"").trim())),ve=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!Se.has(d))),ge=new Map((Array.isArray(e.documents)?e.documents:[]).map(d=>[String(d?.path||"").trim(),String(d?.updatedAt||"").trim()]).filter(([d])=>d.length>0)),Te=e.lastPushedDocumentWatermarks,Le=!Te||Te.size===0,Ie=(Array.isArray(e.documents)?e.documents:[]).map(d=>({op:"document-upsert",path:String(d.path||"").trim(),updatedAt:String(d.updatedAt||"").trim(),content:typeof d.content=="string"?d.content:"",assetId:typeof d.assetId=="string"&&d.assetId.trim().length>0?d.assetId.trim():void 0,documentId:typeof d.documentId=="string"&&d.documentId.trim().length>0?d.documentId.trim():null,referenceNumber:Number.isFinite(Number(d.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,version:Number.isFinite(Number(d.version))?Math.max(1,Math.floor(Number(d.version))):null,taskId:typeof d.taskId=="string"&&d.taskId.trim().length>0?d.taskId.trim():null,logicalName:typeof d.logicalName=="string"&&d.logicalName.trim().length>0?d.logicalName.trim():null,caption:typeof d.caption=="string"&&d.caption.trim().length>0?d.caption.trim():null,originalFilename:typeof d.originalFilename=="string"&&d.originalFilename.trim().length>0?d.originalFilename.trim():null,linkRole:d.linkRole==="reference"?"reference":"attachment"})).filter(d=>d.path.length>0).filter(d=>Le?!0:Te.get(d.path)!==d.updatedAt),Oe=Hf(e.currentAssetPaths,(Array.isArray(e.assets)?e.assets:[]).map(d=>String(d?.path||"").trim())),z=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!Oe.has(d))),T=new Map((Array.isArray(e.assets)?e.assets:[]).map(d=>[String(d?.path||"").trim(),String(d?.updatedAt||"").trim()]).filter(([d])=>d.length>0)),w=e.lastPushedAssetWatermarks,j=!w||w.size===0,F=(Array.isArray(e.assets)?e.assets:[]).map(d=>({op:"asset-upsert",path:String(d.path||"").trim(),updatedAt:String(d.updatedAt||"").trim(),contentBase64:typeof d.contentBase64=="string"?d.contentBase64:"",assetId:typeof d.assetId=="string"&&d.assetId.trim().length>0?d.assetId.trim():void 0,kind:d.kind==="image"?"image":"file",mimeType:typeof d.mimeType=="string"&&d.mimeType.trim().length>0?d.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(d.referenceNumber))?Math.max(1,Math.floor(Number(d.referenceNumber))):null,taskId:typeof d.taskId=="string"&&d.taskId.trim().length>0?d.taskId.trim():null,logicalName:typeof d.logicalName=="string"&&d.logicalName.trim().length>0?d.logicalName.trim():null,caption:typeof d.caption=="string"&&d.caption.trim().length>0?d.caption.trim():null,originalFilename:typeof d.originalFilename=="string"&&d.originalFilename.trim().length>0?d.originalFilename.trim():null,linkRole:d.linkRole==="reference"?"reference":d.linkRole==="image"?"image":"attachment"})).filter(d=>d.path.length>0&&d.contentBase64.length>0).filter(d=>j?!0:w.get(d.path)!==d.updatedAt),ee=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],N=new Set(ee.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),C=new Set([...Array.from(e.lastPushedDocumentReviewSessionIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!N.has(d)),...ee.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),$=new Map(ee.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),K=e.lastPushedDocumentReviewSessionWatermarks,te=!K||K.size===0,L=ee.map(d=>({op:"document-review-session-upsert",session:{id:String(d.id||"").trim(),assetId:String(d.assetId||"").trim(),documentId:typeof d.documentId=="string"&&d.documentId.trim().length>0?d.documentId.trim():null,documentVersion:Number.isFinite(Number(d.documentVersion))?Math.max(1,Math.floor(Number(d.documentVersion))):null,title:typeof d.title=="string"&&d.title.trim().length>0?d.title.trim():null,status:d.status==="resolved"?"resolved":"open",comments:[],createdByActorId:typeof d.createdByActorId=="string"&&d.createdByActorId.trim().length>0?d.createdByActorId.trim():null,updatedByActorId:typeof d.updatedByActorId=="string"&&d.updatedByActorId.trim().length>0?d.updatedByActorId.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),deletedAt:typeof d.deletedAt=="string"&&d.deletedAt.trim().length>0?d.deletedAt.trim():null}})).filter(d=>d.session.id.length>0&&d.session.assetId.length>0&&!d.session.deletedAt).filter(d=>te?!0:K.get(d.session.id)!==d.session.updatedAt),re=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],fe=new Set(re.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),xe=new Set([...Array.from(e.lastPushedDocumentReviewCommentIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!fe.has(d)),...re.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),le=new Map(re.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),we=e.lastPushedDocumentReviewCommentWatermarks,Re=!we||we.size===0,Xe=re.map(d=>({op:"document-review-comment-upsert",comment:{id:String(d.id||"").trim(),sessionId:String(d.sessionId||"").trim(),body:String(d.body||"").trim(),anchor:d.anchor??null,order:Number.isFinite(Number(d.order))?Math.max(0,Math.floor(Number(d.order))):0,authorActorId:typeof d.authorActorId=="string"&&d.authorActorId.trim().length>0?d.authorActorId.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),deletedAt:typeof d.deletedAt=="string"&&d.deletedAt.trim().length>0?d.deletedAt.trim():null}})).filter(d=>d.comment.id.length>0&&d.comment.sessionId.length>0&&!d.comment.deletedAt).filter(d=>Re?!0:we.get(d.comment.id)!==d.comment.updatedAt),ze=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],lt=new Set(ze.filter(d=>String(d?.deletedAt||"").trim().length===0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)),wt=new Set([...Array.from(e.lastPushedAnnotatedAttachmentSessionIds||new Set).map(d=>String(d||"").trim()).filter(d=>d.length>0&&!lt.has(d)),...ze.filter(d=>String(d?.deletedAt||"").trim().length>0).map(d=>String(d?.id||"").trim()).filter(d=>d.length>0)]),$e=new Map(ze.map(d=>[String(d?.id||"").trim(),String(d?.updatedAt||d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),ft=e.lastPushedAnnotatedAttachmentSessionWatermarks,gt=!ft||ft.size===0,at=ze.map(d=>({op:"annotated-attachment-session-upsert",session:{id:String(d.id||"").trim(),workspaceId:String(d.workspaceId||"").trim(),taskId:String(d.taskId||"").trim(),baseImageAssetId:String(d.baseImageAssetId||"").trim(),title:typeof d.title=="string"&&d.title.trim().length>0?d.title.trim():null,globalInstruction:typeof d.globalInstruction=="string"&&d.globalInstruction.trim().length>0?d.globalInstruction.trim():null,annotations:Array.isArray(d.annotations)?d.annotations:[],createdByActorId:typeof d.createdByActorId=="string"&&d.createdByActorId.trim().length>0?d.createdByActorId.trim():null,updatedByActorId:typeof d.updatedByActorId=="string"&&d.updatedByActorId.trim().length>0?d.updatedByActorId.trim():null,createdAt:String(d.createdAt||"").trim(),updatedAt:String(d.updatedAt||d.createdAt||"").trim(),deletedAt:typeof d.deletedAt=="string"&&d.deletedAt.trim().length>0?d.deletedAt.trim():null}})).filter(d=>d.session.id.length>0&&d.session.workspaceId.length>0&&d.session.baseImageAssetId.length>0&&!d.session.deletedAt).filter(d=>gt?!0:ft.get(d.session.id)!==d.session.updatedAt),dt=wv(Array.isArray(e.taskEvents)?e.taskEvents:[]),ne=new Map(dt.map(d=>[String(d?.id||"").trim(),String(d?.createdAt||"").trim()]).filter(([d])=>d.length>0)),tt=e.lastPushedTaskEventWatermarks,rt=!tt||tt.size===0,Pt=dt.map(d=>({op:"task-event-upsert",event:{id:String(d.id||"").trim(),taskId:String(d.taskId||"").trim(),workspaceId:String(d.workspaceId||"").trim(),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&&typeof d.details=="object"&&!Array.isArray(d.details)?d.details:{},createdAt:String(d.createdAt||"").trim()}})).filter(d=>d.event.id.length>0&&d.event.taskId.length>0&&d.event.workspaceId.length>0&&d.event.action.length>0&&Number.isFinite(Date.parse(d.event.createdAt))).filter(d=>rt?!0:tt.get(d.event.id)!==d.event.createdAt),yt=[...oe,...ie,...e.taxonomyState&&typeof e.taxonomyState=="object"?[{op:"taxonomy-upsert",taxonomyState:e.taxonomyState,updatedAt:n}]:Array.isArray(e.taxonomies)?[{op:"taxonomy-upsert",taxonomies:e.taxonomies,updatedAt:n}]:[],...Ce,...Ie,...Array.from(ve).map(d=>({op:"document-delete",path:d,deletedAt:n})),...F,...Array.from(z).map(d=>({op:"asset-delete",path:d,deletedAt:n})),...L,...Array.from(C).map(d=>({op:"document-review-session-delete",sessionId:d,deletedAt:n})),...Xe,...Array.from(xe).map(d=>({op:"document-review-comment-delete",commentId:d,deletedAt:n})),...at,...Array.from(wt).map(d=>({op:"annotated-attachment-session-delete",sessionId:d,deletedAt:n})),...Pt,...h,...k,...Array.from(M).map(d=>({op:"delete",taskId:d,deletedAt:s.get(d)||n}))],Rt=e.baselineResetReason??null,Tt=d=>{const Me=d.upsertCount+(d.deleteCount||0);if(d.currentCount===0&&Me===0)return{mode:"none",reason:null,currentCount:0,baselineCount:d.baselineCount,changeCount:Me};if(d.alwaysFull)return{mode:Me>0?"send-all":"none",reason:Me>0?"full-state-domain":null,currentCount:d.currentCount,baselineCount:d.baselineCount,changeCount:Me};const We=d.baselineCount===0&&d.currentCount>0&&d.upsertCount>=d.currentCount;return{mode:We?"send-all":"delta",reason:We?Rt||"missing-baseline":null,currentCount:d.currentCount,baselineCount:d.baselineCount,changeCount:Me}},Dt=yt.reduce((d,Me)=>{const We=String(Me.op||"").trim();return d[We]=(d[We]||0)+1,d},{});return{changes:yt,currentTaskIds:new Set(Array.from(I).filter(d=>!a.has(d))),currentTaskWatermarks:new Map(Array.from(y.entries()).filter(([d])=>!a.has(d))),currentTaskChangeKeys:new Map(Array.from(v.entries()).filter(([d])=>!a.has(d))),deleteTaskIds:M,currentInitiativeIds:B,currentInitiativeWatermarks:ue,currentWorkstreamIds:be,currentWorkstreamWatermarks:_,currentAiProfileIds:H,currentAiProfileWatermarks:P,currentAiProfileChangeKeys:U,currentDocumentPaths:Se,deleteDocumentPaths:ve,currentDocumentWatermarks:ge,currentAssetPaths:Oe,deleteAssetPaths:z,currentAssetWatermarks:T,currentDocumentReviewSessionIds:N,deleteDocumentReviewSessionIds:C,currentDocumentReviewSessionWatermarks:$,currentDocumentReviewCommentIds:fe,deleteDocumentReviewCommentIds:xe,currentDocumentReviewCommentWatermarks:le,currentAnnotatedAttachmentSessionIds:lt,deleteAnnotatedAttachmentSessionIds:wt,currentAnnotatedAttachmentSessionWatermarks:$e,currentTaskEventWatermarks:ne,pushedWatermarks:b,pushedTaskChangeKeys:g,deltaDiagnostics:{totalChanges:yt.length,byOp:Dt,baselineResetReason:Rt,domains:{tasks:Tt({currentCount:I.size,baselineCount:o?.size||0,upsertCount:h.length+k.length,deleteCount:M.size}),initiatives:Tt({currentCount:B.size,baselineCount:X?.size||0,upsertCount:oe.length}),workstreams:Tt({currentCount:be.size,baselineCount:J?.size||0,upsertCount:ie.length}),aiProfiles:Tt({currentCount:H.size,baselineCount:se?.size||0,upsertCount:Ce.length}),documents:Tt({currentCount:Se.size,baselineCount:Te?.size||0,upsertCount:Ie.length,deleteCount:ve.size}),assets:Tt({currentCount:Oe.size,baselineCount:w?.size||0,upsertCount:F.length,deleteCount:z.size}),documentReviewSessions:Tt({currentCount:N.size,baselineCount:K?.size||0,upsertCount:L.length,deleteCount:C.size}),documentReviewComments:Tt({currentCount:fe.size,baselineCount:we?.size||0,upsertCount:Xe.length,deleteCount:xe.size}),annotatedAttachmentSessions:Tt({currentCount:lt.size,baselineCount:ft?.size||0,upsertCount:at.length,deleteCount:wt.size}),taskEvents:Tt({currentCount:ne.size,baselineCount:tt?.size||0,upsertCount:Pt.length}),taxonomy:Tt({currentCount:e.taxonomyState&&typeof e.taxonomyState=="object"||Array.isArray(e.taxonomies)?1:0,baselineCount:0,upsertCount:Dt["taxonomy-upsert"]||0,alwaysFull:!0})}}}}function _v(e){const n=(e.tasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),a=(e.archivedTasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),s=e.pendingDeletedTaskIds?Array.from(e.pendingDeletedTaskIds).sort():[],o=(e.initiatives||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,l)=>i.id.localeCompare(l.id)),c=(e.workstreams||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),initiativeId:typeof i.initiativeId=="string"?i.initiativeId.trim():"",title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,l)=>i.id.localeCompare(l.id));return JSON.stringify({workspaceId:e.workspaceId,initiatives:o,workstreams:c,taxonomyState:e.taxonomyState&&typeof e.taxonomyState=="object"?e.taxonomyState:null,taxonomies:Array.isArray(e.taxonomies)?e.taxonomies:[],aiProfiles:Array.isArray(e.aiProfiles)?e.aiProfiles.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),name:String(i.name||"").trim(),username:String(i.username||"").trim(),archivedAt:String(i.archivedAt||"").trim(),archivedReason:String(i.archivedReason||"").trim(),mergedIntoProfileId:String(i.mergedIntoProfileId||"").trim(),rosterStateUpdatedAt:String(i.rosterStateUpdatedAt||"").trim()})).filter(i=>i.id.length>0).sort((i,l)=>i.id.localeCompare(l.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,l)=>i.id.localeCompare(l.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,l)=>i.path.localeCompare(l.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,l)=>i.path.localeCompare(l.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,l)=>i.id.localeCompare(l.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,l)=>i.id.localeCompare(l.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,l)=>i.id.localeCompare(l.id)):[],active:n,archived:a,pendingDeletes:s})}function $u(){return{version:2,enabled:!1,phase:"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null,pushBaseline:null}}function Wo(e){const n=String(e||"").trim();return n.length>0?n:null}function Vf(e){return String(e||"").trim().toLowerCase()==="attach-cloud-import"?"attach-cloud-import":null}function Cv(e){if(!Array.isArray(e)||e.length<2)return null;const n=String(e[0]||"").trim(),a=String(e[1]||"").trim();return!n||!a?null:[n,a]}function Av(e){return Array.isArray(e)?e.map(n=>String(n||"").trim()).filter(n=>n.length>0):[]}function Kf(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,a=s=>Array.isArray(n[s])?n[s].map(o=>Cv(o)).filter(o=>Array.isArray(o)):[];return{taskIds:Av(n.taskIds),taskWatermarks:a("taskWatermarks"),taskChangeKeys:a("taskChangeKeys"),initiativeWatermarks:a("initiativeWatermarks"),workstreamWatermarks:a("workstreamWatermarks"),aiProfileWatermarks:a("aiProfileWatermarks"),aiProfileChangeKeys:a("aiProfileChangeKeys"),documentWatermarks:a("documentWatermarks"),assetWatermarks:a("assetWatermarks"),documentReviewSessionWatermarks:a("documentReviewSessionWatermarks"),documentReviewCommentWatermarks:a("documentReviewCommentWatermarks"),annotatedAttachmentSessionWatermarks:a("annotatedAttachmentSessionWatermarks"),taskEventWatermarks:a("taskEventWatermarks"),taxonomyStateFingerprint:String(n.taxonomyStateFingerprint||"").trim()}}function Iv(e,n){if(!!!(e.enabled??e.cloudSyncEnabled))return"idle";const s=String(e.phase||"").trim().toLowerCase();if(s==="idle"||s==="provision-local"||s==="attach-cloud"||s==="active"||s==="error")return s;const o=String(e.bootstrapMode||"").trim().toLowerCase();if(o==="provision-local"||o==="attach-cloud")return o;const c=String(e.sourceOfTruth||"").trim().toLowerCase();return e.onboardingCompleted?"active":c==="cloud"?n.lastPullAt?"active":"attach-cloud":c==="local"?n.lastPullAt||n.lastPushAt?"active":"provision-local":(n.lastPullAt||n.lastPushAt,"active")}function Tv(e){const n=$u();if(!e||typeof e!="object")return{state:n,changed:!1};const a=e,s=a.lastErrorMessage,o=typeof s=="string"&&s.trim().length>0?s:null,c={version:2,enabled:!!(a.enabled??a.cloudSyncEnabled),phase:"idle",setupIntent:Vf(a.setupIntent),pullCursor:Wo(a.pullCursor),lastPullAt:Wo(a.lastPullAt),lastPushAt:Wo(a.lastPushAt),lastSyncedAt:Wo(a.lastSyncedAt),lastErrorMessage:o,pushBaseline:Kf(a.pushBaseline)};c.phase=Iv(a,c),c.enabled||(c.phase="idle",c.pullCursor=null);const l=Number(a.version||0)!==2||!!(a.enabled??a.cloudSyncEnabled)!==c.enabled||String(a.phase||"").trim()!==c.phase||Vf(a.setupIntent)!==c.setupIntent||Wo(a.pullCursor)!==c.pullCursor||Wo(a.lastPullAt)!==c.lastPullAt||Wo(a.lastPushAt)!==c.lastPushAt||Wo(a.lastSyncedAt)!==c.lastSyncedAt||o!==c.lastErrorMessage||JSON.stringify(Kf(a.pushBaseline))!==JSON.stringify(c.pushBaseline);return{state:c,changed:l}}const Nv="taskforce.sync.lease.v1",Rv="taskforce.sync.lease.v1",jv=2500,Pv=9e3;function Vl(e){const n=String(e||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function Nu(e){const n=String(e||"").trim();return n.length>0?n:null}function sp(e){return`${Nv}.${e}`}function Ev(e){if(!e)return null;try{const n=JSON.parse(e),a=String(n?.ownerId||"").trim(),s=String(n?.workspaceId||"").trim(),o=String(n?.operation||"").trim(),c=String(n?.heartbeatAt||"").trim(),i=String(n?.expiresAt||"").trim();return!a||!s||!c||!i||o!=="pull"&&o!=="push"&&o!=="repair"?null:{ownerId:a,workspaceId:s,operation:o,heartbeatAt:c,expiresAt:i}}catch{return null}}function Mv(e,n,a,s){return{ownerId:e,workspaceId:n,operation:a,heartbeatAt:new Date(s).toISOString(),expiresAt:new Date(s+Pv).toISOString()}}function Dv(e,n=Date.now()){if(!e)return!0;const a=Date.parse(e.expiresAt);return!Number.isFinite(a)||a<=n}function op(e,n){const a={...e,...n,version:2,phase:n.phase||e.phase,setupIntent:n.setupIntent===void 0?e.setupIntent??null:n.setupIntent??null,pullCursor:n.pullCursor===void 0?e.pullCursor:Nu(n.pullCursor),lastPullAt:n.lastPullAt===void 0?e.lastPullAt:Nu(n.lastPullAt),lastPushAt:n.lastPushAt===void 0?e.lastPushAt:Nu(n.lastPushAt),lastSyncedAt:n.lastSyncedAt===void 0?e.lastSyncedAt:Nu(n.lastSyncedAt),lastErrorMessage:n.lastErrorMessage===void 0?e.lastErrorMessage:n.lastErrorMessage??null,pushBaseline:n.pushBaseline===void 0?e.pushBaseline??null:n.pushBaseline??null};return a.enabled||(a.phase="idle",a.setupIntent=null,a.pullCursor=null),a}function Lv(e){const{currentWorkspaceId:n,setWorkspaceCloudSyncEnabled:a,setWorkspaceSyncPhase:s,setWorkspaceSyncSetupIntent:o,setWorkspaceLastPullAt:c,setWorkspaceLastPushAt:i,setWorkspaceLastErrorMessage:l}=e,[m,y]=r.useState(null),v=r.useRef(null),b=r.useRef(null),g=r.useRef(0),h=r.useRef(!1),k=r.useRef(!1),I=r.useRef(""),x=r.useRef(""),A=r.useRef(new Set),M=r.useRef(new Set),B=r.useRef(new Map),ue=r.useRef(null),X=r.useRef($u()),ce=r.useRef(""),oe=r.useRef(null),be=r.useRef(null),_=r.useRef(null),J=r.useRef(null);if(!ce.current){const T=Date.now().toString(36),w=Math.random().toString(36).slice(2,10);ce.current=`sync-lease-${T}-${w}`}const Q=r.useCallback(()=>{g.current=0,b.current=null,v.current!==null&&typeof window<"u"&&(window.clearTimeout(v.current),v.current=null),y(null)},[]),ie=r.useCallback((T,w)=>{if(typeof window>"u")return;const j=Math.max(1,g.current+1);g.current=j;const F=tv(j),ee=Number(w?.minDelayMs),N=Number.isFinite(ee)&&ee>0?Math.max(F,Math.floor(ee)):F,C=Date.now()+N;b.current=C,y(new Date(C).toISOString()),v.current!==null&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>{v.current=null,b.current=null,y(null),T()},N)},[]),H=r.useCallback(()=>{const T=b.current;return typeof T=="number"&&Number.isFinite(T)&&T>Date.now()},[]),P=r.useCallback(T=>{if(typeof window>"u")return null;const w=String(T||"").trim();return Vl(w)?Ev(window.localStorage.getItem(sp(w))):null},[]),U=r.useCallback(T=>{const w=String(T||"").trim();if(w)try{J.current?.postMessage({workspaceId:w})}catch{}},[]),se=r.useCallback((T,w)=>{if(typeof window>"u")return null;const j=String(T||"").trim();if(!Vl(j))return null;const F=Mv(ce.current,j,w,Date.now());try{window.localStorage.setItem(sp(j),JSON.stringify(F))}catch{return null}return U(j),F},[U]),he=r.useCallback(()=>{_.current!==null&&typeof window<"u"&&(window.clearInterval(_.current),_.current=null)},[]),V=r.useCallback((T,w)=>{if(typeof window>"u")return;const j=String(T||oe.current||"").trim();if(!j)return;const F=P(j),ee=F?.ownerId===ce.current;if(!(!w?.force&&F&&!ee)){he();try{window.localStorage.removeItem(sp(j))}catch{}oe.current=null,be.current=null,U(j)}},[U,P,he]),Ce=r.useCallback((T,w)=>{typeof window>"u"||(he(),_.current=window.setInterval(()=>{const j=String(oe.current||"").trim(),F=be.current;if(!j||!F){he();return}if(P(j)?.ownerId!==ce.current){he(),oe.current=null,be.current=null;return}se(j,F)},jv),oe.current=T,be.current=w)},[P,he,se]),Se=r.useCallback(async(T,w)=>{if(typeof window>"u")return!0;const j=String(T||"").trim();if(!Vl(j))return!1;const F=P(j);if(F?.ownerId===ce.current)return se(j,w)?(Ce(j,w),!0):!1;if(F&&!Dv(F)||!se(j,w))return!1;const C=P(j);return!C||C.ownerId!==ce.current?!1:(Ce(j,w),!0)},[P,Ce,se]),ve=r.useCallback(T=>{V(T,{force:!0})},[V]),ge=r.useCallback(T=>{const w=X.current,j=op(w,{enabled:!!T.enabled,phase:T.phase||w.phase,setupIntent:T.setupIntent,pullCursor:T.pullCursor,lastPullAt:T.lastPullAt,lastPushAt:T.lastPushAt,lastSyncedAt:T.lastSyncedAt,lastErrorMessage:T.lastErrorMessage});X.current=j,ue.current=j.pullCursor,a(j.enabled),s(j.phase),o(j.setupIntent??null),c(j.lastPullAt),i(j.lastPushAt),l(j.lastErrorMessage??null)},[a,s,o,c,i,l]),Te=r.useCallback(T=>{const w=op(X.current,T);return ge(w),w},[ge]),Le=r.useCallback(()=>X.current,[]),Ie=r.useCallback(async T=>{const w=op(X.current,T);X.current=w,ue.current=w.pullCursor;const j=await Xp({workspaceId:n,stateKey:"workspace-sync",patch:w,throwOnError:!0,respectFailureCooldown:!1}),F=j.response,ee=j.payload;if(j.skipped)return ge(w),w;if(!F)throw new Error("Failed to persist workspace sync state (missing response)");if(!F.ok||ee?.success===!1)throw new Error(ee?.error||`Failed to persist workspace sync state (${F.status})`);return ge(w),w},[ge,n]),Oe=r.useCallback(async()=>{if(!Vl(n)){const T=$u();X.current=T,ge(T);return}try{const T=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const w=await T.json().catch(()=>({})),j=Tv(w?.state&&typeof w.state=="object"?w.state:null);X.current=j.state,ge(j.state),j.changed&&Ie(j.state)}catch{}},[ge,n,Ie]),z=r.useCallback(async(T,w)=>{if(!Vl(n))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!T.enabled)return await Ie({enabled:!1,phase:"idle",setupIntent:null,pullCursor:null}),{success:!0};if(!w.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!w.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const j=await w.ensureCloudWorkspaceReadyForSync();return j.success?(await Ie({enabled:!0,phase:j.provisioned?"provision-local":"attach-cloud",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}),{success:!0}):{success:!1,error:j.error||"Workspace sync handshake failed."}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[n,Ie]);return r.useEffect(()=>{I.current="",x.current="",A.current=new Set,M.current=new Set,B.current=new Map,ue.current=null,X.current=$u(),h.current=!1,k.current=!1,V(),Q()},[Q,n,V]),r.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const T=new BroadcastChannel(Rv);return J.current=T,()=>{T.close(),J.current===T&&(J.current=null)}},[]),r.useEffect(()=>()=>{v.current!==null&&typeof window<"u"&&(window.clearTimeout(v.current),v.current=null),V()},[V]),{workspaceRetryAt:m,isWorkspaceRetryPending:H,workspacePushInFlightRef:h,workspacePullInFlightRef:k,workspaceLastPushedSignatureRef:I,workspacePendingSignatureRef:x,workspaceLastPushedTaskIdsRef:A,workspaceDeletedTaskIdsRef:M,workspaceDeletedTaskWatermarksRef:B,workspacePullCursorRef:ue,clearWorkspaceRetry:Q,scheduleWorkspaceRetry:ie,persistWorkspaceSyncPatch:Ie,applyWorkspaceSyncPatchLocally:Te,readWorkspaceSyncStateSnapshot:Le,loadWorkspaceSyncState:Oe,applyWorkspaceSyncStateSnapshot:ge,saveWorkspaceCloudSyncSettings:z,acquireWorkspaceSyncLease:Se,releaseWorkspaceSyncLease:V,forceClearWorkspaceSyncLease:ve,readWorkspaceSyncLease:P}}class Bv{constructor(n=2048){this.maxSeenEventIds=n}seenEventIds=new Set;seenEventIdQueue=[];activeEpoch="";lastSeq=null;telemetry={accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0};process(n){const a=typeof n.eventId=="string"?n.eventId.trim():"";if(a&&this.seenEventIds.has(a))return this.telemetry.duplicateDiscarded+=1,{accepted:!1,reason:"duplicate",shouldRecover:!1};const s=typeof n.serverEpoch=="string"?n.serverEpoch.trim():"",o=Number(n.seq);if(!(s.length>0&&Number.isFinite(o)&&o>=0))return a?(this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}):(this.telemetry.invalidDiscarded+=1,{accepted:!1,reason:"invalid",shouldRecover:!1});const i=Math.floor(o);if(this.activeEpoch&&this.activeEpoch!==s)return this.activeEpoch=s,this.lastSeq=i,a&&this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=s,this.lastSeq=i,a&&this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const l=this.lastSeq;if(typeof l=="number"){if(i<=l){this.telemetry.outOfOrderDiscarded+=i===l?0:1,this.telemetry.duplicateDiscarded+=i===l?1:0;const m=i<l;return m&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:i===l?"duplicate":"out-of-order",shouldRecover:m}}if(i>l+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=i,a&&this.rememberEventId(a),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}}getTelemetry(){return{...this.telemetry}}rememberEventId(n){for(this.seenEventIds.add(n),this.seenEventIdQueue.push(n);this.seenEventIdQueue.length>this.maxSeenEventIds;){const a=this.seenEventIdQueue.shift();a&&this.seenEventIds.delete(a)}}}function Tg(e){const{enabled:n,workspaceId:a,websocketUrl:s,reconnectBaseMs:o=400,reconnectMaxMs:c=1e4,degradeAfterAttempts:i=5,replayLimit:l=200,onSignal:m,onTelemetry:y,userId:v}=e,[b,g]=r.useState("degraded-fallback"),h=r.useRef(null),k=r.useRef(null),I=r.useRef(0),x=r.useRef(""),A=r.useRef(!1),M=r.useRef(null),B=r.useRef(null),ue=r.useRef(new Bv),X=r.useRef(m),ce=r.useRef(y);r.useEffect(()=>{X.current=m},[m]),r.useEffect(()=>{ce.current=y},[y]);const[oe,be]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),_=r.useMemo(()=>String(a||"").trim(),[a]),J=r.useMemo(()=>String(s||"").trim(),[s]);return r.useEffect(()=>{let Q=!1;const ie=()=>{k.current!==null&&(window.clearTimeout(k.current),k.current=null)},H=()=>{const ge=h.current;if(h.current=null,ge)try{ge.close()}catch{}},P=ge=>ge==="taskforce:replay-gap"||ge==="taskforce:replay-reset"?4:ge==="taskforce:mutation"||ge==="taskforce:replay"?3:1,U=ge=>{const Te=B.current;if(Te){const Le=P(Te.type),Ie=P(ge.type);if(Ie<Le||Ie===Le&&Te.eventId&&!ge.eventId)return}B.current=ge,M.current!==null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{M.current=null;const Le=X.current;if(!B.current||typeof Le!="function")return;const Ie=B.current;B.current=null,Le(Ie)},80)},se=ge=>{try{const Te=JSON.parse(String(ge.data||""));return!Te||typeof Te!="object"?null:Te}catch{return null}},he=ge=>{const Te=typeof ge.serverEpoch=="string"?ge.serverEpoch.trim():"",Le=Number(ge.seq);!Te||!Number.isFinite(Le)||Le<0||(x.current=`${Te}:${Math.floor(Le)}`,A.current=!1)},V=()=>{const ge=ue.current.getTelemetry();be(ge);const Te=ce.current;typeof Te=="function"&&Te(ge)},Ce=ge=>{const Te={type:"taskforce:replay",workspaceId:_,limit:l},Le=x.current;Le&&(Te.cursor=Le),ge.send(JSON.stringify(Te))},Se=()=>{if(!n||Q)return;ie(),I.current+=1;const ge=I.current,Te=Math.max(50,Math.floor(o)),Le=Math.max(Te,Math.floor(c)),Ie=Math.min(Le,Te*Math.pow(2,Math.max(0,ge-1)));g(ge>=i?"degraded-fallback":"reconnecting"),k.current=window.setTimeout(()=>{Q||(k.current=null,ve())},Ie)},ve=()=>{if(!n||Q||!_||!J)return;H();let ge;try{ge=new WebSocket(J)}catch{Se();return}h.current=ge,ge.addEventListener("open",()=>{I.current=0,g("connected"),ge.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:_,userId:v||void 0})),Ce(ge)}),ge.addEventListener("message",Te=>{const Le=se(Te);if(!Le||typeof Le.type!="string")return;const Ie=typeof Le.workspaceId=="string"?Le.workspaceId.trim():_;if(!(!Ie||Ie!==_)){if(Le.type==="taskforce:update"){U({type:"taskforce:update",workspaceId:_,eventId:typeof Le.eventId=="string"?Le.eventId.trim():void 0});return}if(Le.type==="taskforce:mutation"){const Oe=ue.current.process({eventId:Le.eventId,serverEpoch:Le.serverEpoch,seq:Le.seq});if(!Oe.accepted){V(),Oe.shouldRecover&&(x.current="",A.current||(A.current=!0,U({type:"taskforce:replay-gap",workspaceId:_})));return}he(Le),V(),U({type:Le.type,workspaceId:_,eventId:typeof Le.eventId=="string"?Le.eventId.trim():void 0});return}if(Le.type==="taskforce:replay"){const Oe=Array.isArray(Le.events)?Le.events:[];let z=0;for(const T of Oe)ue.current.process({eventId:T.eventId,serverEpoch:T.serverEpoch,seq:T.seq}).accepted&&(z+=1,he(T));A.current=!1,V(),(z>0||Le.truncated===!0)&&U({type:"taskforce:replay",workspaceId:_}),Le.truncated===!0&&Ce(ge);return}if(Le.type==="taskforce:replay-gap"||Le.type==="taskforce:replay-reset"){if(x.current="",A.current)return;A.current=!0,U({type:Le.type,workspaceId:_})}}}),ge.addEventListener("close",Te=>{if(h.current===ge&&(h.current=null),!Q&&n){const Le=Number(Te?.code||0),Ie=String(Te?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${_} user=${String(v||"anonymous").trim()||"anonymous"} code=${Le}${Ie?` reason=${Ie}`:""}`)}Se()}),ge.addEventListener("error",()=>{try{ge.close()}catch{}})};return!n||!_||!J?(g("degraded-fallback"),ie(),H(),()=>{ie(),H()}):(g("reconnecting"),ve(),()=>{Q=!0,ie(),M.current!==null&&(window.clearTimeout(M.current),M.current=null),B.current=null,H()})},[n,_,J,o,c,i,l,v]),{connectionState:b,telemetry:oe}}const Rp="taskforce:context-assets-mutated";function Wv(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Rp,{detail:e}))}const Fv=4,Ru=100;function Xl(e,n,a){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(typeof e=="bigint")return e.toString();if(e instanceof Date)return e.toISOString();if(n>=Fv)return"[MaxDepth]";if(typeof e=="function"||typeof e=="symbol"||typeof e>"u")return String(e);if(Array.isArray(e))return e.slice(0,Ru).map(s=>Xl(s,n+1,a));if(e instanceof Set)return Array.from(e.values()).slice(0,Ru).map(s=>Xl(s,n+1,a));if(e instanceof Map){const s={};for(const[o,c]of Array.from(e.entries()).slice(0,Ru))s[String(o)]=Xl(c,n+1,a);return s}if(typeof e=="object"){if(a.has(e))return"[Circular]";a.add(e);const s={};for(const[o,c]of Object.entries(e).slice(0,Ru))s[o]=Xl(c,n+1,a);return a.delete(e),s}return String(e)}function mm(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return Xl(e,0,new WeakSet)}function Ov(e){const n=mm(e);if(!n)return"null";try{return JSON.stringify(n)}catch{return"[UnserializableSyncEventDetails]"}}const Ng="taskforce.userGlobalSyncMeta.v1",$v="taskforce.syncDebug.v1",Uv=12e4,Rg="taskforce.syncWatermarks.v3",qv=300*1e3,Zf="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function Ci(e){const n=String(e||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function zv(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem($v)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Ga(e,n){if(!zv())return;console.info("[Taskforce Sync]",e,n&&typeof n=="object"?n:{})}function Hv(e){const n=e?.providerMetadata??e?.provider_metadata??null;return{id:String(e?.id||"").trim(),workspaceId:String(e?.workspaceId||e?.workspace_id||"").trim(),profileToken:String(e?.profileToken||e?.profile_token||"").trim(),name:String(e?.name||"").trim(),username:String(e?.username||"").trim(),icon:String(e?.icon||"Bot").trim()||"Bot",color:String(e?.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:$c(e?.avatarUrl??e?.avatar_url),avatarSourceUrl:$c(e?.avatarSourceUrl??e?.avatar_source_url),description:ca(e?.description),role:ca(e?.role),provider:ca(e?.provider),model:ca(e?.model),surfaceType:Cg(e?.surfaceType??e?.surface_type),seatScope:Ag(e?.seatScope??e?.seat_scope),providerMetadata:n&&typeof n=="object"&&!Array.isArray(n)?n:null,archivedAt:ds(e?.archivedAt??e?.archived_at),archivedBy:Qu(e?.archivedBy??e?.archived_by),archivedReason:ca(e?.archivedReason??e?.archived_reason),mergedIntoProfileId:Qu(e?.mergedIntoProfileId??e?.merged_into_profile_id),rosterStateUpdatedAt:ds(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:ds(e?.lastActiveAt??e?.last_active_at)}}function Yf(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Ng);if(!e)return{};const n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}}function Gv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ng,JSON.stringify(e))}catch{}}function Vv(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function Kv(e){return e.flatMap(n=>{const a=String(n?.id||"").trim();return!a||!Array.isArray(n?.comments)?[]:n.comments.map(s=>({id:String(s?.id||"").trim(),sessionId:a,body:String(s?.body||""),anchor:s?.anchor??null,order:Number.isFinite(Number(s?.order))?Math.max(0,Math.floor(Number(s.order))):0,authorActorId:typeof s?.authorActorId=="string"&&s.authorActorId.trim().length>0?s.authorActorId.trim():null,createdAt:String(s?.createdAt||"").trim(),updatedAt:String(s?.updatedAt||s?.createdAt||"").trim(),deletedAt:typeof s?.deletedAt=="string"&&s.deletedAt.trim().length>0?s.deletedAt.trim():null})).filter(s=>s.id.length>0&&s.sessionId.length>0)})}function ju(e,n){const a=new Map;for(const s of[...e||[],...n||[]]){const o=Array.isArray(s?.taskEvents)?s.taskEvents:[];for(const c of o){const i=String(c?.id||"").trim(),l=String(c?.taskId||s?.id||"").trim(),m=String(c?.workspaceId||"").trim(),y=String(c?.createdAt||"").trim();if(!i||!l||!m||!y)continue;const v={id:i,taskId:l,workspaceId:m,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,createdAt:y},b=a.get(i);(!b||v.createdAt>b.createdAt)&&a.set(i,v)}}return Array.from(a.values()).sort((s,o)=>s.createdAt!==o.createdAt?s.createdAt.localeCompare(o.createdAt):s.id.localeCompare(o.id))}function jg(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 Pg(e,n){if(!e||typeof e!="object")return null;const a=typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:"",s=!n||!a||a===n?new Map(Array.isArray(e.taskWatermarks)?e.taskWatermarks:[]):new Map;return{taskIds:new Set(Array.isArray(e.taskIds)?e.taskIds.map(c=>String(c||"").trim()).filter(c=>c.length>0):Array.from(s.keys())),taskWatermarks:s,taskChangeKeys:new Map(Array.isArray(e.taskChangeKeys)?e.taskChangeKeys:[]),initiativeWatermarks:new Map(Array.isArray(e.initiativeWatermarks)?e.initiativeWatermarks:[]),workstreamWatermarks:new Map(Array.isArray(e.workstreamWatermarks)?e.workstreamWatermarks:[]),aiProfileWatermarks:new Map(Array.isArray(e.aiProfileWatermarks)?e.aiProfileWatermarks:[]),aiProfileChangeKeys:new Map(Array.isArray(e.aiProfileChangeKeys)?e.aiProfileChangeKeys:[]),documentWatermarks:new Map(Array.isArray(e.documentWatermarks)?e.documentWatermarks:[]),assetWatermarks:new Map(Array.isArray(e.assetWatermarks)?e.assetWatermarks:[]),documentReviewSessionWatermarks:new Map(Array.isArray(e.documentReviewSessionWatermarks)?e.documentReviewSessionWatermarks:[]),documentReviewCommentWatermarks:new Map(Array.isArray(e.documentReviewCommentWatermarks)?e.documentReviewCommentWatermarks:[]),annotatedAttachmentSessionWatermarks:new Map(Array.isArray(e.annotatedAttachmentSessionWatermarks)?e.annotatedAttachmentSessionWatermarks:[]),taskEventWatermarks:new Map(Array.isArray(e.taskEventWatermarks)?e.taskEventWatermarks:[])}}function Jf(e,n){if(typeof window>"u")return null;try{const a=`${Rg}.${e}`,s=window.localStorage.getItem(a);if(!s)return null;const o=JSON.parse(s);return!o||o.v!==2&&o.v!==3&&o.v!==4&&o.v!==5&&o.v!==6&&o.v!==7&&o.v!==8&&o.v!==9&&o.v!==10&&o.v!==11?null:Pg(o,n)}catch{return null}}function Xf(e,n){if(typeof window>"u")return!1;try{const a=`${Rg}.${e}`;return window.localStorage.setItem(a,JSON.stringify({v:11,savedAt:new Date().toISOString(),...jg(n)})),!0}catch{return!1}}function Zv({currentWorkspaceId:e,workspaceSyncPhase:n,clearWorkspaceRetry:a,setWorkspaceSyncBusy:s,setUserGlobalSyncStatus:o,setUserGlobalSyncError:c,setWorkspaceLastErrorMessage:i,setWorkspaceLastErrorAt:l,reportSyncEvent:m,setAuthBlocked:y,setIsAuthenticated:v,checkAuthSession:b,ensureCloudWorkspaceReadyForSync:g,scheduleWorkspaceSyncRetry:h,persistWorkspaceSyncPatchSafely:k}){const I=async(A,M)=>{a(),s(!1),o("error");const B="Session expired. Sign in again to resume cloud sync.";c(B),i(B),l(new Date().toISOString()),m(e,{eventType:A==="handshake"?"handshake":A,status:"error",statusCode:M,errorMessage:B}),y(!0),v(!1),await b()};return{handleSyncAuthFailure:I,ensureWorkspaceSyncReady:async()=>{if(!Ci(e)){const B="Workspace sync blocked: local workspace ID is unresolved.";return i(B),l(new Date().toISOString()),c(B),o("error"),!1}const A=await g();if(A.success)return!0;if(A.statusCode===401)return await I("handshake",401),!1;const M=A.error||"Workspace sync handshake failed.";return i(M),l(new Date().toISOString()),c(M),o("error"),m(e,{eventType:"handshake",status:"error",statusCode:A.statusCode,errorMessage:M}),A.transient||_s(A.statusCode)?h(A.retryAfterMs):(n==="active"||n==="attach-cloud"||n==="provision-local")&&k({phase:"error",lastErrorMessage:M}),!1}}}function Yv({workspaceSyncPhase:e,lastBootstrapPhaseRef:n,bootstrapPhaseStartedAtRef:a,bootstrapLastProgressAtRef:s}){if(e==="attach-cloud"||e==="provision-local"){n.current=e,a.current===null&&(a.current=Date.now()),s.current=null;return}a.current=null,s.current=null}function Jv({currentWorkspaceId:e,workspaceCloudSyncEnabled:n,workspaceSyncPhase:a,workspacePullInFlightRef:s,workspacePushInFlightRef:o,bootstrapPhaseStartedAtRef:c,bootstrapLastProgressAtRef:i,setWorkspaceLastErrorMessage:l,setWorkspaceLastErrorAt:m,setUserGlobalSyncStatus:y,setUserGlobalSyncError:v,setWorkspaceSyncBusy:b,persistWorkspaceSyncPatchSafely:g}){if(!n||a!=="attach-cloud"&&a!=="provision-local")return;const h=window.setInterval(()=>{if(a!=="attach-cloud"&&a!=="provision-local"||s.current||o.current)return;const k=Math.max(c.current??0,i.current??0);if(k>0&&Date.now()-k<Uv)return;const x=`Workspace sync ${a==="attach-cloud"?"initial cloud pull":"initial cloud upload"} stalled. Press Repair to restart sync for this workspace.`;l(x),m(new Date().toISOString()),y("error"),v(x),b(!1),g({phase:"error",lastErrorMessage:x}),Ga("workspace_sync_bootstrap_timeout",{workspaceId:e,phase:a})},1e4);return()=>window.clearInterval(h)}function Xv(e){const{workspaceSyncPhase:n,lastBootstrapPhase:a,workspaceLastPullAt:s}=e;return n==="provision-local"?"provision-local":n==="attach-cloud"?"attach-cloud":n==="active"||a==="active"?"active":a==="provision-local"||a==="attach-cloud"?a:s?"attach-cloud":"provision-local"}const nf={allowed:!0};function Ka(e,n){return{allowed:!1,reason:e,retainPendingSignature:n?.retainPendingSignature===!0}}function af(e,n){return e.cloudAuthConfigured?e.runtimeMode!=="local"?Ka("runtime-not-local"):e.workspaceCloudSyncEnabled?(n?.requireValidWorkspace??!0)&&!Ci(e.currentWorkspaceId)?Ka("invalid-workspace"):null:Ka("sync-disabled"):Ka("cloud-auth-unconfigured")}function jp(e){const n=af(e);return n||(e.repairModeActive&&!e.repairModeBypass?Ka("repair-active",{retainPendingSignature:!0}):e.workspaceSyncPhase==="attach-cloud"?Ka("attach-cloud",{retainPendingSignature:!0}):e.isAuthenticated?e.pushInFlight?Ka("push-in-flight",{retainPendingSignature:!0}):e.pullInFlight?Ka("pull-in-flight",{retainPendingSignature:!0}):nf:Ka("auth-required"))}function Pp(e){const n=af(e);return n||(e.repairModeActive&&!e.repairModeBypass?Ka("repair-active"):e.workspaceSyncPhase==="provision-local"?Ka("provision-local"):e.retryPending?Ka("retry-pending"):e.isAuthenticated?e.pullInFlight?Ka("pull-in-flight"):e.pushInFlight?Ka("push-in-flight"):nf:Ka("auth-required"))}function Ep(e){const n=af(e,{requireValidWorkspace:!1});return n||(e.isAuthenticated?nf:Ka("auth-required"))}function Qv(e){return Ka("lease-held",{retainPendingSignature:e==="push"})}function yd(e){return e.cloudAuthConfigured&&e.runtimeMode==="local"&&e.workspaceCloudSyncEnabled&&e.authSessionResolved}function eb({enabled:e,phase:n,busy:a,retryAt:s,lastErrorMessage:o}){return e?n==="provision-local"?{status:"syncing",summary:a?"Uploading this workspace to cloud for the first time.":"Preparing the first upload to cloud.",recommendedAction:"Keep this window open while the first upload finishes. If it seems stalled, press Sync."}:n==="attach-cloud"?{status:"syncing",summary:a?"Pulling the cloud workspace into this device.":"Waiting for the first cloud pull into this device.",recommendedAction:"Keep this window open for the first cloud pull. If it does not move, press Repair."}:s?{status:"attention",summary:"Sync hit a temporary problem and will retry automatically.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."}:o||n==="error"?{status:"attention",summary:"Sync needs attention before it can continue.",recommendedAction:"Press Sync to retry. If the same error keeps returning, press Repair."}:a?{status:"syncing",summary:"Sync is currently running.",recommendedAction:"No action needed."}:{status:"healthy",summary:"Sync is healthy.",recommendedAction:"No action needed."}:{status:"off",summary:"Sync is turned off for this workspace.",recommendedAction:"Turn on sync when you are ready to back up this workspace."}}function tb(e){return yd(e)&&e.workspaceSyncPhase!=="attach-cloud"&&e.workspaceSyncReferenceSnapshotsReady}function nb(e){return yd(e)&&e.workspaceSyncPhase==="active"&&e.workspaceSyncReferenceSnapshotsReady}function ab(e){return yd(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 rb(e){return yd(e)&&e.isAuthenticated&&e.workspaceSyncPhase==="active"}function sb(e){return yd(e)&&e.isAuthenticated&&e.workspaceSyncPhase!=="provision-local"&&e.workspaceSyncPhase!=="attach-cloud"&&!e.alreadyRan}function ob({cloudAuthConfigured:e,runtimeMode:n,workspaceCloudSyncEnabled:a,workspaceSyncPhase:s,workspacePullInFlightRef:o,realtimePullDebounceRef:c,realtimeSuppressedEventIdsRef:i,clearWorkspaceRetry:l,isWorkspaceRetryPending:m,pullWorkspaceChangesFromCloud:y}){return{handleRealtimeSignal:h=>{if(!e||n!=="local"||!a||s==="provision-local")return;const k=String(h?.eventId||"").trim();k&&i.current.delete(k)||o.current||(m()&&l(),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{c.current=null,y()},180))},recordSuppressedEventIds:(h,k)=>{const I=k?.queueRef,x=Number.isFinite(k?.maxQueueSize)?Math.max(1,Number(k?.maxQueueSize)):2048,A=Number.isFinite(k?.ttlMs)?Math.max(0,Number(k?.ttlMs)):null;for(const M of h){const B=String(M||"").trim();!B||i.current.has(B)||(i.current.add(B),I&&I.current.push(B),A!==null&&window.setTimeout(()=>{i.current.delete(B)},A))}if(I)for(;I.current.length>x;){const M=I.current.shift();M&&i.current.delete(M)}},clearRealtimePullDebounce:()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)}}}function Eg(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.workspaceBaselineResetReasonRef.current="repair-reset"}function ib(e){Eg(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 cb({currentWorkspaceId:e,workspaceCloudSyncEnabled:n,workspaceSyncPhase:a,workspaceLastPullAt:s,lastBootstrapPhaseRef:o,workspaceRepairModeRef:c,workspaceForceFullAiProfilePushRef:i,workspaceStartupRepairRanRef:l,workspaceStartupFullReconcileRanRef:m,workspaceFullReconcileInFlightRef:y,workspacePullCursorRef:v,workspaceAttachBootstrapBaselineSignatureRef:b,workspaceCaptureAttachBootstrapBaselineRef:g,workspacePendingSignatureRef:h,workspaceLastPushedSignatureRef:k,workspaceLastPushedWatermarksRef:I,workspaceLastPushedTaskChangeKeysRef:x,workspaceLastPushedInitiativeIdsRef:A,workspaceLastPushedInitiativeWatermarksRef:M,workspaceLastPushedWorkstreamIdsRef:B,workspaceLastPushedWorkstreamWatermarksRef:ue,workspaceLastPushedAiProfileIdsRef:X,workspaceLastPushedAiProfileWatermarksRef:ce,workspaceLastPushedAiProfileChangeKeysRef:oe,workspaceLastPushedDocumentPathsRef:be,workspaceLastPushedDocumentWatermarksRef:_,workspaceLastPushedAssetPathsRef:J,workspaceLastPushedAssetWatermarksRef:Q,workspaceLastPushedDocumentReviewSessionIdsRef:ie,workspaceLastPushedDocumentReviewSessionWatermarksRef:H,workspaceLastPushedDocumentReviewCommentIdsRef:P,workspaceLastPushedDocumentReviewCommentWatermarksRef:U,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:se,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:he,workspaceLastPushedTaskEventWatermarksRef:V,workspaceBaselineResetReasonRef:Ce,bootstrapPhaseStartedAtRef:Se,bootstrapLastProgressAtRef:ve,acquireWorkspaceSyncLease:ge,releaseWorkspaceSyncLease:Te,forceClearWorkspaceSyncLease:Le,clearWorkspaceRetry:Ie,clearWorkspaceIssue:Oe,reportWorkspaceWindowContention:z,reportSyncEvent:T,persistWorkspaceSyncPatch:w,persistWorkspaceSyncWatermarksSnapshotBestEffort:j,buildWorkspaceSyncSignature:F,pullWorkspaceChangesFromCloud:ee,pushWorkspaceChangesToCloud:N,cloudAuthConfigured:C,runtimeMode:$,isAuthenticated:K,checkAuthSession:te}){const L=a==="provision-local"?"push":a==="attach-cloud"?"bootstrap":"pull";return{retryWorkspaceCloudSync:async()=>{Ie();let xe=Ep({cloudAuthConfigured:C,runtimeMode:$,workspaceCloudSyncEnabled:n,currentWorkspaceId:e,isAuthenticated:K});if(!xe.allowed&&xe.reason==="auth-required"){if(!await te())return T(e,{eventType:L,status:"error",errorMessage:"Manual sync retry blocked: sign in is required.",details:{source:"retry.blocked",reason:"auth-required",phase:a}}),!1;xe=Ep({cloudAuthConfigured:C,runtimeMode:$,workspaceCloudSyncEnabled:n,currentWorkspaceId:e,isAuthenticated:!0})}if(!xe.allowed)return T(e,{eventType:L,status:"error",errorMessage:`Manual sync retry blocked: ${xe.reason}.`,details:{source:"retry.blocked",reason:xe.reason,phase:a}}),!1;if(i.current=!0,a==="provision-local"){const Re=F();return Re?N(Re,{forceAllAiProfiles:!0}):!1}const le=await ee();if(a==="attach-cloud")return le;const we=F();if(we){h.current=we;const Re=await N(we,{forceAllAiProfiles:i.current===!0});return le||Re}return le},resetWorkspaceSyncCursorAndPull:async()=>{if(!await ge(e,"repair")&&(Le(e),!await ge(e,"repair"))){z("repair"),T(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because another window is already syncing this workspace.",details:{source:"repair.blocked",reason:"lease-held",phase:a}});return}const le=Xv({workspaceSyncPhase:a,lastBootstrapPhase:o.current,workspaceLastPullAt:s}),we=le==="provision-local",Re=le==="active";Ie(),Oe();try{if(!n){T(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because workspace sync is turned off.",details:{source:"repair.blocked",reason:"sync-disabled",phase:a}});return}if(Se.current=null,ve.current=null,v.current=null,b.current="",g.current=!1,h.current="",k.current="",i.current=!1,l.current=!1,m.current=!1,y.current=!1,we?ib({workspaceLastPushedWatermarksRef:I,workspaceLastPushedTaskChangeKeysRef:x,workspaceLastPushedInitiativeIdsRef:A,workspaceLastPushedInitiativeWatermarksRef:M,workspaceLastPushedWorkstreamIdsRef:B,workspaceLastPushedWorkstreamWatermarksRef:ue,workspaceLastPushedAiProfileIdsRef:X,workspaceLastPushedAiProfileWatermarksRef:ce,workspaceLastPushedAiProfileChangeKeysRef:oe,workspaceLastPushedDocumentPathsRef:be,workspaceLastPushedDocumentWatermarksRef:_,workspaceLastPushedAssetPathsRef:J,workspaceLastPushedAssetWatermarksRef:Q,workspaceLastPushedDocumentReviewSessionIdsRef:ie,workspaceLastPushedDocumentReviewSessionWatermarksRef:H,workspaceLastPushedDocumentReviewCommentIdsRef:P,workspaceLastPushedDocumentReviewCommentWatermarksRef:U,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:se,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:he,workspaceLastPushedTaskEventWatermarksRef:V,workspaceBaselineResetReasonRef:Ce}):Re&&Eg({workspaceLastPushedWatermarksRef:I,workspaceLastPushedTaskChangeKeysRef:x,workspaceLastPushedInitiativeIdsRef:A,workspaceLastPushedInitiativeWatermarksRef:M,workspaceLastPushedWorkstreamIdsRef:B,workspaceLastPushedWorkstreamWatermarksRef:ue,workspaceLastPushedAiProfileIdsRef:X,workspaceLastPushedAiProfileWatermarksRef:ce,workspaceLastPushedAiProfileChangeKeysRef:oe,workspaceBaselineResetReasonRef:Ce}),j(),c.current=!0,T(e,{eventType:"bootstrap",status:"success",errorMessage:"Manual sync repair started.",details:{source:"repair.started",phase:a,repairPhase:le,lastBootstrapPhase:o.current}}),await w({phase:le,pullCursor:null,lastErrorMessage:null}),le==="provision-local"){const lt=F();if(!lt)return;await N(lt,{forceAllAiProfiles:!0,repairMode:!0});return}const Xe=await ee({repairMode:!0});if(le!=="active"||!Xe)return;const ze=F();if(!ze)return;h.current=ze,await N(ze,{forceAllAiProfiles:!0,repairMode:!0})}finally{c.current=!1,Te(e)}}}}function lb({workspaceSyncPhase:e,forceCursorNull:n,currentCursor:a}){const s=e==="attach-cloud";return{bootstrap:s,cursor:s||n===!0?null:a,successEventType:s?"bootstrap":"pull"}}function db({workspaceSyncPhase:e,forceCursorNull:n,startupFullReconcileRan:a,pendingSignature:s,fallbackSignature:o,lastPushedSignature:c}){const i=e==="attach-cloud",l=s||o,m=!i&&l&&l!==c?l:null;return{successEventType:i?"bootstrap":"pull",shouldCaptureAttachBootstrapBaseline:i,shouldClearPendingSignature:i||m!==null,shouldRefreshReferenceSnapshots:i,shouldSeedWorkspaceSnapshotPushBaseline:i,shouldScheduleStartupFullReconcile:!n&&!i&&!a,deferredPushSignature:m}}function ub({cloudAuthConfigured:e,runtimeMode:n,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:c,checkAuthSession:i,resolveCloudAuthUrl:l,ensureCloudWorkspaceReadyForSync:m,ensureWorkspaceSyncReady:y,handleSyncAuthFailure:v,clearWorkspaceRetry:b,clearWorkspaceIssue:g,isWorkspaceRetryPending:h,scheduleWorkspaceSyncRetry:k,persistWorkspaceSyncPatchSafely:I,persistWorkspaceSyncPatchBestEffort:x,persistWorkspaceSyncWatermarksSnapshotBestEffort:A,reportSyncEvent:M,acquireWorkspaceSyncLease:B,releaseWorkspaceSyncLease:ue,reportWorkspaceWindowContention:X,refreshWorkspaceSyncMarkdownDocumentsSnapshot:ce,refreshWorkspaceSyncAiProfilesSnapshot:oe,refreshWorkspaceSyncAssetsSnapshot:be,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:_,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:J,refreshLocalWorkspaceTaskCollections:Q,buildWorkspaceSyncPayload:ie,buildWorkspaceSyncSignature:H,seedWorkspaceSnapshotPushBaseline:P,shouldSuppressAttachBootstrapPush:U,recordSuppressedEventIds:se,workspaceRepairModeRef:he,workspaceForceFullAiProfilePushRef:V,workspacePushInFlightRef:Ce,workspacePullInFlightRef:Se,workspacePendingPushReplayRef:ve,workspaceLastPushedSignatureRef:ge,workspacePendingSignatureRef:Te,workspaceLastPushedTaskIdsRef:Le,workspaceDeletedTaskIdsRef:Ie,workspaceDeletedTaskWatermarksRef:Oe,workspacePullCursorRef:z,workspaceLastPushedWatermarksRef:T,workspaceLastPushedTaskChangeKeysRef:w,workspaceLastPushedInitiativeIdsRef:j,workspaceLastPushedInitiativeWatermarksRef:F,workspaceLastPushedWorkstreamIdsRef:ee,workspaceLastPushedWorkstreamWatermarksRef:N,workspaceLastPushedAiProfileIdsRef:C,workspaceLastPushedAiProfileWatermarksRef:$,workspaceLastPushedAiProfileChangeKeysRef:K,workspaceLastPushedDocumentPathsRef:te,workspaceLastPushedDocumentWatermarksRef:L,workspaceLastPushedAssetPathsRef:re,workspaceLastPushedAssetWatermarksRef:fe,workspaceLastPushedDocumentReviewSessionIdsRef:xe,workspaceLastPushedDocumentReviewSessionWatermarksRef:le,workspaceLastPushedDocumentReviewCommentIdsRef:we,workspaceLastPushedDocumentReviewCommentWatermarksRef:Re,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:Xe,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ze,workspaceLastPushedTaskEventWatermarksRef:lt,workspaceBaselineResetReasonRef:wt,workspaceCaptureAttachBootstrapBaselineRef:$e,workspaceStartupFullReconcileRanRef:ft,workspaceFullReconcileInFlightRef:gt,bootstrapLastProgressAtRef:at,realtimeSuppressedEventQueueRef:dt,setWorkspaceSyncBusy:ne,setUserGlobalSyncStatus:tt,setUserGlobalSyncError:rt,setWorkspaceLastErrorMessage:Pt,setWorkspaceLastErrorAt:yt,setWorkspaceLastPullAt:Rt,setWorkspaceLastPushAt:Tt,setWorkspaceSyncPendingChanges:Dt,setTasks:d,setArchivedTasks:Me}){const We=async(ot,de)=>{let Be=jp({cloudAuthConfigured:e,runtimeMode:n,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:c,repairModeActive:he.current===!0,repairModeBypass:de?.repairMode===!0,pushInFlight:Ce.current,pullInFlight:Se.current});if(!Be.allowed&&Be.reason==="auth-required"){if(!await i())return!1;Be=jp({cloudAuthConfigured:e,runtimeMode:n,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:he.current===!0,repairModeBypass:de?.repairMode===!0,pushInFlight:Ce.current,pullInFlight:Se.current})}if(!Be.allowed)return Be.retainPendingSignature&&(Te.current=ot),!1;if(U(ot))return!1;if(!await B(s,"push")){const bt=Qv("push");return!bt.allowed&&bt.retainPendingSignature&&(Te.current=ot),X("push"),!1}Ce.current=!0,ne(!0),tt("syncing"),rt(null);const vt=Date.now(),$t=de?.forceAllAiProfiles===!0||V.current===!0,Ze=de?.repairMode===!0||he.current===!0;let en=null,Lt=!1;try{if(await ce(),await oe(),await be(),await _(),!await y())return!1;const W=ve.current,ke=W&&W.signature===ot?W:null,Ne=ke?.payload||ie({forceAllAiProfiles:$t});en=Ne,Lt=ke!==null,Dt(Ne.changes.length);const ae=await XS({resolveCloudAuthUrl:l,workspaceId:s,payload:Ne,ensureCloudWorkspaceReadyForSync:m,repairMode:ke?.repairMode??Ze});if(!ae.success){if(ae.status===401)return ve.current=null,await v("push",401),!1;let De=ae.error?`Workspace sync push failed (${ae.status||0}): ${ae.error}`:`Workspace sync push failed (${ae.status||0})`;return ae.status===413&&(De="Workspace sync failed because the payload is too large. This usually happens when one or more attachments exceed the project limit."),tt("error"),rt(De),Pt(De),yt(new Date().toISOString()),M(s,{eventType:"push",status:"error",statusCode:ae.status,errorMessage:De,requestMs:ae.requestMs,details:{payloadDiagnostics:Ne.deltaDiagnostics||null,replayedPayload:Lt}}),Te.current=ot,ae.transient||_s(ae.status)?(ve.current={signature:ot,payload:Ne,forceAllAiProfiles:ke?.forceAllAiProfiles??$t,repairMode:ke?.repairMode??Ze},k(ae.retryAfterMs)):(ve.current=null,o==="active"&&I({phase:"error",lastErrorMessage:De})),!1}ve.current=null,ge.current=ot,Le.current=ae.currentTaskIds,T.current=ae.currentTaskWatermarks?new Map(ae.currentTaskWatermarks):new Map(T.current),w.current=ae.currentTaskChangeKeys?new Map(ae.currentTaskChangeKeys):new Map(w.current),j.current=new Set(ae.currentInitiativeIds),F.current=new Map(ae.currentInitiativeWatermarks),ee.current=new Set(ae.currentWorkstreamIds),N.current=new Map(ae.currentWorkstreamWatermarks),C.current=new Set(ae.currentAiProfileIds),$.current=new Map(ae.currentAiProfileWatermarks),K.current=ae.currentAiProfileChangeKeys?new Map(ae.currentAiProfileChangeKeys):new Map(K.current),te.current=new Set(ae.currentDocumentPaths),L.current=new Map(ae.currentDocumentWatermarks),re.current=new Set(ae.currentAssetPaths),fe.current=new Map(ae.currentAssetWatermarks),xe.current=new Set(ae.currentDocumentReviewSessionIds),le.current=new Map(ae.currentDocumentReviewSessionWatermarks),we.current=new Set(ae.currentDocumentReviewCommentIds),Re.current=new Map(ae.currentDocumentReviewCommentWatermarks),Xe.current=new Set(ae.currentAnnotatedAttachmentSessionIds),ze.current=new Map(ae.currentAnnotatedAttachmentSessionWatermarks),lt.current=new Map(ae.currentTaskEventWatermarks),$t&&(V.current=!1);for(const[De,it]of ae.pushedWatermarks)T.current.set(De,it);for(const[De,it]of ae.pushedTaskChangeKeys||new Map)w.current.set(De,it);if(ae.deleteTaskIds.size>0)for(const De of ae.deleteTaskIds)Ie.current.delete(De),Oe.current.delete(De),T.current.delete(De),w.current.delete(De);const Pe=await A();if(wt.current=Pe?null:"storage-write-failed",Array.isArray(ae.emittedEventIds)&&ae.emittedEventIds.length>0&&se(ae.emittedEventIds,{queueRef:dt,maxQueueSize:2048}),Array.isArray(ae.appliedTaskUpserts)&&ae.appliedTaskUpserts.length>0){const De=await Tp(s,ae.appliedTaskUpserts.map(it=>({op:"upsert",archived:it.archived===!0,task:it.task})));if(De.ok){for(const it of ae.appliedTaskUpserts){const Ut=String(it?.task?.id||"").trim(),Gt=String(it?.task?.updatedAt||it?.task?.createdAt||"").trim();!Ut||!Gt||T.current.set(Ut,Gt)}try{await Q()}catch{Ga("push_local_task_refresh_failed",{workspaceId:s,taskCount:ae.appliedTaskUpserts.length})}}else Ga("push_local_task_apply_failed",{workspaceId:s,taskCount:ae.appliedTaskUpserts.length,status:De.status,failures:De.failures})}b(),g();const Ge=ae.syncedAt||new Date().toISOString();return ge.current=H(),Tt(Ge),Dt(0),tt("idle"),I({phase:"active",lastPushAt:Ge,lastSyncedAt:Ge,lastErrorMessage:null}),M(s,{eventType:o==="provision-local"?"bootstrap":"push",status:"success",changeCount:ae.changeCount,requestMs:ae.requestMs,details:{payloadDiagnostics:Ne.deltaDiagnostics||null,replayedPayload:Lt}}),!0}catch(bt){const W="Workspace sync push failed.";return tt("error"),rt(W),Pt(W),yt(new Date().toISOString()),Te.current=ot,en&&(ve.current={signature:ot,payload:en,forceAllAiProfiles:$t,repairMode:Ze}),k(),M(s,{eventType:"push",status:"error",errorMessage:`${W} ${String(bt?.message||"").trim()}`.trim(),details:{replayedPayload:Lt}}),Ga("push_failed_exception",{workspaceId:s,elapsedMs:Date.now()-vt}),!1}finally{Ce.current=!1,ne(Se.current),ue(s);const bt=Te.current,W=H();bt&&W&&W!==ge.current&&!Se.current&&!h()&&(Te.current="",window.setTimeout(()=>{We(W)},120))}},Qe=async ot=>{let de=Pp({cloudAuthConfigured:e,runtimeMode:n,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:c,repairModeActive:he.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:h(),pullInFlight:Se.current,pushInFlight:Ce.current});if(!de.allowed&&de.reason==="auth-required"){if(!await i())return!1;de=Pp({cloudAuthConfigured:e,runtimeMode:n,workspaceCloudSyncEnabled:a,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:he.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:h(),pullInFlight:Se.current,pushInFlight:Ce.current})}if(!de.allowed)return!1;if(!await B(s,"pull"))return X("pull"),!1;Se.current=!0,ne(!0),tt("syncing"),rt(null);const St=Date.now();try{if(!await y())return!1;const $t=lb({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,currentCursor:z.current}),Ze=await QS({resolveCloudAuthUrl:l,workspaceId:s,cursor:$t.cursor,bootstrap:$t.bootstrap,ensureCloudWorkspaceReadyForSync:m,maxPages:20,repairMode:ot?.repairMode===!0||he.current===!0,onPagePulled:()=>{at.current=Date.now()},onChangesApplied:()=>{at.current=Date.now()}});if(!Ze.success){if(Ze.kind==="pull_http"&&Ze.status===401)return await v("pull",401),!1;if(Ze.kind==="apply_auth")return await v("apply",401),!1;if(Ze.kind==="pull_http"&&Ze.errorCode==="INVALID_SYNC_CURSOR"){const ke="Saved sync cursor was invalid. Clearing it and retrying from the beginning.";return z.current=null,I({pullCursor:null}),tt("error"),rt(ke),Pt(ke),yt(new Date().toISOString()),M(s,{eventType:"pull",status:"error",statusCode:Ze.status,errorMessage:ke,requestMs:Ze.pullRequestMs,details:{recovery:"cursor-reset",...Ze.serverDiagnostics?{serverPullDiagnostics:Ze.serverDiagnostics}:{}}}),k(150),!1}let W=Ze.kind==="apply_payload"||Ze.kind==="apply_all_candidates"||Ze.kind==="exception"?String(Ze.error||"Workspace sync apply failed."):`Workspace sync pull failed (${Ze.status||0})`;return Ze.status===413&&(W="Local sync failed because the downloaded payload is too large. This usually happens when the workspace contains massive attachments."),tt("error"),rt(W),Pt(W),yt(new Date().toISOString()),M(s,{eventType:Ze.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:Ze.status,errorMessage:W,requestMs:Ze.pullRequestMs,details:{pages:Ze.pages,applyMs:Ze.applyMs,...Ze.serverDiagnostics?{serverPullDiagnostics:Ze.serverDiagnostics}:{}}}),Ze.transient||Ze.hasTransientApplyFailure||_s(Ze.status)?k(Ze.retryAfterMs):I({phase:"error",lastErrorMessage:W}),!1}Array.isArray(Ze.emittedEventIds)&&se(Ze.emittedEventIds,{ttlMs:6e4}),Ze.pulledDeleteTaskIds.size>0&&(d(W=>W.filter(ke=>!Ze.pulledDeleteTaskIds.has(String(ke.id||"")))),Me(W=>W.filter(ke=>!Ze.pulledDeleteTaskIds.has(String(ke.id||"")))));const en=Array.isArray(Ze.documentDecryptFailures)?Ze.documentDecryptFailures.filter(W=>String(W||"").trim().length>0):[];if(en.length>0&&Ga("pull_document_decrypt_failures",{workspaceId:s,failureCount:en.length}),z.current=Ze.cursor||null,Ze.appliedChanges>0&&(Ze.pulledActiveUpserts||Ze.pulledArchivedUpserts||Ze.pulledTaskEventUpserts))try{await Q()}catch{Ga("pull_local_refresh_failed",{workspaceId:s,appliedChanges:Ze.appliedChanges})}b(),g();const Lt=Ze.syncedAt||new Date().toISOString();Rt(Lt),Dt(0),tt("idle");const bt=db({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,startupFullReconcileRan:ft.current,pendingSignature:Te.current,fallbackSignature:H(),lastPushedSignature:ge.current});if(bt.shouldCaptureAttachBootstrapBaseline&&($e.current=!0),bt.shouldClearPendingSignature&&(Te.current="",ve.current=null),await x({phase:"active",pullCursor:z.current,lastPullAt:Lt,lastSyncedAt:Lt,lastErrorMessage:null}),M(s,{eventType:bt.successEventType,status:"success",changeCount:Ze.appliedChanges,requestMs:Ze.pullRequestMs,details:{pages:Ze.pages,applyMs:Ze.applyMs,...Ze.serverDiagnostics?{serverPullDiagnostics:Ze.serverDiagnostics}:{}}}),bt.shouldRefreshReferenceSnapshots&&(await ce(),await be(),await _(),await J()),bt.shouldSeedWorkspaceSnapshotPushBaseline&&P(),bt.shouldRefreshReferenceSnapshots||bt.shouldSeedWorkspaceSnapshotPushBaseline)return!0;if(bt.shouldScheduleStartupFullReconcile&&(ft.current=!0,window.setTimeout(()=>{gt.current||(gt.current=!0,Qe({forceCursorNull:!0}).finally(()=>{gt.current=!1}))},250)),bt.deferredPushSignature){const W=bt.deferredPushSignature;window.setTimeout(()=>{We(W)},120)}return!0}catch(vt){const $t=String(vt?.message||"").trim(),Ze=$t?`Workspace sync pull failed. ${$t}`:"Workspace sync pull failed.";return tt("error"),rt(Ze),Pt(Ze),yt(new Date().toISOString()),k(),M(s,{eventType:"pull",status:"error",errorMessage:Ze,requestMs:Date.now()-St}),Ga("pull_failed_exception",{workspaceId:s,elapsedMs:Date.now()-St,error:$t||null}),!1}finally{Se.current=!1,ne(Ce.current),ue(s)}};return{pushWorkspaceChangesToCloud:We,pullWorkspaceChangesFromCloud:Qe}}const Qf={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1};function mb(e){const{currentWorkspaceId:n,cloudAuthConfigured:a,runtimeMode:s,authSessionResolved:o,isAuthenticated:c,authUserId:i,projectName:l,resolveCloudAuthUrl:m,resolveWebSocketUrl:y,realtimeSyncEnabled:v,tasks:b,archivedTasks:g,deletedTasks:h=[],initiatives:k,workstreams:I,taxonomies:x,taxonomyState:A,setupState:M,globalTheme:B,locale:ue,globalWeekStartsOn:X,themeUseGlobalDefault:ce,setTasks:oe,setArchivedTasks:be,setAuthBlocked:_,setIsAuthenticated:J,checkAuthSession:Q,setGlobalTheme:ie,setCurrentTheme:H,setSetupState:P,setLocale:U,setGlobalWeekStartsOn:se,fetchPlanningEntities:he}=e,V=r.useMemo(()=>Vv(A),[A]),[Ce,Se]=r.useState("disconnected"),[ve,ge]=r.useState(null),[Te,Le]=r.useState(null),[Ie,Oe]=r.useState(null),[z,T]=r.useState(null),[w,j]=r.useState(null),[F,ee]=r.useState(!1),[N,C]=r.useState("idle"),[$,K]=r.useState(null),[te,L]=r.useState(!1),[re,fe]=r.useState(0),[xe,le]=r.useState([]),[we,Re]=r.useState(""),Xe=r.useRef(b||[]),ze=r.useRef(g||[]),lt=r.useRef(k||[]),wt=r.useRef(I||[]),$e=r.useRef([]),ft=r.useRef(new Set),[gt,at]=r.useState([]),[dt,ne]=r.useState(""),[tt,rt]=r.useState(null),[Pt,yt]=r.useState(null),[Rt,Tt]=r.useState(0),[Dt,d]=r.useState(null),Me=r.useRef([]),[We,Qe]=r.useState([]),[ot,de]=r.useState(""),Be=r.useRef([]),St=r.useRef(new Set),[vt,$t]=r.useState([]),[Ze,en]=r.useState(""),Lt=r.useRef([]),bt=r.useRef([]),[W,ke]=r.useState([]),[Ne,ae]=r.useState(""),Pe=r.useRef([]),[Ge,De]=r.useState(Qf),[it,Ut]=r.useState("degraded-fallback"),[Gt,nn]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),Ft=r.useRef(!1),Wt=r.useRef(null),Vt=r.useRef("missing-baseline"),an=r.useRef(0),Kt=r.useRef(!1),Kn=r.useRef(new Set),Fn=r.useRef(""),Jn=r.useRef(""),_n=r.useRef(""),pe=r.useRef(""),et=r.useRef(""),Ae=r.useRef(""),Nt=r.useRef(!1),Ye=r.useRef(null),Ot=r.useRef(new Set),dn=r.useRef([]),yn=r.useRef(null),on=r.useRef(()=>Promise.resolve(!1)),rn=r.useRef(async()=>{}),kt=r.useRef(null),zt=r.useRef(null),Ln=r.useRef("idle"),Et=r.useCallback(()=>{Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null)},[]),On=r.useCallback(R=>{if(typeof window>"u")return;Et();const E=Math.max(1,Math.floor(an.current)+1);an.current=E;const je=1500*2**Math.max(0,E-1),ct=Number.isFinite(Number(R))?Math.max(0,Math.floor(Number(R))):0,nt=Math.max(Math.min(12e4,je),ct);Wt.current=window.setTimeout(()=>{Wt.current=null,rn.current({preferCloudOnFirstSync:!1})},nt)},[Et]),kn=r.useCallback(R=>{De(E=>E[R]?E:{...E,[R]:!0})},[]),Jt=Object.values(Ge).every(Boolean),{workspaceRetryAt:Dr,isWorkspaceRetryPending:Rn,workspacePushInFlightRef:Xn,workspacePullInFlightRef:In,workspaceLastPushedSignatureRef:Yt,workspacePendingSignatureRef:jn,workspaceLastPushedTaskIdsRef:ln,workspaceDeletedTaskIdsRef:ga,workspaceDeletedTaskWatermarksRef:la,workspacePullCursorRef:Za,clearWorkspaceRetry:fn,scheduleWorkspaceRetry:Cr,persistWorkspaceSyncPatch:Lr,applyWorkspaceSyncPatchLocally:ya,readWorkspaceSyncStateSnapshot:Bn,loadWorkspaceSyncState:Ar,applyWorkspaceSyncStateSnapshot:ka,saveWorkspaceCloudSyncSettings:ja,acquireWorkspaceSyncLease:Qn,releaseWorkspaceSyncLease:Tn,forceClearWorkspaceSyncLease:Br}=Lv({currentWorkspaceId:n,setWorkspaceCloudSyncEnabled:ee,setWorkspaceSyncPhase:C,setWorkspaceSyncSetupIntent:K,setWorkspaceLastPullAt:Le,setWorkspaceLastPushAt:Oe,setWorkspaceLastErrorMessage:j}),_t=r.useCallback(R=>{(R.phase==="attach-cloud"||R.phase==="provision-local")&&(Ln.current=R.phase,kt.current===null&&(kt.current=Date.now()),zt.current=null),ka(R)},[ka]),Sa=r.useRef(new Map),da=r.useRef(new Map),va=r.useRef(new Set),$n=r.useRef(new Map),Pa=r.useRef(new Set),wn=r.useRef(new Map),Un=r.useRef(new Set),ba=r.useRef(new Map),un=r.useRef(new Map),Ea=r.useRef(new Set),Qt=r.useRef(new Map),qn=r.useRef(new Set),Cn=r.useRef(new Map),Ya=r.useRef(new Set),Ja=r.useRef(new Map),Mn=r.useRef(new Set),cn=r.useRef(new Map),hn=r.useRef(new Set),ua=r.useRef(new Map),ea=r.useRef(new Map),pr=r.useCallback(R=>R?(ln.current=new Set(R.taskIds),Sa.current=R.taskWatermarks,da.current=R.taskChangeKeys||new Map,va.current=new Set(Array.from(R.initiativeWatermarks.keys())),$n.current=R.initiativeWatermarks,Pa.current=new Set(Array.from(R.workstreamWatermarks.keys())),wn.current=R.workstreamWatermarks,Un.current=new Set(Array.from(R.aiProfileWatermarks.keys())),ba.current=R.aiProfileWatermarks,un.current=R.aiProfileChangeKeys||new Map,Ea.current=new Set(Array.from(R.documentWatermarks.keys())),Qt.current=R.documentWatermarks,qn.current=new Set(Array.from(R.assetWatermarks.keys())),Cn.current=R.assetWatermarks,Ya.current=new Set(Array.from(R.documentReviewSessionWatermarks.keys())),Ja.current=R.documentReviewSessionWatermarks,Mn.current=new Set(Array.from(R.documentReviewCommentWatermarks.keys())),cn.current=R.documentReviewCommentWatermarks,hn.current=new Set(Array.from(R.annotatedAttachmentSessionWatermarks.keys())),ua.current=R.annotatedAttachmentSessionWatermarks,ea.current=R.taskEventWatermarks,Vt.current=null,!0):!1,[ln]),fr=r.useCallback(()=>({taskIds:ln.current,taskWatermarks:Sa.current,taskChangeKeys:da.current,initiativeWatermarks:$n.current,workstreamWatermarks:wn.current,aiProfileWatermarks:ba.current,aiProfileChangeKeys:un.current,documentWatermarks:Qt.current,assetWatermarks:Cn.current,documentReviewSessionWatermarks:Ja.current,documentReviewCommentWatermarks:cn.current,annotatedAttachmentSessionWatermarks:ua.current,taskEventWatermarks:ea.current}),[]),Xt=r.useRef(!1),ms=r.useRef(!1),zn=r.useRef(!1),Xa=r.useRef(""),Vr=r.useRef(!1),ma=3e4,qa=v?3e4:15e3,Wr=Math.max(3e4,qa),wa=r.useMemo(()=>{const R=Te?Date.parse(Te):NaN,E=Ie?Date.parse(Ie):NaN;return Number.isFinite(R)&&Number.isFinite(E)?R>=E?Te:Ie:Number.isFinite(R)?Te:Number.isFinite(E)?Ie:null},[Te,Ie]),Hn=r.useMemo(()=>eb({enabled:F,phase:N,busy:te,retryAt:Dr,lastErrorMessage:w}),[F,N,te,Dr,w]),Ir=Hn.status,Pn=Hn.summary,ps=Hn.recommendedAction,ta=r.useCallback(R=>{const E=String(R||"").trim();if(!E)return null;const ct=Yf()[E]?.updatedAt;return typeof ct=="string"&&ct.trim().length>0?ct.trim():null},[]),Tr=r.useCallback((R,E)=>{const je=String(R||"").trim(),ct=String(E||"").trim();if(!je||!ct)return;const nt=Yf();nt[je]={updatedAt:ct},Gv(nt)},[]),hr=r.useCallback(()=>{const R=M?.mode==="operations"?"operations":"core";return{theme:B,operatingMode:R,localization:{locale:ue,weekStartsOn:X}}},[B,M?.mode,ue,X]),Fr=r.useCallback(async R=>{if(!(!R||typeof R!="object")){Kt.current=!0;try{const E={},je=Rc(R.theme);if(je&&(ie(je),ce&&H(je),E.theme=je),(R.operatingMode==="core"||R.operatingMode==="operations")&&(P(ct=>ct&&{...ct,mode:R.operatingMode}),E.setup={mode:R.operatingMode}),R.localization&&typeof R.localization=="object"){const ct={};if(typeof R.localization.locale=="string"&&R.localization.locale.trim().length>0){const Y=pg(R.localization.locale.trim());U(Y)}const nt=String(R.localization.weekStartsOn||"").trim().toLowerCase();(nt==="sunday"||nt==="monday")&&(se(nt),ct.weekStartsOn=nt),Object.keys(ct).length>0&&(E.schedulePreferences=ct)}Object.keys(E).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(E)})}finally{Kt.current=!1}}},[ce,ie,H,P,U,se]),pa=r.useCallback(async R=>{const E=R?.preferCloudOnFirstSync!==!1;if(!a)return;if(s!=="local"||!c){Et(),an.current=0,Se("disconnected");return}const je=String(i||"").trim();if(!je||je==="anonymous"){Et(),an.current=0,Se("disconnected");return}if(!Ft.current){Se("syncing"),ge(null),Ft.current=!0;try{const ct=await ev({resolveCloudAuthUrl:m,userId:je,preferCloudOnFirstSync:E,getLocalUpdatedAt:ta,buildLocalSettings:hr,applyRemoteSettings:Fr});if(!ct.success){Se("error"),ct.transient?(ge(ct.error||"Sync failed temporarily. Retrying automatically."),On(ct.retryAfterMs)):(Et(),an.current=0,ge(ct.error||"Sync failed."));return}Et(),an.current=0;const nt=String(ct.updatedAt||"").trim()||new Date().toISOString();Tr(je,nt),Se("idle"),ge(null),Kn.current.add(je),ct.mode==="pulled"&&(Fn.current="")}catch{Se("error"),ge("Sync failed temporarily. Retrying automatically."),On()}finally{Ft.current=!1}}},[a,s,c,i,m,ta,hr,Fr,Tr,Et,On]);r.useEffect(()=>{rn.current=pa},[pa]),r.useEffect(()=>()=>{Et()},[Et]);const gr=r.useCallback(()=>{j(null),T(null)},[]),xa=r.useCallback(R=>{j(Zf),T(new Date().toISOString()),Se("error"),ge(Zf),Ga("workspace_sync_window_contention",{workspaceId:n,operation:R})},[n]),Ma=r.useCallback(async R=>{try{return await Lr(R)}catch{return ya(R)}},[ya,Lr]),Qa=r.useCallback(R=>{Ma(R).catch(()=>{})},[Ma]),Kr=r.useCallback(()=>{const R={...fr(),taxonomyStateFingerprint:V},E=Xf(n,R);return Ma({pushBaseline:jg(R)}).catch(()=>{}),E},[fr,n,Ma,V]);r.useEffect(()=>{Jn.current="",_n.current="",pe.current="",et.current="",Ae.current="",Xa.current="",Vr.current=!1,le([]),Re(""),Me.current=[],at([]),ne(""),Qe([]),de(""),Lt.current=[],bt.current=[],$t([]),en(""),Pe.current=[],ke([]),ae(""),De(Qf),j(null),T(null),fe(0),Ot.current=new Set,dn.current=[],Sa.current=new Map,da.current=new Map,va.current=new Set,$n.current=new Map,Pa.current=new Set,wn.current=new Map,Un.current=new Set,ba.current=new Map,un.current=new Map,Ea.current=new Set,Qt.current=new Map,qn.current=new Set,Cn.current=new Map,Ya.current=new Set,Ja.current=new Map,Mn.current=new Set,cn.current=new Map,hn.current=new Set,ua.current=new Map,ea.current=new Map,ms.current=!1,Dn.current=!1;const R=Jf(n,V);pr(R)||(Vt.current="missing-baseline")},[n,pr,V]),r.useEffect(()=>{if(Vt.current!=="missing-baseline")return;const R=Jf(n,V);if(pr(R))return;const E=Pg(Bn().pushBaseline,V);pr(E)&&Xf(n,{...fr(),taxonomyStateFingerprint:V})},[fr,n,pr,Bn,V,F,N]);const Or=r.useCallback(R=>{Cr(()=>on.current(),{minDelayMs:R})},[Cr]);r.useEffect(()=>{Yv({workspaceSyncPhase:N,lastBootstrapPhaseRef:Ln,bootstrapPhaseStartedAtRef:kt,bootstrapLastProgressAtRef:zt})},[N]),r.useEffect(()=>Jv({currentWorkspaceId:n,workspaceCloudSyncEnabled:F,workspaceSyncPhase:N,workspacePullInFlightRef:In,workspacePushInFlightRef:Xn,bootstrapPhaseStartedAtRef:kt,bootstrapLastProgressAtRef:zt,setWorkspaceLastErrorMessage:R=>j(R),setWorkspaceLastErrorAt:R=>T(R),setUserGlobalSyncStatus:Se,setUserGlobalSyncError:R=>ge(R),setWorkspaceSyncBusy:L,persistWorkspaceSyncPatchSafely:Qa}),[n,F,N,Qa,In,Xn]);const Ve=r.useCallback(async()=>YS({cloudAuthConfigured:a,runtimeMode:s,isAuthenticated:c,resolveCloudAuthUrl:m,workspaceId:n,workspaceName:l||n,allowProvisionOnMismatch:N!=="attach-cloud"}),[a,s,c,m,n,l,N]);r.useEffect(()=>{Xe.current=b||[]},[b]),r.useEffect(()=>{ze.current=g||[]},[g]),r.useEffect(()=>{ga.current=new Set((h||[]).map(R=>String(R?.taskId||"").trim()).filter(R=>R.length>0)),la.current=new Map((h||[]).map(R=>[String(R?.taskId||"").trim(),String(R?.deletedAt||"").trim()]).filter(([R,E])=>R.length>0&&Number.isFinite(Date.parse(E))))},[h,ga,la]),r.useEffect(()=>{lt.current=k||[]},[k]),r.useEffect(()=>{wt.current=I||[]},[I]);const Bt=r.useRef(!1),Dn=r.useRef(!1),sn=r.useCallback(R=>{const E=R?.forceAllAiProfiles===!0;return xv({tasks:Xe.current,archivedTasks:ze.current,taskEvents:ju(Xe.current,ze.current),lastPushedTaskIds:ln.current,pendingDeletedTaskIds:ga.current,pendingDeletedTaskWatermarks:la.current,initiatives:lt.current,workstreams:wt.current,taxonomies:x||[],taxonomyState:A,lastPushedInitiativeIds:va.current,lastPushedInitiativeWatermarks:$n.current,lastPushedWorkstreamIds:Pa.current,lastPushedWorkstreamWatermarks:wn.current,aiProfiles:Me.current,lastPushedAiProfileIds:E?new Set:Un.current,lastPushedAiProfileWatermarks:E?new Map:ba.current,lastPushedAiProfileChangeKeys:E?new Map:un.current,documents:$e.current,assets:Be.current,currentDocumentPaths:ft.current,currentAssetPaths:St.current,documentReviewSessions:Lt.current,documentReviewComments:bt.current,annotatedAttachmentSessions:Pe.current,lastPushedDocumentPaths:Ea.current,lastPushedDocumentWatermarks:Qt.current,lastPushedAssetPaths:qn.current,lastPushedAssetWatermarks:Cn.current,lastPushedDocumentReviewSessionIds:Ya.current,lastPushedDocumentReviewSessionWatermarks:Ja.current,lastPushedDocumentReviewCommentIds:Mn.current,lastPushedDocumentReviewCommentWatermarks:cn.current,lastPushedAnnotatedAttachmentSessionIds:hn.current,lastPushedAnnotatedAttachmentSessionWatermarks:ua.current,lastPushedTaskEventWatermarks:ea.current,baselineResetReason:Vt.current,lastPushedWatermarks:Sa.current,lastPushedTaskChangeKeys:da.current})},[x,A]),_a=r.useCallback((R,E)=>{if(s==="local")try{const je={...E,workspaceId:R,details:mm(E.details)};fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(je)}).catch(ct=>{Ga("sync_event_post_failed",{workspaceId:R,eventType:E.eventType,status:E.status,error:String(ct?.message||ct||"")})})}catch(je){Ga("sync_event_post_failed",{workspaceId:R,eventType:E.eventType,status:E.status,error:String(je?.message||je||"")})}},[s]),Zn=r.useCallback(()=>_v({workspaceId:n,tasks:Xe.current,archivedTasks:ze.current,taskEvents:ju(Xe.current,ze.current),pendingDeletedTaskIds:ga.current,initiatives:lt.current,workstreams:wt.current,taxonomies:x||[],aiProfiles:Me.current,documents:$e.current,assets:Be.current,documentReviewSessions:Lt.current,documentReviewComments:bt.current,annotatedAttachmentSessions:Pe.current}),[n,x,A]),Is=r.useMemo(()=>JSON.stringify({tasks:(b||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),status:String(R.status||"").trim(),referenceNumber:R.referenceNumber??null,localReferenceNumber:R.localReferenceNumber??null})).sort((R,E)=>R.id.localeCompare(E.id)),archivedTasks:(g||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),status:String(R.status||"").trim(),referenceNumber:R.referenceNumber??null,localReferenceNumber:R.localReferenceNumber??null})).sort((R,E)=>R.id.localeCompare(E.id)),initiatives:(k||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),isArchived:!!R.isArchived})).sort((R,E)=>R.id.localeCompare(E.id)),workstreams:(I||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),initiativeId:typeof R.initiativeId=="string"?R.initiativeId.trim():"",isArchived:!!R.isArchived})).sort((R,E)=>R.id.localeCompare(E.id)),taskEvents:ju(b||[],g||[]).map(R=>({id:String(R.id||"").trim(),taskId:String(R.taskId||"").trim(),createdAt:String(R.createdAt||"").trim(),action:String(R.action||"").trim()})).sort((R,E)=>R.id.localeCompare(E.id)),deletedTasks:(h||[]).map(R=>({taskId:String(R?.taskId||"").trim(),deletedAt:String(R?.deletedAt||"").trim()})).filter(R=>R.taskId.length>0&&Number.isFinite(Date.parse(R.deletedAt))).sort((R,E)=>R.taskId.localeCompare(E.taskId)),taxonomies:Array.isArray(x)?x:[],taxonomyState:A&&typeof A=="object"?A:null}),[b,g,h,k,I,x,A]),Zr=r.useMemo(()=>{const R=[];for(const E of b||[]){const je=Array.isArray(E.attachments)?E.attachments.length:0;je>0&&R.push(`${E.id}:${je}`)}return R.join("|")},[b]),Yr=r.useCallback(R=>{if(!R)return!1;if(Vr.current)return Vr.current=!1,Xa.current=R,Yt.current=R,fe(0),!0;const E=Xa.current;return E?R===E?(Yt.current=R,fe(0),!0):(Xa.current="",!1):!1},[]),Yn=r.useCallback(async()=>{if(s==="local"&&Ci(n)&&!(a&&(!o||!c)))try{const R=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const E=await R.json().catch(()=>({})),je=Array.isArray(E?.documents)?E.documents.map(Y=>({path:String(Y?.path||"").trim(),updatedAt:String(Y?.updatedAt||"").trim(),content:typeof Y?.content=="string"?Y.content:"",assetId:typeof Y?.assetId=="string"&&Y.assetId.trim().length>0?Y.assetId.trim():void 0,documentId:typeof Y?.documentId=="string"&&Y.documentId.trim().length>0?Y.documentId.trim():null,referenceNumber:Number.isFinite(Number(Y?.referenceNumber))?Math.max(1,Math.floor(Number(Y.referenceNumber))):null,version:Number.isFinite(Number(Y?.version))?Math.max(1,Math.floor(Number(Y.version))):null,taskId:typeof Y?.taskId=="string"&&Y.taskId.trim().length>0?Y.taskId.trim():null,logicalName:typeof Y?.logicalName=="string"&&Y.logicalName.trim().length>0?Y.logicalName.trim():null,caption:typeof Y?.caption=="string"&&Y.caption.trim().length>0?Y.caption.trim():null,originalFilename:typeof Y?.originalFilename=="string"&&Y.originalFilename.trim().length>0?Y.originalFilename.trim():null,linkRole:Y?.linkRole==="reference"?"reference":"attachment"})).filter(Y=>Y.path.length>0):[],ct=new Set(Array.isArray(E?.knownPaths)?E.knownPaths.map(Y=>String(Y||"").trim()).filter(Y=>Y.length>0):je.map(Y=>Y.path)),nt=typeof E?.fingerprint=="string"?E.fingerprint:JSON.stringify(je.map(Y=>`${Y.path}:${Y.updatedAt}:${Y.content.length}`).sort());if(nt===Jn.current)return;Jn.current=nt,$e.current=je,ft.current=ct,le(je),Re(nt)}catch(R){Ga("documents_snapshot_refresh_failed",{workspaceId:n,error:String(R?.message||R||"")})}finally{kn("documents")}},[s,n,a,o,c,kn]),Mt=r.useCallback(async()=>{if(s!=="local"){d("runtime-not-local");return}if(!Ci(n)){d("workspace-id-invalid");return}if(a&&(!o||!c)){d(o?"auth-required":"auth-unresolved");return}d(null);try{const R=await fetch(`/api/taskforce/sync/workspace/ai-profiles?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!R.ok){yt(`HTTP ${R.status}`),rt(new Date().toISOString());return}const E=await R.json().catch(()=>({})),je=Array.isArray(E?.aiProfiles)?E.aiProfiles:[];Tt(je.length);const ct=Array.isArray(E?.aiProfiles)?E.aiProfiles.map(Y=>Hv(Y)).filter(Y=>Y.id.length>0&&Y.workspaceId.length>0):[];yt(null),rt(new Date().toISOString());const nt=typeof E?.fingerprint=="string"?E.fingerprint:JSON.stringify(ct.map(Y=>[Y.id,Y.updatedAt,Y.name,Y.username,Y.archivedAt??"",Y.archivedReason??"",Y.mergedIntoProfileId??"",Y.rosterStateUpdatedAt??""].join(":")).sort());if(nt===_n.current)return;_n.current=nt,Me.current=ct,at(ct),ne(nt)}catch(R){yt(String(R?.message||R||"unknown-error")),rt(new Date().toISOString()),Ga("ai_profiles_snapshot_refresh_failed",{workspaceId:n,error:String(R?.message||R||"")})}finally{kn("aiProfiles")}},[s,n,a,o,c,kn]),mn=r.useCallback(async()=>{if(s==="local"&&Ci(n)&&!(a&&(!o||!c)))try{const R=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const E=await R.json().catch(()=>({})),je=Array.isArray(E?.assets)?E.assets.map(Y=>({path:String(Y?.path||"").trim(),updatedAt:String(Y?.updatedAt||"").trim(),contentBase64:typeof Y?.contentBase64=="string"?Y.contentBase64:"",assetId:typeof Y?.assetId=="string"&&Y.assetId.trim().length>0?Y.assetId.trim():void 0,kind:Y?.kind==="image"?"image":"file",mimeType:typeof Y?.mimeType=="string"&&Y.mimeType.trim().length>0?Y.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(Y?.referenceNumber))?Math.max(1,Math.floor(Number(Y.referenceNumber))):null,taskId:typeof Y?.taskId=="string"&&Y.taskId.trim().length>0?Y.taskId.trim():null,logicalName:typeof Y?.logicalName=="string"&&Y.logicalName.trim().length>0?Y.logicalName.trim():null,caption:typeof Y?.caption=="string"&&Y.caption.trim().length>0?Y.caption.trim():null,originalFilename:typeof Y?.originalFilename=="string"&&Y.originalFilename.trim().length>0?Y.originalFilename.trim():null,linkRole:Y?.linkRole==="reference"?"reference":Y?.linkRole==="image"?"image":"attachment"})).filter(Y=>Y.path.length>0&&Y.contentBase64.length>0):[],ct=new Set(Array.isArray(E?.knownPaths)?E.knownPaths.map(Y=>String(Y||"").trim()).filter(Y=>Y.length>0):je.map(Y=>Y.path)),nt=typeof E?.fingerprint=="string"?E.fingerprint:JSON.stringify(je.map(Y=>`${Y.path}:${Y.updatedAt}:${Y.contentBase64.length}`).sort());if(nt===pe.current)return;pe.current=nt,Be.current=je,St.current=ct,Qe(je),de(nt)}catch(R){Ga("assets_snapshot_refresh_failed",{workspaceId:n,error:String(R?.message||R||"")})}finally{kn("assets")}},[s,n,a,o,c,kn]),Da=r.useCallback(async()=>{if(s==="local"&&Ci(n)&&!(a&&(!o||!c)))try{const R=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const E=await R.json().catch(()=>({})),je=Array.isArray(E?.sessions)?E.sessions.map(Y=>({id:String(Y?.id||"").trim(),assetId:String(Y?.assetId||"").trim(),documentId:typeof Y?.documentId=="string"&&Y.documentId.trim().length>0?Y.documentId.trim():null,documentVersion:Number.isFinite(Number(Y?.documentVersion))?Math.max(1,Math.floor(Number(Y.documentVersion))):null,title:typeof Y?.title=="string"&&Y.title.trim().length>0?Y.title.trim():null,status:Y?.status==="resolved"?"resolved":"open",comments:Array.isArray(Y?.comments)?Y.comments:[],createdByActorId:typeof Y?.createdByActorId=="string"&&Y.createdByActorId.trim().length>0?Y.createdByActorId.trim():null,updatedByActorId:typeof Y?.updatedByActorId=="string"&&Y.updatedByActorId.trim().length>0?Y.updatedByActorId.trim():null,createdAt:String(Y?.createdAt||"").trim(),updatedAt:String(Y?.updatedAt||Y?.createdAt||"").trim(),deletedAt:typeof Y?.deletedAt=="string"&&Y.deletedAt.trim().length>0?Y.deletedAt.trim():null})).filter(Y=>Y.id.length>0&&Y.assetId.length>0):[],ct=Array.isArray(E?.comments)?E.comments.map(Y=>({id:String(Y?.id||"").trim(),sessionId:String(Y?.sessionId||"").trim(),body:typeof Y?.body=="string"?Y.body:"",anchor:Y?.anchor??null,order:Number.isFinite(Number(Y?.order))?Math.max(0,Math.floor(Number(Y.order))):0,authorActorId:typeof Y?.authorActorId=="string"&&Y.authorActorId.trim().length>0?Y.authorActorId.trim():null,createdAt:String(Y?.createdAt||"").trim(),updatedAt:String(Y?.updatedAt||Y?.createdAt||"").trim(),deletedAt:typeof Y?.deletedAt=="string"&&Y.deletedAt.trim().length>0?Y.deletedAt.trim():null})).filter(Y=>Y.id.length>0&&Y.sessionId.length>0):Kv(je),nt=typeof E?.fingerprint=="string"?E.fingerprint:JSON.stringify([...je.map(Y=>`${Y.id}:${Y.updatedAt}:${Y.status}:${Y.deletedAt||""}:${Y.comments.length}`).sort(),...ct.map(Y=>`${Y.id}:${Y.sessionId}:${Y.updatedAt}:${Y.deletedAt||""}`).sort()]);if(nt===et.current)return;et.current=nt,Lt.current=je,bt.current=ct,$t(je),en(nt)}catch(R){Ga("document_review_sessions_snapshot_refresh_failed",{workspaceId:n,error:String(R?.message||R||"")})}finally{kn("documentReviewSessions")}},[s,n,a,o,c,kn]),yr=r.useCallback(async()=>{if(s==="local"&&Ci(n)&&!(a&&(!o||!c)))try{const R=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(n)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const E=await R.json().catch(()=>({})),je=Array.isArray(E?.sessions)?E.sessions.map(nt=>({id:String(nt?.id||"").trim(),workspaceId:String(nt?.workspaceId||"").trim(),taskId:String(nt?.taskId||"").trim(),baseImageAssetId:String(nt?.baseImageAssetId||"").trim(),title:typeof nt?.title=="string"&&nt.title.trim().length>0?nt.title.trim():null,globalInstruction:typeof nt?.globalInstruction=="string"&&nt.globalInstruction.trim().length>0?nt.globalInstruction.trim():null,annotations:Array.isArray(nt?.annotations)?nt.annotations:[],createdByActorId:typeof nt?.createdByActorId=="string"&&nt.createdByActorId.trim().length>0?nt.createdByActorId.trim():null,updatedByActorId:typeof nt?.updatedByActorId=="string"&&nt.updatedByActorId.trim().length>0?nt.updatedByActorId.trim():null,createdAt:String(nt?.createdAt||"").trim(),updatedAt:String(nt?.updatedAt||nt?.createdAt||"").trim(),deletedAt:typeof nt?.deletedAt=="string"&&nt.deletedAt.trim().length>0?nt.deletedAt.trim():null})).filter(nt=>nt.id.length>0&&nt.workspaceId.length>0&&nt.taskId.length>0&&nt.baseImageAssetId.length>0):[],ct=typeof E?.fingerprint=="string"?E.fingerprint:JSON.stringify(je.map(nt=>`${nt.id}:${nt.updatedAt}:${nt.taskId}:${nt.baseImageAssetId}:${nt.annotations.length}:${nt.deletedAt||""}`).sort());if(ct===Ae.current)return;Ae.current=ct,Pe.current=je,ke(je),ae(ct)}catch(R){Ga("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:n,error:String(R?.message||R||"")})}finally{kn("annotatedAttachmentSessions")}},[s,n,a,o,c,kn]),kr=r.useCallback(()=>{ln.current=new Set([...Xe.current,...ze.current].map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),Sa.current=new Map([...Xe.current,...ze.current].map(E=>[String(E?.id||"").trim(),ls.getWatermark(E)]).filter(([E])=>E.length>0)),da.current=new Map([...Xe.current.map(E=>[String(E?.id||"").trim(),ls.getChangeKey({...E,isArchived:!1})]),...ze.current.map(E=>[String(E?.id||"").trim(),ls.getChangeKey({...E,isArchived:!0})])].filter(([E])=>E.length>0)),va.current=new Set(lt.current.map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),$n.current=new Map(lt.current.map(E=>[String(E?.id||"").trim(),String(E?.updatedAt||E?.createdAt||"").trim()]).filter(([E])=>E.length>0)),Pa.current=new Set(wt.current.map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),wn.current=new Map(wt.current.map(E=>[String(E?.id||"").trim(),String(E?.updatedAt||E?.createdAt||"").trim()]).filter(([E])=>E.length>0)),Un.current=new Set(Me.current.map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),ba.current=new Map(Me.current.map(E=>[String(E?.id||"").trim(),rd.getWatermark(E)]).filter(([E])=>E.length>0)),un.current=new Map(Me.current.map(E=>[String(E?.id||"").trim(),rd.getChangeKey(E)]).filter(([E])=>E.length>0)),Ea.current=new Set($e.current.map(E=>String(E?.path||"").trim()).filter(E=>E.length>0)),Qt.current=new Map($e.current.map(E=>[String(E?.path||"").trim(),String(E?.updatedAt||"").trim()]).filter(([E])=>E.length>0)),qn.current=new Set(Be.current.map(E=>String(E?.path||"").trim()).filter(E=>E.length>0)),Cn.current=new Map(Be.current.map(E=>[String(E?.path||"").trim(),String(E?.updatedAt||"").trim()]).filter(([E])=>E.length>0)),Ya.current=new Set(Lt.current.map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),Ja.current=new Map(Lt.current.map(E=>[String(E?.id||"").trim(),String(E?.updatedAt||E?.createdAt||"").trim()]).filter(([E])=>E.length>0)),Mn.current=new Set(bt.current.map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),cn.current=new Map(bt.current.map(E=>[String(E?.id||"").trim(),String(E?.updatedAt||E?.createdAt||"").trim()]).filter(([E])=>E.length>0)),hn.current=new Set(Pe.current.map(E=>String(E?.id||"").trim()).filter(E=>E.length>0)),ua.current=new Map(Pe.current.map(E=>[String(E?.id||"").trim(),String(E?.updatedAt||E?.createdAt||"").trim()]).filter(([E])=>E.length>0)),ea.current=new Map(ju(Xe.current,ze.current).map(E=>[String(E?.id||"").trim(),String(E?.createdAt||"").trim()]).filter(([E])=>E.length>0));const R=Kr();Vt.current=R?null:"storage-write-failed"},[Kr]),er=r.useCallback(async()=>{const[R,E]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(R.ok){const je=await R.json().catch(()=>({})),ct=Array.isArray(je?.tasks)?je.tasks.map(nt=>fo(nt)):[];oe(ct)}if(E.ok){const je=await E.json().catch(()=>({})),ct=Array.isArray(je?.archived)?je.archived.map(nt=>({...fo(nt),isArchived:!0})):[];be(ct)}await he().catch(()=>{Ga("refresh_planning_entities_failed",{workspaceId:n})})},[n,he,be,oe]),{handleSyncAuthFailure:fs,ensureWorkspaceSyncReady:Nr}=r.useMemo(()=>Zv({currentWorkspaceId:n,workspaceSyncPhase:N,clearWorkspaceRetry:fn,setWorkspaceSyncBusy:L,setUserGlobalSyncStatus:Se,setUserGlobalSyncError:R=>ge(R),setWorkspaceLastErrorMessage:R=>j(R),setWorkspaceLastErrorAt:R=>T(R),reportSyncEvent:_a,setAuthBlocked:_,setIsAuthenticated:J,checkAuthSession:Q,ensureCloudWorkspaceReadyForSync:Ve,scheduleWorkspaceSyncRetry:Or,persistWorkspaceSyncPatchSafely:Qa}),[n,N,fn,_a,_,J,Q,Ve,Or,Qa]),Jr=r.useMemo(()=>ub({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:n,workspaceSyncPhase:N,isAuthenticated:c,checkAuthSession:Q,resolveCloudAuthUrl:m,ensureCloudWorkspaceReadyForSync:Ve,ensureWorkspaceSyncReady:Nr,handleSyncAuthFailure:fs,clearWorkspaceRetry:fn,clearWorkspaceIssue:gr,isWorkspaceRetryPending:Rn,scheduleWorkspaceSyncRetry:Or,persistWorkspaceSyncPatchSafely:Qa,persistWorkspaceSyncPatchBestEffort:Ma,persistWorkspaceSyncWatermarksSnapshotBestEffort:Kr,reportSyncEvent:_a,acquireWorkspaceSyncLease:Qn,releaseWorkspaceSyncLease:Tn,reportWorkspaceWindowContention:xa,refreshWorkspaceSyncMarkdownDocumentsSnapshot:Yn,refreshWorkspaceSyncAiProfilesSnapshot:Mt,refreshWorkspaceSyncAssetsSnapshot:mn,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:Da,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:yr,refreshLocalWorkspaceTaskCollections:er,buildWorkspaceSyncPayload:sn,buildWorkspaceSyncSignature:Zn,seedWorkspaceSnapshotPushBaseline:kr,shouldSuppressAttachBootstrapPush:Yr,recordSuppressedEventIds:(...R)=>Ts.current.recordSuppressedEventIds(...R),workspaceRepairModeRef:zn,workspaceForceFullAiProfilePushRef:Bt,workspacePushInFlightRef:Xn,workspacePullInFlightRef:In,workspacePendingPushReplayRef:yn,workspaceLastPushedSignatureRef:Yt,workspacePendingSignatureRef:jn,workspaceLastPushedTaskIdsRef:ln,workspaceDeletedTaskIdsRef:ga,workspaceDeletedTaskWatermarksRef:la,workspacePullCursorRef:Za,workspaceLastPushedWatermarksRef:Sa,workspaceLastPushedTaskChangeKeysRef:da,workspaceLastPushedInitiativeIdsRef:va,workspaceLastPushedInitiativeWatermarksRef:$n,workspaceLastPushedWorkstreamIdsRef:Pa,workspaceLastPushedWorkstreamWatermarksRef:wn,workspaceLastPushedAiProfileIdsRef:Un,workspaceLastPushedAiProfileWatermarksRef:ba,workspaceLastPushedAiProfileChangeKeysRef:un,workspaceLastPushedDocumentPathsRef:Ea,workspaceLastPushedDocumentWatermarksRef:Qt,workspaceLastPushedAssetPathsRef:qn,workspaceLastPushedAssetWatermarksRef:Cn,workspaceLastPushedDocumentReviewSessionIdsRef:Ya,workspaceLastPushedDocumentReviewSessionWatermarksRef:Ja,workspaceLastPushedDocumentReviewCommentIdsRef:Mn,workspaceLastPushedDocumentReviewCommentWatermarksRef:cn,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:hn,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ua,workspaceLastPushedTaskEventWatermarksRef:ea,workspaceBaselineResetReasonRef:Vt,workspaceCaptureAttachBootstrapBaselineRef:Vr,workspaceStartupFullReconcileRanRef:ms,workspaceFullReconcileInFlightRef:Dn,bootstrapLastProgressAtRef:zt,realtimeSuppressedEventQueueRef:dn,setWorkspaceSyncBusy:L,setUserGlobalSyncStatus:Se,setUserGlobalSyncError:ge,setWorkspaceLastErrorMessage:j,setWorkspaceLastErrorAt:T,setWorkspaceLastPullAt:Le,setWorkspaceLastPushAt:Oe,setWorkspaceSyncPendingChanges:fe,setTasks:oe,setArchivedTasks:be}),[a,s,F,n,N,V,c,Q,m,Ve,Nr,fs,fn,gr,Or,Qa,Ma,Kr,_a,Qn,Tn,xa,Yn,Mt,mn,Da,yr,er,sn,Zn,kr,Yr,oe,be]),{pushWorkspaceChangesToCloud:tr,pullWorkspaceChangesFromCloud:ra}=Jr,Ts=r.useRef({handleRealtimeSignal:()=>{},recordSuppressedEventIds:()=>{},clearRealtimePullDebounce:()=>{}}),q=r.useMemo(()=>ob({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,workspaceSyncPhase:N,workspacePullInFlightRef:In,realtimePullDebounceRef:Ye,realtimeSuppressedEventIdsRef:Ot,clearWorkspaceRetry:fn,isWorkspaceRetryPending:Rn,pullWorkspaceChangesFromCloud:ra}),[a,s,F,N,fn,Rn,ra]);Ts.current=q;const Je=y("/taskforce-ws"),Ct=String(i||"").trim(),Nn=Tg({enabled:!!(v&&a&&s==="local"&&F&&o&&c&&Ct&&Ct!=="anonymous"&&Je),workspaceId:n,websocketUrl:Je,onSignal:q.handleRealtimeSignal,onTelemetry:nn,userId:Ct||void 0});r.useEffect(()=>{Ut(Nn.connectionState)},[Nn.connectionState]),r.useEffect(()=>()=>q.clearRealtimePullDebounce(),[q]);const nr=r.useCallback(async R=>ja(R,{cloudAuthConfigured:a,isAuthenticated:c,ensureCloudWorkspaceReadyForSync:Ve}),[ja,a,c,Ve]),Ca=r.useCallback(async()=>{await pa({preferCloudOnFirstSync:!1})},[pa]),ho=r.useMemo(()=>cb({currentWorkspaceId:n,workspaceCloudSyncEnabled:F,workspaceSyncPhase:N,workspaceLastPullAt:Te,lastBootstrapPhaseRef:Ln,workspaceRepairModeRef:zn,workspaceForceFullAiProfilePushRef:Bt,workspaceStartupRepairRanRef:Xt,workspaceStartupFullReconcileRanRef:ms,workspaceFullReconcileInFlightRef:Dn,workspacePullCursorRef:Za,workspaceAttachBootstrapBaselineSignatureRef:Xa,workspaceCaptureAttachBootstrapBaselineRef:Vr,workspacePendingSignatureRef:jn,workspaceLastPushedSignatureRef:Yt,workspaceLastPushedWatermarksRef:Sa,workspaceLastPushedTaskChangeKeysRef:da,workspaceLastPushedInitiativeIdsRef:va,workspaceLastPushedInitiativeWatermarksRef:$n,workspaceLastPushedWorkstreamIdsRef:Pa,workspaceLastPushedWorkstreamWatermarksRef:wn,workspaceLastPushedAiProfileIdsRef:Un,workspaceLastPushedAiProfileWatermarksRef:ba,workspaceLastPushedAiProfileChangeKeysRef:un,workspaceLastPushedDocumentPathsRef:Ea,workspaceLastPushedDocumentWatermarksRef:Qt,workspaceLastPushedAssetPathsRef:qn,workspaceLastPushedAssetWatermarksRef:Cn,workspaceLastPushedDocumentReviewSessionIdsRef:Ya,workspaceLastPushedDocumentReviewSessionWatermarksRef:Ja,workspaceLastPushedDocumentReviewCommentIdsRef:Mn,workspaceLastPushedDocumentReviewCommentWatermarksRef:cn,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:hn,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ua,workspaceLastPushedTaskEventWatermarksRef:ea,workspaceBaselineResetReasonRef:Vt,bootstrapPhaseStartedAtRef:kt,bootstrapLastProgressAtRef:zt,acquireWorkspaceSyncLease:Qn,releaseWorkspaceSyncLease:Tn,forceClearWorkspaceSyncLease:Br,clearWorkspaceRetry:fn,clearWorkspaceIssue:gr,reportWorkspaceWindowContention:xa,reportSyncEvent:_a,persistWorkspaceSyncPatch:Lr,persistWorkspaceSyncWatermarksSnapshotBestEffort:Kr,buildWorkspaceSyncSignature:Zn,pullWorkspaceChangesFromCloud:ra,pushWorkspaceChangesToCloud:tr,cloudAuthConfigured:a,runtimeMode:s,isAuthenticated:c,checkAuthSession:Q}),[n,V,F,N,Te,Qn,Tn,Br,fn,gr,xa,_a,Lr,Kr,Zn,ra,tr,a,s,c,Q]),{retryWorkspaceCloudSync:Ns,resetWorkspaceSyncCursorAndPull:qo}=ho,Gn=r.useCallback(()=>{const R=jp({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:n,workspaceSyncPhase:N,isAuthenticated:c,repairModeActive:zn.current===!0,repairModeBypass:!1,pushInFlight:Xn.current,pullInFlight:In.current}),E=Rn(),je=Pp({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:n,workspaceSyncPhase:N,isAuthenticated:c,repairModeActive:zn.current===!0,repairModeBypass:!1,retryPending:E,pushInFlight:Xn.current,pullInFlight:In.current}),ct=Ep({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,currentWorkspaceId:n,isAuthenticated:c});return{workspaceId:n,enabled:F,phase:N,status:Ir,summary:Pn,lastSuccessfulSyncAt:wa,lastPullAt:Te,lastPushAt:Ie,lastErrorAt:z,pendingChanges:re,lastErrorMessage:w,recommendedAction:ps,pushBlockedReason:R.allowed?null:R.reason,pullBlockedReason:je.allowed?null:je.reason,retryBlockedReason:ct.allowed?null:ct.reason,repairActive:zn.current===!0,pushInFlight:Xn.current===!0,pullInFlight:In.current===!0,retryPending:E,documentSnapshotCount:xe.length,aiProfileSnapshotCount:gt.length,aiProfileSnapshotRawCount:Rt,aiProfileSnapshotLastFetchAt:tt,aiProfileSnapshotLastFetchError:Pt,aiProfileSnapshotLastSkipReason:Dt,assetSnapshotCount:We.length,documentReviewSessionSnapshotCount:vt.length,documentReviewSessionSnapshotFingerprint:Ze,annotatedAttachmentSessionSnapshotCount:W.length,annotatedAttachmentSessionSnapshotFingerprint:Ne,lastPushedAiProfileCount:Un.current.size,lastPushedAiProfileWatermarkCount:ba.current.size,forceFullAiProfilePushQueued:Bt.current===!0}},[a,n,s,F,N,c,Ir,Pn,wa,Te,Ie,z,re,w,ps,xe.length,gt.length,Rt,tt,Pt,Dt,We.length,vt.length,Ze,W.length,Ne,Rn]);r.useEffect(()=>{on.current=Ns},[Ns]);const La=r.useCallback(()=>{Yn(),mn()},[Yn,mn]);return r.useEffect(()=>{if(!a||s!=="local"||!F||!o||!c)return;Yn(),Mt(),mn(),Da(),yr();const R=zs=>{const ar=zs.detail;(String(ar?.workspaceId||"").trim()||"default")===n&&La()};window.addEventListener(Rp,R);const E=window.setInterval(()=>{Yn()},ma),je=window.setInterval(()=>{Mt()},ma),ct=window.setInterval(()=>{mn()},ma),nt=window.setInterval(()=>{Da()},ma),Y=window.setInterval(()=>{yr()},ma);return()=>{window.removeEventListener(Rp,R),window.clearInterval(E),window.clearInterval(je),window.clearInterval(ct),window.clearInterval(nt),window.clearInterval(Y)}},[a,s,F,o,c,n,La,Yn,Mt,mn,Da,yr,ma]),r.useEffect(()=>{!a||s!=="local"||!F||!o||!c||Zr&&La()},[a,s,F,o,c,Zr,La]),r.useEffect(()=>{if(!tb({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,workspaceSyncPhase:N,workspaceSyncReferenceSnapshotsReady:Jt}))return;const R=Zn();if(Yr(R)||!R||R===Yt.current)return;const E=sn();if(fe(E.changes.length),Xn.current||In.current){jn.current=R;return}const je=window.setTimeout(()=>{tr(R)},1500);return()=>window.clearTimeout(je)},[a,s,F,o,N,Jt,Zn,Yr,sn,Is,dt,we,ot,Ze,Ne,tr,Xn,In]),r.useEffect(()=>{if(!nb({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,workspaceSyncPhase:N,workspaceSyncReferenceSnapshotsReady:Jt}))return;const R=window.setInterval(()=>{if(Xn.current||In.current||Rn())return;const E=jn.current||Zn();if(!E||E===Yt.current)return;const je=sn();fe(je.changes.length),je.changes.length!==0&&tr(E)},Wr);return()=>window.clearInterval(R)},[a,s,F,o,N,Jt,Zn,sn,tr,Rn,Wr]),r.useEffect(()=>{a&&s==="local"&&F||(fn(),L(!1))},[a,s,F,fn]),r.useEffect(()=>{const R=ab({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,workspaceSyncPhase:N,lastPullAt:Te,retryPending:Rn()});if(!R.shouldStart)return;R.shouldKickOffImmediately&&ra();const E=window.setInterval(()=>{ra()},qa);return()=>{window.clearInterval(E)}},[a,s,F,o,N,Te,Rn,ra,qa]),r.useEffect(()=>{if(!rb({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,isAuthenticated:c,workspaceSyncPhase:N}))return;const R=window.setInterval(()=>{Dn.current||(Dn.current=!0,ra({forceCursorNull:!0}).finally(()=>{Dn.current=!1}))},qv);return()=>window.clearInterval(R)},[a,s,F,o,c,N,ra]),r.useEffect(()=>{s!=="local"||!c||!i||i==="anonymous"||pa({preferCloudOnFirstSync:!0})},[s,c,i,pa]),r.useEffect(()=>{if(s!=="local"||!c||!i||i==="anonymous"||!Kn.current.has(i)||Kt.current)return;const R=hr(),E=JSON.stringify(R);if(!Fn.current){Fn.current=E;return}if(E===Fn.current)return;Fn.current=E,Tr(i,new Date().toISOString());const je=window.setTimeout(()=>{pa({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(je)},[s,c,i,hr,Tr,pa]),r.useEffect(()=>{sb({cloudAuthConfigured:a,runtimeMode:s,workspaceCloudSyncEnabled:F,authSessionResolved:o,isAuthenticated:c,workspaceSyncPhase:N,alreadyRan:Xt.current})&&(Xt.current=!0,fetch("/api/taskforce/sync/workspace/repair-startup",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:n})}).then(async R=>{if(!R.ok)return;const E=await R.json().catch(()=>({}));E?.applied>0&&(Ga("startup_repair_applied",{workspaceId:n,applied:E.applied,skipped:E.skipped,failed:E.failed}),Yn(),Mt(),mn(),Da())}).catch(()=>{}))},[a,s,F,o,c,N,n,Yn,Mt,mn,Da]),{userGlobalSyncStatus:Ce,setUserGlobalSyncStatus:Se,userGlobalSyncError:ve,setUserGlobalSyncError:ge,workspaceLastPullAt:Te,workspaceLastPushAt:Ie,workspaceLastErrorAt:z,workspaceLastErrorMessage:w,workspaceLastSuccessfulSyncAt:wa,workspaceCloudSyncEnabled:F,workspaceSyncPhase:N,workspaceSyncSetupIntent:$,workspaceSyncStatus:Ir,workspaceSyncSummary:Pn,workspaceSyncRecommendedAction:ps,workspaceSyncBusy:te,workspaceSyncPendingChanges:re,syncInFlightRef:Nt,workspaceRetryAt:Dr,isWorkspaceRetryPending:Rn,workspacePushInFlightRef:Xn,workspacePullInFlightRef:In,workspaceLastPushedSignatureRef:Yt,workspacePendingSignatureRef:jn,workspaceLastPushedTaskIdsRef:ln,workspaceDeletedTaskIdsRef:ga,workspaceDeletedTaskWatermarksRef:la,workspacePullCursorRef:Za,clearWorkspaceRetry:fn,persistWorkspaceSyncPatch:Lr,loadWorkspaceSyncState:Ar,applyWorkspaceSyncStateSnapshot:_t,syncUserGlobalSettings:pa,buildWorkspaceSyncSignature:Zn,pushWorkspaceChangesToCloud:tr,pullWorkspaceChangesFromCloud:ra,saveWorkspaceCloudSyncSettings:nr,retryUserGlobalSettingsSync:Ca,retryWorkspaceCloudSync:Ns,resetWorkspaceSyncCursorAndPull:qo,getWorkspaceSyncDiagnostics:Gn}}function pb(e,n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:e==="error"?3600:2600}function fb(){const[e,n]=r.useState(null),a=r.useRef(null),s=r.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null),n(null)},[]),o=r.useCallback((c,i="info",l)=>{if(!c)return;a.current!==null&&(window.clearTimeout(a.current),a.current=null),n({message:c,tone:i,ttlMs:l});const m=pb(i,l);a.current=window.setTimeout(()=>{a.current=null,n(null)},m)},[]);return r.useEffect(()=>()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),{uiNotice:e,pushNotice:o,clearNotice:s}}function hb({storagePath:e,shouldDeferProtectedApiCalls:n,shouldBlockProtectedApiCalls:a}){const[s,o]=r.useState("antigravity"),[c,i]=r.useState([]),[l,m]=r.useState(".agent/workflows"),[y,v]=r.useState(null),[b,g]=r.useState(null),h=r.useRef(null),k=n||a;r.useEffect(()=>{const M=c.find(B=>B.id===s);M&&m(M.directory)},[s,c]);const I=r.useCallback(()=>{typeof window>"u"||(h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,g(null)},5e3))},[]),x=r.useCallback(async()=>{if(k)return;const M=await fetch("/api/taskforce/environments");if(!M.ok)return;const B=await M.json().catch(()=>({}));B.environments&&i(B.environments)},[k]),A=r.useCallback(async(M,B)=>{v("workflows"),g(null);try{const X=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:M,workflowNames:B,variables:{STORAGE_PATH:e.replace(/\/$/,"")||".Taskforce"}})})).json();X.success?g({type:"success",message:`Successfully exported ${X.count} workflows to ${M}`}):g({type:"error",message:X.error||"Export failed"})}catch{g({type:"error",message:"Network error exporting workflows"})}finally{v(null),I()}},[I,e]);return r.useEffect(()=>()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),{exportEnvironment:s,setExportEnvironment:o,availableEnvironments:c,loadAvailableEnvironments:x,exportWorkflowsPath:l,setExportWorkflowsPath:m,exportingResource:y,exportResult:b,handleExportWorkflows:A}}function gb(e){const{resolveCloudAuthUrl:n,currentWorkspaceId:a,normalizedCloudAuthBaseUrl:s,normalizedCloudMcpBaseUrl:o,mergedConfig:c,availableWorkspaces:i,currentTheme:l,configLoaded:m,globalTheme:y,themeUseGlobalDefault:v,keyShortcut:b,jsonBackupEnabled:g,globalJsonBackupEnabled:h,globalWeekStartsOn:k,locale:I,supportedLocales:x,jsonBackupUseGlobalDefault:A,manualComplexityEnabled:M,checklistDropdownEnabled:B,showTaskCardStatusLabel:ue,exportWorkflowsPath:X,exportingResource:ce,exportResult:oe,pathSaved:be,settingsSection:_,exportEnvironment:J,setupState:Q,buildInfo:ie,saveSetupMode:H,saveWorkspaceProfile:P,setCurrentTheme:U,handleSaveTheme:se,handleSaveGlobalTheme:he,setKeyShortcut:V,handleJsonBackupEnabledChange:Ce,handleSaveGlobalJsonBackupEnabled:Se,handleSaveGlobalWeekStartsOn:ve,handleSaveLocale:ge,handleManualComplexityEnabledChange:Te,handleChecklistDropdownEnabledChange:Le,handleShowTaskCardStatusLabelChange:Ie,handleResetProjectToGlobal:Oe,handleSaveSettings:z,setExportWorkflowsPath:T,setExportEnvironment:w,availableWorkflows:j,initiativeTemplates:F,availableEnvironments:ee,fetchWorkflows:N,fetchInitiativeTemplates:C,createInitiativeFromTemplate:$,fetchWorkflowTemplate:K,fetchWorkflowOverrideNames:te,saveWorkflowTemplateDraft:L,resetWorkflowTemplateDraft:re,handleExportWorkflows:fe,setShowFolderBrowser:xe,setBrowserTarget:le,fetchFolders:we,activeCategories:Re,pathValidation:Xe,taxonomyDisplayLabels:ze,handleUpdateCategory:lt,handleRemoveCategory:wt,handleSaveCategory:$e,handleAddPath:ft,handleRemovePath:gt,handleUpdateCategoryIcon:at,handleUpdateCategoryColor:dt,activeTypes:ne,handleSaveType:tt,handleRemoveType:rt,handleUpdateType:Pt,taxonomies:yt,handleUpdateTaxonomies:Rt,priorities:Tt,handleUpdatePriorities:Dt,analyzeSystemTaxonomyPack:d,handleApplySystemTaxonomyPack:Me,handleUpdateTaxonomyDisplayLabels:We,projectRoot:Qe,projectName:ot,mcpHostRoot:de,serverHostRoot:Be,mcpScriptPath:St,tenantId:vt,runtimeMode:$t,workspaceSwitchingEnabled:Ze,deleteWorkspace:en,setMcpHostRoot:Lt,isAuthenticated:bt}=e,W=r.useCallback(async(Ne,ae)=>{const Pe=n(Ne),Ge=new Headers(ae?.headers||void 0);if(Ne.startsWith("/api/taskforce/settings/mcp/")){const it=String(a||"").trim();it&&it!=="default"&&!Ge.has("x-taskforce-workspace-id")&&Ge.set("x-taskforce-workspace-id",it)}const De={...ae,headers:Ge,credentials:ae?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(Pe))try{new URL(Pe,window.location.origin).origin!==window.location.origin&&De.mode===void 0&&(De.mode="cors")}catch{}return fetch(Pe,De)},[a,n]),ke=i.find(Ne=>Ne.id===a);return{fetchCloudAuthApi:W,currentTheme:l,configLoaded:m,globalTheme:y,themeUseGlobalDefault:v,keyShortcut:b,jsonBackupEnabled:g,globalJsonBackupEnabled:h,globalWeekStartsOn:k,locale:I,supportedLocales:x,jsonBackupUseGlobalDefault:A,manualComplexityEnabled:M,checklistDropdownEnabled:B,showTaskCardStatusLabel:ue,exportWorkflowsPath:X,exportingResource:ce,exportResult:oe,pathSaved:be,initialSection:_,exportEnvironment:J,setupState:Q,buildInfo:ie,onSaveSetupMode:H,onSaveWorkspaceProfile:P,onThemeChange:U,onSaveTheme:se,onSaveGlobalTheme:he,onKeyShortcutChange:V,onJsonBackupEnabledChange:Ce,onSaveGlobalJsonBackupEnabled:Se,onSaveGlobalWeekStartsOn:ve,onSaveLocale:ge,onManualComplexityEnabledChange:Te,onChecklistDropdownEnabledChange:Le,onShowTaskCardStatusLabelChange:Ie,onResetProjectToGlobal:Oe,onSaveSettings:z,onExportWorkflowsPathChange:T,onExportEnvironmentChange:w,availableWorkflows:j,initiativeTemplates:F,availableEnvironments:ee,onRefreshWorkflows:N,onRefreshInitiativeTemplates:C,onCreateInitiativeFromTemplate:$,onFetchWorkflowTemplate:K,onFetchWorkflowOverrideNames:te,onSaveWorkflowTemplateDraft:L,onResetWorkflowTemplateDraft:re,onExportWorkflows:fe,onShowFolderBrowserChange:xe,onBrowserTargetChange:le,onFetchFolders:we,categories:Re,pathValidation:Xe,taxonomyDisplayLabels:ze,onUpdateCategory:lt,onRemoveCategory:wt,onSaveCategory:$e,onAddPath:ft,onRemovePath:gt,onUpdateCategoryIcon:at,onUpdateCategoryColor:dt,types:ne,onSaveType:tt,onRemoveType:rt,onUpdateType:Pt,taxonomies:yt,onUpdateTaxonomies:Rt,priorities:Tt,onUpdatePriorities:Dt,onAnalyzeSystemTaxonomyPack:d,onApplySystemTaxonomyPack:Me,onUpdateTaxonomyDisplayLabels:We,projectRoot:Qe,projectName:ot,mcpHostRoot:de,serverHostRoot:Be,mcpScriptPath:St,tenantId:vt,workspaceId:a,runtimeMode:$t,cloudAuthBaseUrl:s||c.cloudAuthBaseUrl,cloudMcpBaseUrl:o||void 0,workspaceSwitchingEnabled:Ze,currentWorkspaceRole:ke?.role||"member",currentWorkspaceName:String(ke?.name||""),onDeleteWorkspace:en,onMcpHostRootChange:Lt,isAuthenticated:bt}}function yb(e){const{keyShortcut:n,themeUseGlobalDefault:a,runtimeMode:s,jsonBackupUseGlobalDefault:o,globalTheme:c,globalJsonBackupEnabled:i,setCurrentTheme:l,setThemeUseGlobalDefault:m,setGlobalTheme:y,setJsonBackupEnabled:v,setJsonBackupUseGlobalDefault:b,setGlobalJsonBackupEnabled:g,setGlobalWeekStartsOn:h,setLocale:k,setManualComplexityEnabled:I,setChecklistDropdownEnabled:x,setShowTaskCardStatusLabel:A,setShowChecklist:M}=e,B=r.useCallback(async()=>{try{const P=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:n})});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}},[n]),ue=r.useCallback(async P=>{l(P),m(!1);try{const U=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:P})});if(!U.ok)throw new Error(`Failed to save config (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project theme"),!1}},[l,m]),X=r.useCallback(async P=>{y(P),a&&l(P);try{const U=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:P})});if(!U.ok)throw new Error(`Failed to save global settings (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global theme"),!1}},[y,a,l]),ce=r.useCallback(async P=>{if(s==="cloud")return v(!1),b(!1),!1;v(P),b(!1);try{const U=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:P})});if(!U.ok)throw new Error(`Failed to save config (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project backup setting"),!1}},[s,v,b]),oe=r.useCallback(async P=>{if(s==="cloud")return g(!1),o&&v(!1),!1;g(P),o&&v(P);try{const U=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:P})});if(!U.ok)throw new Error(`Failed to save global settings (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global backup setting"),!1}},[s,g,o,v]),be=r.useCallback(async P=>{h(P);try{const U=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:P}})});if(!U.ok)throw new Error(`Failed to save global settings (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save regional week start setting"),!1}},[h]),_=r.useCallback(async P=>{const U=pg(P);return k(U),!0},[k]),J=r.useCallback(async P=>{I(P);try{const U=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:P})});if(!U.ok)throw new Error(`Failed to save config (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save manual complexity setting"),!1}},[I]),Q=r.useCallback(async P=>{x(P),P||M(!1);try{const U=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:P})});if(!U.ok)throw new Error(`Failed to save config (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save checklist dropdown setting"),!1}},[x,M]),ie=r.useCallback(async P=>{A(P);try{const U=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:P})});if(!U.ok)throw new Error(`Failed to save config (${U.status})`);return!0}catch{return console.error("[Taskforce] Failed to save task card status label setting"),!1}},[A]),H=r.useCallback(async()=>{m(!0),b(!0),l(c),v(i),I(!1),x(!0),A(!0),M(!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,b,l,c,v,i,I,x,A,M]);return{handleSaveSettings:B,handleSaveTheme:ue,handleSaveGlobalTheme:X,handleJsonBackupEnabledChange:ce,handleSaveGlobalJsonBackupEnabled:oe,handleSaveGlobalWeekStartsOn:be,handleSaveLocale:_,handleManualComplexityEnabledChange:J,handleChecklistDropdownEnabledChange:Q,handleShowTaskCardStatusLabelChange:ie,handleResetProjectToGlobal:H}}function kb(e){const{activeCategories:n,activeTab:a,activeTypes:s,archivedTasks:o,browserTarget:c,category:i,configLoaded:l,customCategories:m,refreshTaskCollections:y,fetchTasks:v,filterCategories:b,getCategoryPaths:g,normalizePath:h,pathValidation:k,setBrowserTarget:I,setCategory:x,setCustomCategories:A,setCustomTypes:M,setFilterCategories:B,setPathValidation:ue,setPriorities:X,setShowFolderBrowser:ce,setTaxonomies:oe,tasks:be}=e,_=r.useCallback(async(T,w)=>{const j=await T.json().catch(()=>({}));return String(j?.error||w)},[]),J=r.useCallback(()=>[...be,...o],[o,be]),Q=r.useCallback(T=>T.priorities.find(w=>w.value===2)?.value||T.priorities[0]?.value||2,[]),ie=r.useCallback(async T=>{if(T.length!==0)try{const w=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:T})});if(w.ok){const j=await w.json();ue(F=>({...F,...j.results}))}}catch(w){console.error("[Taskforce] Failed to validate paths:",w)}},[ue]);r.useEffect(()=>{if(a!=="settings"||!l)return;const T=[];n.forEach(j=>{g(j).forEach(ee=>{T.includes(ee)||T.push(ee)})});const w=T.filter(j=>!k[j]);w.length>0&&ie(w)},[n,a,l,g,k,ie]);const H=r.useCallback(async(T,w)=>{if(l){A(j=>(j.length>0?j:n).map(ee=>ee.value===T.value?T:ee)),w&&w!==T.label&&(i===w&&x(T.label),b.includes(w)&&B(j=>j.map(F=>F===w?T.label:F)));try{const ee={categories:(m.length>0?m:n).map(N=>N.value===T.value?T:N)};w&&w!==T.label&&(ee.reassignFrom=w,ee.reassignTo=T.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}),w&&await v()}catch(j){console.error("[Taskforce] Failed to update category",j)}}},[n,i,l,m,v,b,x,A,B]),P=r.useCallback(async T=>{if(!l)return;const w=T.trim().toLowerCase().replace(/\s+/g,"-");if(n.some(F=>F.value===w))return;const j={value:w,label:T.trim(),color:"blue-200",icon:"Folder"};A(F=>[...F.length>0?F:n,j]);try{const ee=[...m.length>0?m:n,j];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:ee})})}catch(F){console.error("[Taskforce] Failed to create category",F)}},[n,l,m,A]),U=r.useCallback((T,w)=>{if(!w.trim())return;const j=n.find(C=>C.value===T);if(!j)return;const F=g(j),ee=w.trim();if(F.includes(ee))return;const N=[...F,ee];H({...j,path:void 0,paths:N}),ie(N)},[n,g,H,ie]),se=r.useCallback((T,w)=>{const j=n.find(F=>F.value===T);j&&H({...j,icon:w})},[n,H]),he=r.useCallback((T,w)=>{const j=n.find(F=>F.value===T);j&&H({...j,color:w})},[n,H]),V=r.useCallback((T,w)=>{const j=n.find(N=>N.value===T);if(!j)return;const ee=g(j).filter(N=>N!==w);H({...j,path:void 0,paths:ee})},[n,g,H]),Ce=r.useCallback(T=>{const w=h(T);if(c&&typeof c=="object"&&c.type==="category"){const j=n.find(F=>F.value===c.value);if(j){const F=g(j);if(!F.includes(w)){const ee=[...F,w];H({...j,path:void 0,paths:ee})}}}ce(!1),I(null)},[n,c,g,H,h,I,ce]),Se=r.useCallback(async T=>{if(!l)return;const w=Dc,j=n.find(C=>C.value===w),F=j?{...j}:{value:w,label:dm,icon:"Inbox"},ee=F.label,N=n.find(C=>C.value===T);A(C=>{let K=(C.length>0?C:n).filter(te=>te.value!==T);return K.some(te=>te.value===w)||(K=[F,...K]),K}),N&&((i===N.label||i===N.value)&&x(w),(b.includes(N.label)||b.includes(N.value))&&B(C=>{const $=C.filter(K=>K!==N.label&&K!==N.value);return $.includes(w)?$:[...$,w]}));try{let C=(m.length>0?m:n).filter($=>$.value!==T);C.some($=>$.value===w)||(C=[F,...C]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:C,reassignFrom:N?.label||T,reassignTo:ee})}),await v()}catch(C){console.error("[Taskforce] Failed to remove category",C)}},[n,i,l,m,v,b,x,A,B]),ve=r.useCallback(async T=>{if(!T.trim())return;const w=T.trim().toLowerCase().replace(/\s+/g,"-");if(s.some(F=>F.value===w))return;const j=[...s,{value:w,label:T.trim(),status:"active"}];M(j);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:j})})}catch(F){console.error("Failed to save type",F)}},[s,M]),ge=r.useCallback(async T=>{const w=s.map(j=>j.value===T?{...j,status:"retired"}:j);M(w);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:w})}),await v()}catch(j){console.error("Failed to save type",j)}},[s,v,M]),Te=r.useCallback(async(T,w)=>{const j=s.find(C=>C.value===T);if(!j)return;const F=typeof w.label=="string"?w.label.trim():j.label;if(!F)return;const ee=s.map(C=>C.value===T?{...C,...w,label:F}:C);if(JSON.stringify(ee)!==JSON.stringify(s)){M(ee);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:ee})})}catch(C){console.error("Failed to update type",C)}}},[s,M]),Le=r.useCallback(async T=>{if(l){oe(T);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:T})})}catch(w){console.error("[Taskforce] Failed to save taxonomies",w)}}},[l,oe]),Ie=r.useCallback(async T=>{if(l){X(T);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:T})})}catch(w){console.error("[Taskforce] Failed to save priorities",w)}}},[l,X]),Oe=r.useCallback(T=>{const w=J(),j=new Set(T.categories.map(K=>K.value)),F=new Set(T.types.map(K=>K.value)),ee=new Set(T.priorities.map(K=>Number(K.value))),N=Array.from(new Set(w.map(K=>String(K.category||"").trim()).filter(K=>K.length>0&&!j.has(K)))).sort(),C=Array.from(new Set(w.map(K=>String(K.type||"").trim()).filter(K=>K.length>0&&!F.has(K)))).sort(),$=Array.from(new Set(w.map(K=>Number(K.priority)).filter(K=>Number.isFinite(K)&&K>0&&!ee.has(K)))).sort((K,te)=>K-te);return{unmatchedCategoryValues:N,unmatchedTypeValues:C,incompatiblePriorityValues:$}},[J]),z=r.useCallback(async T=>{if(!l)return{success:!1,error:"Settings are still loading."};const{pack:w,sections:j,remapExistingValuesToDefault:F,workspaceIdOverride:ee}=T,N=String(ee||"").trim(),C=N.length>0,$=C?[]:J(),K=L=>{if(!N)return L;const re=L.includes("?")?"&":"?";return`${L}${re}workspaceId=${encodeURIComponent(N)}`},te=()=>{const L={"Content-Type":"application/json"};return N&&(L["x-taskforce-workspace-id"]=N),L};try{if(j.categories){const L=new Set(w.categories.map(xe=>xe.value)),re=F?[...w.categories]:[...w.categories,...n.filter(xe=>!L.has(xe.value)).map(xe=>({...xe,disabled:!0}))];C||A(re);const fe=await fetch(K("/api/taskforce/categories"),{method:"POST",headers:te(),body:JSON.stringify({categories:re})});if(!fe.ok)return{success:!1,error:await _(fe,"Failed to apply category library pack.")}}if(j.types){const L=new Set(w.types.map(le=>le.value)),re=w.types.find(le=>le.value===Mr)?.value||w.types[0]?.value||Mr;if(F){const le=$.filter(we=>we.type&&!L.has(String(we.type))).map(we=>({id:we.id,type:re}));if(le.length>0){const we=await fetch(K("/api/taskforce/bulk-update-fields"),{method:"POST",headers:te(),body:JSON.stringify({updates:le})});if(!we.ok)return{success:!1,error:await _(we,"Failed to remap task types to the pack default.")}}}const fe=F?[...w.types]:[...w.types,...s.filter(le=>!L.has(le.value)).map(le=>({...le,status:"retired"}))];C||M(fe);const xe=await fetch(K("/api/taskforce/types"),{method:"POST",headers:te(),body:JSON.stringify({types:fe})});if(!xe.ok)return{success:!1,error:await _(xe,"Failed to apply task type library pack.")}}if(j.priorities){const L=new Set(w.priorities.map(le=>le.value)),re=Array.from(new Set($.map(le=>Number(le.priority)).filter(le=>Number.isFinite(le)&&le>0&&!L.has(le)))).sort((le,we)=>le-we);if(re.length>0&&!F)return{success:!1,error:`This workspace still uses priority levels ${re.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(re.length>0){const le=Q(w),we=$.filter(Re=>re.includes(Number(Re.priority))).map(Re=>({id:Re.id,priority:le}));if(we.length>0){const Re=await fetch(K("/api/taskforce/bulk-update-fields"),{method:"POST",headers:te(),body:JSON.stringify({updates:we})});if(!Re.ok)return{success:!1,error:await _(Re,"Failed to remap task priorities to the pack default.")}}}const fe=w.priorities.map(le=>({...le,value:Number(le.value)}));C||X(fe);const xe=await fetch(K("/api/taskforce/priorities"),{method:"POST",headers:te(),body:JSON.stringify({priorities:fe})});if(!xe.ok)return{success:!1,error:await _(xe,"Failed to apply priority library pack.")}}return C||await y({isSilent:!0}),{success:!0}}catch(L){return console.error("[Taskforce] Failed to apply system taxonomy pack",L),{success:!1,error:L instanceof Error?L.message:"Failed to apply system taxonomy pack."}}},[n,s,l,J,Q,_,y,A,M,X]);return{getCategoryPaths:g,validatePaths:ie,handleUpdateCategory:H,handleSaveCategory:P,handleAddPath:U,handleUpdateCategoryIcon:se,handleUpdateCategoryColor:he,handleRemovePath:V,handleSelectPath:Ce,handleRemoveCategory:Se,handleSaveType:ve,handleRemoveType:ge,handleUpdateType:Te,handleUpdateTaxonomies:Le,handleUpdatePriorities:Ie,analyzeSystemTaxonomyPack:Oe,handleApplySystemTaxonomyPack:z}}function Sb({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:n}){const[a,s]=r.useState([]),[o,c]=r.useState([]),i=e||n,l=r.useCallback(async()=>{if(!i)try{const h=await fetch("/api/taskforce/workflow-templates");if(h.ok){const k=await h.json();s(k.templates||[])}}catch{}},[i]),m=r.useCallback(async()=>{if(i)return[];try{const h=await fetch("/api/taskforce/initiative-templates");if(!h.ok)return[];const k=await h.json(),I=Array.isArray(k?.templates)?k.templates:[];return c(I),I}catch{return[]}},[i]),y=r.useCallback(async h=>{if(!h||i)return null;const k=[`/api/taskforce/workflow-template/${encodeURIComponent(h)}`,`/api/taskforce/workflow-templates/${encodeURIComponent(h)}`];try{for(const I of k){const x=await fetch(I);if(!x.ok)continue;const A=await x.json();if(A?.template)return A.template}return null}catch{return null}},[i]),v=r.useCallback(async()=>{if(i)return[];try{const h=await fetch("/api/taskforce/workflow-editor/overrides");if(!h.ok)return[];const k=await h.json();return Array.isArray(k?.names)?k.names:[]}catch{return[]}},[i]),b=r.useCallback(async(h,k)=>{try{const I=await fetch("/api/taskforce/workflow-editor/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h,draft:k})}),x=await I.json().catch(()=>({}));return!I.ok||!x.success?{success:!1,error:x.error||`Save failed (${I.status})`}:(l(),{success:!0})}catch(I){return{success:!1,error:I.message}}},[l]),g=r.useCallback(async h=>{try{const k=await fetch(`/api/taskforce/workflow-editor/reset/${encodeURIComponent(h)}`,{method:"POST"}),I=await k.json().catch(()=>({}));return!k.ok||!I.success?{success:!1,error:I.error||`Reset failed (${k.status})`}:(l(),{success:!0})}catch(k){return{success:!1,error:k.message}}},[l]);return{availableWorkflows:a,initiativeTemplates:o,fetchWorkflows:l,fetchInitiativeTemplates:m,fetchWorkflowTemplate:y,fetchWorkflowOverrideNames:v,saveWorkflowTemplateDraft:b,resetWorkflowTemplateDraft:g}}function vb(){const[e,n]=r.useState(!1),a=r.useCallback(async()=>{if(!document.fullscreenElement){try{await document.documentElement.requestFullscreen(),n(!0)}catch(s){console.error(`Error attempting to enable full-screen mode: ${s}`)}return}document.exitFullscreen&&(await document.exitFullscreen(),n(!1))},[]);return r.useEffect(()=>{const s=()=>{n(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",s),()=>document.removeEventListener("fullscreenchange",s)},[]),{zenMode:e,setZenModeState:n,toggleZenMode:a}}async function bb(e,n,a){if(e.current){n.current=!0;return}e.current=!0;try{do n.current=!1,await a();while(n.current)}finally{e.current=!1}}function wb({tasks:e,archivedTasks:n,setTasks:a,setArchivedTasks:s,setLoadingTasks:o,getCurrentWorkspaceId:c,workspaceResetKey:i,shouldDeferProtectedApiCalls:l,shouldBlockProtectedApiCalls:m,handleUnauthorized:y,authRequiredForApi:v}){const b=r.useRef(new Map),g=r.useRef(!1),h=r.useRef([]),k=r.useRef([]),I=r.useRef(!1),x=r.useRef(!1),A=r.useRef(null),M=r.useRef(null);r.useEffect(()=>{h.current=e},[e]),r.useEffect(()=>{k.current=n},[n]);const B=r.useCallback(P=>`${P.updatedAt||P.createdAt||""}|${P.status}|${P.priority}|${P.title}`,[]),ue=r.useCallback((P,U)=>U.aborted?P===U.reason?!0:P instanceof DOMException?P.name==="AbortError":String(P?.name||"").toLowerCase()==="aborterror":!1,[]),[X,ce]=r.useState([]),oe=r.useRef(new Map),be=r.useCallback(P=>{!P.length||typeof window>"u"||(ce(U=>Array.from(new Set([...U,...P]))),P.forEach(U=>{const se=oe.current.get(U);se&&window.clearTimeout(se);const he=window.setTimeout(()=>{oe.current.delete(U),ce(V=>V.filter(Ce=>Ce!==U))},4e3);oe.current.set(U,he)}))},[]);r.useEffect(()=>()=>{typeof window>"u"||(oe.current.forEach(P=>window.clearTimeout(P)),oe.current.clear())},[]),r.useEffect(()=>{b.current=new Map,g.current=!1,I.current=!1,x.current=!1,A.current?.abort("workspace-reset"),A.current=null,M.current?.abort("workspace-reset"),M.current=null,typeof window<"u"&&(oe.current.forEach(P=>window.clearTimeout(P)),oe.current.clear()),ce([])},[i]);const _=r.useCallback(async(P=!1,U)=>{if(!(U?.ignoreAuthGuard===!0)&&(l||m))return;o(!P);const he=String(c()||"").trim();A.current?.abort("superseded");const V=new AbortController;A.current=V;try{const Ce=await fetch("/api/taskforce/tasks",{signal:V.signal});if(Ce.status===401){y(),a([]),P||o(!1);return}if(Ce.ok){const ve=((await Ce.json()).tasks||[]).map(Ie=>fo(Ie));if(String(c()||"").trim()!==he)return;const Te=new Map,Le=[];for(const Ie of ve){const Oe=B(Ie);if(Te.set(Ie.id,Oe),!g.current)continue;const z=b.current.get(Ie.id);(!z||z!==Oe)&&Le.push(Ie.id)}b.current=Te,g.current?be(Le):g.current=!0,a(ve)}}catch(Ce){if(ue(Ce,V.signal))return;console.error("[Taskforce] Failed to fetch tasks:",Ce)}finally{A.current===V&&(A.current=null,o(!1))}},[B,c,be,y,a,o,v,l,m]),J=r.useCallback(async(P=!1,U)=>{if(!(U?.ignoreAuthGuard===!0)&&(l||m))return;const he=String(c()||"").trim();M.current?.abort("superseded");const V=new AbortController;M.current=V;try{const Ce=await fetch("/api/taskforce/archive",{signal:V.signal});if(Ce.ok){const Se=await Ce.json();if(String(c()||"").trim()!==he)return;const ge=(Se.archived||[]).map(Te=>({...fo(Te),isArchived:!0}));s(ge)}}catch(Ce){if(ue(Ce,V.signal))return;console.error("[Taskforce] Failed to fetch archive:",Ce)}finally{M.current===V&&(M.current=null)}},[c,ue,s,l,m]),Q=r.useCallback(async P=>{const U=P?.isSilent!==!1,se=P?.ignoreAuthGuard===!0;await Promise.all([_(U,{ignoreAuthGuard:se}),J(U,{ignoreAuthGuard:se})])},[J,_]),ie=r.useCallback(async()=>{await bb(I,x,async()=>{await Q({isSilent:!0})})},[Q]),H=r.useCallback(P=>{const U=sS(P,h.current,k.current);h.current=U.tasks,k.current=U.archivedTasks,a(U.tasks),s(U.archivedTasks)},[a,s]);return{tasksRef:h,archivedTasksRef:k,recentlyChangedTaskIds:X,markRecentlyChangedTasks:be,fetchTasks:_,fetchArchive:J,refreshTaskCollections:Q,refreshTaskCollectionsFromInvalidation:ie,mergeTaskFromServer:H,getTaskRevisionKey:B}}function xb(e){const{editingTaskId:n,relationshipTasks:a,initiatives:s=[],workstreams:o=[],supplementalTasks:c=[],setComments:i}=e,l=r.useMemo(()=>{if(c.length===0)return a;const b=new Map;return a.forEach(g=>b.set(g.id,g)),c.forEach(g=>b.set(g.id,g)),Array.from(b.values())},[a,c]),m=r.useMemo(()=>{if(n)return l.find(b=>b.id===n)},[l,n]);r.useEffect(()=>{n&&i(m?.comments||[])},[n,m?.id,m?.updatedAt,m?.comments,i]);const y=r.useMemo(()=>{if(m?.workstreamId)return o.find(b=>b.id===m.workstreamId)},[m,o]),v=r.useMemo(()=>{if(y?.initiativeId)return s.find(b=>b.id===y.initiativeId)},[y,s]);return{currentTask:m,currentTaskWorkstream:y,currentTaskInitiative:v}}const rf="WS-",sf="IN-";function uo(e){return Oc(rf,e)}function Mg(e){return Gp(rf,e)}function em(e){return gd(rf,e)}function xs(e){return Oc(sf,e)}function _b(e){return Gp(sf,e)}function Dg(e){return gd(sf,e)}function ip(e,n){const a=String(n||"").trim();if(!a)return null;const s=_b(a);return e.find(o=>o.id===a||xs(o)===a||s!==null&&o.referenceNumber===s)||null}function Cb(e){const n={};return e.forEach(a=>{const s=a.defaultValue;if(s!=null){if(Array.isArray(s)){s.length>0&&(n[a.id]=s.map(o=>typeof o=="number"?o:String(o)));return}n[a.id]=typeof s=="number"?s:String(s)}}),n}function Ab(e,n){return e.filter(a=>{const s=n[a.id],o=Array.isArray(s)?s.length>0:s!=null&&s!=="";return a.status==="retired"&&!o?!1:a.formEnabled!==!1||a.isRequired===!0||o})}function Ib(e){const{activeCategories:n,activeTypes:a,activeTab:s,attachments:o,checklistItems:c,comments:i,description:l,editingTaskId:m,flushPendingAutoSave:y,getPreferredCategoryValue:v,lastUsedCategory:b,newCommentText:g,relationshipTasks:h,workstreams:k,showArchive:I,taxonomies:x,setActiveTab:A,setApproach:M,setAssignee:B,setAttachments:ue,setAttachmentsDirty:X,setCategory:ce,setChecklistItems:oe,setComments:be,setComplexity:_,setDescription:J,setDueDate:Q,setEditingTaskId:ie,setError:H,setFormTaxonomies:P,setIsOpen:U,setNewCommentText:se,setPendingNavigation:he,setWorkstreamInput:V,setPriority:Ce,setScheduledDate:Se,setShowArchive:ve,setStatus:ge,setTaskReturnTrail:Te,setTitle:Le,setType:Ie,setUnsavedModalOpen:Oe,taskReturnTrail:z,title:T}=e,w=r.useCallback(()=>a.find(re=>String(re.value||"").trim().length>0)?.value||Mr,[a]),j=r.useCallback(re=>{if(m){y(),re();return}if(!(T.trim()!==""||l.trim()!==""||c.length>0||g.trim()!==""||i.length>0||o.length>0)){re();return}he(()=>re),Oe(!0)},[o,i.length,l,m,y,c,g,he,Oe,T]),F=r.useCallback(()=>{U(!1)},[U]),ee=r.useCallback(()=>{ie(null),Le(""),J("");const re=b,fe=n.some(xe=>xe.label===re||xe.value===re);if(re&&fe){const xe=n.find(le=>le.label===re||le.value===re);ce(xe?.value||re)}else ce(v(n));Ie(w()),Ce(2),_(3),ge("task"),M("default"),B("unassigned"),Se(""),Q(""),V(""),oe([]),P(Cb(x)),be([]),se(""),ue([]),X(!1),H("")},[n,v,w,b,M,B,ue,X,ce,oe,be,_,J,Q,ie,H,P,se,Ce,Se,ge,Le,Ie,x]),N=r.useCallback(re=>{const fe=re.trim();if(!fe)return null;const xe=ig(fe);if(xe){const Re=h.find(Xe=>Xe.referenceNumber===xe);if(Re)return Re}const le=h.find(Re=>Re.id===fe);if(le)return le;const we=h.find(Re=>qs(Re)===fe);return we||null},[h]),C=r.useCallback(re=>{const fe=re.trim();if(!fe)return null;const xe=fe.toLowerCase(),le=Mg(fe);if(le){const Xe=k.find(ze=>ze.referenceNumber===le);if(Xe)return Xe}const we=k.find(Xe=>Xe.id===fe);if(we)return we;const Re=k.find(Xe=>Xe.title.trim().toLowerCase()===xe);return Re||null},[k]),$=r.useCallback((re,fe)=>{fe?.preserveReturnTrail||Te([]),ie(re.id),Le(re.title),J(re.description||""),ce(re.category||v(n)),Ie(re.type||w()),Ce(typeof re.priority=="number"?re.priority:2),_(typeof re.complexity=="number"?re.complexity:3),ge(re.status||"task"),M(re.approach||"default"),B(re.assignee||"unassigned"),Se(re.scheduledDate||""),Q(re.dueDate||"");const xe=re.workstreamId&&k.find(le=>le.id===re.workstreamId)||null;V(xe?uo(xe)||xe.id:""),oe(re.checklistItems||[]),be(re.comments||[]),P(re.taxonomies||{}),re.taxonomies?.approach&&M(re.taxonomies.approach),ue(re.attachments||[]),X(!1),A("add")},[n,v,w,A,M,B,ue,X,ce,oe,be,_,J,Q,ie,P,Ce,Se,ge,Te,Le,Ie,k]),K=r.useCallback(re=>{const fe=h.find(xe=>xe.id===re);fe&&(s==="add"&&m&&m!==fe.id&&Te(xe=>xe[xe.length-1]===m?xe:[...xe,m]),fe.isArchived&&!I&&ve(!0),$(fe,{preserveReturnTrail:!0}))},[s,m,$,h,ve,Te,I]),te=r.useCallback(()=>{if(s!=="add"||!m||z.length===0)return!1;const re=[...z];for(;re.length>0;){const fe=re.pop();if(!fe)continue;const xe=h.find(le=>le.id===fe);if(xe)return xe.isArchived&&!I&&ve(!0),Te(re),$(xe,{preserveReturnTrail:!0}),!0}return Te([]),!1},[s,m,$,h,ve,Te,I,z]),L=r.useCallback(()=>{Te([])},[Te]);return{handleNavigation:j,handleClose:F,resetForm:ee,resolveTaskIdInput:N,resolveWorkstreamIdInput:C,handleEdit:$,handleOpenTaskById:K,returnToPreviousTask:te,clearReturnToParentTask:L}}function Tb(e){return e.map(n=>({...n}))}function Nb(e){return e.map(n=>({...n}))}function Rb(e){return e.map(n=>({...n}))}const jb={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"}]},Pb=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",isDefaultStarter:!0,categories:[{value:Dc,label:dm,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"}]},jb];function Lg(){return Pb.map(e=>({...e,categories:Tb(e.categories),types:Nb(e.types),priorities:Rb(e.priorities)}))}const Pc=[{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"}],mo=Pc.map(({value:e,label:n,icon:a,color:s})=>({value:e,label:n,icon:a,color:s}));function sd(e){const n=String(e||"task").trim().toLowerCase();return n==="completed"?Pc.find(a=>a.value==="done")||Pc[0]:Pc.find(a=>a.value===n)||Pc[0]}const Bg=["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"],Uc=Bg.reduce((e,n)=>(e[n]=us[n]||Ti,e),{}),vF=Bg,tm=Object.fromEntries(Lg().flatMap(e=>e.types).filter(e=>e.icon&&e.color).reduce((e,n)=>(e.some(([a])=>a===n.value)||e.push([n.value,{icon:n.icon,color:n.color}]),e),[])),Eb={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"},eh={"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"},bF=["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 Ra(e){if(e)return eh[e]?eh[e]:e}function Mb(e){const n=String(e||"").trim().toLowerCase();return Ra(tm[n]?.color)||Ra("violet-200")||"#9c7aeb"}function wF(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 Db(e){const n=String(e||"").trim().toUpperCase();return Ra(Eb[n])||"var(--text-muted)"}function Lb(e,n){const a=e.taxonomies?.[n];return a==null||a===""?!1:Array.isArray(a)?a.some(s=>String(s).trim().length>0):String(a).trim().length>0}function kd(e,n){const a=e.filter(o=>o.status!=="retired"),s=e.filter(o=>o.status==="retired"&&n.some(c=>Lb(c,o.id)));return[...a,...s.filter(o=>!a.some(c=>c.id===o.id))]}function Wg(e,n=[]){return kd(e,n).filter(a=>a.sortEnabled===!0).map(a=>({value:`taxonomy:${a.id}`,label:a.status==="retired"?`${a.label} (Retired)`:a.label}))}function th(e,n){const a=e.taxonomies?.[n.id];if(a==null||a==="")return null;const s=Array.isArray(a)?a.map(o=>String(o)):[String(a)];for(let o=0;o<n.options.length;o+=1)if(s.includes(String(n.options[o]?.value)))return o;return null}function vi(e,n){return new Date(n.createdAt).getTime()-new Date(e.createdAt).getTime()}function nm(e,n,a,s,o=[]){let c=0;if(a==="created")return c=vi(e,n),s==="desc"?c:-c;if(a==="updated"){const i=e.updatedAt||e.createdAt,l=n.updatedAt||n.createdAt;return c=new Date(l).getTime()-new Date(i).getTime(),s==="desc"?c:-c}if(a==="priority"){const i=Zu(e.priority),l=Zu(n.priority);return c=i!==l?l-i:vi(e,n),s==="desc"?c:-c}if(a==="complexity"){const i=typeof e.complexity=="number"?e.complexity:3,l=typeof n.complexity=="number"?n.complexity:3;return c=i!==l?l-i:vi(e,n),s==="desc"?c:-c}if(a.startsWith("taxonomy:")){const i=a.slice(9),l=o.find(v=>v.id===i);if(!l)return c=vi(e,n),s==="desc"?c:-c;const m=th(e,l),y=th(n,l);return m===null&&y===null?vi(e,n):m===null?1:y===null?-1:m!==y?s==="desc"?y-m:m-y:vi(e,n)}return c=vi(e,n),s==="desc"?c:-c}function Bb(e,n,a){const s=e.taxonomies?.[n];return s==null||s===""?!1:Array.isArray(s)?s.some(o=>String(o)===String(a)):String(s)===String(a)}function of(e,n){const a=e.options.filter(o=>o.status!=="retired"),s=e.options.filter(o=>o.status==="retired"&&n.some(c=>Bb(c,e.id,o.value)));return[...a,...s.filter(o=>!a.some(c=>String(c.value)===String(o.value)))]}function Wb({tasks:e,archivedTasks:n,activeCategories:a,activeTypes:s,priorities:o,taxonomies:c,configLoaded:i,referenceDataLoaded:l,assigneeOptionsLoaded:m,assigneeOptions:y}){const v=r.useMemo(()=>Sg(y),[y]),b=r.useMemo(()=>kd(c,[...e,...n]).filter(C=>C.filterEnabled!==!1).map(C=>({...C,options:of(C,[...e,...n])})),[n,e,c]),g=r.useMemo(()=>v.map(C=>C.value),[v]),[h,k]=r.useState(""),[I,x]=r.useState([]),[A,M]=r.useState([]),[B,ue]=r.useState([]),[X,ce]=r.useState(!1),[oe,be]=r.useState(mo.map(C=>C.value)),[_,J]=r.useState(g),[Q,ie]=r.useState(!0),[H,P]=r.useState({}),[U,se]=r.useState("created"),[he,V]=r.useState("desc"),Ce=r.useCallback(()=>{V(C=>C==="asc"?"desc":"asc")},[]),[Se,ve]=r.useState("category"),[ge,Te]=r.useState("show"),[Le,Ie]=r.useState({}),Oe=r.useCallback((C,$)=>$.length===0?!0:$.every(K=>C.includes(K)),[]),z=r.useCallback((C,$)=>C.length===$.length&&C.every((K,te)=>K===$[te]),[]);r.useEffect(()=>{Se==="approach"&&ve("status")},[Se]),r.useEffect(()=>{if(!(!i||!l)&&m&&!X&&a.length>0&&s.length>0&&o.length>0){x(a.map($=>$.value)),M(o.map($=>$.value)),ue(s.map($=>$.value)),J(g),ie(!0);const C={};b.forEach($=>{C[$.id]=$.options.map(K=>K.value)}),P(C),ce(!0)}},[i,l,m,a,s,o,b,X,g]),r.useEffect(()=>{if(!X||!m)return;const C=new Set(g),$=_.filter(L=>C.has(L)),K=Q?g:$.length>0||_.length===0?$:g;(K.length!==_.length||K.some((L,re)=>L!==_[re]))&&J(K)},[g,_,Q,X,m]),r.useEffect(()=>{if(!X||!m)return;const C=_.filter(K=>g.includes(K)),$=g.length>0&&g.every(K=>C.includes(K));$!==Q&&ie($)},[g,_,Q,X,m]),r.useEffect(()=>{if(!i||!l||!X||a.length===0)return;const C=iS(I,a);(C.length!==I.length||C.some((K,te)=>K!==I[te]))&&x(C)},[i,l,a,X,I]),r.useEffect(()=>{if(!i||!l||!X||o.length===0||A.length===0)return;const C=oS(A,o),$=Array.from(new Set(A.map(te=>Number(te)).filter(te=>Number.isFinite(te))));(C.length!==$.length||C.some((te,L)=>te!==$[L]))&&M(C)},[i,l,X,o,A]),r.useEffect(()=>{if(!i||!l||!X||s.length===0)return;const C=new Set(s.map(te=>te.value)),$=B.filter(te=>C.has(te)),K=$.length>0||B.length===0?$:s.map(te=>te.value);z(K,B)||ue(K)},[s,i,B,X,z,l]),r.useEffect(()=>{if(!i||!l||!X)return;const C={};b.forEach(re=>{const fe=re.options.map(we=>we.value);if(fe.length===0)return;const xe=Array.isArray(H[re.id])?H[re.id]:[],le=xe.filter(we=>fe.includes(we));C[re.id]=le.length>0||xe.length===0?le:fe});const $=Object.keys(H).sort(),K=Object.keys(C).sort(),te=$.length!==K.length||$.some((re,fe)=>re!==K[fe]),L=K.some(re=>!z(H[re]||[],C[re]||[]));(te||L)&&P(C)},[i,H,b,X,z,l]);const T=r.useCallback(()=>{k(""),x(a.map($=>$.value)),M(o.map($=>$.value)),ue(s.map($=>$.value)),be(mo.map($=>$.value)),J(g),ie(!0);const C={};b.forEach($=>{C[$.id]=$.options.map(K=>K.value)}),P(C),se("created"),V("desc")},[a,o,s,b,g]),w=r.useCallback(C=>{J($=>{const K=typeof C=="function"?C($):C,te=Array.from(new Set(K.filter(re=>typeof re=="string"&&re.trim().length>0))),L=g.length>0&&g.every(re=>te.includes(re));return ie(L),te})},[g]),j=r.useMemo(()=>{const C=Oe(I,a.map(L=>L.value)),$=Oe(B,s.map(L=>L.value)),K=Oe(Array.from(new Set(A.map(L=>Number(L)).filter(L=>Number.isFinite(L)))),o.map(L=>Number(L.value)).filter(L=>Number.isFinite(L))),te=Oe(oe,mo.map(L=>L.value));return e.filter(L=>{const re=qs(L).toLowerCase(),fe=L.title.toLowerCase().includes(h.toLowerCase())||(L.description?.toLowerCase()||"").includes(h.toLowerCase())||L.id.toLowerCase().includes(h.toLowerCase())||re.includes(h.toLowerCase()),xe=!X||C||I.includes(L.category),le=!X||K||Qm(L.priority,A),we=!X||$||B.includes(L.type||Mr),Re=!X||te||oe.includes(L.status),Xe=!X||Q||_.includes(L.assignee||"unassigned"),ze=Object.entries(H).every(([lt,wt])=>{const $e=b.find(at=>at.id===lt);if(!$e)return!0;const ft=$e?.options.every(at=>wt.includes(at.value))??!0;if(ft)return!0;const gt=L.taxonomies?.[lt];return gt?Array.isArray(gt)?gt.some(at=>wt.includes(at)):wt.includes(gt):ft||wt.includes("")});return fe&&xe&&le&&we&&Re&&Xe&&ze}).sort((L,re)=>nm(L,re,U,he,c))},[e,n,h,I,A,B,oe,_,Q,H,U,he,X,b,a,s,o,Oe,c]),F=r.useMemo(()=>{const C=Oe(I,a.map(L=>L.value)),$=Oe(B,s.map(L=>L.value)),K=Oe(Array.from(new Set(A.map(L=>Number(L)).filter(L=>Number.isFinite(L)))),o.map(L=>Number(L.value)).filter(L=>Number.isFinite(L))),te=Oe(oe,mo.map(L=>L.value));return e.filter(L=>{const re=!X||C||I.includes(L.category),fe=!X||K||Qm(L.priority,A),xe=!X||$||B.includes(L.type||Mr),le=!X||te||oe.includes(L.status),we=!X||Q||_.includes(L.assignee||"unassigned"),Re=Object.entries(H).every(([Xe,ze])=>{const lt=b.find(ft=>ft.id===Xe);if(!lt)return!0;const wt=lt?.options.every(ft=>ze.includes(ft.value))??!0;if(wt)return!0;const $e=L.taxonomies?.[Xe];return $e?Array.isArray($e)?$e.some(ft=>ze.includes(ft)):ze.includes($e):wt||ze.includes("")});return re&&fe&&xe&&le&&we&&Re})},[e,n,I,A,B,oe,_,Q,H,X,b,a,s,o,Oe]),ee=r.useMemo(()=>{const C=a.every(te=>I.includes(te.value)),$=Oe(B,s.map(te=>te.value)),K=Oe(Array.from(new Set(A.map(te=>Number(te)).filter(te=>Number.isFinite(te)))),o.map(te=>Number(te.value)).filter(te=>Number.isFinite(te)));return n.filter(te=>{const L=qs(te).toLowerCase(),re=te.title.toLowerCase().includes(h.toLowerCase())||(te.description?.toLowerCase()||"").includes(h.toLowerCase())||te.id.toLowerCase().includes(h.toLowerCase())||L.includes(h.toLowerCase()),fe=!X||C||I.includes(te.category),xe=!X||K||Qm(te.priority,A),le=!X||$||B.includes(te.type||Mr),we=!X||Q||_.includes(te.assignee||"unassigned"),Re=Object.entries(H).every(([Xe,ze])=>{const lt=b.find(ft=>ft.id===Xe);if(!lt)return!0;const wt=lt?.options.every(ft=>ze.includes(ft.value))??!0;if(wt)return!0;const $e=te.taxonomies?.[Xe];return $e?Array.isArray($e)?$e.some(ft=>ze.includes(ft)):ze.includes($e):wt||ze.includes("")});return re&&fe&&xe&&le&&we&&Re}).sort((te,L)=>nm(te,L,U,he,c))},[n,h,I,A,B,_,Q,H,U,he,X,a,s,o,b,Oe,c]),N=r.useMemo(()=>{const C={};return j.forEach($=>{const K=a.find(L=>L.value===$.category),te=K?K.label:$.category||"General";C[te]||(C[te]=[]),C[te].push($)}),C},[j,a]);return{searchQuery:h,setSearchQuery:k,filterCategories:I,setFilterCategories:x,filterPriorities:A,setFilterPriorities:M,filterTypes:B,setFilterTypes:ue,filterStatus:oe,setFilterStatus:be,filterAssignees:_,setFilterAssignees:w,filterAssigneesAllSelected:Q,setFilterAssigneesAllSelected:ie,filterTaxonomies:H,setFilterTaxonomies:P,hasInitedFilters:X,setHasInitedFilters:ce,sortBy:U,setSortBy:se,sortOrder:he,setSortOrder:V,toggleSortOrder:Ce,groupBy:Se,setGroupBy:ve,emptyColumnMode:ge,setEmptyColumnMode:Te,collapsedCategories:Le,setCollapsedCategories:Ie,clearFilters:T,filteredTasks:j,searchAgnosticTasks:F,filteredArchive:ee,groupedTasks:N}}const Fb=Wb;function Ob(e){const{activeCategories:n,activeTab:a,apiEndpoint:s,approach:o,assignee:c,attachments:i,attachmentsDirty:l,category:m,checklistItems:y,comments:v,complexity:b,description:g,dueDate:h,editingTaskId:k,fetchTasks:I,formTaxonomies:x,getPreferredCategoryValue:A,mergeTaskFromServer:M,workstreamInput:B,priority:ue,pushNotice:X,queueWorkspaceSyncFromAuthoritativeTaskState:ce,relationshipTasks:oe,resetForm:be,resolveWorkstreamIdInput:_,scheduledDate:J,setActiveTab:Q,setAttachmentsDirty:ie,setComments:H,setError:P,setLastUsedCategory:U,setLoading:se,setNewCommentText:he,status:V,title:Ce,taxonomies:Se,type:ve}=e,[ge,Te]=r.useState(null),[Le,Ie]=r.useState("idle"),[Oe,z]=r.useState(null),T=r.useRef(null),w=r.useCallback(()=>JSON.stringify({title:Ce.trim(),description:g||"",category:typeof m=="string"?m:m.label||A(n),type:typeof ve=="string"?ve:ve.label||Mr,priority:Number(ue),complexity:Number(b)||3,approach:o||"default",assignee:c||"agent",scheduledDate:J||"",dueDate:h||"",workstreamInput:B.trim(),checklistItems:y,comments:v,taxonomies:x,attachments:i}),[n,o,c,i,m,y,v,b,g,h,x,A,ue,J,Ce,ve,B]),j=r.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),F=r.useCallback(async L=>{const re=L?.quiet??!1,fe=L?.source??"manual";if(!Ce.trim())return P("Title is required"),k&&Ie(fe==="autosave"?"error":"idle"),!1;const xe=Se.filter(le=>le.isRequired).filter(le=>{const we=x[le.id];return Array.isArray(we)?we.filter(Re=>String(Re).trim().length>0).length===0:typeof we!="string"&&typeof we!="number"||String(we).trim().length===0}).map(le=>le.label);if(xe.length>0)return P(`Required taxonomy values are missing: ${xe.join(", ")}`),k&&Ie(fe==="autosave"?"error":"idle"),!1;if(k&&oe.find(we=>we.id===k)?.isArchived)return P("Archived tasks are read-only. Unarchive first to make changes."),Ie(fe==="autosave"?"error":"idle"),!1;se(!0),P(""),k&&Ie("saving");try{const le=k?`/api/taskforce/task/${k}`:s.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),we=k?"PATCH":"POST",Re=typeof m=="string"?m:m.label||A(n),Xe=typeof ve=="string"?ve:ve.label||Mr,ze=B.trim()?_(B):null,lt={title:Ce,description:g||null,category:Re||A(n),type:Xe,priority:ue,complexity:Number(b)||3,status:k?void 0:V,completedAt:k?void 0:V==="done"?new Date().toISOString():null,approach:o||"default",assignee:c||"agent",scheduledDate:J||null,dueDate:h||null,workstreamId:B.trim()?ze?.id||B.trim():null,checklistItems:y,comments:v,taxonomies:x,...k?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};(!k||l)&&(lt.attachments=i),k&&(lt.saveSource=fe);const wt=await fetch(le,{method:we,headers:{"Content-Type":"application/json"},body:JSON.stringify(lt)});if(!wt.ok){const gt=(await wt.json()).message||`Failed to ${k?"update":"save"} task`;return P(gt),re||X(gt,"error"),se(!1),k&&Ie("error"),!1}const $e=await wt.json().catch(()=>null);return k&&$e&&typeof $e=="object"&&(M($e),ce()),U(Re),ie(!1),se(!1),k&&Ie("saved"),!0}catch{return P("Failed to connect to server"),re||X("Failed to connect to server","error"),se(!1),k&&Ie("error"),!1}},[n,s,o,c,i,l,m,y,v,b,g,h,k,x,A,M,B,ue,X,ce,_,ie,P,U,se,J,V,Ce,Se,ve]),ee=r.useCallback(async()=>{await F({source:"manual"})&&(k||X("Task added successfully","success"),a==="add"&&!k&&(be(),Q("tasks"),await I()))},[a,k,I,X,be,F,Q]);r.useEffect(()=>{if(j(),!k){z(null),Ie("idle");return}z(w()),Ie("idle")},[j,k]);const N=r.useCallback(async()=>{if(j(),!k||Oe===null)return;const L=w();if(L===Oe||!Ce.trim()||h&&J&&h<J)return;await F({quiet:!0,source:"autosave"})&&z(L)},[w,j,h,k,Oe,F,J,Ce]);r.useEffect(()=>{if(!k||Oe===null)return;const L=w();if(L!==Oe){if(!Ce.trim()){Ie("idle");return}if(h&&J&&h<J){Ie("error");return}return Ie(re=>re==="error"?"error":"idle"),j(),T.current=window.setTimeout(async()=>{await F({quiet:!0,source:"autosave"})&&z(L)},700),()=>{j()}}},[w,j,h,k,Oe,F,J,Ce]);const C=r.useCallback(async L=>{if(L.preventDefault(),h&&J&&h<J){Te({dueDate:h,scheduledDate:J});return}await ee()},[h,ee,J]),$=r.useCallback(async()=>{Te(null),await ee()},[ee]),K=r.useCallback(()=>{Te(null)},[]),te=r.useCallback(async L=>{if(!k||!L.trim())return;const re=L.trim();try{const fe=await fetch(`/api/taskforce/task/${k}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:re,author:"user"})});if(!fe.ok){const we=(await fe.json().catch(()=>({}))).error||"Failed to add comment.";P(we),X(we,"error");return}const xe=await fe.json().catch(()=>null);if(he(""),xe&&typeof xe=="object"){const le=fo(xe);H(le.comments||[]),M(xe),z(w()),Ie("saved")}else await I(!0);ce()}catch(fe){console.error("Failed to add comment",fe),P("Failed to add comment."),X("Failed to add comment.","error")}},[k,I,w,M,X,ce,H,P,he]);return{autoSaveState:Le,flushAutoSave:N,scheduleWarningPrompt:ge,saveTask:F,handleSubmit:C,confirmScheduleWarning:$,cancelScheduleWarning:K,handleAddComment:te}}function $b(e){const{editingTaskId:n,fetchTasks:a,mergeTaskFromServer:s,workstreamInput:o,pushNotice:c,queueWorkspaceSyncFromAuthoritativeTaskState:i,relationshipTasks:l,resolveWorkstreamIdInput:m,setError:y}=e;return{handleSetWorkstreamForCurrentTask:r.useCallback(async b=>{if(!n)return;const g=l.find(x=>x.id===n);if(!g)return;const h=typeof b=="string"?b.trim():b===null?"":o.trim(),k=h?m(h):null,I=h.length>0?k?.id||h:null;if((g.workstreamId||null)===I){c(I?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const x=await fetch(`/api/taskforce/task/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:I})});if(!x.ok){const B=(await x.json().catch(()=>({}))).error||"Failed to set workstream.";y(B),c(B,"error");return}y(""),c(I?"Workstream set":"Workstream removed","info");const A=await x.json().catch(()=>null);A?(s(A),i()):(await a(!0),i())}catch{y("Failed to set workstream."),c("Failed to set workstream.","error")}},[n,a,s,o,c,i,l,m,y])}}function Ub({tasks:e,archivedTasks:n,editingTaskId:a,setTasks:s,setArchivedTasks:o,setDeletedTasks:c,setError:i,resetForm:l,setActiveTab:m,fetchTasks:y,fetchArchive:v,fetchDeletedTasks:b,mergeTaskFromServer:g,pushNotice:h,cloudAuthConfigured:k,runtimeMode:I,isAuthenticated:x,workspaceCloudSyncEnabled:A,buildWorkspaceSyncSignature:M,pushWorkspaceChangesToCloud:B,workspacePendingSignatureRef:ue,workspaceDeletedTaskIdsRef:X,workspaceDeletedTaskWatermarksRef:ce}){const[oe,be]=r.useState(null),_=r.useRef(null),J=r.useRef(null),Q=r.useRef(null);r.useEffect(()=>()=>{typeof window>"u"||(J.current!==null&&(window.clearTimeout(J.current),J.current=null),Q.current=null)},[]);const ie=r.useCallback((z=0)=>{if(!(k&&I==="local"&&x&&A)||typeof window>"u")return;const T=Math.max(0,z),w=Date.now()+T,j=Q.current;if(J.current!==null){if(T<=0||j!==null&&j>=w)return;window.clearTimeout(J.current),J.current=null}Q.current=w,J.current=window.setTimeout(()=>{J.current=null,Q.current=null;const F=M();F&&(ue.current=F,B(F))},T)},[k,I,x,A,M,ue,B]),H=r.useCallback(async(z,T)=>{let w=await fetch(`/api/taskforce/deleted${z}`,T);return w.status===404&&(w=await fetch(`/api/taskforce/trash${z}`,T)),w},[]),P=async(z,T=!1,w={})=>{if(!w.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const j=T||n.some(F=>F.id===z);try{const F=await fetch(`/api/taskforce/task/${z}`,{method:"DELETE"});if(!F.ok){const $=(await F.json().catch(()=>({}))).error||"Failed to delete task.";return i($),h($,"error"),!1}const ee=await F.json().catch(()=>({})),N=ee?.deleted&&typeof ee.deleted=="object"&&ee.deleted.taskSnapshot?{...ee.deleted,taskSnapshot:fo(ee.deleted.taskSnapshot)}:null;if(window.location.search.includes(z)){const C=new URL(window.location.href);C.searchParams.delete("task"),window.history.pushState({},"",C.toString())}if(j?o(C=>C.filter($=>$.id!==z)):s(C=>C.filter($=>$.id!==z)),N){c($=>[N,...$.filter(K=>K.taskId!==z)]);const C=String(N.deletedAt||"").trim();Number.isFinite(Date.parse(C))&&ce.current.set(z,C)}else await b(!0),ce.current.set(z,new Date().toISOString());if(X.current.add(z),k&&I==="local"&&x&&A){const C=M();ue.current=C,B(C)}return a===z&&(l(),m("tasks")),i(""),h("Task moved to Trash.","info"),!0}catch(F){return console.error("Failed to delete task:",F),i("Failed to delete task."),h("Failed to delete task.","error"),!1}},U=r.useCallback(async z=>{try{const T=await H(`/${z}/restore`,{method:"POST"});if(!T.ok){const ee=(await T.json().catch(()=>({}))).error||"Failed to restore deleted task.";return i(ee),h(ee,"error"),null}const w=await T.json().catch(()=>null);w?g(w):await y(!0),c(F=>F.filter(ee=>ee.id!==z&&ee.taskId!==z));const j=String(w?.id||"").trim();return X.current.delete(z),ce.current.delete(z),j&&(X.current.delete(j),ce.current.delete(j)),ie(),i(""),h("Task restored from Trash.","info"),w?fo(w):null}catch(T){return console.error("Failed to restore deleted task:",T),i("Failed to restore deleted task."),h("Failed to restore deleted task.","error"),null}},[y,g,h,ie,H,c,i]),se=r.useCallback(async z=>{try{const T=await H(`/${z}`,{method:"DELETE"});if(!T.ok){const j=(await T.json().catch(()=>({}))).error||"Failed to permanently delete deleted task.";return i(j),h(j,"error"),!1}return c(w=>w.filter(j=>j.id!==z&&j.taskId!==z)),ie(),i(""),h("Deleted task permanently removed.","info"),!0}catch(T){return console.error("Failed to permanently delete deleted task:",T),i("Failed to permanently delete deleted task."),h("Failed to permanently delete deleted task.","error"),!1}},[h,ie,H,c,i]),he=r.useCallback(async()=>{try{const z=await H("/empty",{method:"POST"});if(!z.ok){const F=(await z.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return i(F),h(F,"error"),null}const T=await z.json().catch(()=>({})),w=Number(T?.deleted||0);return c([]),ie(),i(""),h(w===1?"Deleted task permanently removed.":`${w} deleted tasks permanently removed.`,"info"),w}catch(z){return console.error("Failed to empty deleted tasks:",z),i("Failed to permanently delete deleted tasks."),h("Failed to permanently delete deleted tasks.","error"),null}},[h,ie,H,c,i]),V=r.useCallback(async(z,T)=>{const w=e,j=n;s(F=>F.map(ee=>ee.id===z?{...ee,...T}:ee)),o(F=>F.map(ee=>ee.id===z?{...ee,...T}:ee));try{const F=await fetch(`/api/taskforce/task/${z}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!F.ok){const C=(await F.json().catch(()=>({}))).error||`Failed to update task ${z}.`;i(C),h(C,"error"),s(w),o(j);return}const ee=await F.json().catch(()=>null);g(ee),ie(T.attachments!==void 0?150:0),i("")}catch(F){console.error("Failed to update task",F);const ee=`Failed to update task ${z}.`;i(ee),h(ee,"error"),s(w),o(j)}},[e,n,h,g,ie]);return{copiedId:oe,handleDelete:P,handleUpdateTask:V,handleToggleComplete:async z=>{const T=z.status==="done"?"task":"done",w=T==="done"?new Date().toISOString():void 0,j={status:T,completedAt:w,completed:T==="done",inProgress:!1,readyForReview:!1,cancelled:!1},F=e,ee=n;s(N=>N.map(C=>C.id===z.id?{...C,...j}:C)),o(N=>N.map(C=>C.id===z.id?{...C,...j}:C));try{const N=await fetch(`/api/taskforce/task/${z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T,completedAt:w})});if(!N.ok){const K=(await N.json().catch(()=>({}))).error||"Failed to update task status.";i(K),h(K,"error"),s(F),o(ee);return}const C=await N.json().catch(()=>null);C?(g(C),ie()):(await y(!0),ie()),i("")}catch(N){console.error("Failed to toggle complete",N),i("Failed to update task status."),h("Failed to update task status.","error"),s(F),o(ee)}},handleToggleCancel:async z=>{const T=z.status==="cancelled"?"task":"cancelled";try{const w=await fetch(`/api/taskforce/task/${z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T})});if(!w.ok){const ee=(await w.json().catch(()=>({}))).error||"Failed to update task status.";i(ee),h(ee,"error"),await y(!0);return}const j=await w.json().catch(()=>null);j?(g(j),ie()):(await y(!0),ie()),i("")}catch(w){console.error("Failed to toggle cancel",w),i("Failed to update task status."),h("Failed to update task status.","error"),y()}},handleToggleInProgress:async z=>{const T=z.status==="in-progress"?"task":"in-progress";s(w=>w.map(j=>j.id===z.id?{...j,status:T}:j));try{const w=await fetch(`/api/taskforce/task/${z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T})});if(!w.ok){await y(!0);return}const j=await w.json().catch(()=>null);g(j),ie()}catch{y()}},handleToggleReview:async z=>{const T=z.status==="review"?"task":"review";s(w=>w.map(j=>j.id===z.id?{...j,status:T}:j));try{const w=await fetch(`/api/taskforce/task/${z.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T})});if(!w.ok){await y(!0);return}const j=await w.json().catch(()=>null);g(j),ie()}catch{y()}},handleArchiveTask:async z=>{try{const w=z.status==="cancelled"?"cancel":"complete",j=await fetch(`/api/taskforce/task/${z.id}/${w}`,{method:"POST"});if(j.ok){const F=await j.json().catch(()=>null),ee=[];if(F&&typeof F=="object"&&ee.push(F),ee.length>0){for(const C of ee)g(C);ie()}else v();const N=new Set(ee.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0));a&&N.has(a)&&(l(),m("tasks"))}else{const ee=(await j.json().catch(()=>({}))).error||"Failed to archive task.";i(ee),h(ee,"error")}}catch(T){console.error("Failed to archive",T),i("Failed to archive task."),h("Failed to archive task.","error")}},handleBulkArchive:async()=>{const z=e.filter(T=>T.status==="done"||T.status==="cancelled");if(z.length!==0&&confirm(`Archive ${z.length} completed/cancelled tasks?`))try{const T=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:z.map(w=>w.id)})});if(T.ok){const w=await T.json(),j=Array.isArray(w?.results?.archived)?w.results.archived:[];if(j.length>0){for(const F of j)g(F);ie()}else s(F=>F.filter(ee=>!["done","cancelled"].includes(ee.status))),v();h(`${w.archived||z.length} tasks archived`,"info"),i("")}else{const j=(await T.json().catch(()=>({}))).error||"Failed to bulk archive tasks.";i(j),h(j,"error")}}catch(T){console.error("Failed to bulk archive",T),i("Failed to bulk archive tasks."),h("Failed to bulk archive tasks.","error")}},handleUnarchive:async z=>{try{const T=await fetch(`/api/taskforce/task/${z}/unarchive`,{method:"POST"});if(T.ok){const w=await T.json().catch(()=>null);w?(g(w),ie()):(o(j=>j.filter(F=>F.id!==z)),await y(!0),ie()),i(""),h("Task restored from archive.","info")}}catch(T){console.error("Failed to unarchive",T),i("Failed to unarchive task."),h("Failed to unarchive task.","error")}},handleRestoreDeletedTask:U,handlePermanentlyDeleteDeletedTask:se,handleEmptyDeletedTasks:he,handleCopyId:(z,T)=>{z.stopPropagation(),navigator.clipboard.writeText(T),be(T),_.current!==null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{_.current=null,be(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:ie}}const qb=Ub;function Pu(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function zb(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 Hb({currentWorkspaceIdRef:e,resolveApiUrl:n,runtimeMode:a}){r.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const s=window.fetch.bind(window),o=c=>{if(typeof c=="string")return a!=="cloud"?c:c.startsWith("/api/taskforce")&&!Pu(c)?n(c):c;if(c instanceof URL)return a!=="cloud"?c:c.origin===window.location.origin&&c.pathname.startsWith("/api/taskforce")?Pu(c.pathname)?c:new URL(n(`${c.pathname}${c.search}${c.hash}`)):c;if(typeof Request<"u"&&c instanceof Request){if(a!=="cloud")return c;const i=new URL(c.url,window.location.origin);if(i.origin===window.location.origin&&i.pathname.startsWith("/api/taskforce"))return Pu(i.pathname)?c:n(`${i.pathname}${i.search}${i.hash}`)}return c};return window.fetch=((c,i)=>{const l=o(c),m=zb(l);if(!!!(m&&m.pathname.startsWith("/api/taskforce")&&!Pu(m.pathname)))return s(l,i);const v=String(e.current||"").trim();if(typeof Request<"u"&&l instanceof Request){const g=new Headers(l.headers);i?.headers&&new Headers(i.headers).forEach((I,x)=>g.set(x,I)),v&&v!=="default"&&!g.has("x-taskforce-workspace-id")&&(g.set("x-taskforce-workspace-id",v),g.set("x-taskforce-workspace-authoritative","1"));const h=new Request(l,{...i,headers:g});return s(h)}const b=new Headers(i?.headers);return v&&v!=="default"&&!b.has("x-taskforce-workspace-id")&&(b.set("x-taskforce-workspace-id",v),b.set("x-taskforce-workspace-authoritative","1")),s(l,{...i,headers:b})}),()=>{window.fetch=s}},[e,n,a])}function nh(){return typeof performance<"u"?performance.now():Date.now()}function Gb({runtimeConfigReady:e,shouldProbeCloudAuth:n,authSessionResolved:a,resolveCloudAuthUrl:s,authOnlyCloudMode:o,authRequiredError:c,runtimeMode:i,workspaceSelectionScope:l,markBootstrapPhase:m,markBootstrapStalled:y,setRuntimeMode:v,setAuthRequiredForApi:b,setIsAuthenticated:g,setAuthUserId:h,setAuthWorkspaceId:k,setAuthUserEmail:I,setAuthUserDisplayName:x,setAuthUserAvatarUrl:A,setUserGlobalSyncStatus:M,setUserGlobalSyncError:B,setHasBetaAccess:ue,setAvailableWorkspaces:X,setHydratedWorkspaceRole:ce,setAssigneeOptions:oe,setAuthBlocked:be,setAuthSessionResolved:_,setError:J,applyResolvedWorkspaceId:Q,readPersistedWorkspaceId:ie,authSessionRequestRef:H,authSessionEpochRef:P,authSessionLastCheckedAtRef:U,authSessionLastResultRef:se,isLoopbackHost:he,setAuthStateReadyRefs:V}){const Ce=r.useCallback(async ve=>{const ge=ve?.force===!0;if(m("auth"),!e)return se.current;if(!n)return v("local"),b(!1),g(!1),h("anonymous"),k(""),Jl(null),I(""),x(""),A(""),M("disconnected"),B(null),ue(!0),X([]),ce(null),oe($o()),be(!1),_(!0),V(!1,!0,!1),se.current=!1,U.current=Date.now(),!1;const Te=s("/api/taskforce/auth/session"),Le=Date.now();if(!ge&&H.current)return H.current;if(!ge&&a&&Le-U.current<1500)return se.current;const Ie=++P.current;let Oe=null;return Oe=(async()=>{const z=nh(),T=new AbortController,w=typeof window<"u"?window.setTimeout(()=>T.abort(),8e3):null,j=()=>P.current!==Ie,F=(ee,N)=>{Ht(ee,{durationMs:Math.max(0,Math.round(nh()-z)),force:ge,sessionUrl:Te,...N})};try{const ee=await fetch(Te,{method:"GET",credentials:"include",mode:"cors",signal:T.signal});if(j())return se.current;if(ee.status===429)return _(!0),V(se.current,!0,!1),F("auth_session_rate_limited",{status:ee.status}),se.current;if(!ee.ok)return j()?se.current:(he&&Jl(null),_(!0),V(!1,!0,!1),se.current=!1,F("auth_session_request_failed",{status:ee.status}),!1);const N=await ee.json();if(j())return se.current;const C=!!N.authRequiredForApi,$=!!N.authenticated,K=$?N.betaAccess!==!1:!0,te=typeof N.workspaceId=="string"&&N.workspaceId.trim().length>0?N.workspaceId.trim():"",L=typeof N.userId=="string"&&N.userId.trim().length>0?N.userId.trim():"anonymous",re=typeof N.email=="string"&&N.email.trim().length>0?N.email.trim().toLowerCase():"",fe=typeof N.displayName=="string"?N.displayName.trim():"",xe=typeof N.avatarUrl=="string"?N.avatarUrl.trim():"",le=i==="local",we=i==="local"||o,Re=o||le?!1:C;return b(Re),g($),h($?L:"anonymous"),k($?te:""),he&&Jl($?L:null),I($?re:""),x($?fe:""),A($?xe:""),$&&J(Xe=>Xe===c?"":Xe),M($?"idle":"disconnected"),B(null),ue(K),we||Q(te||ie(l)||"default",{preserveNonDefaultDefault:!0}),be(o||le?!1:C&&!$),_(!0),V($,!0,Re),se.current=$,$&&m("ready"),F("auth_session_resolved",{status:ee.status,authenticated:$,workspaceId:$?te:"",userId:$?L:"anonymous",authRequiredForApi:Re}),$}catch(ee){return j()||(he&&Jl(null),_(!0),V(!1,!0,!1),se.current=!1,y("Unable to verify your session."),F("auth_session_exception",{error:ee instanceof Error?ee.message:String(ee)})),se.current}finally{w!==null&&typeof window<"u"&&window.clearTimeout(w),j()||(U.current=Date.now()),Oe&&H.current===Oe&&(H.current=null)}})(),H.current=Oe,Oe},[e,n,a,s,o,c,i,l,m,y,v,b,g,h,k,I,x,A,M,B,ue,X,ce,oe,be,_,J,Q,ie,H,P,U,se,he,V]),Se=i==="local"&&he&&n?ef():"";return r.useEffect(()=>{Se&&(g(!0),_(!0),h(Se),V(!0,!0,!1),se.current=!0)},[Se,_,V,h,g,se]),r.useEffect(()=>{if(i!=="local"||!n||typeof window>"u")return;const ve=()=>{Ce()},ge=()=>{document.visibilityState==="visible"&&ve()};window.addEventListener("focus",ve),window.addEventListener("online",ve),document.addEventListener("visibilitychange",ge);const Te=window.setInterval(ve,3e4);return()=>{window.removeEventListener("focus",ve),window.removeEventListener("online",ve),document.removeEventListener("visibilitychange",ge),window.clearInterval(Te)}},[i,n,Ce]),{checkAuthSession:Ce}}function Vb(e){const n=e.runtimeMode==="cloud",a=!!(e.shouldGateProtectedApiCalls&&n&&!e.authSessionResolved),s=!!(e.shouldGateProtectedApiCalls&&n&&e.authSessionResolved&&e.authRequiredForApi&&!e.isAuthenticated);return{shouldDeferProtectedApiCalls:a,shouldBlockProtectedApiCalls:s,canCallProtectedApi:!(a||s)}}function Kb(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function Zb(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}function ah(e){if(!Array.isArray(e))return;const n=e.filter(a=>typeof a=="string"&&a.trim().length>0).map(a=>a.trim());return n.length>0?n:void 0}function Yb(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const n=e;return Array.isArray(n.categories)||Array.isArray(n.types)||Array.isArray(n.priorities)||Array.isArray(n.taxonomies)||!!n.displayLabels&&typeof n.displayLabels=="object"&&!Array.isArray(n.displayLabels)}function Jb(e){const n=e||{};return{categories:Array.isArray(n.categories)?n.categories.map(s=>typeof s=="string"?{value:s.toLowerCase().replace(/\s+/g,"-"),label:s}:s):[],types:Array.isArray(n.types)?n.types.map(s=>({...zk(s.value),...s,aliases:Array.isArray(s.aliases)?s.aliases.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):void 0,status:s.status==="retired"?"retired":"active"})):[],priorities:Array.isArray(n.priorities)?n.priorities:[],taxonomies:Array.isArray(n.taxonomies)?n.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 n.displayLabels?.category=="string"&&n.displayLabels.category.trim().length>0?n.displayLabels.category.trim():void 0,type:typeof n.displayLabels?.type=="string"&&n.displayLabels.type.trim().length>0?n.displayLabels.type.trim():void 0,priority:typeof n.displayLabels?.priority=="string"&&n.displayLabels.priority.trim().length>0?n.displayLabels.priority.trim():void 0}}}function Vn(){return typeof performance<"u"?performance.now():Date.now()}function Xb(e){const{shouldDeferProtectedApiCalls:n,shouldBlockProtectedApiCalls:a,getWorkspaceRequestState:s,isWorkspaceRequestStale:o,isWorkspaceEpochStale:c,isAbortError:i,isBootstrapTimeoutError:l,fetchWithTimeout:m,handleUnauthorized:y,applyBootstrapConfig:v,loadPersistedUiState:b,fetchBuildInfo:g,markBootstrapPhase:h,markBootstrapStalled:k,fetchWorkflows:I,fetchInitiativeTemplates:x,loadAvailableEnvironments:A,setReferenceDataLoaded:M,setCustomCategories:B,setCustomTypes:ue,setPriorities:X,setTaxonomies:ce,setTaxonomyDisplayLabels:oe,setConfigLoaded:be,hasLoadedUiStateRef:_,currentWorkspaceIdRef:J,referenceDataRequestRef:Q,referenceDataAbortRef:ie,bootstrapConfigAbortRef:H,workspaceListAbortRef:P,assigneeOptionsAbortRef:U,workspaceListHydratedRef:se,setAvailableWorkspaces:he,runtimeMode:V,applyResolvedWorkspaceId:Ce,workspaceSwitchingEnabled:Se,authSessionResolved:ve,isAuthenticated:ge,authUserId:Te,authUserAvatarUrl:Le,setHydratedWorkspaceRole:Ie,setAssigneeOptions:Oe,setAssigneeOptionsLoaded:z,commitCurrentWorkspaceId:T,currentWorkspaceId:w,workspaceSelectionScope:j,abortWorkspaceScopedRequests:F,setWorkspaceBootstrapPending:ee,checkAuthSession:N,lastConfigRefreshKeyRef:C,lastAssigneeOptionsLoadKeyRef:$,lastWorkspaceSyncStateLoadKeyRef:K,lastTaskSurfaceLoadKeyRef:te,lastSettingsSurfaceLoadKeyRef:L,isOpen:re,activeTab:fe,showArchive:xe,taskScope:le,settingsSection:we,workspaceBootstrapPending:Re,fetchTasks:Xe,fetchArchive:ze,fetchPlanningEntities:lt,refreshTaskCollections:wt,loadWorkspaceSyncState:$e,archiveBootstrapTimerRef:ft,hasBootstrappedDataRef:gt}=e,at=r.useCallback(async d=>{const Me=d?.ignoreAuthGuard===!0,We=d?.force===!0;if(!Me&&(n||a)){Ht("bootstrap_reference_data_skipped",{reason:a?"auth_blocked":"auth_deferred",runtimeMode:V,workspaceId:String(s().workspaceId||"").trim()||"default",force:We});return}const Qe=s(),ot=String(Qe.workspaceId||"").trim()||"default";if(!(V!=="cloud"||!ve||!ge||ot!==""&&ot!=="default")){Ht("bootstrap_reference_data_skipped",{reason:"workspace_unresolved",runtimeMode:V,workspaceId:ot,force:We});return}if(!We&&Q.current?.workspaceId===Qe.workspaceId){Ht("bootstrap_reference_data_reused",{workspaceId:ot,force:We}),await Q.current.promise;return}M(!1);const Be=Vn(),St=new AbortController;ie.current=St;const vt=(async()=>{await Promise.allSettled([(async()=>{let $t="empty-taxonomy-state";const Ze=await fetch("/api/taskforce/taxonomy-state",{signal:St.signal});if(!Ze.ok)return;const en=await Ze.json().catch(()=>({}));if(Yb(en))$t="taxonomy-state";else{$t="fallback-endpoints";const[bt,W,ke,Ne]=await Promise.all([fetch("/api/taskforce/categories",{signal:St.signal}),fetch("/api/taskforce/types",{signal:St.signal}),fetch("/api/taskforce/priorities",{signal:St.signal}),fetch("/api/taskforce/taxonomies",{signal:St.signal})]),[ae,Pe,Ge,De]=await Promise.all([bt.ok?bt.json().catch(()=>({})):Promise.resolve({}),W.ok?W.json().catch(()=>({})):Promise.resolve({}),ke.ok?ke.json().catch(()=>({})):Promise.resolve({}),Ne.ok?Ne.json().catch(()=>({})):Promise.resolve({})]);en.categories=ae.categories,en.types=Pe.types,en.priorities=Ge.priorities,en.taxonomies=De.taxonomies}const Lt=Jb(en);if(o(Qe)){Ht("bootstrap_reference_data_stale_drop",{workspaceId:ot,source:$t});return}Lt.categories.length>0&&B(Lt.categories),Lt.types.length>0&&ue(Lt.types),Lt.priorities.length>0&&X(Lt.priorities),ce(Lt.taxonomies),oe(Lt.displayLabels||{}),Ht("bootstrap_reference_data_source",{workspaceId:ot,source:$t,categories:Lt.categories.length,types:Lt.types.length,priorities:Lt.priorities.length,taxonomies:Lt.taxonomies.length})})(),I(),x(),A()]),!o(Qe)&&(M(!0),Ht("bootstrap_reference_data_loaded",{durationMs:Math.max(0,Math.round(Vn()-Be)),workspaceId:ot,force:We}))})();Q.current={workspaceId:Qe.workspaceId,promise:vt};try{await vt}finally{Q.current?.promise===vt&&(Q.current=null),ie.current===St&&(ie.current=null)}},[ve,x,I,s,ge,o,A,ie,Q,V,B,ue,X,M,ce,oe,a,n]),dt=r.useCallback(async d=>{if(!(d?.ignoreAuthGuard===!0)&&(n||a))return;h("config");const We=s(),Qe=Vn(),ot=new AbortController;H.current=ot;try{const de=await m("/api/taskforce/config",void 0,12e3,{signal:ot.signal});if(c(We))return;if(de.status===401){y(),be(!0);return}let Be="";if(de.ok){const St=await de.json();if(c(We))return;Be=typeof St?.workspaceId=="string"&&St.workspaceId.trim().length>0?St.workspaceId.trim():"",v(St)}if(c(We)){const St=String(J.current||"default").trim()||"default";if(!Be||St!==Be)return}if(_.current||(_.current=!0,await b(Be||We.workspaceId)),c(We)){const St=String(J.current||"default").trim()||"default";if(!Be||St!==Be)return}be(!0),h("ready"),Ht("bootstrap_config_loaded",{durationMs:Math.max(0,Math.round(Vn()-Qe)),status:de.status,workspaceId:Be||We.workspaceId}),g()}catch(de){if(i(de)||c(We))return;_.current||(_.current=!0,await b(We.workspaceId)),k(l(de)?"Startup checks timed out.":"Unable to finish startup checks."),be(!0),Ht("bootstrap_config_failed",{durationMs:Math.max(0,Math.round(Vn()-Qe)),workspaceId:We.workspaceId,error:de instanceof Error?de.message:String(de)})}finally{H.current===ot&&(H.current=null)}},[v,H,J,g,m,s,y,_,i,l,c,b,h,k,be,a,n]),ne=r.useCallback(async d=>{await dt(d),await at(d)},[dt,at]),tt=r.useCallback(()=>{typeof window>"u"||(ft.current!==null&&window.clearTimeout(ft.current),ft.current=window.setTimeout(()=>{ft.current=null,ze(!0).then(()=>Ht("bootstrap_archive_loaded_deferred",{}))},1500))},[ft,ze]),rt=r.useCallback(async()=>{if(!Se)return he([]),se.current=!1,{success:!0,workspaces:[]};const d=s(),Me=Vn(),We=new AbortController;P.current=We;try{const Qe=await m("/api/taskforce/workspaces",{method:"GET",credentials:"include"},12e3,{signal:We.signal});if(c(d))return{success:!1,error:"Workspace changed while loading workspaces."};if(Qe.status===401)return he([]),se.current=!1,{success:!1,error:"Authentication required."};const ot=await Qe.json().catch(()=>({}));if(c(d))return{success:!1,error:"Workspace changed while loading workspaces."};if(!Qe.ok||ot?.success===!1)return he([]),se.current=!1,{success:!1,error:ot?.error||`Failed to load workspaces (${Qe.status})`};const de=Array.isArray(ot?.workspaces)?ot.workspaces.map(Be=>({id:String(Be?.id||"").trim(),name:String(Be?.name||"").trim(),role:String(Be?.role||"member").trim().toLowerCase(),slug:typeof Be?.slug=="string"?Be.slug:null,description:typeof Be?.description=="string"?Be.description:null,status:typeof Be?.status=="string"?Be.status:"",betaAccess:Be?.betaAccess===!0})).filter(Be=>Be.id&&Be.name):[];return he(de),se.current=!0,V!=="local"&&typeof ot?.currentWorkspaceId=="string"&&ot.currentWorkspaceId.trim().length>0&&Ce(ot.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),Ht("bootstrap_workspaces_loaded",{durationMs:Math.max(0,Math.round(Vn()-Me)),workspaceId:d.workspaceId,count:de.length,status:Qe.status}),{success:!0,workspaces:de}}catch(Qe){return l(Qe)&&k("Startup checks timed out."),he([]),se.current=!1,Ht("bootstrap_workspaces_failed",{durationMs:Math.max(0,Math.round(Vn()-Me)),workspaceId:d.workspaceId,error:Qe instanceof Error?Qe.message:String(Qe)}),{success:!1,error:i(Qe)?"Workspace list request aborted.":"Failed to load workspaces."}}finally{P.current===We&&(P.current=null)}},[Ce,m,s,i,l,c,k,V,he,P,se,Se]),Pt=r.useCallback(async()=>{const d=s(),Me=Vn(),We=new AbortController;U.current=We,z(!1);try{const[Qe,ot]=await Promise.all([m("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},12e3,{signal:We.signal}),ve&&ge?m("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},12e3,{signal:We.signal}).catch(()=>null):Promise.resolve(null)]);if(o(d))return{success:!1,error:"Workspace changed while loading assignee options."};if(Qe.status===401)return Oe($o()),z(!0),{success:!1,error:"Authentication required."};const de=await Qe.json().catch(()=>({}));if(o(d))return{success:!1,error:"Workspace changed while loading assignee options."};if(!Qe.ok)return Oe($o()),z(!0),{success:!1,error:de?.error||`Failed to load assignee options (${Qe.status})`};const Be=String(Te||"").trim(),St=String(Le||"").trim(),vt=(W,ke)=>{const Ne=typeof W?.avatarUrl=="string"&&W.avatarUrl.trim().length>0?W.avatarUrl.trim():"";if(Ne)return Ne;const ae=String(W?.userId||ke||"").trim();return Be&&ae===Be&&St?St:null},$t=Array.isArray(de?.assignees)?de.assignees:[],Ze=$t.map(W=>{const ke=String(W?.value||"").trim(),Ne=String(W?.kind||"").trim().toLowerCase();return ke?Ne==="agent"||Ne==="ai"?{value:ke,label:String(W?.label||ke).trim()||ke,icon:String(W?.icon||"Bot"),color:String(W?.color||"#8b5cf6"),kind:"agent",avatarUrl:typeof W?.avatarUrl=="string"&&W.avatarUrl.trim().length>0?W.avatarUrl.trim():null}:Ne==="member"||Ne==="human"?{value:ke,label:String(W?.label||ke).trim()||ke,icon:String(W?.icon||"User"),color:String(W?.color||"#22c55e"),kind:"member",avatarUrl:vt(W,ke)}:null:null}).filter(Boolean),en=$t.map(W=>({userId:String(W?.userId||"").trim(),email:String(W?.email||"").trim().toLowerCase(),displayName:typeof W?.displayName=="string"?W.displayName:null,avatarUrl:vt(W)})).filter(W=>W.userId);let Lt=en;if(ot?.ok){const W=await ot.json().catch(()=>({})),ke=Array.isArray(W?.users)?W.users:[],Ne=ke.find(Ge=>String(Ge?.userId||"").trim()===Be),ae=String(Ne?.role||"").trim().toLowerCase();ae==="owner"||ae==="admin"||ae==="member"||ae==="read-only"?Ie(ae):!Se&&ke.length===0&&Ie(null);const Pe=ke.map(Ge=>({userId:String(Ge?.userId||"").trim(),email:String(Ge?.email||"").trim().toLowerCase(),displayName:typeof Ge?.displayName=="string"?Ge.displayName:null,avatarUrl:vt(Ge)})).filter(Ge=>Ge.userId);Lt=Array.from(new Map([...en,...Pe].map(Ge=>[Ge.userId,Ge])).values())}else!Se&&!en.length&&Ie(null);const bt=dd([...Ze,...jS(Lt).filter(W=>W.kind==="member")]);return o(d)?{success:!1,error:"Workspace changed while loading assignee options."}:(Oe(bt),z(!0),Ht("bootstrap_assignee_options_loaded",{durationMs:Math.max(0,Math.round(Vn()-Me)),workspaceId:d.workspaceId,count:bt.length}),{success:!0})}catch(Qe){return o(d)||(Oe($o()),z(!0)),Ht("bootstrap_assignee_options_failed",{durationMs:Math.max(0,Math.round(Vn()-Me)),workspaceId:d.workspaceId,error:Qe instanceof Error?Qe.message:String(Qe)}),{success:!1,error:i(Qe)?"Assignee options request aborted.":"Failed to load assignee options."}}finally{U.current===We&&(U.current=null)}},[U,ve,Le,Te,m,s,i,ge,o,Oe,z,Ie,Se]),yt=r.useCallback(async(d,Me)=>{if(!Se)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const We=String(d||"").trim();if(!We)return{success:!1,error:"workspaceId is required."};const Qe=String(J.current||"").trim()||"default",ot=Vn();try{Ht("bootstrap_workspace_switch_started",{fromWorkspaceId:Qe,toWorkspaceId:We,hydrate:Me?.hydrate!==!1});const de=await fetch("/api/taskforce/session/workspace",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:We})}),Be=await de.json().catch(()=>({}));if(!de.ok||Be?.success===!1)return{success:!1,error:Be?.error||`Failed to switch workspace (${de.status})`,code:Be?.code};T(We,{clearExplicitSelection:!1}),F(),ee(!0),h("workspace");const St=await N({force:!0});return Me?.hydrate===!1?await rt():(C.current=`${V}:${We}:${j}`,$.current=`${V}:${St?"auth":"guest"}:${We}`,K.current=We,re&&fe==="tasks"&&(te.current=`${We}:${fe}:${xe?"archive":"active"}:${le}`),re&&fe==="settings"&&(L.current=`${We}:${fe}:${we}`),await Promise.all([ne(),rt(),wt({isSilent:!1}),$e()]),lt({ignoreAuthGuard:!0})),Ht("bootstrap_workspace_switch_completed",{fromWorkspaceId:Qe,toWorkspaceId:We,hydrate:Me?.hydrate!==!1,durationMs:Math.max(0,Math.round(Vn()-ot))}),{success:!0}}catch(de){return Ht("bootstrap_workspace_switch_failed",{fromWorkspaceId:Qe,toWorkspaceId:We,hydrate:Me?.hydrate!==!1,durationMs:Math.max(0,Math.round(Vn()-ot)),error:de instanceof Error?de.message:String(de)}),{success:!1,error:"Failed to switch workspace."}}finally{ee(!1)}},[F,fe,N,T,J,ne,lt,rt,re,$,C,L,te,K,$e,h,wt,V,we,ee,xe,le,j,Se]),Rt=r.useCallback(async d=>{h("workspace"),ee(!0);try{if(!Se){const vt=String(w||"").trim()||"default";return T(vt),{success:!0,workspaceSetupRequired:!1,workspaceId:vt}}const Me=String(d?.preferredWorkspaceId||"").trim(),We=Ap(j),Qe=await rt();if(!Qe.success)return{success:!1,workspaceSetupRequired:!1,error:Qe.error||"Failed to load workspaces after authentication."};const ot=Array.isArray(Qe.workspaces)?Qe.workspaces:[];if(ot.length===0)return T("default"),{success:!0,workspaceSetupRequired:!0};const de=new Set(ot.map(vt=>String(vt.id||"").trim()).filter(Boolean)),Be=(Me&&de.has(Me)?Me:"")||(We&&de.has(We)?We:"")||String(ot[0]?.id||"").trim();if(!Be)return T("default"),{success:!0,workspaceSetupRequired:!0};if(String(J.current||"").trim()!==Be){const vt=await yt(Be,{hydrate:!1});if(!vt.success)return{success:!1,workspaceSetupRequired:!1,error:vt.error||"Failed to set workspace after authentication.",code:vt.code}}else T(Be);return{success:!0,workspaceSetupRequired:!1,workspaceId:Be}}catch{return k("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{ee(!1)}},[T,w,J,rt,h,k,ee,yt,j,Se]),Tt=r.useCallback(async()=>{h("auth");const d=Vn();Ht("bootstrap_retry_started",{workspaceId:String(J.current||"default").trim()||"default"});const Me=await N({force:!0});let We=!1;if(Se&&Me){const Qe=await Rt();if(!Qe.success||Qe.workspaceSetupRequired){await ne({ignoreAuthGuard:!0}),Ht("bootstrap_retry_completed",{workspaceId:String(J.current||"default").trim()||"default",authenticated:Me,workspaceSetupRequired:Qe.workspaceSetupRequired===!0,success:Qe.success,durationMs:Math.max(0,Math.round(Vn()-d))});return}}ee(!0);try{await ne({ignoreAuthGuard:!0}),Me&&!We&&(await Promise.all([Xe(!0,{ignoreAuthGuard:!0}),at({ignoreAuthGuard:!0,force:!0})]),lt({ignoreAuthGuard:!0})),Ht("bootstrap_retry_completed",{workspaceId:String(J.current||"default").trim()||"default",authenticated:Me,workspaceSetupRequired:We,success:!0,durationMs:Math.max(0,Math.round(Vn()-d))})}finally{ee(!1)}},[N,J,ne,lt,at,Xe,h,Rt,ee,Se]),Dt=r.useCallback(async d=>{const Me=d?.reason||"initial-load",We=d?.ignoreAuthGuard===!0,Qe=d?.tasksSilent!==!1,ot=d?.includeDeferredArchive!==!1,de=Vn();if(h("auth"),!await N({force:!0}))return await ne({ignoreAuthGuard:!0}),Ht("cloud_bootstrap_completed",{reason:Me,durationMs:Math.max(0,Math.round(Vn()-de)),authenticated:!1,workspaceSetupRequired:!1,success:!1}),{success:!1,authenticated:!1,workspaceSetupRequired:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};if(Se){const St=await Rt();if(!St.success)return await ne({ignoreAuthGuard:!0}),Ht("cloud_bootstrap_completed",{reason:Me,durationMs:Math.max(0,Math.round(Vn()-de)),authenticated:!0,workspaceSetupRequired:!1,success:!1,error:St.error||"Workspace resolution failed."}),{success:!1,authenticated:!0,workspaceSetupRequired:!1,error:St.error||"Unable to resolve workspace access.",code:St.code};if(St.workspaceSetupRequired)return await ne({ignoreAuthGuard:!0}),Ht("cloud_bootstrap_completed",{reason:Me,durationMs:Math.max(0,Math.round(Vn()-de)),authenticated:!0,workspaceSetupRequired:!0,success:!0}),{success:!0,authenticated:!0,workspaceSetupRequired:!0}}ee(!0);try{return await dt({ignoreAuthGuard:We}),await Promise.all([Xe(Qe,{ignoreAuthGuard:We}),at({ignoreAuthGuard:We})]),lt({ignoreAuthGuard:We}),ot&&tt(),Ht("cloud_bootstrap_completed",{reason:Me,durationMs:Math.max(0,Math.round(Vn()-de)),authenticated:!0,workspaceSetupRequired:!1,success:!0,workspaceId:String(J.current||"default").trim()||"default"}),{success:!0,authenticated:!0,workspaceSetupRequired:!1}}finally{ee(!1)}},[N,J,dt,lt,at,Xe,h,Rt,tt,ee,Se]);return r.useEffect(()=>{!n&&!a&&!gt.current&&(gt.current=!0,(async()=>{const d=Vn();if(V==="cloud"&&ve&&ge){const Me=await Dt({reason:"initial-load",tasksSilent:!1,includeDeferredArchive:!0});if(!Me.success||Me.workspaceSetupRequired)return}else await Promise.all([dt(),Xe(!1),at()]),lt();V!=="cloud"&&tt(),Ht("bootstrap_initial_load_completed",{durationMs:Math.max(0,Math.round(Vn()-d)),runtimeMode:V,workspaceId:String(J.current||"default").trim()||"default"})})())},[ve,J,dt,lt,at,Xe,gt,ge,Dt,V,tt,a,n]),r.useEffect(()=>{if(n||a||Re||j==="bootstrap"||!gt.current)return;const d=`${V}:${w}:${j}`;C.current!==d&&(C.current=d,ne())},[w,ne,gt,C,V,a,n,Re,j]),r.useEffect(()=>{if(n||a||Re)return;const d=w;K.current!==d&&(K.current=d,$e())},[w,K,$e,a,n,Re]),r.useEffect(()=>{if(V!=="cloud"||!ve||!ge){V!=="cloud"&&he([]),se.current=!1;return}Re||!gt.current||se.current||rt()},[ve,rt,gt,ge,V,he,Re,se]),{fetchReferenceData:at,fetchBootstrapConfig:dt,fetchConfig:ne,fetchWorkspaces:rt,fetchAssigneeOptions:Pt,switchWorkspace:yt,resolveWorkspaceAfterAuth:Rt,retryBootstrapChecks:Tt,runCloudBootstrap:Dt}}function Qb({isOpen:e,authBlocked:n,authRequiredForApi:a,isAuthenticated:s,canCallProtectedApi:o,shouldGateProtectedApiCalls:c,authSessionResolvedRef:i,authRequiredForApiRef:l,isAuthenticatedRef:m,dataVersionRef:y,refreshTaskCollectionsForDataVersion:v}){r.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||Kb({isOpen:e,authBlocked:n,authRequiredForApi:a,isAuthenticated:s,canCallProtectedApi:o}))return;let b=!1;const g=async()=>{if(!(b||document.visibilityState!=="visible")&&!Zb({shouldGateProtectedApiCalls:c,authSessionResolved:i.current,authRequiredForApi:l.current,isAuthenticated:m.current}))try{const I=await fetch("/api/taskforce/data-version");if(!I.ok)return;const x=await I.json(),A=Number(x?.dataVersion);if(!Number.isFinite(A))return;if(y.current===null){y.current=A;return}A!==y.current&&(y.current=A,await v())}catch{}},h=()=>{document.visibilityState==="visible"&&g()},k=window.setInterval(()=>{g()},3e3);return document.addEventListener("visibilitychange",h),g(),()=>{b=!0,window.clearInterval(k),document.removeEventListener("visibilitychange",h)}},[e,n,a,s,o,c,i,l,m,y,v])}const ew={};function Fo(e,n){const a=e.findIndex(s=>s.id===n.id);return a===-1?[...e,n]:e.map((s,o)=>o===a?n:s)}const lo=Jp(ew),cp=(()=>{const e=lo.baseUrl,n=lo.cloudAuthBaseUrl;if(n)return n;const a=lo.apiBaseUrl;return a||e||"https://app.taskforcehq.ai"})(),Eu=12e3,rh=2e4,tw=new Set(["external-abort","superseded","workspace-reset","workspace-transition"]);function Uu(e){return typeof DOMException<"u"&&e instanceof DOMException?e.name==="AbortError":String(e?.name||"").toLowerCase()==="aborterror"}function Mp(e){return typeof e=="string"&&tw.has(e)}function lp(e,n){return n.aborted?e===n.reason||Mp(e)||Mp(n.reason)?!0:Uu(e):!1}function nw(e){const n=new Error(`Startup checks timed out after ${e}ms.`);return n.name="BootstrapTimeoutError",n}function sh(e){const n=e&&typeof e=="object"?e:{},a=Array.isArray(n.initiatives)?n.initiatives.filter(c=>!!(c&&typeof c=="object"&&typeof c.id=="string")):[],s=Array.isArray(n.workstreams)?n.workstreams.filter(c=>!!(c&&typeof c=="object"&&typeof c.id=="string")):[],o=Array.isArray(n.workstreamTaskSummaries)?n.workstreamTaskSummaries.flatMap(c=>{if(!c||typeof c!="object")return[];const i=String(c.workstreamId||"").trim();if(!i)return[];const l=Array.isArray(c.tasks)?c.tasks:[],m=Math.max(0,Number(c.taskCount)||0),y=Math.max(0,Number(c.completedTaskCount)||0);return[{workstreamId:i,taskCount:m,completedTaskCount:y,tasks:l.filter(v=>!!(v&&typeof v=="object"&&typeof v.id=="string")).map(v=>({id:String(v.id||"").trim(),referenceNumber:typeof v.referenceNumber=="number"?v.referenceNumber:null,title:String(v.title||"").trim()||"Untitled Task",status:typeof v.status=="string"?v.status:null}))}]}):[];return{initiatives:a,workstreams:s,workstreamTaskSummaries:o}}function aw({config:e={},initialTaskId:n,onTaskCountChange:a,onClose:s}){const o={...Vk,...e},{categories:c,types:i,apiEndpoint:l,apiBaseUrl:m,cloudAuthBaseUrl:y,cloudMcpBaseUrl:v,wsBaseUrl:b,shortcut:g}=o,h=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",k=h==="localhost"||h==="127.0.0.1"||h==="::1",I=typeof window<"u"&&!k,[x,A]=r.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[M,B]=r.useState(!1),ue=r.useCallback(f=>typeof f=="string"?f.trim().replace(/\/+$/,""):"",[]);r.useEffect(()=>{if(typeof window>"u"){B(!0);return}let f=!1;return(async()=>{try{const O=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!O.ok)return;const G=await O.json().catch(()=>({})),Z=G?.config&&typeof G.config=="object"?G.config:{};if(f)return;const Fe=String(Z.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",Ue=String(Z.workspaceMode||"").trim(),tn=Ue==="single-local"||Ue==="multi-cloud"?Ue:Fe==="cloud"?"multi-cloud":"single-local";j(Fe),A({cloudEnvironment:typeof Z.cloudEnvironment=="string"?String(Z.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:ue(Z.cloudBaseUrl),cloudMcpBaseUrl:ue(Z.cloudMcpBaseUrl),baseUrl:ue(Z.baseUrl),apiBaseUrl:ue(Z.apiBaseUrl),cloudAuthBaseUrl:ue(Z.cloudAuthBaseUrl),wsBaseUrl:ue(Z.wsBaseUrl),cloudAuthViaLocalProxy:!!Z.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:tn,workspaceSwitchingEnabled:typeof Z.workspaceSwitchingEnabled=="boolean"?!!Z.workspaceSwitchingEnabled:tn==="multi-cloud"})}catch{}finally{f||B(!0)}})(),()=>{f=!0}},[ue]);const X=typeof window>"u"?"":k?cp:"",ce=ue(lo.baseUrl),oe=ue(lo.apiBaseUrl),be=ue(lo.cloudBaseUrl),_=ue(lo.cloudMcpBaseUrl),J=ue(lo.cloudAuthBaseUrl),Q=ue(lo.wsBaseUrl),ie=ue(m),H=ue(y),P=ue(v),U=x.apiBaseUrl||x.baseUrl,he=ie||U||(k?"":oe||ce)||"",V=H||J||ce,Ce=x.cloudAuthBaseUrl||x.baseUrl,ve=((k?Ce||V:V||Ce)||he||X).trim().replace(/\/+$/,""),ge=ue(xS(x.cloudMcpBaseUrl||x.cloudAuthBaseUrl||x.cloudBaseUrl||P||H||_||J||be||ve)),Te=(x.cloudMcpBaseUrl||P||ge||x.cloudBaseUrl||_||be||ve||X).trim().replace(/\/+$/,""),Le=!I&&!!ve&&!he,Ie=I||M&&!!(ve||he),Oe=Ie&&!Le,z=!!(ve||he||I),T=I?"cloud":"local",[w,j]=r.useState(()=>T),F=T==="local"&&k&&z?ef():"",ee=F.length>0,N=r.useCallback(f=>!f||/^https?:\/\//i.test(f)||!he||!f.startsWith("/")?f:`${he}${f}`,[he]),C=r.useCallback(f=>{if(!f||/^https?:\/\//i.test(f)||!f.startsWith("/"))return f;const O=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(!I&&O&&(w==="cloud"||!M||x.cloudAuthViaLocalProxy||x.workspaceMode==="multi-cloud"))return f;const G=ve||he;if(G){const Z=`${G}${f}`;if(typeof window<"u"&&!I&&O)try{if(new URL(Z,window.location.origin).origin===window.location.origin)return`${cp}${f}`}catch{return`${cp}${f}`}return Z}return f},[M,x.cloudAuthViaLocalProxy,x.workspaceMode,ve,he,I,w]),$=r.useCallback(f=>{const O=String(f||"").trim()||"/taskforce-ws",G=O.startsWith("/")?O:`/${O}`,Z=String(b||x.wsBaseUrl||Q||he||"").trim().replace(/\/+$/,""),Ke=typeof window<"u"?window.location.origin:"",Fe=Z||Ke;if(!Fe)return"";try{const Ue=new URL(G,Fe);return Ue.protocol==="https:"&&(Ue.protocol="wss:"),Ue.protocol==="http:"&&(Ue.protocol="ws:"),Ue.toString()}catch{return""}},[b,x.wsBaseUrl,Q,he]),[K,te]=r.useState("tasks"),[L,re]=r.useState(!1),[fe,xe]=r.useState(!1),[le,we]=r.useState("open"),[Re,Xe]=r.useState(Rc(o.theme)||Ku),[ze,lt]=r.useState(Rc(o.theme)||Ku),[wt,$e]=r.useState(!0),[ft]=r.useState(".taskforce"),gt=!1,[at,dt]=r.useState(!1),[ne,tt]=r.useState([]),[rt,Pt]=r.useState([]),[yt,Rt]=r.useState(""),[Tt,Dt]=r.useState(null),[d,Me]=r.useState(null),[We,Qe]=r.useState(""),[ot,de]=r.useState(""),Be=r.useMemo(()=>gS({projectRoot:We,runtimeMode:T}),[We,T]),[St,vt]=r.useState(""),[$t,Ze]=r.useState(""),en=vS(w),Lt=x.workspaceMode==="single-local"||x.workspaceMode==="multi-cloud"?x.workspaceMode:en.workspaceMode,bt=typeof x.workspaceSwitchingEnabled=="boolean"?x.workspaceSwitchingEnabled:en.workspaceSwitchingEnabled,[W,ke]=r.useState(!1),[Ne,ae]=r.useState(!1),[Pe,Ge]=r.useState(ee),[De,it]=r.useState(ee?F:"anonymous"),[Ut,Gt]=r.useState(""),[nn,Ft]=r.useState(""),[Wt,Vt]=r.useState(""),[an,Kt]=r.useState([]),[Kn,Fn]=r.useState(""),[Jn,_n]=r.useState(!0),[pe,et]=r.useState(null),[Ae,Nt]=r.useState(()=>{if(T==="local")return"default";const f=Ap(Be);return f&&f.toLowerCase()!=="default"?f:"default"}),Ye=r.useMemo(()=>yS({projectRoot:We,runtimeMode:w,workspaceId:Ae}),[We,w,Ae]),[Ot,dn]=r.useState([]),[yn,on]=r.useState(()=>$o()),[rn,kt]=r.useState(!1),[zt,Ln]=r.useState(ee),[Et,On]=r.useState("idle"),[kn,Jt]=r.useState(null),[Dr,Rn]=r.useState(null),Xn=r.useRef(null),In=r.useRef(0),Yt=r.useRef(0),jn=r.useRef(ee),ln=r.useRef(Ae),ga=r.useRef(null),la=r.useRef(0),Za=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"),[fn,Cr]=r.useState(0),Lr=r.useRef(null),ya=r.useRef(null),Bn=r.useRef(null),Ar=r.useRef(null),ka=r.useRef(null),ja=r.useRef(null),Qn=r.useRef(null),Tn=r.useCallback((f,O)=>{const G=String(f||"").trim();if(!G)return;const Z=String(ln.current||"").trim();Z&&Z!==G&&(la.current+=1,Cr(la.current)),ln.current=G,O?.clearExplicitSelection!==!1&&(ga.current=null),Nt(G)},[]);r.useEffect(()=>{ln.current=Ae},[Ae]);const Br=r.useCallback(f=>{const O=String(f||"").trim();O&&Nt(()=>{const G=String(ga.current||"").trim();let Z=O;return G&&G!==O&&(Z=G),ln.current=Z,Z})},[]),_t=r.useCallback(()=>({workspaceId:String(ln.current||"default").trim()||"default",epoch:la.current}),[]),Sa=r.useCallback(f=>(String(ln.current||"default").trim()||"default")!==f.workspaceId||la.current!==f.epoch,[]),da=r.useCallback(f=>la.current!==f.epoch,[]),va=r.useCallback(f=>Uu(f)||Mp(f),[]),$n=r.useCallback(()=>{[Lr,ya,Bn,Ar,ka,ja].forEach(f=>{f.current?.abort("workspace-transition"),f.current=null}),Qn.current!==null&&typeof window<"u"&&(window.clearTimeout(Qn.current),Qn.current=null),ic.current=null},[]),Pa=r.useMemo(()=>Vb({shouldGateProtectedApiCalls:Oe,runtimeMode:w,authSessionResolved:zt,authRequiredForApi:W,isAuthenticated:Pe}),[Oe,w,zt,W,Pe]),wn=Pa.shouldDeferProtectedApiCalls,Un=Pa.shouldBlockProtectedApiCalls,[ba,un]=r.useState(null),[Ea,Qt]=r.useState(null),[qn,Cn]=r.useState(!1),[Ya,Ja]=r.useState("unknown"),[Mn,cn]=r.useState(null),[hn,ua]=r.useState(o.shortcut||"Alt+T"),[ea,pr]=r.useState(o.priorities||[]),[fr]=r.useState(rg()),[Xt,ms]=r.useState(""),[zn,Xa]=r.useState(!1),[Vr,ma]=r.useState(!1),[qa,Wr]=r.useState(!0),[wa,Hn]=r.useState(()=>pS()),Ir=r.useMemo(()=>mS(),[]),[Pn,ps]=r.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[ta,Tr]=r.useState(!1),[hr,Fr]=r.useState(!0),[pa,gr]=r.useState(!0),[xa,Ma]=r.useState(""),[Qa,Kr]=r.useState(null);Hb({currentWorkspaceIdRef:ln,resolveApiUrl:N,runtimeMode:w});const{availableWorkflows:Or,initiativeTemplates:Ve,fetchWorkflows:Bt,fetchInitiativeTemplates:Dn,fetchWorkflowTemplate:sn,fetchWorkflowOverrideNames:_a,saveWorkflowTemplateDraft:Zn,resetWorkflowTemplateDraft:Is}=Sb({shouldDeferProtectedApiCalls:wn,shouldBlockProtectedApiCalls:Un}),{zenMode:Zr,setZenModeState:Yr,toggleZenMode:Yn}=vb(),{exportEnvironment:Mt,setExportEnvironment:mn,availableEnvironments:Da,loadAvailableEnvironments:yr,exportWorkflowsPath:kr,setExportWorkflowsPath:er,exportingResource:fs,exportResult:Nr,handleExportWorkflows:Jr}=hb({storagePath:ft,shouldDeferProtectedApiCalls:wn,shouldBlockProtectedApiCalls:Un}),[tr,ra]=r.useState(!1),[Ts,q]=r.useState(null),{uiNotice:Je,pushNotice:Ct,clearNotice:jt}=fb(),[Nn,nr]=r.useState([]),Ca=r.useRef(null),[ho,Ns]=r.useState(0),qo=r.useCallback(f=>!f||!We?f:f.startsWith(We)?f.slice(We.length).replace(/^[/\\]+/,""):f,[We]),[Gn,La]=r.useState([]),[R,E]=r.useState([]),[je,ct]=r.useState([]),[nt,Y]=r.useState([]),[zs,ar]=r.useState([]),[Hs,Ba]=r.useState([]),[Hc,rr]=r.useState(!1),[sr,Xr]=r.useState(null),[Gc,Vc]=r.useState(!1),[Gs,zo]=r.useState([]),[Aa,Vs]=r.useState(!1),[Ho,Go]=r.useState({}),Mi=r.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});r.useEffect(()=>{Mi.current={authSessionResolved:zt,configLoaded:Aa,workspaceBootstrapPending:rn}},[zt,Aa,rn]);const Rr=r.useCallback(f=>{On(f),f!=="ready"&&(Jt(null),Rn(Date.now()))},[]),Ks=r.useCallback(f=>{const O=Mi.current;O.authSessionResolved&&O.configLoaded&&!O.workspaceBootstrapPending||(On("stalled"),Jt(f),Rn(G=>G??Date.now()))},[]),go=r.useCallback(async(f,O,G=Eu,Z)=>{const Ke=new AbortController,Fe=Z?.signal,Ue=Number(G)>0?Number(G):Eu,tn=_t(),bn=f.startsWith("/api/taskforce/")?ap(O,Df({workspaceId:tn.workspaceId,epoch:tn.epoch,seed:Za.current})):O,Wn=typeof window<"u"?window.setTimeout(()=>Ke.abort("bootstrap-timeout"),Ue):null,ia=()=>{Ke.abort(Fe?.reason||"external-abort")};Fe&&(Fe.aborted?ia():Fe.addEventListener("abort",ia,{once:!0}));try{return await fetch(f,{...bn||{},signal:Ke.signal})}catch(Ha){throw Fe?.aborted&&lp(Ha,Fe)?Fe.reason||Ha:Uu(Ha)||Ha==="bootstrap-timeout"?nw(Ue):Ha}finally{Fe&&Fe.removeEventListener("abort",ia),Wn!==null&&typeof window<"u"&&window.clearTimeout(Wn)}},[_t]),Kc=r.useMemo(()=>{const f=!zt,O=Et==="stalled",G=zt&&(!Aa||rn||O);let Z="Checking account, workspace access, and setup status...";return Et==="auth"?Z="Verifying session...":Et==="workspace"?Z="Resolving workspace access...":Et==="config"&&(Z="Loading configuration..."),{phase:Et,auth:{resolved:zt,pending:f},config:{loaded:Aa},workspace:{pending:rn},pending:f||G,authPending:f,appPending:G,ready:zt&&Aa&&!rn&&Et==="ready",stalled:O,subtitle:Z,error:kn,startedAt:Dr}},[zt,kn,Et,Dr,Aa,rn]),yo=r.useCallback(f=>String(f?.name||"")==="BootstrapTimeoutError",[]),[hs,Vo]=r.useState([]),[Sr,An]=r.useState({}),[or,jr]=r.useState(o.taxonomies||[]),Sn=r.useMemo(()=>(Gs.length>0?Gs:c||[]).map(O=>typeof O=="string"?{value:O.toLowerCase().replace(/\s+/g,"-"),label:O}:O).sort((O,G)=>O.label.localeCompare(G.label)),[Gs,c]),Zc=r.useMemo(()=>({categories:Sn,types:hs,priorities:ea,taxonomies:or,displayLabels:Sr}),[Sn,hs,ea,or,Sr]);r.useMemo(()=>Sn.filter(f=>!f.disabled),[Sn]);const gs=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",[]),fa=hs.length>0?hs:i,[Qr,ko]=r.useState(!1),[Wa,vr]=r.useState(""),ys="Authentication required. Sign in to continue.",[Zs,es]=r.useState(!1),[Ys,ks]=r.useState(!1),$r=r.useCallback(()=>{ae(w==="cloud"),Ge(!1),Ft(""),Vt(""),Fn(""),vr(ys)},[ys,w]),{recentlyChangedTaskIds:Js,fetchTasks:Di,fetchArchive:Rs,refreshTaskCollections:ts,refreshTaskCollectionsFromInvalidation:ns,mergeTaskFromServer:Yc}=wb({tasks:Gn,archivedTasks:R,setTasks:La,setArchivedTasks:E,setLoadingTasks:rr,getCurrentWorkspaceId:()=>ln.current,workspaceResetKey:`${Ae}:${fn}`,shouldDeferProtectedApiCalls:wn,shouldBlockProtectedApiCalls:Un,handleUnauthorized:$r,authRequiredForApi:W});r.useEffect(()=>{fn!==0&&(ic.current=null,di.current="",ui.current="",oc.current="",vl.current="",To.current="",mi.current="",pi(!1),es(!1),on($o()),ks(!1),Ba([]),La([]),E([]),rr(!1),za.current!==null&&typeof window<"u"&&(window.clearTimeout(za.current),za.current=null),rs.current!==null&&typeof window<"u"&&(window.clearTimeout(rs.current),rs.current=null))},[E,rr,La,fn]);const ir=r.useCallback(async(f=!1,O)=>{if(!(O?.ignoreAuthGuard===!0)&&(wn||Un))return;f||rr(!0);const Z=_t(),Ke=new AbortController;ka.current=Ke;try{let Fe=await fetch("/api/taskforce/deleted",{signal:Ke.signal});if(Fe.status===404&&(Fe=await fetch("/api/taskforce/trash",{signal:Ke.signal})),Fe.status===401){$r(),Ba([]);return}if(Fe.status===404){Ba([]);return}if(Fe.ok){const Ue=await Fe.json();if(Sa(Z))return;const tn=Array.isArray(Ue?.deleted)?Ue.deleted.map(bn=>{const Wn=bn?.taskSnapshot&&typeof bn.taskSnapshot=="object"?fo(bn.taskSnapshot):null;return Wn?{...bn,taskSnapshot:Wn}:null}).filter(bn=>!!bn):[];Ba(tn)}}catch(Fe){if(lp(Fe,Ke.signal)||va(Fe))return;console.error("[Taskforce] Failed to fetch deleted tasks:",Fe)}finally{ka.current===Ke&&(ka.current=null),f||rr(!1)}},[_t,$r,va,Sa,wn,Un]),vn=r.useCallback(async f=>{if(!(f?.ignoreAuthGuard===!0)&&(wn||Un))return;const G=_t();ja.current?.abort("superseded"),Qn.current!==null&&typeof window<"u"&&(window.clearTimeout(Qn.current),Qn.current=null);const Z=new AbortController;ja.current=Z;try{const Ke=Df({workspaceId:G.workspaceId,epoch:G.epoch,seed:Za.current}),Fe=async bn=>{if(typeof window>"u")return fetch(bn,ap({signal:Z.signal},Ke));const Wn=new AbortController,ia=window.setTimeout(()=>Wn.abort("planning-timeout"),rh),Ha=()=>Wn.abort(Z.signal.reason||"external-abort");Z.signal.aborted?Ha():Z.signal.addEventListener("abort",Ha,{once:!0});try{return await fetch(bn,ap({signal:Wn.signal},Ke))}catch(ur){if(Z.signal.aborted)throw Z.signal.reason||ur;if(Uu(ur)||ur==="planning-timeout")return null;throw ur}finally{window.clearTimeout(ia),Z.signal.removeEventListener("abort",Ha)}};let Ue=null;const tn=await Fe("/api/taskforce/planning/bootstrap");if(tn?.status===401){$r(),ct([]),Y([]),ar([]);return}if(tn?.ok)Ue=sh(await tn.json().catch(()=>({})));else{const[bn,Wn]=await Promise.all([Fe("/api/taskforce/initiatives"),Fe("/api/taskforce/workstreams")]);if(!bn||!Wn)throw new Error("Planning endpoints timed out during startup.");if(bn.status===401||Wn.status===401){$r(),ct([]),Y([]),ar([]);return}const[ia,Ha]=await Promise.all([bn.ok?bn.json().catch(()=>[]):[],Wn.ok?Wn.json().catch(()=>[]):[]]);Ue=sh({initiatives:ia,workstreams:Ha,workstreamTaskSummaries:[]})}if(Sa(G))return;ct(Ue.initiatives),Y(Ue.workstreams),ar(Ue.workstreamTaskSummaries)}catch(Ke){if(lp(Ke,Z.signal)||va(Ke))return;console.error("[Taskforce] Failed to fetch planning entities:",Ke),typeof window<"u"&&!Sa(G)&&je.length===0&&nt.length===0&&(Qn.current=window.setTimeout(()=>{Qn.current=null,vn(f)},3e3))}finally{ja.current===Z&&(ja.current=null)}},[Eu,rh,je.length,_t,$r,va,Sa,wn,Un,nt.length]),Ia=r.useCallback(async(f=!1,O)=>{await Di(f,O)},[Di]),br=r.useCallback(async(f=!1,O)=>{await Rs(f,O)},[Rs]),Xs=r.useCallback(async f=>{const O=f?.isSilent!==!1,G=f?.ignoreAuthGuard===!0;await Promise.all([ts({isSilent:O,ignoreAuthGuard:G}),ir(O,{ignoreAuthGuard:G}),vn({ignoreAuthGuard:G})])},[ir,vn,ts]),Ur=r.useCallback(async()=>{await ns(),await ir(!0),await vn()},[ir,vn,ns]),So=r.useRef(()=>{}),Sd=r.useRef(()=>{}),Li=r.useRef(async()=>!1),Fa=r.useCallback(f=>Li.current(f),[]),{userGlobalSyncStatus:Jc,setUserGlobalSyncStatus:Oa,userGlobalSyncError:Qs,setUserGlobalSyncError:js,workspaceLastPullAt:Ko,workspaceLastPushAt:fm,workspaceLastErrorAt:vd,workspaceLastErrorMessage:vo,workspaceLastSuccessfulSyncAt:hm,workspaceCloudSyncEnabled:Zo,workspaceSyncPhase:bd,workspaceSyncSetupIntent:Ps,workspaceSyncStatus:wd,workspaceSyncSummary:Xc,workspaceSyncRecommendedAction:xd,workspaceSyncBusy:Qc,workspaceSyncPendingChanges:bo,workspacePendingSignatureRef:Yo,workspaceDeletedTaskIdsRef:Bi,workspaceDeletedTaskWatermarksRef:el,loadWorkspaceSyncState:Wi,applyWorkspaceSyncStateSnapshot:eo,syncUserGlobalSettings:na,buildWorkspaceSyncSignature:Jo,pushWorkspaceChangesToCloud:tl,saveWorkspaceCloudSyncSettings:_d,retryUserGlobalSettingsSync:Cd,retryWorkspaceCloudSync:Es,resetWorkspaceSyncCursorAndPull:Fi,getWorkspaceSyncDiagnostics:Oi}=mb({currentWorkspaceId:Ae,cloudAuthConfigured:z,runtimeMode:w,authSessionResolved:zt,isAuthenticated:Pe,authUserId:De,projectName:ot,resolveCloudAuthUrl:C,resolveWebSocketUrl:$,realtimeSyncEnabled:qn,tasks:Gn,archivedTasks:R,deletedTasks:Hs,initiatives:je,workstreams:nt,taxonomies:or,taxonomyState:Zs?Zc:void 0,setupState:ba,globalTheme:ze,locale:wa,globalWeekStartsOn:Pn,themeUseGlobalDefault:wt,setTasks:La,setArchivedTasks:E,setAuthBlocked:ae,setIsAuthenticated:Ge,checkAuthSession:Fa,setGlobalTheme:lt,setCurrentTheme:Xe,setSetupState:un,setLocale:Hn,setGlobalWeekStartsOn:ps,fetchPlanningEntities:vn}),$i=r.useCallback((f=fa)=>f.find(O=>String(O.value||"").trim().length>0)?.value||Mr,[fa]),[Ms,sa]=r.useState(()=>gs(Sn)),[qr,nl]=r.useState(()=>$i(fa)),[Ad,cr]=r.useState(2),[Xo,Ui]=r.useState(3),[Qo,al]=r.useState("task"),[rl,to]=r.useState("default"),[qi,Id]=r.useState("unassigned"),[zi,ei]=r.useState(""),[sl,Hi]=r.useState(""),[xt,ol]=r.useState(""),[Gi,Ss]=r.useState(""),[Vi,Ki]=r.useState(""),[Zi,Td]=r.useState([]),[il,wr]=r.useState([]),[aa,wo]=r.useState(""),[Nd,Rd]=r.useState({}),ti=r.useRef(null),[cl,ll]=r.useState(!1),[lr,jd]=r.useState("");r.useEffect(()=>{if(sr)return;const f=String(qr||"").trim();fa.some(G=>String(G.value||"").trim()===f)||nl($i(fa))},[fa,sr,$i,qr]);const{searchQuery:Yi,setSearchQuery:dl,filterCategories:no,setFilterCategories:ao,filterPriorities:xo,setFilterPriorities:ul,filterTypes:ni,setFilterTypes:Pd,filterStatus:ml,setFilterStatus:ai,filterAssignees:as,setFilterAssignees:dr,filterAssigneesAllSelected:_o,setFilterAssigneesAllSelected:ri,filterTaxonomies:si,setFilterTaxonomies:Ji,hasInitedFilters:pl,setHasInitedFilters:oi,sortBy:Co,setSortBy:fl,sortOrder:Xi,setSortOrder:Qi,toggleSortOrder:gm,groupBy:ii,setGroupBy:Ed,emptyColumnMode:ec,setEmptyColumnMode:Md,collapsedCategories:ci,setCollapsedCategories:tc,clearFilters:nc,filteredTasks:Dd,searchAgnosticTasks:ac,filteredArchive:ym,groupedTasks:hl}=Fb({tasks:Gn,archivedTasks:R,activeCategories:Sn,activeTypes:fa,priorities:ea,taxonomies:or,configLoaded:Aa,referenceDataLoaded:Zs,assigneeOptionsLoaded:Ys,assigneeOptions:yn});So.current=Oa,Sd.current=js;const{checkAuthSession:km}=Gb({runtimeConfigReady:M,shouldProbeCloudAuth:Ie,authSessionResolved:zt,resolveCloudAuthUrl:C,authOnlyCloudMode:Le,authRequiredError:ys,runtimeMode:w,workspaceSelectionScope:Be,markBootstrapPhase:Rr,markBootstrapStalled:Ks,setRuntimeMode:j,setAuthRequiredForApi:ke,setIsAuthenticated:Ge,setAuthUserId:it,setAuthWorkspaceId:Gt,setAuthUserEmail:Ft,setAuthUserDisplayName:Vt,setAuthUserAvatarUrl:Fn,setUserGlobalSyncStatus:f=>So.current(f),setUserGlobalSyncError:f=>Sd.current(f),setHasBetaAccess:_n,setAvailableWorkspaces:dn,setHydratedWorkspaceRole:et,setAssigneeOptions:on,setAuthBlocked:ae,setAuthSessionResolved:Ln,setError:vr,applyResolvedWorkspaceId:Br,readPersistedWorkspaceId:Ap,authSessionRequestRef:Xn,authSessionEpochRef:In,authSessionLastCheckedAtRef:Yt,authSessionLastResultRef:jn,isLoopbackHost:k,setAuthStateReadyRefs:(f,O,G)=>{li.current=O,Sl.current=G,Io.current=f}});Li.current=km;const[ro,gl]=r.useState("tasks"),[Pr,Sm]=r.useState(!1),[Ld,yl]=r.useState(!1),[vm,bm]=r.useState(!1),[rc,sc]=r.useState([]),[kl,Ao]=r.useState(!1),wm=r.useRef(null),za=r.useRef(null),rs=r.useRef(null),Bd=r.useRef(!1),li=r.useRef(zt),Sl=r.useRef(W),Io=r.useRef(Pe),Ds=r.useRef(!1),di=r.useRef(""),ui=r.useRef(""),oc=r.useRef(""),vl=r.useRef(""),To=r.useRef(""),mi=r.useRef(""),bl=r.useRef(!1),ic=r.useRef(null),Wd=r.useRef(!1),oa=r.useRef(!1),[cc,pi]=r.useState(!1),{handleSaveSettings:wl,handleSaveTheme:Fd,handleSaveGlobalTheme:xl,handleJsonBackupEnabledChange:Od,handleSaveGlobalJsonBackupEnabled:lc,handleSaveGlobalWeekStartsOn:xm,handleSaveLocale:vs,handleManualComplexityEnabledChange:dc,handleChecklistDropdownEnabledChange:uc,handleShowTaskCardStatusLabelChange:_m,handleResetProjectToGlobal:_l}=yb({keyShortcut:hn,themeUseGlobalDefault:wt,runtimeMode:w,jsonBackupUseGlobalDefault:qa,globalTheme:ze,globalJsonBackupEnabled:Vr,setCurrentTheme:Xe,setThemeUseGlobalDefault:$e,setGlobalTheme:lt,setJsonBackupEnabled:Xa,setJsonBackupUseGlobalDefault:Wr,setGlobalJsonBackupEnabled:ma,setGlobalWeekStartsOn:ps,setLocale:Hn,setManualComplexityEnabled:Tr,setChecklistDropdownEnabled:Fr,setShowTaskCardStatusLabel:gr,setShowChecklist:ll});r.useEffect(()=>{w==="cloud"&&Be!==ji&&BS(Ae,Be)},[w,Ae,Be]),r.useEffect(()=>{li.current=zt,Sl.current=W,Io.current=Pe},[zt,W,Pe]);const so=r.useCallback(f=>{if(!f)return;const O=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";typeof f.activeWorkspaceModule=="string"?gl(f.activeWorkspaceModule):f.groupBy==="docs"&&gl("docs"),f.groupBy&&f.groupBy!=="docs"&&Ed(f.groupBy),(f.emptyColumnMode==="show"||f.emptyColumnMode==="collapse"||f.emptyColumnMode==="hide")&&Md(f.emptyColumnMode),typeof f.zenMode=="boolean"&&Yr(f.zenMode),typeof f.searchQuery=="string"&&dl(f.searchQuery),Array.isArray(f.filterCategories)&&ao(f.filterCategories),Array.isArray(f.filterPriorities)&&ul(f.filterPriorities),Array.isArray(f.filterTypes)&&Pd(f.filterTypes),Array.isArray(f.filterStatus)&&ai(f.filterStatus),Array.isArray(f.filterAssignees)&&dr(f.filterAssignees),typeof f.filterAssigneesAllSelected=="boolean"&&ri(f.filterAssigneesAllSelected),f.filterTaxonomies&&typeof f.filterTaxonomies=="object"&&Ji(f.filterTaxonomies),(f.sortBy==="created"||f.sortBy==="priority"||f.sortBy==="updated"||f.sortBy==="complexity")&&fl(f.sortBy),(f.sortOrder==="asc"||f.sortOrder==="desc")&&Qi(f.sortOrder),typeof f.hasInitedFilters=="boolean"?oi(f.hasInitedFilters):O&&oi(!0),typeof f.showChecklist=="boolean"&&ll(f.showChecklist),typeof f.lastCategory=="string"&&jd(f.lastCategory),typeof f.exportEnvironment=="string"&&f.exportEnvironment.trim().length>0&&mn(f.exportEnvironment.trim())},[]),Cl=r.useCallback(async f=>{const O=String(f||ln.current||Ae||"default").trim()||"default",G=`${w}:${Ye}:${O}`;try{const Z=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(O)}`,{method:"GET",credentials:"include"}),Ke=Z.ok?await Z.json().catch(()=>({})):{},Fe=Ke?.state&&typeof Ke.state=="object"?Ke.state:null,Ue=Wf(Ye),tn=Fe||Ue?{...Ue||{},...Fe||{}}:null;if(ln.current!==O)return;so(tn),di.current=G}catch{const Z=Wf(Ye);ln.current===O&&(so(Z),di.current=G)}finally{if(ln.current!==O)return;bl.current=!0,pi(!0)}},[so,Ae,w,Ye]);r.useEffect(()=>{const f=`${w}:${Ye}:${Ae}`;Ds.current&&di.current!==f&&(pi(!1),Cl(Ae))},[Ae,Cl,w,Ye]),r.useEffect(()=>{if(!cc)return;if(bl.current){bl.current=!1;return}const f={groupBy:ii,activeWorkspaceModule:ro,emptyColumnMode:ec,zenMode:Zr,searchQuery:Yi,filterCategories:no,filterPriorities:xo,filterTypes:ni,filterStatus:ml,filterAssignees:as,filterAssigneesAllSelected:_o,filterTaxonomies:si,sortBy:Co,sortOrder:Xi,hasInitedFilters:pl,showChecklist:cl,lastCategory:lr||"",exportEnvironment:Mt};WS(f,Ye);const O=window.setTimeout(async()=>{try{await Xp({stateKey:"app",workspaceId:ln.current,patch:f})}catch{}},250);return()=>window.clearTimeout(O)},[cc,ii,ro,ec,Zr,Yi,no,xo,ni,ml,as,_o,si,Co,Xi,pl,cl,lr,Mt,Ye]);const Al=r.useCallback(f=>{const O=f.runtimeMode==="cloud"?"cloud":"local",G=!!f.authRequiredForApi,Z=typeof f.userId=="string"&&f.userId.trim().length>0?f.userId.trim():"anonymous",Ke=O==="cloud"&&Z!=="anonymous",Fe=Ke||Io.current,Ue=li.current;if(j(O),ke(G),Ke&&(Ge(!0),it(Z),ae(!1),Ue||Ln(!0)),typeof f.workspaceId=="string"&&f.workspaceId.trim().length>0){const Cc=f.workspaceId.trim();O==="local"?Tn(Cc):Br(Cc)}ae(O==="cloud"&&G?!Fe:!1),f.setupState&&typeof f.setupState=="object"?un(f.setupState):un(null),f.runtimeCapabilities&&typeof f.runtimeCapabilities=="object"?Qt(f.runtimeCapabilities):Qt(null),Cn(!!f.realtimeSyncEnabled);const tn=String(f.realtimeSyncFlagSource||"").trim().toLowerCase();Ja(tn==="env"||tn==="settings"||tn==="default"?tn:"unknown"),typeof f.shortcut=="string"&&f.shortcut.trim().length>0&&ua(f.shortcut);const bn=Rc(f.theme);bn&&Xe(bn);const Wn=Rc(f.globalTheme);Wn&&lt(Wn),typeof f.themeUseGlobalDefault=="boolean"&&$e(f.themeUseGlobalDefault);const ia=f.runtimeMode==="cloud"?"cloud":"local";typeof f.projectRoot=="string"?Qe(f.projectRoot):ia==="cloud"&&Qe(""),typeof f.tenantId=="string"?Ze(f.tenantId.trim()):ia==="cloud"&&Ze("");const Ha=ia==="cloud"?String(f.projectName||"").trim():f.projectName||f.paths?.projectName||"";(String(Ha||"").trim().length>0||ia==="cloud")&&de(Ha),typeof f.mcpScript=="string"?vt(f.mcpScript):ia==="cloud"&&vt(""),typeof f.hostRoot=="string"?Ma(f.hostRoot):ia==="cloud"&&Ma(""),typeof f.jsonBackupEnabled=="boolean"&&Xa(f.jsonBackupEnabled),typeof f.globalJsonBackupEnabled=="boolean"&&ma(f.globalJsonBackupEnabled),typeof f.jsonBackupUseGlobalDefault=="boolean"&&Wr(f.jsonBackupUseGlobalDefault);const ur=f?.schedulePreferences?.weekStartsOn;(ur==="sunday"||ur==="monday")&&ps(ur),typeof f.manualComplexityEnabled=="boolean"&&Tr(f.manualComplexityEnabled),typeof f.checklistDropdownEnabled=="boolean"?Fr(f.checklistDropdownEnabled):Fr(!0),typeof f.showTaskCardStatusLabel=="boolean"?gr(f.showTaskCardStatusLabel):gr(!0)},[Br,Tn]),$d=r.useCallback(async()=>{const f=typeof performance<"u"?performance.now():Date.now();try{const O=await go("/api/taskforce/version",void 0,Eu);if(!O.ok)return;const G=await O.json().catch(()=>({}));G?.build&&typeof G.build=="object"&&cn({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}),Ht("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-f)})}catch(O){yo(O)&&Ks("Startup checks timed out.")}},[go,yo,Ks]),{fetchReferenceData:mc,fetchConfig:Ta,fetchWorkspaces:Na,fetchAssigneeOptions:Ls,switchWorkspace:ss,resolveWorkspaceAfterAuth:Il,retryBootstrapChecks:Cm,runCloudBootstrap:No}=Xb({shouldDeferProtectedApiCalls:wn,shouldBlockProtectedApiCalls:Un,getWorkspaceRequestState:_t,isWorkspaceRequestStale:Sa,isWorkspaceEpochStale:da,isAbortError:va,isBootstrapTimeoutError:yo,fetchWithTimeout:go,handleUnauthorized:$r,applyBootstrapConfig:Al,loadPersistedUiState:Cl,fetchBuildInfo:$d,markBootstrapPhase:Rr,markBootstrapStalled:Ks,fetchWorkflows:Bt,fetchInitiativeTemplates:Dn,loadAvailableEnvironments:yr,setReferenceDataLoaded:es,setCustomCategories:zo,setCustomTypes:Vo,setPriorities:pr,setTaxonomies:jr,setTaxonomyDisplayLabels:An,setConfigLoaded:Vs,hasLoadedUiStateRef:Ds,currentWorkspaceIdRef:ln,referenceDataRequestRef:ic,referenceDataAbortRef:ya,bootstrapConfigAbortRef:Lr,workspaceListAbortRef:Bn,assigneeOptionsAbortRef:Ar,workspaceListHydratedRef:Wd,setAvailableWorkspaces:dn,runtimeMode:w,applyResolvedWorkspaceId:Br,workspaceSwitchingEnabled:bt,authSessionResolved:zt,isAuthenticated:Pe,authUserId:De,authUserAvatarUrl:Kn,setHydratedWorkspaceRole:et,setAssigneeOptions:on,setAssigneeOptionsLoaded:ks,commitCurrentWorkspaceId:(f,O)=>{ga.current=f,Tn(f,O),O?.clearExplicitSelection!==!1&&(ga.current=null)},currentWorkspaceId:Ae,workspaceSelectionScope:Be,abortWorkspaceScopedRequests:$n,setWorkspaceBootstrapPending:kt,checkAuthSession:Fa,lastConfigRefreshKeyRef:oc,lastAssigneeOptionsLoadKeyRef:ui,lastWorkspaceSyncStateLoadKeyRef:vl,lastTaskSurfaceLoadKeyRef:To,lastSettingsSurfaceLoadKeyRef:mi,isOpen:L,activeTab:K,showArchive:fe,taskScope:le,settingsSection:d,workspaceBootstrapPending:rn,fetchTasks:Ia,fetchArchive:br,fetchPlanningEntities:vn,refreshTaskCollections:Xs,loadWorkspaceSyncState:Wi,archiveBootstrapTimerRef:rs,hasBootstrappedDataRef:oa}),Ro=r.useCallback(async()=>{await Fa(),await Ta()},[Fa,Ta]);r.useEffect(()=>{if(!Aa||rn)return;const f=`${w}:${Pe?"auth":"guest"}:${Ae}:${Kn||"no-avatar"}`;Ys&&ui.current===f||(ui.current=f,Ls())},[Ys,Kn,Aa,Ae,Ls,Pe,w,rn]),r.useEffect(()=>{if(!zt||!Pe)return;const f=String(De||"").trim();if(!f||f==="anonymous")return;const O=String(Kn||"").trim()||null;on(G=>{let Z=!1;const Ke=G.map(Fe=>Fe.kind!=="member"||String(Fe.value||"").trim()!==f||(typeof Fe.avatarUrl=="string"&&Fe.avatarUrl.trim().length>0?Fe.avatarUrl.trim():null)===O?Fe:(Z=!0,{...Fe,avatarUrl:O}));return Z?Ke:G})},[zt,Kn,De,Pe]);const zr=r.useMemo(()=>bt?Ot.find(O=>O.id===Ae)?.role??null:pe,[Ot,Ae,pe,bt]);r.useEffect(()=>{Pe||et(null)},[Pe]);const Ud=r.useCallback(async()=>{Jt(null);const f=await No({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"}},[No]),ha=r.useCallback(async f=>{const O=f?.reason||"retry",G=typeof f?.preferredWorkspaceId=="string"?f.preferredWorkspaceId.trim():"",Z=f?.allowCommercialGate===!0;if(G&&bt){if(!await Fa({force:!0}))return await Ta({ignoreAuthGuard:!0}),{success:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};const Ue=await Il({preferredWorkspaceId:G});if(!Ue.success)return await Ta({ignoreAuthGuard:!0}),{success:!1,error:Ue.error||"Unable to resolve workspace access.",code:Ue.code};if(Ue.workspaceSetupRequired)return await Ta({ignoreAuthGuard:!0}),{success:!0,workspaceSetupRequired:!0}}const Ke=await No({reason:O,ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return Ke.authenticated?Ke.success?Ke.workspaceSetupRequired?Z?{success:!0,workspaceSetupRequired:!1}:{success:!0,workspaceSetupRequired:!0}:(Z||na({preferCloudOnFirstSync:!0}),{success:!0,workspaceSetupRequired:!1}):{success:!1,error:Ke.error||"Unable to resolve workspace access.",code:Ke.code}:{success:!1,error:Ke.error||"Sign in required.",code:Ke.code||"AUTH_REQUIRED"}},[Fa,Ta,Il,No,na,bt]),qd=r.useCallback(async(f,O)=>{if(!bt)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 O=="string"?O:void 0})}),Ke=await Z.json().catch(()=>({}));if(!Z.ok||Ke?.success===!1)return{success:!1,error:Ke?.error||`Failed to create workspace (${Z.status})`,code:Ke?.code};const Fe=Ke?.workspace;if(await Na(),Fe?.id){const Ue=await ss(Fe.id);if(!Ue.success)return{success:!1,error:Ue.error||"Workspace created but failed to activate.",code:Ue.code}}return{success:!0,workspace:Fe}}catch{return{success:!1,error:"Failed to create workspace."}}},[Na,ss,bt]),Tl=r.useCallback(async f=>{if(!bt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const O=String(f||"").trim();if(!O)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const G=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(O)}`,{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 Fa({force:!0}),await Promise.all([Ta(),Na()]);const Ke=typeof Z?.nextWorkspaceId=="string"?Z.nextWorkspaceId.trim():"";return Ke&&Tn(Ke),{success:!0,nextWorkspaceId:Ke||void 0,workspaceSetupRequired:Z?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(Z?.cleanupWarnings)?Z.cleanupWarnings.map(Fe=>String(Fe||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[Fa,Tn,Ta,Na,bt]),fi=r.useCallback(async f=>{const O=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:O}})}),Z=await G.json().catch(()=>({}));return!G.ok||Z?.success===!1?!1:(await Ro(),!0)}catch{return!1}},[Ro]),pc=r.useCallback(async f=>{const O=String(f?.name||"").trim(),G=typeof f?.workspaceId=="string"?f.workspaceId.trim():"";if(!O)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":w},credentials:"include",body:JSON.stringify({workspaceId:G&&G!=="default"?G:void 0,name:O,description:typeof f.description=="string"?f.description:void 0,allowCreate:!0})}),Ke=await Z.json().catch(()=>({}));if(!Z.ok||Ke?.success===!1)return{success:!1,error:Ke?.error||`Failed to save workspace (${Z.status})`,code:Ke?.code};const Fe=String(Ke?.workspace?.id||"").trim();if(Fe&&(Tn(Fe),await new Promise(Ue=>window.setTimeout(Ue,0)),w==="cloud"&&Pe&&Fe!==Ae)){const Ue=await ss(Fe);if(!Ue.success)return{success:!1,error:Ue.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await Ro(),{success:!0,workspaceId:Fe||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[Tn,Ro,w,Pe,Ae,ss]),hi=r.useCallback(async(f,O)=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const G=f.trim().toLowerCase(),Z=O;if(!G||!Z)return{success:!1,error:"Email and password are required."};try{const Ke=await fetch(C("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:G,password:Z})}),Fe=await Ke.json().catch(()=>({}));if(!Ke.ok||!Fe?.success)return{success:!1,error:Fe?.error||"Sign in failed.",code:Fe?.code};vr("");const Ue=await ha();return Ue.success?{success:!0,workspaceSetupRequired:Ue.workspaceSetupRequired===!0}:{success:!1,error:Ue.error||"Unable to resolve workspace after sign in.",code:Ue.code}}catch{return{success:!1,error:"Sign in failed."}}},[C,z,ha]),Am=r.useCallback((f,O,G)=>{const Z=O&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(O)?O:"/";let Ke=`/api/taskforce/auth/oauth/${encodeURIComponent(f)}/start?return_to=${encodeURIComponent(Z)}`;G&&(Ke+=`&invite_token=${encodeURIComponent(G)}`),window.location.href=C(Ke)},[C]),jo=r.useCallback(async(f,O,G)=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const Z=f.trim().toLowerCase(),Ke=O;if(!Z||!Ke)return{success:!1,error:"Email and password are required."};try{const Fe=await fetch(C("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:Z,password:Ke,...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()}:{}})}),Ue=await Fe.json().catch(()=>({}));if(!Fe.ok||!Ue?.success)return{success:!1,error:Ue?.error||"Create account failed.",code:Ue?.code,verificationRequired:!!Ue?.verificationRequired,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0};const tn=Ue?.planSelectionRequired===!0,bn=Ue?.checkoutPending===!0,Wn=typeof Ue?.commercialState=="string"?Ue.commercialState:null,ia=!!Ue?.verificationRequired;if(!ia){if(vr(""),!!(tn||bn||Wn==="pending_plan_selection"||Wn==="checkout_pending"))return await Fa({force:!0})?{success:!0,workspaceSetupRequired:!1,planSelectionRequired:tn,checkoutPending:bn,commercialState:Wn,verificationRequired:ia,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0}:{success:!1,error:"Unable to resolve workspace after registration.",code:"AUTH_REQUIRED"};const ur=await ha({allowCommercialGate:!1});return ur.success?{success:!0,workspaceSetupRequired:ur.workspaceSetupRequired===!0,planSelectionRequired:tn,checkoutPending:bn,commercialState:Wn,verificationRequired:ia,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0}:{success:!1,error:ur.error||"Unable to resolve workspace after registration.",code:ur.code}}return{success:!0,workspaceSetupRequired:!!Ue?.workspaceSetupRequired,planSelectionRequired:tn,checkoutPending:bn,commercialState:Wn,verificationRequired:ia,verificationToken:typeof Ue?.verificationToken=="string"?Ue.verificationToken:void 0,emailSent:Ue?.emailSent!==!1,emailError:typeof Ue?.emailError=="string"?Ue.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[Fa,C,z,ha]),Nl=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=String(f.displayName||"").trim(),G=typeof f.avatarDraftId=="string"?f.avatarDraftId.trim():"",Z=f.clearAvatar===!0;if(!O)return{success:!1,error:"Display name is required."};try{const Ke=await fetch(C("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:O,...G?{avatarDraftId:G}:{},...Z?{clearAvatar:!0}:{}})}),Fe=await Ke.json().catch(()=>({}));if(!Ke.ok||!Fe?.success)return{success:!1,error:Fe?.error||"Failed to update profile.",code:Fe?.code};const Ue={userId:typeof Fe?.profile?.userId=="string"?Fe.profile.userId:De,email:typeof Fe?.profile?.email=="string"?Fe.profile.email:nn,displayName:typeof Fe?.profile?.displayName=="string"?Fe.profile.displayName:null,avatarUrl:typeof Fe?.profile?.avatarUrl=="string"?Fe.profile.avatarUrl:null};return Vt(Ue.displayName||""),Fn(Ue.avatarUrl||""),{success:!0,profile:Ue}}catch{return{success:!1,error:"Failed to update profile."}}},[C,z,nn,De]),zd=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=f.trim().toLowerCase();if(!O)return{success:!1,error:"Email is required."};try{const G=await fetch(C("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:O})}),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."}}},[C,z]),Im=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=f.trim();if(!O)return{success:!1,error:"Token is required."};try{const G=await fetch(C("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:O})}),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."}}},[C,z]),Hd=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=f.trim().toLowerCase();if(!O)return{success:!1,error:"Email is required."};try{const G=await fetch(C("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:O})}),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."}}},[C,z]),Gd=r.useCallback(async(f,O)=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const G=f.trim(),Z=O;if(!G||!Z)return{success:!1,error:"Token and password are required."};try{const Ke=await fetch(C("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:G,password:Z})}),Fe=await Ke.json().catch(()=>({}));return!Ke.ok||!Fe?.success?{success:!1,error:Fe?.error||"Failed to reset password.",code:Fe?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[C,z]),Tm=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=f.trim();if(!O)return{success:!1,error:"Token is required."};try{const G=await fetch(C("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:O})}),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."}}},[C,z]),Rl=r.useCallback(async(f,O)=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const G=f.trim(),Z=O;if(!G||!Z)return{success:!1,error:"Token and password are required."};try{const Ke=await fetch(C("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:G,password:Z})}),Fe=await Ke.json().catch(()=>({}));if(!Ke.ok||!Fe?.success)return{success:!1,error:Fe?.error||"Invite acceptance failed.",code:Fe?.code};vr("");const Ue=typeof Fe?.workspaceId=="string"?Fe.workspaceId:null;if(Ue&&bt){const bn=await ss(Ue,{hydrate:!1});if(!bn.success)return{success:!1,error:bn.error||"Unable to resolve workspace after invite acceptance.",code:bn.code}}const tn=await ha();return tn.success?(Ue&&ln.current!==Ue&&Tn(Ue,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:tn.workspaceSetupRequired===!0}):{success:!1,error:tn.error||"Unable to resolve workspace after invite acceptance.",code:tn.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[Tn,C,z,ln,ha,ss,bt]),Vd=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth endpoint is not configured."};const O=f.trim();if(!O)return{success:!1,error:"Token is required."};try{const G=await fetch(C("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:O})}),Z=await G.json().catch(()=>({}));if(!G.ok||!Z?.success)return{success:!1,error:Z?.error||"Invite join failed.",code:Z?.code};vr("");const Ke=typeof Z?.workspaceId=="string"?Z.workspaceId:null;if(Ke&&bt){const Ue=await ss(Ke,{hydrate:!1});if(!Ue.success)return{success:!1,error:Ue.error||"Unable to resolve workspace after invite join.",code:Ue.code}}const Fe=await ha();return Fe.success?(Ke&&ln.current!==Ke&&Tn(Ke,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:Fe.workspaceSetupRequired===!0}):{success:!1,error:Fe.error||"Unable to resolve workspace after invite join.",code:Fe.code}}catch{return{success:!1,error:"Invite join failed."}}},[Tn,C,z,ln,ha,ss,bt]),Nm=r.useCallback(async()=>{if(!z)return{success:!1,error:"Cloud auth not configured."};try{const f=await fetch(C("/api/taskforce/account/login-methods"),{credentials:"include"}),O=await f.json().catch(()=>({}));return!f.ok||!O?.success?{success:!1,error:O?.error||"Failed to fetch login methods."}:{success:!0,methods:Array.isArray(O?.methods)?O.methods:[]}}catch{return{success:!1,error:"Failed to fetch login methods."}}},[C,z]),Rm=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth not configured."};try{const O=await fetch(C(`/api/taskforce/account/login-methods/${encodeURIComponent(f)}`),{method:"DELETE",credentials:"include"}),G=await O.json().catch(()=>({}));return!O.ok||!G?.success?{success:!1,error:G?.error||"Unlink failed.",code:G?.code}:{success:!0}}catch{return{success:!1,error:"Unlink failed."}}},[C,z]),jm=r.useCallback(async f=>{if(!z)return{success:!1,error:"Cloud auth not configured."};try{const O=await fetch(C("/api/taskforce/account/login-methods/password"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({password:f})}),G=await O.json().catch(()=>({}));return!O.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."}}},[C,z]),fc=r.useCallback((f,O)=>{const G=O&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(O)?O:"/",Z=`/api/taskforce/auth/oauth/${encodeURIComponent(f)}/start?flow=link&return_to=${encodeURIComponent(G)}`;window.location.href=C(Z)},[C]),oo=r.useCallback(()=>{$n(),ic.current=null,di.current="",ui.current="",oc.current="",vl.current="",To.current="",mi.current="",pi(!1),es(!1),on($o()),ks(!1),Ba([]),La([]),E([]),ct([]),Y([]),ar([]),rr(!1),za.current!==null&&typeof window<"u"&&(window.clearTimeout(za.current),za.current=null),rs.current!==null&&typeof window<"u"&&(window.clearTimeout(rs.current),rs.current=null)},[$n,E,La]),hc=r.useCallback(async()=>{try{z&&await fetch(C("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if($n(),In.current+=1,Xn.current=null,jn.current=!1,Yt.current=Date.now(),Ge(!1),Ln(!0),it("anonymous"),Gt(""),Jl(null),Ft(""),Vt(""),Fn(""),Oa("disconnected"),js(null),_n(!0),de(""),Vs(!1),es(!1),un(null),On("idle"),Jt(null),Ds.current=!1,w!=="local"&&Bf(Be),ae(w==="cloud"&&W),Tn("default"),dn([]),Wd.current=!1,et(null),w==="local"){await Promise.allSettled([Ta({ignoreAuthGuard:!0}),Ia(!0,{ignoreAuthGuard:!0}),vn({ignoreAuthGuard:!0}),mc({ignoreAuthGuard:!0,force:!0})]);return}oa.current=!1,oo()}},[$n,W,Bf,Tn,C,z,Be,w,Ta,vn,mc,Ia,oo]),xr=r.useCallback(async f=>{try{const O=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}),G=await O.json().catch(()=>({}));return!O.ok||!G?.success?{success:!1,error:G?.error||`Create failed (${O.status})`}:(await Ia(!0),{success:!0,result:G?.results})}catch(O){return{success:!1,error:O.message}}},[Ia]),gi=r.useCallback(async f=>{const O=await fetch("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f||{})}),G=await O.json().catch(()=>({}));if(!O.ok)throw new Error(G?.error||`Failed to create initiative (${O.status})`);return await vn(),ct(Z=>Fo(Z,G)),G},[vn]),gc=r.useCallback(async(f,O)=>{const G=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(O||{})}),Z=await G.json().catch(()=>({}));if(!G.ok)throw new Error(Z?.error||`Failed to update initiative (${G.status})`);return await vn(),ct(Ke=>Fo(Ke,Z)),Z},[vn]),Kd=r.useCallback(async f=>{const O=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}/archive`,{method:"POST"}),G=await O.json().catch(()=>({}));if(!O.ok)throw new Error(G?.error||`Failed to archive initiative (${O.status})`);return await vn(),ct(Z=>Fo(Z,G)),G},[vn]),Pm=r.useCallback(async f=>{const O=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}/unarchive`,{method:"POST"}),G=await O.json().catch(()=>({}));if(!O.ok)throw new Error(G?.error||`Failed to unarchive initiative (${O.status})`);return await vn(),ct(Z=>Fo(Z,G)),G},[vn]),Zd=r.useCallback(async f=>{const O=await fetch("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f||{})}),G=await O.json().catch(()=>({}));if(!O.ok)throw new Error(G?.error||`Failed to create workstream (${O.status})`);return await vn(),Y(Z=>Fo(Z,G)),G},[vn]),pf=r.useCallback(async(f,O)=>{const G=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(O||{})}),Z=await G.json().catch(()=>({}));if(!G.ok)throw new Error(Z?.error||`Failed to update workstream (${G.status})`);return await vn(),Y(Ke=>Fo(Ke,Z)),Z},[vn]),yc=r.useCallback(async f=>{const O=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}/archive`,{method:"POST"}),G=await O.json().catch(()=>({}));if(!O.ok)throw new Error(G?.error||`Failed to archive workstream (${O.status})`);return await vn(),Y(Z=>Fo(Z,G)),G},[vn]),Yd=r.useCallback(async f=>{const O=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}/unarchive`,{method:"POST"}),G=await O.json().catch(()=>({}));if(!O.ok)throw new Error(G?.error||`Failed to unarchive workstream (${O.status})`);return await vn(),Y(Z=>Fo(Z,G)),G},[vn]),Jd=r.useRef(!1);r.useEffect(()=>{re(!0),!Jd.current&&(Jd.current=!0,Fa())},[Fa]),r.useEffect(()=>{M&&Fa()},[M,Fa]),r.useEffect(()=>{if(!z)return;let f=!1;const O=new AbortController,G=typeof window<"u"?window.setTimeout(()=>O.abort(),5e3):null;return fetch(C("/api/taskforce/auth/providers"),{credentials:"include",signal:O.signal}).then(Z=>Z.ok?Z.json():null).then(Z=>{!f&&Array.isArray(Z?.providers)&&Kt(Z.providers)}).catch(()=>{}).finally(()=>{G!==null&&typeof window<"u"&&window.clearTimeout(G)}),()=>{f=!0,O.abort()}},[z,C]),r.useEffect(()=>{if(w!=="local"||!Ie||typeof window>"u")return;const f=()=>{Fa()},O=()=>{document.visibilityState==="visible"&&f()};window.addEventListener("focus",f),window.addEventListener("online",f),document.addEventListener("visibilitychange",O);const G=window.setInterval(f,3e4);return()=>{window.removeEventListener("focus",f),window.removeEventListener("online",f),document.removeEventListener("visibilitychange",O),window.clearInterval(G)}},[w,Ie,Fa]),r.useEffect(()=>{a&&a(Gn.length)},[Gn.length,a]),r.useEffect(()=>{if(n&&Gn.length>0){const f=Gn.find(O=>O.id.endsWith(n)||O.id===n);f&&(lu(f),Do("add"))}},[n,Gn]);const kc=r.useRef(!1);r.useEffect(()=>{if(!Aa)return;if(!kc.current&&Sn.length>0){kc.current=!0;const O=lr,G=Sn.some(Z=>Z.label===O||Z.value===O);if(O&&G){const Z=Sn.find(Ke=>Ke.label===O||Ke.value===O);sa(Z?.value||O)}else sa(gs(Sn));return}const f=Sn.some(O=>O.value===Ms);Sn.length>0&&!f&&sa(gs(Sn))},[Aa,Sn,Ms,gs,lr]),r.useEffect(()=>{if(!Aa||Sn.length===0)return;const f=Z=>!Sn.some(Ke=>Ke.value===Z.category),O=Gn.some(f),G=R.some(f);if(O||G){const Z=gs(Sn);O&&La(Ke=>Ke.map(Fe=>f(Fe)?{...Fe,category:Z}:Fe)),G&&E(Ke=>Ke.map(Fe=>f(Fe)?{...Fe,category:Z}:Fe))}},[Aa,Sn,Gn,R,gs]),r.useEffect(()=>()=>{rs.current!==null&&typeof window<"u"&&(window.clearTimeout(rs.current),rs.current=null),za.current!==null&&typeof window<"u"&&(window.clearTimeout(za.current),za.current=null)},[]),r.useEffect(()=>{},[Xs]);const jl=r.useCallback(async()=>{await Ur()},[Ur]),Pl=String(Ae||"").trim(),os=String(De||"").trim(),Xd=$("/taskforce-ws"),Qd=!!(z&&w==="cloud"&&zt&&Pe&&os&&os!=="anonymous"&&Pl&&!Zp(Pl)&&Xd),Em=r.useCallback(()=>{w==="cloud"&&(Ur(),!(typeof window>"u")&&(za.current!==null&&window.clearTimeout(za.current),za.current=window.setTimeout(()=>{za.current=null,Ur()},250)))},[w,Ur]);Tg({enabled:Qd,workspaceId:Pl,websocketUrl:Xd,onSignal:Em,userId:os||void 0}),Qb({isOpen:L,authBlocked:Ne,authRequiredForApi:W,isAuthenticated:Pe,canCallProtectedApi:Pa.canCallProtectedApi,shouldGateProtectedApiCalls:Oe,authSessionResolvedRef:li,authRequiredForApiRef:Sl,isAuthenticatedRef:Io,dataVersionRef:wm,refreshTaskCollectionsForDataVersion:jl});const yi=r.useMemo(()=>{const f=new Map;for(const O of R)f.set(O.id,O);for(const O of Gn)f.set(O.id,O);return Array.from(f.values())},[Gn,R]),Bs=r.useMemo(()=>Hs.map(f=>({...f.taskSnapshot,isDeleted:!0,deletedRecordId:f.id})),[Hs]);r.useEffect(()=>{if(!(wn||Un)&&L&&!rn){if(K==="tasks"){const f=`${Ae}:${K}:${fe?"archive":"active"}:${le}`;if(!Bd.current){Bd.current=!0,To.current=f;return}if(To.current===f)return;To.current=f,Ia(),vn(),(fe||le==="archived")&&br(!0),le==="deleted"&&ir();return}if(K==="settings"){const f=`${Ae}:${K}:${d}`;if(mi.current===f)return;mi.current=f,Ta(),(d==="commands"||d==="resources")&&Bt()}}},[Ae,L,K,d,fe,le,Ia,vn,br,ir,Ta,Bt,wn,Un,rn]);const eu=r.useCallback(async(f="")=>{try{const O=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(f)}`);if(O.ok){const G=await O.json();tt(G.folders||[]),Pt(G.files||[]),Rt(f)}}catch(O){console.error("[Taskforce] Failed to fetch folders:",O)}},[]),tu=r.useCallback(f=>{const O=[];if(f.path&&O.push(f.path),f.paths&&f.paths.length>0)for(const G of f.paths)O.includes(G)||O.push(G);return O},[]),{validatePaths:Mm,handleUpdateCategory:nu,handleSaveCategory:au,handleAddPath:Er,handleUpdateCategoryIcon:El,handleUpdateCategoryColor:Po,handleRemovePath:is,handleSelectPath:Dm,handleRemoveCategory:Sc,handleSaveType:ru,handleRemoveType:Ml,handleUpdateType:su,handleUpdateTaxonomies:Eo,handleUpdatePriorities:Ws,analyzeSystemTaxonomyPack:vc,handleApplySystemTaxonomyPack:ou}=kb({activeCategories:Sn,activeTab:K,activeTypes:fa,archivedTasks:R,browserTarget:Tt,category:Ms,configLoaded:Aa,customCategories:Gs,refreshTaskCollections:Xs,fetchTasks:Ia,filterCategories:no,getCategoryPaths:tu,normalizePath:qo,pathValidation:Ho,setBrowserTarget:Dt,setCategory:sa,setCustomCategories:zo,setCustomTypes:Vo,setFilterCategories:ao,setPathValidation:Go,setPriorities:pr,setShowFolderBrowser:dt,setTaxonomies:jr,tasks:Gn}),Mo=r.useCallback(async f=>{const O=Sr,G={...O,...f};An(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 Ke=await Z.json().catch(()=>({}));Ke?.displayLabels&&typeof Ke.displayLabels=="object"&&An({...G,...Ke.displayLabels})}catch(Z){console.error("[Taskforce] Failed to update taxonomy display labels",Z),An(O)}},[Sr]),Do=r.useCallback(f=>{K==="tasks"&&Ca.current&&Ns(Ca.current.scrollTop),te(f)},[K]),iu=r.useRef(async()=>{}),{handleNavigation:cu,handleClose:ki,resetForm:Dl,resolveWorkstreamIdInput:bc,handleEdit:lu,handleOpenTaskById:Ll,returnToPreviousTask:du,clearReturnToParentTask:uu}=Ib({activeCategories:Sn,activeTypes:fa,activeTab:K,attachments:rc,checklistItems:Zi,comments:il,description:Vi,editingTaskId:sr,flushPendingAutoSave:()=>iu.current(),getPreferredCategoryValue:gs,lastUsedCategory:lr,newCommentText:aa,relationshipTasks:yi,workstreams:nt,showArchive:fe,taxonomies:or,setActiveTab:Do,setApproach:to,setAssignee:Id,setAttachments:sc,setAttachmentsDirty:Ao,setCategory:sa,setChecklistItems:Td,setComments:wr,setComplexity:Ui,setDescription:Ki,setDueDate:Hi,setEditingTaskId:Xr,setError:vr,setFormTaxonomies:Rd,setIsOpen:re,setNewCommentText:wo,setPendingNavigation:q,setWorkstreamInput:ol,setPriority:cr,setScheduledDate:ei,setShowArchive:xe,setStatus:al,setTaskReturnTrail:nr,setTitle:Ss,setType:nl,setUnsavedModalOpen:ra,taskReturnTrail:Nn,title:Gi}),{copiedId:Fs,handleDelete:wc,handleUpdateTask:xc,handleToggleComplete:_c,handleToggleCancel:Bl,handleToggleInProgress:Wl,handleToggleReview:Fl,handleArchiveTask:Ol,handleBulkArchive:Lo,handleUnarchive:$l,handleRestoreDeletedTask:mu,handlePermanentlyDeleteDeletedTask:pu,handleEmptyDeletedTasks:fu,handleCopyId:cs,queueWorkspaceSyncFromAuthoritativeTaskState:Hr}=qb({tasks:Gn,archivedTasks:R,editingTaskId:sr,setTasks:La,setArchivedTasks:E,setDeletedTasks:Ba,setError:vr,resetForm:Dl,setActiveTab:Do,fetchTasks:Ia,fetchArchive:br,fetchDeletedTasks:ir,mergeTaskFromServer:Yc,pushNotice:Ct,cloudAuthConfigured:z,runtimeMode:w,isAuthenticated:Pe,workspaceCloudSyncEnabled:Zo,buildWorkspaceSyncSignature:Jo,pushWorkspaceChangesToCloud:tl,workspacePendingSignatureRef:Yo,workspaceDeletedTaskIdsRef:Bi,workspaceDeletedTaskWatermarksRef:el}),{autoSaveState:hu,flushAutoSave:Ul,scheduleWarningPrompt:gu,handleSubmit:ql,confirmScheduleWarning:io,cancelScheduleWarning:yu,handleAddComment:ku}=Ob({activeCategories:Sn,activeTab:K,apiEndpoint:l,approach:rl,assignee:qi,attachments:rc,attachmentsDirty:kl,category:Ms,checklistItems:Zi,comments:il,complexity:Xo,description:Vi,dueDate:sl,editingTaskId:sr,fetchTasks:Ia,formTaxonomies:Nd,getPreferredCategoryValue:gs,mergeTaskFromServer:Yc,workstreamInput:xt,priority:Ad,pushNotice:Ct,queueWorkspaceSyncFromAuthoritativeTaskState:Hr,relationshipTasks:yi,resetForm:Dl,resolveWorkstreamIdInput:bc,scheduledDate:zi,setActiveTab:Do,setAttachmentsDirty:Ao,setComments:wr,setError:vr,setLastUsedCategory:jd,setLoading:ko,setNewCommentText:wo,status:Qo,title:Gi,taxonomies:or,type:qr});r.useEffect(()=>{iu.current=Ul},[Ul]);const{handleSetWorkstreamForCurrentTask:Lm}=$b({editingTaskId:sr,mergeTaskFromServer:Yc,workstreamInput:xt,pushNotice:Ct,queueWorkspaceSyncFromAuthoritativeTaskState:Hr,relationshipTasks:yi,resolveWorkstreamIdInput:bc,setError:vr,fetchTasks:Ia}),{currentTask:Bm,currentTaskWorkstream:Su,currentTaskInitiative:Wm}=xb({editingTaskId:sr,relationshipTasks:yi,initiatives:je,workstreams:nt,supplementalTasks:Bs,setComments:wr}),vu=gb({resolveCloudAuthUrl:C,currentWorkspaceId:Ae,normalizedCloudAuthBaseUrl:ve,normalizedCloudMcpBaseUrl:Te,mergedConfig:o,availableWorkspaces:Ot,currentTheme:Re,configLoaded:Aa,globalTheme:ze,themeUseGlobalDefault:wt,keyShortcut:hn,jsonBackupEnabled:zn,globalJsonBackupEnabled:Vr,globalWeekStartsOn:Pn,locale:wa,supportedLocales:Ir,jsonBackupUseGlobalDefault:qa,manualComplexityEnabled:ta,checklistDropdownEnabled:hr,showTaskCardStatusLabel:pa,exportWorkflowsPath:kr,exportingResource:fs,exportResult:Nr,pathSaved:gt,settingsSection:d,exportEnvironment:Mt,setupState:ba,buildInfo:Mn,saveSetupMode:fi,saveWorkspaceProfile:pc,setCurrentTheme:Xe,handleSaveTheme:Fd,handleSaveGlobalTheme:xl,setKeyShortcut:ua,handleJsonBackupEnabledChange:Od,handleSaveGlobalJsonBackupEnabled:lc,handleSaveGlobalWeekStartsOn:xm,handleSaveLocale:vs,handleManualComplexityEnabledChange:dc,handleChecklistDropdownEnabledChange:uc,handleShowTaskCardStatusLabelChange:_m,handleResetProjectToGlobal:_l,handleSaveSettings:wl,setExportWorkflowsPath:er,setExportEnvironment:mn,availableWorkflows:Or,initiativeTemplates:Ve,availableEnvironments:Da,fetchWorkflows:Bt,fetchInitiativeTemplates:Dn,createInitiativeFromTemplate:xr,fetchWorkflowTemplate:sn,fetchWorkflowOverrideNames:_a,saveWorkflowTemplateDraft:Zn,resetWorkflowTemplateDraft:Is,handleExportWorkflows:Jr,setShowFolderBrowser:dt,setBrowserTarget:Dt,fetchFolders:eu,activeCategories:Sn,pathValidation:Ho,taxonomyDisplayLabels:Sr,handleUpdateCategory:nu,handleRemoveCategory:Sc,handleSaveCategory:au,handleAddPath:Er,handleRemovePath:is,handleUpdateCategoryIcon:El,handleUpdateCategoryColor:Po,activeTypes:fa,handleSaveType:ru,handleRemoveType:Ml,handleUpdateType:su,taxonomies:or,handleUpdateTaxonomies:Eo,priorities:ea,handleUpdatePriorities:Ws,analyzeSystemTaxonomyPack:vc,handleApplySystemTaxonomyPack:ou,handleUpdateTaxonomyDisplayLabels:Mo,projectRoot:We,projectName:ot,mcpHostRoot:Xt,serverHostRoot:xa,mcpScriptPath:St,tenantId:$t,runtimeMode:w,workspaceSwitchingEnabled:bt,deleteWorkspace:Tl,setMcpHostRoot:ms,isAuthenticated:Pe});r.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:Gn,archivedTasks:R,runtimeMode:w,currentWorkspaceId:Ae,isAuthenticated:Pe,workspaceCloudSyncEnabled:Zo,realtimeSyncEnabled:qn,fetchTasks:Ia,fetchArchive:br,retryWorkspaceCloudSync:Es,resetWorkspaceSyncCursorAndPull:Fi,getSyncDiagnostics:Oi,__dispatch:{handleUpdateTask:xc,handleToggleComplete:_c,handleArchiveTask:Ol,handleToggleCancel:Bl,handleToggleInProgress:Wl,handleToggleReview:Fl,handleSubmit:ql,handleDelete:wc}})},[Gn,R,w,Ae,Pe,Zo,qn,Ia,br,Es,Fi,Oi,xc,_c,Ol,Bl,Wl,Fl,ql,wc]);const Fm=Je&&Je.tone!=="error"?{message:Je.message,type:"info"}:null,Os=String(b||x.wsBaseUrl||he||"").trim().replace(/\/+$/,"");return{config:{...o,cloudEnvironment:x.cloudEnvironment||o.cloudEnvironment||"",apiBaseUrl:he||o.apiBaseUrl,cloudAuthBaseUrl:ve||o.cloudAuthBaseUrl,wsBaseUrl:Os||o.wsBaseUrl},isOpen:L,setIsOpen:re,activeTab:K,setActiveTab:Do,currentTheme:Re,setCurrentTheme:Xe,configLoaded:Aa,storagePath:ft,saveSettings:wl,pathSaved:gt,keyShortcut:hn,setKeyShortcut:ua,globalWeekStartsOn:Pn,locale:wa,supportedLocales:Ir,saveLocale:vs,jsonBackupEnabled:zn,setJsonBackupEnabled:Xa,manualComplexityEnabled:ta,checklistDropdownEnabled:hr,showTaskCardStatusLabel:pa,setManualComplexityEnabled:Tr,mcpHostRoot:Xt,setMcpHostRoot:ms,settingsSection:d,setSettingsSection:Me,runtimeMode:w,workspaceMode:Lt,workspaceSwitchingEnabled:bt,cloudAuthConfigured:z,authRequiredForApi:W,authBlocked:Ne,isAuthenticated:Pe,authUserId:De,authUserEmail:nn,authUserDisplayName:Wt,authUserAvatarUrl:Kn,authWorkspaceId:Ut,userGlobalSyncStatus:Jc,workspaceLastPullAt:Ko,workspaceLastPushAt:fm,workspaceLastErrorAt:vd,userGlobalSyncError:Qs,workspaceLastErrorMessage:vo,workspaceLastSuccessfulSyncAt:hm,workspaceSyncPhase:bd,workspaceSyncSetupIntent:Ps,workspaceSyncStatus:wd,workspaceSyncSummary:Xc,workspaceSyncRecommendedAction:xd,workspaceSyncBusy:Qc,workspaceSyncPendingChanges:bo,retryUserGlobalSettingsSync:Cd,retryWorkspaceCloudSync:Es,resetWorkspaceSyncCursorAndPull:Fi,getWorkspaceSyncDiagnostics:Oi,hasBetaAccess:Jn,realtimeSyncEnabled:qn,realtimeSyncFlagSource:Ya,currentWorkspaceId:Ae,currentWorkspaceRole:zr,availableWorkspaces:Ot,assigneeOptions:yn,workspaceCloudSyncEnabled:Zo,saveWorkspaceCloudSyncSettings:_d,applyWorkspaceSyncStateSnapshot:eo,bootstrapState:Kc,authSessionResolved:zt,workspaceBootstrapPending:rn,bootstrapPhase:Et,bootstrapError:kn,bootstrapStartedAt:Dr,setupState:ba,runtimeCapabilities:Ea,refreshSetupContext:Ro,retryBootstrapChecks:Cm,continueAfterCommercialOnboarding:Ud,saveWorkspaceProfile:pc,fetchWorkspaces:Na,createWorkspace:qd,deleteWorkspace:Tl,switchWorkspace:ss,loginWithCredentials:hi,beginOAuthLogin:Am,availableAuthProviders:an,fetchLoginMethods:Nm,unlinkLoginMethod:Rm,addPasswordToAccount:jm,beginOAuthLink:fc,registerWithCredentials:jo,updateCurrentUserProfile:Nl,requestEmailVerification:zd,confirmEmailVerification:Im,requestPasswordReset:Hd,confirmPasswordReset:Gd,inspectInviteAcceptance:Tm,acceptInviteWithToken:Rl,joinInviteWithToken:Vd,logout:hc,showFolderBrowser:at,setShowFolderBrowser:dt,folders:ne,files:rt,currentBrowsePath:yt,fetchFolders:eu,browserTarget:Tt,setBrowserTarget:Dt,groupBy:ii,setGroupBy:Ed,activeWorkspaceModule:ro,setActiveWorkspaceModule:gl,emptyColumnMode:ec,setEmptyColumnMode:Md,zenMode:Zr,setZenMode:Yn,handleSelectPath:Dm,handleAddPath:Er,handleRemovePath:is,tasks:Gn,loadingTasks:Hc,archivedTasks:R,initiatives:je,workstreams:nt,planningBootstrapTaskSummaries:zs,deletedTasks:Hs,activeCategories:Sn,activeTypes:fa,priorities:ea,taxonomyDisplayLabels:Sr,approaches:fr,taxonomies:or,searchQuery:Yi,setSearchQuery:dl,filterCategories:no,setFilterCategories:ao,filterTypes:ni,setFilterTypes:Pd,filterPriorities:xo,setFilterPriorities:ul,filterStatus:ml,setFilterStatus:ai,filterAssignees:as,setFilterAssignees:dr,filterTaxonomies:si,setFilterTaxonomies:Ji,hasInitedFilters:pl,sortBy:Co,setSortBy:fl,sortOrder:Xi,setSortOrder:Qi,toggleSortOrder:gm,showArchive:fe,setShowArchive:xe,taskScope:le,setTaskScope:we,clearFilters:nc,filteredTasks:Dd,searchAgnosticTasks:ac,filteredArchive:ym,groupedTasks:hl,collapsedCategories:ci,setCollapsedCategories:tc,fetchTasks:Ia,fetchArchive:br,fetchDeletedTasks:ir,fetchPlanningEntities:vn,fetchAssigneeOptions:Ls,createInitiative:gi,updateInitiative:gc,archiveInitiative:Kd,unarchiveInitiative:Pm,createWorkstream:Zd,updateWorkstream:pf,archiveWorkstream:yc,unarchiveWorkstream:Yd,handleEdit:lu,handleDelete:wc,handleCopyId:cs,handleToggleComplete:_c,handleToggleCancel:Bl,handleToggleInProgress:Wl,handleToggleReview:Fl,handleArchiveTask:Ol,handleBulkArchive:Lo,handleUnarchive:$l,handleRestoreDeletedTask:mu,handlePermanentlyDeleteDeletedTask:pu,handleEmptyDeletedTasks:fu,handleUpdateTask:xc,editingTaskId:sr,loading:Qr,error:Wa,title:Gi,setTitle:Ss,description:Vi,setDescription:Ki,checklistItems:Zi,setChecklistItems:Td,category:Ms,setCategory:sa,type:qr,setType:nl,priority:Ad,setPriority:cr,complexity:Xo,setComplexity:Ui,status:Qo,setStatus:al,approach:rl,setApproach:to,assignee:qi,setAssignee:Id,scheduledDate:zi,setScheduledDate:ei,dueDate:sl,setDueDate:Hi,workstreamInput:xt,setWorkstreamInput:ol,formTaxonomies:Nd,setFormTaxonomies:Rd,comments:il,newCommentText:aa,setNewCommentText:wo,attachments:rc,setAttachments:sc,attachmentsDirty:kl,setAttachmentsDirty:Ao,descriptionFocused:Ld,setDescriptionFocused:yl,showMarkdownHelp:Gc,setShowMarkdownHelp:Vc,showChecklist:cl,setShowChecklist:ll,showComments:Pr,setShowComments:Sm,isCapturingScreenshot:vm,setIsCapturingScreenshot:bm,handleSubmit:ql,resetForm:Dl,handleAddComment:ku,handleSetWorkstreamForCurrentTask:Lm,handleOpenTaskById:Ll,returnToPreviousTask:du,autoSaveState:hu,unsavedModalOpen:tr,setUnsavedModalOpen:ra,pendingNavigation:Ts,handleNavigation:cu,handleClose:ki,uiNotice:Je,pushNotice:Ct,clearNotice:jt,successBanner:Fm,taskReturnTrail:Nn,clearReturnToParentTask:uu,copiedId:Fs,recentlyChangedTaskIds:Js,scheduleWarningPrompt:gu,confirmScheduleWarning:io,cancelScheduleWarning:yu,tasksScrollRef:Ca,setTasksScrollPos:Ns,exportEnvironment:Mt,setExportEnvironment:mn,exportWorkflowsPath:kr,setExportWorkflowsPath:er,exportResult:Nr,exportingResource:fs,handleUpdateCategory:nu,handleRemoveCategory:Sc,handleSaveCategory:au,handleUpdateCategoryIcon:El,handleUpdateCategoryColor:Po,handleSaveType:ru,handleRemoveType:Ml,handleUpdateType:su,handleUpdateTaxonomies:Eo,handleUpdatePriorities:Ws,handleUpdateTaxonomyDisplayLabels:Mo,pathValidation:Ho,validatePaths:Mm,getCategoryPaths:tu,customCategories:Gs,setCustomCategories:zo,projectRoot:We,projectName:ot,mcpScriptPath:St,serverHostRoot:xa,commentsEndRef:ti,currentTask:Bm,currentTaskWorkstream:Su,currentTaskInitiative:Wm,availableWorkflows:Or,initiativeTemplates:Ve,availableEnvironments:Da,fetchWorkflows:Bt,fetchInitiativeTemplates:Dn,createInitiativeFromTemplate:xr,fetchWorkflowTemplate:sn,fetchWorkflowOverrideNames:_a,saveWorkflowTemplateDraft:Zn,resetWorkflowTemplateDraft:Is,onExportWorkflows:Jr,settingsModel:vu}}const rw="modulepreload",sw=function(e){return"/taskforce/"+e},oh={},Uo=function(n,a,s){let o=Promise.resolve();if(a&&a.length>0){let m=function(y){return Promise.all(y.map(v=>Promise.resolve(v).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),l=i?.nonce||i?.getAttribute("nonce");o=m(a.map(y=>{if(y=sw(y),y in oh)return;oh[y]=!0;const v=y.endsWith(".css"),b=v?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${y}"]${b}`))return;const g=document.createElement("link");if(g.rel=v?"stylesheet":rw,v||(g.as="script"),g.crossOrigin="",g.href=y,l&&g.setAttribute("nonce",l),document.head.appendChild(g),v)return new Promise((h,k)=>{g.addEventListener("load",h),g.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${y}`)))})}))}function c(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return o.then(i=>{for(const l of i||[])l.status==="rejected"&&c(l.reason);return n().catch(c)})},ow="_filterGlow_lx2xq_8",iw="_floatingButton_lx2xq_18",cw="_badge_lx2xq_49",lw="_configBadge_lx2xq_66",dw="_configBadgeActive_lx2xq_76",uw="_configBadgeRevoked_lx2xq_82",mw="_configBadgeExpired_lx2xq_88",pw="_header_lx2xq_98",fw="_headerTitle_lx2xq_113",hw="_brandIcon_lx2xq_130",gw="_brandCloudSuffix_lx2xq_136",yw="_projectSlash_lx2xq_141",kw="_projectName_lx2xq_148",Sw="_taskCountBadge_lx2xq_167",vw="_taskCountBadgeIcon_lx2xq_184",bw="_taskCountBadgeAlert_lx2xq_188",ww="_headerActions_lx2xq_194",xw="_sortDirectionBtn_lx2xq_201",_w="_sortDirectionBtnWidget_lx2xq_208",Cw="_form_lx2xq_216",Aw="_topRow_lx2xq_228",Iw="_field_lx2xq_234",Tw="_labelRow_lx2xq_240",Nw="_label_lx2xq_240",Rw="_manageLink_lx2xq_254",jw="_input_lx2xq_273",Pw="_select_lx2xq_274",Ew="_textarea_lx2xq_275",Mw="_taskIdInlineLink_lx2xq_309",Dw="_readOnly_lx2xq_328",Lw="_selectWithConfig_lx2xq_336",Bw="_configBtn_lx2xq_346",Ww="_configBtnActive_lx2xq_376",Fw="_hasPath_lx2xq_384",Ow="_pathIndicator_lx2xq_389",$w="_formActions_lx2xq_395",Uw="_hasCancel_lx2xq_402",qw="_submitBtn_lx2xq_406",zw="_cancelBtn_lx2xq_422",Hw="_successMessage_lx2xq_454",Gw="_errorMessage_lx2xq_460",Vw="_successIcon_lx2xq_472",Kw="_spinner_lx2xq_492",Zw="_spin_lx2xq_492",Yw="_boardRefreshIndicator_lx2xq_496",Jw="_destructiveBtn_lx2xq_526",Xw="_warningBtn_lx2xq_549",Qw="_viewTab_lx2xq_572",ex="_deleteBtn_lx2xq_583",tx="_loading_lx2xq_593",nx="_emptyState_lx2xq_599",ax="_taskList_lx2xq_609",rx="_taskIdBadge_lx2xq_615",sx="_taskIdBadgeLabel_lx2xq_637",ox="_copiedId_lx2xq_656",ix="_highlight_lx2xq_662",cx="_modal_lx2xq_674",lx="_priorityEmoji_lx2xq_682",dx="_metaItem_lx2xq_686",ux="_taskFormDateInput_lx2xq_700",mx="_metaBadge_lx2xq_710",px="_complexityPill_lx2xq_725",fx="_complexityDots_lx2xq_729",hx="_dot_lx2xq_735",gx="_dotFilled_lx2xq_743",yx="_typePill_lx2xq_749",kx="_type_bug_lx2xq_753",Sx="_type_feature_lx2xq_757",vx="_type_chore_lx2xq_761",bx="_type_refactor_lx2xq_765",wx="_type_documentation_lx2xq_769",xx="_type_research_lx2xq_773",_x="_type_security_lx2xq_781",Cx="_approachPill_lx2xq_786",Ax="_approach_evaluate_lx2xq_791",Ix="_approach_collaborate_lx2xq_797",Tx="_approach_plan_lx2xq_803",Nx="_approachActive_lx2xq_809",Rx="_statusActionsGroup_lx2xq_814",jx="_statusActionsGroupCompact_lx2xq_820",Px="_statusSelectWrap_lx2xq_824",Ex="_statusTaxonomyDropdownWrap_lx2xq_830",Mx="_statusTaxonomyDropdown_lx2xq_830",Dx="_statusTaxonomyDropdownCompact_lx2xq_838",Lx="_statusTaxonomyDropdownIconOnly_lx2xq_842",Bx="_taxonomyDropdownButton_lx2xq_847",Wx="_taxonomyDropdownButtonContent_lx2xq_864",Fx="_statusTaxonomyDropdownIconOnlyPanel_lx2xq_868",Ox="_actionBtn_lx2xq_874",$x="_startWorkBtn_lx2xq_898",Ux="_workingBtn_lx2xq_907",qx="_pulse_lx2xq_1",zx="_reviewBtn_lx2xq_913",Hx="_reviewActiveBtn_lx2xq_923",Gx="_reviewPill_lx2xq_929",Vx="_archiveTaskBtn_lx2xq_936",Kx="_bulkArchiveBtn_lx2xq_945",Zx="_bulkDeleteBtn_lx2xq_967",Yx="_completeBtn_lx2xq_1008",Jx="_completeActiveBtn_lx2xq_1018",Xx="_deleteActiveBtn_lx2xq_1024",Qx="_disabledBtn_lx2xq_1030",e_="_archiveList_lx2xq_1037",t_="_archiveHeader_lx2xq_1045",n_="_settingsTab_lx2xq_1056",a_="_settingsTabs_lx2xq_1068",r_="_settingsLayout_lx2xq_1082",s_="_settingsSidebar_lx2xq_1089",o_="_settingsSidebarHeader_lx2xq_1099",i_="_settingsSidebarNav_lx2xq_1108",c_="_settingsSidebarBtn_lx2xq_1117",l_="_settingsSidebarBtnActive_lx2xq_1141",d_="_settingsSidebarGroup_lx2xq_1148",u_="_settingsSidebarGroupBtn_lx2xq_1154",m_="_settingsSidebarGroupLabel_lx2xq_1158",p_="_settingsSidebarGroupChevron_lx2xq_1162",f_="_settingsSidebarSubnav_lx2xq_1168",h_="_settingsSidebarSubBtn_lx2xq_1175",g_="_appScrollbar_lx2xq_1198",y_="_settingsTabBtn_lx2xq_1202",k_="_settingsTabBtnActive_lx2xq_1228",S_="_settingsContent_lx2xq_1234",v_="_settingsToast_lx2xq_1282",b_="_settingsToastSuccess_lx2xq_1299",w_="_settingsToastError_lx2xq_1305",x_="_inputWithPrefix_lx2xq_1311",__="_pathHint_lx2xq_1318",C_="_settingGroup_lx2xq_1331",A_="_settingTitle_lx2xq_1337",I_="_settingTitleRow_lx2xq_1346",T_="_settingTitleActionBtn_lx2xq_1353",N_="_themeOptions_lx2xq_1373",R_="_buttonGrid_lx2xq_1378",j_="_themeBtn_lx2xq_1390",P_="_activeTheme_lx2xq_1414",E_="_pathInputGroup_lx2xq_1422",M_="_saveSettingsBtn_lx2xq_1431",D_="_shortcutInputWrapper_lx2xq_1452",L_="_inputIcon_lx2xq_1457",B_="_settingHelper_lx2xq_1466",W_="_browseBtn_lx2xq_1473",F_="_inlineCategoryManager_lx2xq_1492",O_="_categoryManager_lx2xq_1503",$_="_categoryList_lx2xq_1509",U_="_categoryChip_lx2xq_1521",q_="_categoryChipLabel_lx2xq_1534",z_="_chipActionBtn_lx2xq_1542",H_="_removeCategoryBtn_lx2xq_1562",G_="_addCategoryForm_lx2xq_1582",V_="_addCategoryBtn_lx2xq_1587",K_="_filesList_lx2xq_1612",Z_="_helpLink_lx2xq_1639",Y_="_inlineCode_lx2xq_1660",J_="_codeBlock_lx2xq_1671",X_="_taskChildrenSummaryBadges_lx2xq_1695",Q_="_taskChildrenProgressBar_lx2xq_1703",eC="_taskChildrenProgressBarSegmentDone_lx2xq_1714",tC="_taskChildrenProgressBarSegmentReview_lx2xq_1720",nC="_taskChildrenProgressBarSegmentInProgress_lx2xq_1726",aC="_taskChildrenProgressBarSegmentBlocked_lx2xq_1732",rC="_taskChildrenProgressText_lx2xq_1738",sC="_taskChildUnlinkBtn_lx2xq_1747",oC="_aboutText_lx2xq_1765",iC="_versionInfo_lx2xq_1772",cC="_filterBar_lx2xq_1780",lC="_kanbanHintText_lx2xq_1794",dC="_searchContainer_lx2xq_1800",uC="_searchIcon_lx2xq_1807",mC="_searchInput_lx2xq_1815",pC="_searchActive_lx2xq_1841",fC="_searchCount_lx2xq_1846",hC="_clearSearchBtn_lx2xq_1862",gC="_filterRow_lx2xq_1884",yC="_sortLabel_lx2xq_1890",kC="_archiveToggle_lx2xq_1898",SC="_filterContainer_lx2xq_1935",vC="_filterButton_lx2xq_1940",bC="_filterActive_lx2xq_1965",wC="_filterDropdown_lx2xq_1971",xC="_filterOption_lx2xq_1986",_C="_filterDivider_lx2xq_2016",CC="_filterSelect_lx2xq_2022",AC="_filterToggleBtn_lx2xq_2063",IC="_inProgressToggle_lx2xq_2085",TC="_activeInProgress_lx2xq_2103",NC="_activeFilter_lx2xq_2112",RC="_resetFiltersBtn_lx2xq_2122",jC="_categoryChip_disabled_lx2xq_2155",PC="_categoryVisibilityToggle_lx2xq_2165",EC="_editCategoryInput_lx2xq_2178",MC="_categoryChipActionBtn_lx2xq_2189",DC="_categoryChipActionBtn_active_lx2xq_2207",LC="_categoryGroup_lx2xq_2212",BC="_categoryHeader_lx2xq_2220",WC="_categoryTitle_lx2xq_2234",FC="_categoryCount_lx2xq_2244",OC="_categoryItems_lx2xq_2250",$C="_priorityItem_low_lx2xq_2259",UC="_priorityItem_medium_lx2xq_2263",qC="_priorityItem_high_lx2xq_2267",zC="_priorityItem_critical_lx2xq_2271",HC="_priorityPill_low_lx2xq_2275",GC="_priorityPill_medium_lx2xq_2281",VC="_priorityPill_high_lx2xq_2287",KC="_priorityPill_critical_lx2xq_2293",ZC="_selectPriority_low_lx2xq_2308",YC="_selectPriority_medium_lx2xq_2313",JC="_selectPriority_high_lx2xq_2318",XC="_selectPriority_critical_lx2xq_2323",QC="_levelSelect_lx2xq_2332",eA="_levelOption_lx2xq_2345",tA="_levelOptionFilled_lx2xq_2362",nA="_levelOption_priority_low_lx2xq_2369",aA="_levelOption_priority_medium_lx2xq_2374",rA="_levelOption_priority_high_lx2xq_2379",sA="_levelOption_priority_critical_lx2xq_2384",oA="_levelOption_complexity_tiny_lx2xq_2391",iA="_levelOption_complexity_low_lx2xq_2396",cA="_levelOption_complexity_medium_lx2xq_2401",lA="_levelOption_complexity_high_lx2xq_2406",dA="_levelOption_complexity_epic_lx2xq_2411",uA="_levelOptionActive_lx2xq_2418",mA="_levelOptionSelected_lx2xq_2423",pA="_levelLabel_lx2xq_2431",fA="_fadeIn_lx2xq_1",hA="_closeConfigBtn_lx2xq_2456",gA="_configItem_lx2xq_2478",yA="_settingsLabel_lx2xq_2484",kA="_settingsHint_lx2xq_2493",SA="_pathList_lx2xq_2500",vA="_pathChip_lx2xq_2507",bA="_pathValid_lx2xq_2520",wA="_pathInvalid_lx2xq_2525",xA="_pathValidIcon_lx2xq_2530",_A="_pathInvalidIcon_lx2xq_2535",CA="_pathText_lx2xq_2540",AA="_removePathBtn_lx2xq_2547",IA="_pathCount_lx2xq_2569",TA="_specialistSection_lx2xq_2592",NA="_toggleHeading_lx2xq_2600",RA="_dropdownList_lx2xq_2640",jA="_specialistBadge_lx2xq_2649",PA="_iconGrid_lx2xq_2679",EA="_iconPickerBtn_lx2xq_2690",MA="_iconPickerBtnActive_lx2xq_2709",DA="_categorySubConfig_lx2xq_2716",LA="_colorPickerRow_lx2xq_2724",BA="_colorPickerGrid_lx2xq_2730",WA="_colorSwatch_lx2xq_2737",FA="_colorSwatchActive_lx2xq_2756",OA="_categoryChipIcon_lx2xq_2762",$A="_fieldIconWrapper_lx2xq_2767",UA="_fieldIcon_lx2xq_2767",qA="_field_dynamic_lx2xq_2789",zA="_fieldIcon_dynamic_lx2xq_2795",HA="_categoryTitleIcon_lx2xq_2799",GA="_editActionsHeader_lx2xq_2805",VA="_editActionsGroup_lx2xq_2814",KA="_urlInputGroup_lx2xq_2821",ZA="_iconBtn_lx2xq_2834",YA="_stickyActionHeader_lx2xq_2855",JA="_taskHierarchyHeader_lx2xq_2872",XA="_taskHierarchyBadgeRow_lx2xq_2879",QA="_taskHierarchyDivider_lx2xq_2887",eI="_taskHierarchyMeta_lx2xq_2893",tI="_taskHierarchyAddBtn_lx2xq_2906",nI="_taskHierarchyEditor_lx2xq_2912",aI="_taskHierarchyInput_lx2xq_2919",rI="_taskSaveStatus_lx2xq_2928",sI="_taskSaveStatusCenter_lx2xq_2939",oI="_taskSaveStatusError_lx2xq_2947",iI="_headerSuccessFeedback_lx2xq_2951",cI="_slideInUp_lx2xq_1",lI="_successCheck_lx2xq_2963",dI="_scaleIn_lx2xq_1",uI="_primaryUpdateBtn_lx2xq_2999",mI="_secondaryHeaderBtn_lx2xq_3027",pI="_secondaryHeaderBtnDestructive_lx2xq_3048",fI="_commentSection_lx2xq_3061",hI="_attachmentCaptureContainer_lx2xq_3097",gI="_capturePrompt_lx2xq_3105",yI="_previewContainer_lx2xq_3119",kI="_previewHeader_lx2xq_3125",SI="_attachmentCapturePreview_lx2xq_3135",vI="_actions_lx2xq_3142",bI="_primaryButton_lx2xq_3148",wI="_secondaryButton_lx2xq_3163",xI="_iconButton_lx2xq_3178",_I="_attachmentGrid_lx2xq_3200",CI="_attachmentCard_lx2xq_3207",AI="_attachmentPreviewContainer_lx2xq_3221",II="_contextFileLink_lx2xq_3242",TI="_attachmentActions_lx2xq_3268",NI="_attachmentActionBtn_lx2xq_3282",RI="_attachmentCaptionInput_lx2xq_3304",jI="_hiddenInput_lx2xq_3322",PI="_contextUploadPanel_lx2xq_3326",EI="_contextUploadActions_lx2xq_3334",MI="_contextDropzone_lx2xq_3342",DI="_contextDropzoneActive_lx2xq_3358",LI="_contextDropzonePulse_lx2xq_1",BI="_contextLinkRow_lx2xq_3366",WI="_contextNotice_lx2xq_3372",FI="_documentAttachmentList_lx2xq_3378",OI="_documentAttachmentItem_lx2xq_3385",$I="_documentAttachmentRow_lx2xq_3392",UI="_documentAttachmentLink_lx2xq_3400",qI="_documentAttachmentMain_lx2xq_3414",zI="_documentAttachmentText_lx2xq_3421",HI="_documentAttachmentIcon_lx2xq_3429",GI="_documentAttachmentName_lx2xq_3440",VI="_documentAttachmentType_lx2xq_3449",KI="_documentAttachmentActions_lx2xq_3462",ZI="_documentAttachmentActionBtn_lx2xq_3468",YI="_documentAttachmentCaptionInput_lx2xq_3489",JI="_brokenImage_lx2xq_3517",XI="_brokenImagePlaceholder_lx2xq_3525",QI="_regionOverlay_lx2xq_3539",eT="_selectionBox_lx2xq_3550",tT="_exportRow_lx2xq_3558",nT="_exportItem_lx2xq_3563",aT="_taxonomyDrillDown_lx2xq_3572",rT="_drillDownList_lx2xq_3582",sT="_drillDownSection_lx2xq_3590",oT="_drillDownSectionHeader_lx2xq_3596",iT="_drillDownSectionTitle_lx2xq_3603",cT="_drillDownItem_lx2xq_3612",lT="_drillDownItemDimmed_lx2xq_3634",dT="_drillDownItemActive_lx2xq_3642",uT="_drillDownItemInfo_lx2xq_3647",mT="_drillDownItemText_lx2xq_3653",pT="_drillDownItemLabel_lx2xq_3658",fT="_drillDownItemSubtext_lx2xq_3663",hT="_addTaxonomyBtnSmall_lx2xq_3668",gT="_taxonomyDetailView_lx2xq_3690",yT="_slideIn_lx2xq_1",kT="_detailHeader_lx2xq_3710",ST="_detailTitle_lx2xq_3719",vT="_detailContent_lx2xq_3726",bT="_createOverlay_lx2xq_3733",wT="_createDialog_lx2xq_3745",xT="_zoomIn_lx2xq_1",_T="_dialogActions_lx2xq_3773",CT="_settingsGroup_lx2xq_3791",AT="_settingsItem_lx2xq_3797",IT="_settingLabelGroup_lx2xq_3803",TT="_settingLabel_lx2xq_3803",NT="_settingDescription_lx2xq_3815",RT="_settingInput_lx2xq_3822",jT="_codeBlockWrapper_lx2xq_3845",PT="_codeHeader_lx2xq_3854",ET="_codeHeaderActions_lx2xq_3865",MT="_codeLabel_lx2xq_3872",DT="_codeHeaderDescription_lx2xq_3880",LT="_mcpTokenCardBody_lx2xq_3888",BT="_mcpTokenFormGrid_lx2xq_3896",WT="_mcpTokenOutputWrap_lx2xq_3903",FT="_mcpTokenValueField_lx2xq_3910",OT="_mcpTokenValueText_lx2xq_3920",$T="_mcpTokenActionRow_lx2xq_3933",UT="_copyBtn_lx2xq_3954",qT="_copyBtnActive_lx2xq_3975",zT="_copyBtnNeutralActive_lx2xq_3981",HT="_headerDivider_lx2xq_3999",GT="_groupByContainer_lx2xq_4005",VT="_groupByLabel_lx2xq_4013",KT="_groupBySelect_lx2xq_4018",ZT="_viewSwitcher_lx2xq_4040",YT="_selectWithIcon_lx2xq_4048",JT="_marginBottom16_lx2xq_4052",XT="_headerDraggable_lx2xq_4057",QT="_headerDragging_lx2xq_4061",eN="_filterSelectSort_lx2xq_4069",tN="_archiveRow_lx2xq_4073",nN="_taskScopeToggle_lx2xq_4079",aN="_taskScopeTabs_lx2xq_4087",rN="_taskScopeTab_lx2xq_4087",sN="_taskScopeTabActive_lx2xq_4120",oN="_taskToolbarAction_lx2xq_4132",iN="_overlayHighZ_lx2xq_4148",cN="_savedText_lx2xq_4158",lN="_shortcutInput_lx2xq_1452",dN="_saveSettingsBtnWrapper_lx2xq_4166",uN="_marginBottom12_lx2xq_4170",mN="_exportRowGrid_lx2xq_4174",pN="_settingSubtitleCustom_lx2xq_4179",fN="_capitalize_lx2xq_4185",hN="_marginTop12_lx2xq_4189",gN="_marginTop16_lx2xq_4193",yN="_labelGroupFlex_lx2xq_4197",kN="_codeBlockWrapperCustom_lx2xq_4203",SN="_kanbanWrapper_lx2xq_4209",vN="_kanbanContainer_lx2xq_4217",bN="_kanbanTopScroll_lx2xq_4239",wN="_kanbanTopScrollSpacer_lx2xq_4248",xN="_kanbanColumn_lx2xq_4252",_N="_kanbanColumnSticky_lx2xq_4268",CN="_kanbanColumnCollapsed_lx2xq_4274",AN="_kanbanColumnPast_lx2xq_4279",IN="_kanbanColumnSelectedDay_lx2xq_4284",TN="_kanbanHeader_lx2xq_4291",NN="_kanbanCount_lx2xq_4301",RN="_kanbanHeaderDraggable_lx2xq_4321",jN="_kanbanHeaderPanning_lx2xq_4325",PN="_kanbanQuickAdd_lx2xq_4329",EN="_kanbanColorDot_lx2xq_4350",MN="_kanbanDroppable_lx2xq_4362",DN="_kanbanDroppableScroll_lx2xq_4371",LN="_kanbanEmpty_lx2xq_4381",BN="_kanbanCard_lx2xq_4391",WN="_kanbanCardWrapper_lx2xq_4401",FN="_taxonomyDropdownActive_lx2xq_4409",ON="_kanbanCardWrapperRaised_lx2xq_4413",$N="_kanbanCardTitle_lx2xq_4417",UN="_kanbanBadges_lx2xq_4421",qN="_kanbanBadge_lx2xq_4421",zN="_headerFlex_lx2xq_4437",HN="_marginBottom8_lx2xq_4444",GN="_marginBottom20_lx2xq_4448",VN="_configPanel_lx2xq_4452",KN="_configPanelLarge_lx2xq_4461",ZN="_subLabelBlock_lx2xq_4465",YN="_subLabelBlock12_lx2xq_4472",JN="_flexBetween_lx2xq_4476",XN="_flexBetweenCenter_lx2xq_4483",QN="_deleteBtnSmall_lx2xq_4488",eR="_deleteBtnMedium_lx2xq_4494",tR="_trashIcon_lx2xq_4501",nR="_gridConfig_lx2xq_4505",aR="_flexColGap4_lx2xq_4512",rR="_flexColGap4Center_lx2xq_4518",sR="_flex1_lx2xq_4525",oR="_flexCol_lx2xq_4512",iR="_flexGrow1_lx2xq_4535",cR="_inputLabel_lx2xq_4539",lR="_inputLabelBlock_lx2xq_4543",dR="_checkboxInput_lx2xq_4549",uR="_configDividerMargin_lx2xq_4555",mR="_configDividerMargin24_lx2xq_4560",pR="_pathListMargin_lx2xq_4565",fR="_cancelBtnRed_lx2xq_4569",hR="_code_lx2xq_1671",gR="_workflowList_lx2xq_4596",yR="_workflowActions_lx2xq_4604",kR="_textBtn_lx2xq_4613",SR="_workflowGrid_lx2xq_4627",vR="_checkboxLabel_lx2xq_4635",bR="_checkboxSmall_lx2xq_4649",wR="_docWorkspace_lx2xq_4668",xR="_docIndexPanel_lx2xq_4677",_R="_docSpinning_lx2xq_4689",CR="_docSpin_lx2xq_4689",AR="_docViewerPanel_lx2xq_4700",IR="_docViewerEmpty_lx2xq_4708",TR="_agentsModuleRoot_lx2xq_4723",NR="_agentsModuleContent_lx2xq_4733",RR="_agentsModuleGroup_lx2xq_4738",jR="_marginTop24_lx2xq_4742",PR="_settingSubTitle_lx2xq_4746",ER="_dangerBtn_lx2xq_4755",MR="_aiProfilesExplorer_lx2xq_4771",DR="_aiProfilesListPane_lx2xq_4782",LR="_aiProfilesList_lx2xq_4782",BR="_aiProfilesSection_lx2xq_4801",WR="_aiProfilesSectionHeader_lx2xq_4807",FR="_aiProfileGroup_lx2xq_4815",OR="_aiProfileGroupSelected_lx2xq_4836",$R="_aiProfileGroupDuplicate_lx2xq_4844",UR="_aiProfileGroupHeader_lx2xq_4849",qR="_aiProfileGroupAvatar_lx2xq_4857",zR="_aiProfileGroupIdentity_lx2xq_4879",HR="_aiProfileName_lx2xq_4888",GR="_aiProfileHandle_lx2xq_4896",VR="_aiProfileRole_lx2xq_4897",KR="_aiProfileSeatSummary_lx2xq_4908",ZR="_aiProfileSeatScopeIcon_lx2xq_4917",YR="_aiProfileSeatScopeIconDetail_lx2xq_4928",JR="_aiProfileSeatScopeIconCloud_lx2xq_4933",XR="_aiProfileSeatScopeIconLocal_lx2xq_4937",QR="_aiProfileDuplicateBadge_lx2xq_4941",ej="_aiProfileMergeSection_lx2xq_4953",tj="_aiProfileMergeRow_lx2xq_4960",nj="_aiProfileIdChip_lx2xq_4967",aj="_aiProfileKeepBadge_lx2xq_4979",rj="_aiProfileMergeActions_lx2xq_4993",sj="_aiProfileDetailPane_lx2xq_5000",oj="_aiProfileDetailCard_lx2xq_5006",ij="_aiProfileDetailHero_lx2xq_5018",cj="_aiProfileDetailIcon_lx2xq_5024",lj="_aiProfileDetailAvatar_lx2xq_5038",dj="_aiProfileDetailHeading_lx2xq_5042",uj="_aiProfileDetailTitleRow_lx2xq_5047",mj="_aiProfileDetailTitle_lx2xq_5047",pj="_aiProfileDetailMetaRow_lx2xq_5062",fj="_aiProfileDetailHandle_lx2xq_5070",hj="_aiProfileDetailRole_lx2xq_5075",gj="_aiProfileDetailLinkedCount_lx2xq_5082",yj="_aiProfileDetailDescription_lx2xq_5087",kj="_aiProfileDetailDataList_lx2xq_5094",Sj="_aiProfileDetailDataGroup_lx2xq_5103",vj="_aiProfileDetailDateGroup_lx2xq_5110",bj="_aiProfileDetailDataRow_lx2xq_5115",wj="_aiProfileDetailDataLabel_lx2xq_5124",xj="_aiProfileDetailDataValue_lx2xq_5131",_j="_aiProfileStatusSelect_lx2xq_5137",Cj="_aiProfileInstanceSection_lx2xq_5172",Aj="_aiProfileInstanceSectionHeader_lx2xq_5178",Ij="_aiProfileInstanceList_lx2xq_5188",Tj="_aiProfileInstanceCard_lx2xq_5194",Nj="_aiProfileIdFooter_lx2xq_5207",Rj="_aiProfileIdFooterValue_lx2xq_5217",jj="_aiProfileDangerTextButton_lx2xq_5227",Pj="_aiProfileInstanceTopRow_lx2xq_5259",Ej="_aiProfileInstanceName_lx2xq_5266",Mj="_aiProfileInstanceMeta_lx2xq_5273",Dj="_aiProfileInlineError_lx2xq_5281",p={filterGlow:ow,floatingButton:iw,badge:cw,configBadge:lw,configBadgeActive:dw,configBadgeRevoked:uw,configBadgeExpired:mw,header:pw,headerTitle:fw,brandIcon:hw,brandCloudSuffix:gw,projectSlash:yw,projectName:kw,taskCountBadge:Sw,taskCountBadgeIcon:vw,taskCountBadgeAlert:bw,headerActions:ww,sortDirectionBtn:xw,sortDirectionBtnWidget:_w,form:Cw,topRow:Aw,field:Iw,labelRow:Tw,label:Nw,manageLink:Rw,input:jw,select:Pw,textarea:Ew,taskIdInlineLink:Mw,readOnly:Dw,selectWithConfig:Lw,configBtn:Bw,configBtnActive:Ww,hasPath:Fw,pathIndicator:Ow,formActions:$w,hasCancel:Uw,submitBtn:qw,cancelBtn:zw,successMessage:Hw,errorMessage:Gw,successIcon:Vw,spinner:Kw,spin:Zw,boardRefreshIndicator:Yw,destructiveBtn:Jw,warningBtn:Xw,viewTab:Qw,deleteBtn:ex,loading:tx,emptyState:nx,taskList:ax,taskIdBadge:rx,taskIdBadgeLabel:sx,copiedId:ox,highlight:ix,modal:cx,priorityEmoji:lx,metaItem:dx,taskFormDateInput:ux,metaBadge:mx,complexityPill:px,complexityDots:fx,dot:hx,dotFilled:gx,typePill:yx,type_bug:kx,type_feature:Sx,type_chore:vx,type_refactor:bx,type_documentation:wx,type_research:xx,"type_ui-ux":"_type_ui-ux_lx2xq_777",type_security:_x,approachPill:Cx,approach_evaluate:Ax,approach_collaborate:Ix,approach_plan:Tx,approachActive:Nx,statusActionsGroup:Rx,statusActionsGroupCompact:jx,statusSelectWrap:Px,statusTaxonomyDropdownWrap:Ex,statusTaxonomyDropdown:Mx,statusTaxonomyDropdownCompact:Dx,statusTaxonomyDropdownIconOnly:Lx,taxonomyDropdownButton:Bx,taxonomyDropdownButtonContent:Wx,statusTaxonomyDropdownIconOnlyPanel:Fx,actionBtn:Ox,startWorkBtn:$x,workingBtn:Ux,pulse:qx,reviewBtn:zx,reviewActiveBtn:Hx,reviewPill:Gx,archiveTaskBtn:Vx,bulkArchiveBtn:Kx,bulkDeleteBtn:Zx,completeBtn:Yx,completeActiveBtn:Jx,deleteActiveBtn:Xx,disabledBtn:Qx,archiveList:e_,archiveHeader:t_,settingsTab:n_,settingsTabs:a_,settingsLayout:r_,settingsSidebar:s_,settingsSidebarHeader:o_,settingsSidebarNav:i_,settingsSidebarBtn:c_,settingsSidebarBtnActive:l_,settingsSidebarGroup:d_,settingsSidebarGroupBtn:u_,settingsSidebarGroupLabel:m_,settingsSidebarGroupChevron:p_,settingsSidebarSubnav:f_,settingsSidebarSubBtn:h_,appScrollbar:g_,settingsTabBtn:y_,settingsTabBtnActive:k_,settingsContent:S_,settingsToast:v_,settingsToastSuccess:b_,settingsToastError:w_,inputWithPrefix:x_,pathHint:__,settingGroup:C_,settingTitle:A_,settingTitleRow:I_,settingTitleActionBtn:T_,themeOptions:N_,buttonGrid:R_,themeBtn:j_,activeTheme:P_,pathInputGroup:E_,saveSettingsBtn:M_,shortcutInputWrapper:D_,inputIcon:L_,settingHelper:B_,browseBtn:W_,inlineCategoryManager:F_,categoryManager:O_,categoryList:$_,categoryChip:U_,categoryChipLabel:q_,chipActionBtn:z_,removeCategoryBtn:H_,addCategoryForm:G_,addCategoryBtn:V_,filesList:K_,helpLink:Z_,inlineCode:Y_,codeBlock:J_,taskChildrenSummaryBadges:X_,taskChildrenProgressBar:Q_,taskChildrenProgressBarSegmentDone:eC,taskChildrenProgressBarSegmentReview:tC,taskChildrenProgressBarSegmentInProgress:nC,taskChildrenProgressBarSegmentBlocked:aC,taskChildrenProgressText:rC,taskChildUnlinkBtn:sC,aboutText:oC,versionInfo:iC,filterBar:cC,kanbanHintText:lC,searchContainer:dC,searchIcon:uC,searchInput:mC,searchActive:pC,searchCount:fC,clearSearchBtn:hC,filterRow:gC,sortLabel:yC,archiveToggle:kC,filterContainer:SC,filterButton:vC,filterActive:bC,filterDropdown:wC,filterOption:xC,filterDivider:_C,filterSelect:CC,filterToggleBtn:AC,inProgressToggle:IC,activeInProgress:TC,activeFilter:NC,resetFiltersBtn:RC,categoryChip_disabled:jC,categoryVisibilityToggle:PC,editCategoryInput:EC,categoryChipActionBtn:MC,categoryChipActionBtn_active:DC,categoryGroup:LC,categoryHeader:BC,categoryTitle:WC,categoryCount:FC,categoryItems:OC,priorityItem_low:$C,priorityItem_medium:UC,priorityItem_high:qC,priorityItem_critical:zC,priorityPill_low:HC,priorityPill_medium:GC,priorityPill_high:VC,priorityPill_critical:KC,selectPriority_low:ZC,selectPriority_medium:YC,selectPriority_high:JC,selectPriority_critical:XC,"critical-glow":"_critical-glow_lx2xq_1",levelSelect:QC,levelOption:eA,levelOptionFilled:tA,levelOption_priority_low:nA,levelOption_priority_medium:aA,levelOption_priority_high:rA,levelOption_priority_critical:sA,levelOption_complexity_tiny:oA,levelOption_complexity_low:iA,levelOption_complexity_medium:cA,levelOption_complexity_high:lA,levelOption_complexity_epic:dA,levelOptionActive:uA,levelOptionSelected:mA,levelLabel:pA,fadeIn:fA,closeConfigBtn:hA,configItem:gA,settingsLabel:yA,settingsHint:kA,pathList:SA,pathChip:vA,pathValid:bA,pathInvalid:wA,pathValidIcon:xA,pathInvalidIcon:_A,pathText:CA,removePathBtn:AA,pathCount:IA,specialistSection:TA,toggleHeading:NA,dropdownList:RA,specialistBadge:jA,iconGrid:PA,iconPickerBtn:EA,iconPickerBtnActive:MA,categorySubConfig:DA,colorPickerRow:LA,colorPickerGrid:BA,colorSwatch:WA,colorSwatchActive:FA,categoryChipIcon:OA,fieldIconWrapper:$A,fieldIcon:UA,field_dynamic:qA,fieldIcon_dynamic:zA,categoryTitleIcon:HA,editActionsHeader:GA,editActionsGroup:VA,urlInputGroup:KA,iconBtn:ZA,stickyActionHeader:YA,taskHierarchyHeader:JA,taskHierarchyBadgeRow:XA,taskHierarchyDivider:QA,taskHierarchyMeta:eI,taskHierarchyAddBtn:tI,taskHierarchyEditor:nI,taskHierarchyInput:aI,taskSaveStatus:rI,taskSaveStatusCenter:sI,taskSaveStatusError:oI,headerSuccessFeedback:iI,slideInUp:cI,successCheck:lI,scaleIn:dI,primaryUpdateBtn:uI,secondaryHeaderBtn:mI,secondaryHeaderBtnDestructive:pI,commentSection:fI,attachmentCaptureContainer:hI,capturePrompt:gI,previewContainer:yI,previewHeader:kI,attachmentCapturePreview:SI,actions:vI,primaryButton:bI,secondaryButton:wI,iconButton:xI,attachmentGrid:_I,attachmentCard:CI,attachmentPreviewContainer:AI,contextFileLink:II,attachmentActions:TI,attachmentActionBtn:NI,attachmentCaptionInput:RI,hiddenInput:jI,contextUploadPanel:PI,contextUploadActions:EI,contextDropzone:MI,contextDropzoneActive:DI,contextDropzonePulse:LI,contextLinkRow:BI,contextNotice:WI,documentAttachmentList:FI,documentAttachmentItem:OI,documentAttachmentRow:$I,documentAttachmentLink:UI,documentAttachmentMain:qI,documentAttachmentText:zI,documentAttachmentIcon:HI,documentAttachmentName:GI,documentAttachmentType:VI,documentAttachmentActions:KI,documentAttachmentActionBtn:ZI,documentAttachmentCaptionInput:YI,brokenImage:JI,brokenImagePlaceholder:XI,regionOverlay:QI,selectionBox:eT,exportRow:tT,exportItem:nT,taxonomyDrillDown:aT,drillDownList:rT,drillDownSection:sT,drillDownSectionHeader:oT,drillDownSectionTitle:iT,drillDownItem:cT,drillDownItemDimmed:lT,drillDownItemActive:dT,drillDownItemInfo:uT,drillDownItemText:mT,drillDownItemLabel:pT,drillDownItemSubtext:fT,addTaxonomyBtnSmall:hT,taxonomyDetailView:gT,slideIn:yT,detailHeader:kT,detailTitle:ST,detailContent:vT,createOverlay:bT,createDialog:wT,zoomIn:xT,dialogActions:_T,settingsGroup:CT,settingsItem:AT,settingLabelGroup:IT,settingLabel:TT,settingDescription:NT,settingInput:RT,codeBlockWrapper:jT,codeHeader:PT,codeHeaderActions:ET,codeLabel:MT,codeHeaderDescription:DT,mcpTokenCardBody:LT,mcpTokenFormGrid:BT,mcpTokenOutputWrap:WT,mcpTokenValueField:FT,mcpTokenValueText:OT,mcpTokenActionRow:$T,copyBtn:UT,copyBtnActive:qT,copyBtnNeutralActive:zT,headerDivider:HT,groupByContainer:GT,groupByLabel:VT,groupBySelect:KT,viewSwitcher:ZT,selectWithIcon:YT,marginBottom16:JT,headerDraggable:XT,headerDragging:QT,filterSelectSort:eN,archiveRow:tN,taskScopeToggle:nN,taskScopeTabs:aN,taskScopeTab:rN,taskScopeTabActive:sN,taskToolbarAction:oN,overlayHighZ:iN,savedText:cN,shortcutInput:lN,saveSettingsBtnWrapper:dN,marginBottom12:uN,exportRowGrid:mN,settingSubtitleCustom:pN,capitalize:fN,marginTop12:hN,marginTop16:gN,labelGroupFlex:yN,codeBlockWrapperCustom:kN,kanbanWrapper:SN,kanbanContainer:vN,kanbanTopScroll:bN,kanbanTopScrollSpacer:wN,kanbanColumn:xN,kanbanColumnSticky:_N,kanbanColumnCollapsed:CN,kanbanColumnPast:AN,kanbanColumnSelectedDay:IN,kanbanHeader:TN,kanbanCount:NN,kanbanHeaderDraggable:RN,kanbanHeaderPanning:jN,kanbanQuickAdd:PN,kanbanColorDot:EN,kanbanDroppable:MN,kanbanDroppableScroll:DN,kanbanEmpty:LN,kanbanCard:BN,kanbanCardWrapper:WN,taxonomyDropdownActive:FN,kanbanCardWrapperRaised:ON,kanbanCardTitle:$N,kanbanBadges:UN,kanbanBadge:qN,headerFlex:zN,marginBottom8:HN,marginBottom20:GN,configPanel:VN,configPanelLarge:KN,subLabelBlock:ZN,subLabelBlock12:YN,flexBetween:JN,flexBetweenCenter:XN,deleteBtnSmall:QN,deleteBtnMedium:eR,trashIcon:tR,gridConfig:nR,flexColGap4:aR,flexColGap4Center:rR,flex1:sR,flexCol:oR,flexGrow1:iR,inputLabel:cR,inputLabelBlock:lR,checkboxInput:dR,configDividerMargin:uR,configDividerMargin24:mR,pathListMargin:pR,cancelBtnRed:fR,code:hR,workflowList:gR,workflowActions:yR,textBtn:kR,workflowGrid:SR,checkboxLabel:vR,checkboxSmall:bR,docWorkspace:wR,docIndexPanel:xR,docSpinning:_R,docSpin:CR,docViewerPanel:AR,docViewerEmpty:IR,agentsModuleRoot:TR,agentsModuleContent:NR,agentsModuleGroup:RR,marginTop24:jR,settingSubTitle:PR,dangerBtn:ER,aiProfilesExplorer:MR,aiProfilesListPane:DR,aiProfilesList:LR,aiProfilesSection:BR,aiProfilesSectionHeader:WR,aiProfileGroup:FR,aiProfileGroupSelected:OR,aiProfileGroupDuplicate:$R,aiProfileGroupHeader:UR,aiProfileGroupAvatar:qR,aiProfileGroupIdentity:zR,aiProfileName:HR,aiProfileHandle:GR,aiProfileRole:VR,aiProfileSeatSummary:KR,aiProfileSeatScopeIcon:ZR,aiProfileSeatScopeIconDetail:YR,aiProfileSeatScopeIconCloud:JR,aiProfileSeatScopeIconLocal:XR,aiProfileDuplicateBadge:QR,aiProfileMergeSection:ej,aiProfileMergeRow:tj,aiProfileIdChip:nj,aiProfileKeepBadge:aj,aiProfileMergeActions:rj,aiProfileDetailPane:sj,aiProfileDetailCard:oj,aiProfileDetailHero:ij,aiProfileDetailIcon:cj,aiProfileDetailAvatar:lj,aiProfileDetailHeading:dj,aiProfileDetailTitleRow:uj,aiProfileDetailTitle:mj,aiProfileDetailMetaRow:pj,aiProfileDetailHandle:fj,aiProfileDetailRole:hj,aiProfileDetailLinkedCount:gj,aiProfileDetailDescription:yj,aiProfileDetailDataList:kj,aiProfileDetailDataGroup:Sj,aiProfileDetailDateGroup:vj,aiProfileDetailDataRow:bj,aiProfileDetailDataLabel:wj,aiProfileDetailDataValue:xj,aiProfileStatusSelect:_j,aiProfileInstanceSection:Cj,aiProfileInstanceSectionHeader:Aj,aiProfileInstanceList:Ij,aiProfileInstanceCard:Tj,aiProfileIdFooter:Nj,aiProfileIdFooterValue:Rj,aiProfileDangerTextButton:jj,aiProfileInstanceTopRow:Pj,aiProfileInstanceName:Ej,aiProfileInstanceMeta:Mj,aiProfileInlineError:Dj},Lj="_standaloneWrapper_1mq9f_1",Bj="_standalonePage_1mq9f_11",Wj="_standaloneHeader_1mq9f_21",Fj="_standaloneTitle_1mq9f_27",Oj="_standaloneContent_1mq9f_31",$j="_workspaceToolRail_1mq9f_37",Uj="_workspaceToolRailMain_1mq9f_54",qj="_workspaceToolRailBottom_1mq9f_62",zj="_workspaceToolRailDivider_1mq9f_72",Hj="_workspaceToolButton_1mq9f_79",Gj="_workspaceToolButtonActive_1mq9f_99",Vj="_headerTitleWidget_1mq9f_123",pn={standaloneWrapper:Lj,standalonePage:Bj,standaloneHeader:Wj,standaloneTitle:Fj,standaloneContent:Oj,workspaceToolRail:$j,workspaceToolRailMain:Uj,workspaceToolRailBottom:qj,workspaceToolRailDivider:zj,workspaceToolButton:Hj,workspaceToolButtonActive:Gj,headerTitleWidget:Vj},Kj="_overlay_11v7l_1",Zj="_browser_11v7l_16",Yj="_header_11v7l_27",Jj="_pathInfo_11v7l_36",Xj="_actions_11v7l_52",Qj="_list_11v7l_57",e0="_item_11v7l_63",t0="_itemCurrent_11v7l_80",n0="_itemFile_11v7l_86",a0="_empty_11v7l_90",En={overlay:Kj,browser:Zj,header:Yj,pathInfo:Jj,actions:Xj,list:Qj,item:e0,itemCurrent:t0,itemFile:n0,empty:a0},r0="_overlay_1hk7m_2",s0="_overlayHighZ_1hk7m_15",o0="_modal_1hk7m_20",i0="_draggableModal_1hk7m_46",c0="_draggableHeader_1hk7m_53",l0="_headerActions_1hk7m_61",d0="_modalContent_1hk7m_69",u0="_form_1hk7m_80",m0="_formActions_1hk7m_91",p0="_modalFooter_1hk7m_98",f0="_modalSizeSm_1hk7m_104",h0="_modalSizeMd_1hk7m_108",g0="_modalSizeMdWide_1hk7m_112",y0="_modalSizeLg_1hk7m_116",k0="_modalSizeXl_1hk7m_120",S0="_modalSizeFull_1hk7m_124",v0="_settingsViewModal_1hk7m_129",b0="_unsavedOverlay_1hk7m_148",w0="_unsavedModal_1hk7m_153",x0="_unsavedHeader_1hk7m_159",_0="_unsavedTitle_1hk7m_164",C0="_unsavedContent_1hk7m_168",A0="_unsavedText_1hk7m_172",I0="_unsavedActions_1hk7m_177",At={overlay:r0,overlayHighZ:s0,modal:o0,draggableModal:i0,draggableHeader:c0,headerActions:l0,modalContent:d0,form:u0,formActions:m0,modalFooter:p0,modalSizeSm:f0,modalSizeMd:h0,modalSizeMdWide:g0,modalSizeLg:y0,modalSizeXl:k0,modalSizeFull:S0,settingsViewModal:v0,unsavedOverlay:b0,unsavedModal:w0,unsavedHeader:x0,unsavedTitle:_0,unsavedContent:C0,unsavedText:A0,unsavedActions:I0};function T0(e){const n=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),a={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return a[n]?a[n]:`${e}s`}function xi({label:e,options:n,selected:a,onChange:s,variant:o="label",containerStyle:c}){const[i,l]=r.useState(!1),m=r.useRef(null);r.useEffect(()=>{const x=A=>{m.current&&!m.current.contains(A.target)&&l(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]);const y=x=>{a.includes(x)?s(a.filter(A=>A!==x)):s([...a,x])},v=n.length>0&&n.every(x=>{const A=o==="label"?x.label:x.value;return a.includes(A)}),b=!n.some(x=>{const A=o==="label"?x.label:x.value;return a.includes(A)}),g=()=>{s(v?[]:n.map(x=>o==="label"?x.label:x.value))},h=n.filter(x=>{const A=o==="label"?x.label:x.value;return a.includes(A)}).length,k=T0(e),I=v?`All ${k}`:b?`No ${k}`:h===1?`1 ${e}`:`${h} ${k}`;return t.jsxs("div",{className:p.filterContainer,ref:m,style:c,children:[t.jsxs("button",{className:`${p.filterButton} ${v?"":p.filterActive}`,onClick:()=>l(!i),title:`Filter by ${e}`,children:[t.jsx("span",{children:I}),t.jsx(fd,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&t.jsxs("div",{className:`${p.filterDropdown} ${p.appScrollbar} tf-scrollbar`,children:[t.jsxs("div",{className:p.filterOption,onClick:g,children:[t.jsx("input",{type:"checkbox",checked:v,onChange:()=>{}}),t.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),t.jsx("div",{className:p.filterDivider}),n.map(x=>{const A=o==="label"?x.label:x.value,M=a.includes(A);return t.jsxs("div",{className:p.filterOption,onClick:()=>y(A),children:[t.jsx("input",{type:"checkbox",checked:M,onChange:()=>{}}),t.jsx("span",{children:x.label})]},x.value)})]})]})}const N0="_taskItem_rim4v_1",R0="_compressed_rim4v_20",j0="_taskHeader_rim4v_25",P0="_taskReferenceCluster_rim4v_30",E0="_taskMeta_rim4v_34",M0="_taskTitle_rim4v_40",D0="_taskItemRecentlyChanged_rim4v_67",L0="_assigneeAvatarImage_rim4v_107",B0="_assigneeAvatarIndicator_rim4v_115",W0="_assigneeAvatarEmpty_rim4v_137",F0="_inProgress_rim4v_164",O0="_onHold_rim4v_175",$0="_readyForReview_rim4v_186",U0="_completed_rim4v_197",q0="_cancelled_rim4v_208",z0="_archived_rim4v_219",H0="_taskContent_rim4v_229",G0="_kanbanCardOverlay_rim4v_238",V0="_taskReferenceText_rim4v_277",K0="_taskReferenceDivider_rim4v_286",Z0="_taskActions_rim4v_293",Y0="_taskMetaCompact_rim4v_318",J0="_taskMetaRow_rim4v_325",X0="_taskMetaBadgeGroup_rim4v_333",Q0="_taskDescription_rim4v_339",eP="_taskLatestComment_rim4v_398",tP="_taskCancellationReason_rim4v_419",nP="_archiveBadge_rim4v_573",aP="_attachmentThumbnails_rim4v_578",rP="_attachmentImageRow_rim4v_585",sP="_attachmentDocumentList_rim4v_592",oP="_attachmentThumbnail_rim4v_578",iP="_contextDocThumb_rim4v_625",cP="_contextDocMain_rim4v_651",lP="_contextDocText_rim4v_658",dP="_contextDocIcon_rim4v_666",uP="_contextDocName_rim4v_677",mP="_contextDocType_rim4v_687",pP="_taskSpecialists_rim4v_699",fP="_taxonomiesList_rim4v_708",Zt={taskItem:N0,compressed:R0,taskHeader:j0,taskReferenceCluster:P0,taskMeta:E0,taskTitle:M0,taskItemRecentlyChanged:D0,assigneeAvatarImage:L0,assigneeAvatarIndicator:B0,assigneeAvatarEmpty:W0,inProgress:F0,onHold:O0,readyForReview:$0,completed:U0,cancelled:q0,archived:z0,taskContent:H0,kanbanCardOverlay:G0,taskReferenceText:V0,taskReferenceDivider:K0,taskActions:Z0,taskMetaCompact:Y0,taskMetaRow:J0,taskMetaBadgeGroup:X0,taskDescription:Q0,taskLatestComment:eP,taskCancellationReason:tP,archiveBadge:nP,attachmentThumbnails:aP,attachmentImageRow:rP,attachmentDocumentList:sP,attachmentThumbnail:oP,contextDocThumb:iP,contextDocMain:cP,contextDocText:lP,contextDocIcon:dP,contextDocName:uP,contextDocType:mP,taskSpecialists:pP,taxonomiesList:fP},Dp=({children:e,className:n,onTaskIdClick:a})=>{if(!e)return null;const s=i=>pt.Children.toArray(i).some(m=>pt.isValidElement(m)?String(m.props?.className||"").includes("task-list-item"):!1),o=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,c=i=>{if(!a)return i;if(typeof i=="string"){const y=Array.from(i.matchAll(o));if(!y.length)return i;const v=[];let b=0;for(let g=0;g<y.length;g+=1){const h=y[g],k=h[1],I=h.index??-1;I<b||(I>b&&v.push(i.slice(b,I)),v.push(t.jsx("button",{type:"button",className:p.taskIdInlineLink,onClick:x=>{x.preventDefault(),x.stopPropagation(),a(k)},children:k},`${k}-${I}-${g}`)),b=I+k.length)}return b<i.length&&v.push(i.slice(b)),v}if(Array.isArray(i))return i.map(c);if(!pt.isValidElement(i))return i;const l=typeof i.type=="string"?i.type:"";if(l==="code"||l==="pre"||l==="a")return i;const m=i.props?.children;return m===void 0?i:pt.cloneElement(i,{},pt.Children.map(m,c))};return t.jsx("div",{className:n,children:t.jsx(Ck,{remarkPlugins:[Ak,Ik],components:{p:({children:i})=>t.jsx("p",{children:c(i)}),ul:({children:i})=>t.jsx("ul",{style:s(i)?{paddingLeft:0}:void 0,children:i}),li:({children:i,className:l})=>{const m=String(l||"").includes("task-list-item");return t.jsx("li",{className:l,style:m?{listStyle:"none"}:void 0,children:c(i)})},input:({type:i,checked:l})=>i!=="checkbox"?t.jsx("input",{type:i,checked:l,readOnly:!0}):t.jsx("input",{type:"checkbox",checked:!!l,readOnly:!0,style:{cursor:"default",marginRight:8}}),code:({children:i,className:l,...m})=>{const y=String(i||"").replace(/\n$/,"");return/language-(\w+)/.test(l||"")||y.includes(`
3
+ `)?t.jsx("pre",{className:p.codeBlock,children:t.jsx("code",{className:l,...m,children:y})}):t.jsx("code",{className:p.inlineCode,...m,children:y})}},children:e})})};function Fg({label:e,title:n,ariaLabel:a,copied:s=!1,disabled:o=!1,className:c="",onClick:i,children:l}){return t.jsxs("button",{type:"button",className:`${p.taskIdBadge} ${s?p.copiedId:""} ${c}`.trim(),onClick:i,disabled:o,title:n,"aria-label":a,children:[s?t.jsx(po,{size:13}):t.jsx(nd,{size:13}),t.jsx("span",{className:p.taskIdBadgeLabel,children:l??e})]})}function qu({copied:e,disabled:n=!1,label:a,onClick:s,title:o="Copy task reference",ariaLabel:c,className:i=""}){return t.jsx(Fg,{copied:e,disabled:n,label:"",onClick:s,title:o,ariaLabel:c,className:i,children:a})}const hP=(e,n=10)=>{const a=tm[e?.toLowerCase()]||{icon:"FileCode"},s=us[a.icon]||Yy;return t.jsx(s,{size:n})},Mu=(e,n)=>{if(!e)return null;if(!n.trim())return e;const a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=e.split(new RegExp(`(${a})`,"gi"));return t.jsx(t.Fragment,{children:s.map((o,c)=>o.toLowerCase()===n.toLowerCase()?t.jsx("mark",{className:p.highlight,children:o},c):o)})};function md(e){return e.trim().replace(/\\/g,"/")}function Og(e){return e.split("?")[0].split("#")[0]}function pm(e){return typeof e=="string"?e:String(e.path||"").trim()}function $g(e){const a=Og(md(e)).match(/\/api\/taskforce\/documents\/([^/]+)\/content$/i);if(!a?.[1])return null;try{return decodeURIComponent(a[1]).trim()||null}catch{return a[1].trim()||null}}function Ug(e){if(!e.includes("/api/taskforce/context-link?path="))return null;try{const a=new URL(e,window.location.origin).searchParams.get("path");return a?md(a):null}catch{return null}}function gP(e,n){const a=(n||(typeof e=="string"?"":e.fsPath||"")).trim();if(a)return md(a);const s=pm(e),o=Ug(s);return o?md(o):null}function yP(e,n){const a=String(typeof e=="string"?"":e.assetId||"").trim();if(a)return a;const s=pm(e);return $g(s)}function kP(e,n){const a=pm(e);return $g(a)?!0:[(n||(typeof e=="string"?"":e.fsPath||"")).trim(),typeof e=="string"?"":String(e.originalFilename||"").trim(),typeof e=="string"?"":String(e.displayName||"").trim(),typeof e=="string"?"":String(e.caption||"").trim(),Ug(a)||"",a].some(o=>{if(!o)return!1;const c=Og(md(o)).toLowerCase();return c.endsWith(".md")||c.endsWith(".markdown")})}function Lp(e,n){const a=pm(e),s=gP(e,n);if(!s||!kP(e,s))return!1;const o=yP(e),c=new CustomEvent("taskforce:open-markdown-document",{detail:{path:a,fsPath:s,...o?{assetId:o}:{}},cancelable:!0});return!window.dispatchEvent(c)}const SP="I-";function qg(e){return gd(SP,e)}function vP(e){return e.trim().replace(/\\/g,"/")}function zg(e){return typeof e=="string"?e:String(e.path||"").trim()}function bP(e){return/\.(png|jpe?g|webp)(\?|#|$)/i.test(e)}function wP(e){return typeof e=="string"?vP(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function Hg(e,n){if(typeof e=="string")return!1;const a=String(e.assetId||"").trim(),s=zg(e);return!!(a&&s&&bP(s))}function Bp(e,n){if(!Hg(e))return!1;const a=e,s=String(n?.taskId||a.taskId||"").trim(),o=String(n?.taskReferenceLabel||"").trim(),c=String(a.assetId||"").trim(),i=qg(a),l=zg(e),m=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...s?{taskId:s}:{},...o?{taskReferenceLabel:o}:{},assetId:c,...i?{imageReferenceLabel:i}:{},path:l,displayName:wP(e)},cancelable:!0});return!window.dispatchEvent(m)}function ih(e,n){if(!e)return null;const a=String(e.taskId||"").trim(),s=String(e.assetId||"").trim(),o=String(e.path||"").trim(),c=String(e.displayName||"").trim()||"Image attachment";if(!s||!o)return null;const i=String(e.taskReferenceLabel||"").trim(),l=a?n.find(y=>y.id===a):void 0,m=a?i||qs(l)||a:void 0;return{...a?{taskId:a}:{},...m?{taskReferenceLabel:m}:{},assetId:s,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,path:o,displayName:c}}function am(e){const n=String(e||"").trim().replace(/\\/g,"/");if(!n)return"";const a=n.split("/").filter(Boolean);return a[a.length-1]||""}function cf(e){const n=String(e||"").trim(),a=n.lastIndexOf(".");return a<=0?{stem:n,ext:""}:{stem:n.slice(0,a),ext:n.slice(a)}}function Gg(e,n){const a=String(e||"").trim(),s=String(n||"").trim();return a?s&&a.startsWith(`${s}-`)?a.slice(s.length+1):a.replace(/^asset-[a-z0-9-]+-/i,""):""}function xP(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function ch(e,n){const{stem:a,ext:s}=cf(am(e)),o=Gg(a,n),c=xP(o||a);return c?`${c}${s}`:am(e)||"Untitled document"}function dp(e,n){const a=String(e||"").trim();if(!a)return!0;const s=am(a),{stem:o}=cf(s),c=String(n||"").trim();if(c&&o.toLowerCase()===c.toLowerCase())return!0;const i=Gg(o,n);return i?i!==o:!0}function _P(e){const n=String(e.logicalName||"").trim();if(n&&!dp(n,e.assetId))return n;const a=String(e.displayName||"").trim();if(a&&!dp(a,e.assetId))return a;const s=String(e.title||"").trim();if(s&&!dp(s,e.assetId))return s;const o=String(e.originalFilename||"").trim();if(o)return ch(o,e.assetId);const c=String(e.fsPath||"").trim();return c?ch(c,e.assetId):"Untitled document"}function CP(e){return _P(e)}function AP(e){const n=CP(e),a=String(e.originalFilename||e.fsPath||"").trim(),s=cf(am(a)).ext;return s?n.toLowerCase().endsWith(s.toLowerCase())?n:`${n}${s}`:n}const IP="_taxonomyDropdown_tt12a_1",TP="_taxonomyDropdownActive_tt12a_6",NP="_taxonomyDropdownButton_tt12a_11",RP="_taxonomyDropdownOpen_tt12a_50",jP="_taxonomyDropdownButtonContent_tt12a_56",PP="_taxonomyDropdownIcon_tt12a_64",EP="_taxonomyDropdownLabel_tt12a_72",MP="_taxonomyDropdownChevron_tt12a_81",DP="_taxonomyDropdownChevronOpen_tt12a_87",LP="_taxonomyDropdownPanel_tt12a_91",BP="_taxonomyDropdownPanelPortal_tt12a_110",WP="_taxonomyDropdownOption_tt12a_129",FP="_taxonomyDropdownOptionHighlighted_tt12a_157",OP="_taxonomyDropdownOptionSelected_tt12a_163",mr={taxonomyDropdown:IP,taxonomyDropdownActive:TP,taxonomyDropdownButton:NP,taxonomyDropdownOpen:RP,taxonomyDropdownButtonContent:jP,taxonomyDropdownIcon:PP,taxonomyDropdownLabel:EP,taxonomyDropdownChevron:MP,taxonomyDropdownChevronOpen:DP,taxonomyDropdownPanel:LP,taxonomyDropdownPanelPortal:BP,taxonomyDropdownOption:WP,taxonomyDropdownOptionHighlighted:FP,taxonomyDropdownOptionSelected:OP};function Ql({value:e,options:n,onChange:a,placeholder:s="Select...",required:o=!1,disabled:c=!1,className:i="",ariaLabelledBy:l,ariaLabel:m,hideSelectedLabel:y=!1,hideChevron:v=!1,panelClassName:b="",portalPanel:g=!1,panelMinWidth:h}){const[k,I]=r.useState(!1),[x,A]=r.useState(-1),[M,B]=r.useState({}),ue=r.useRef(null),X=r.useRef(null),ce=r.useRef(null),oe=n.find(H=>String(H.value)===String(e));r.useEffect(()=>{if(!k)return;const H=P=>{const U=P.target,se=!!ue.current?.contains(U),he=!!ce.current?.contains(U);!se&&!he&&(I(!1),A(-1))};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[k]),r.useEffect(()=>{if(!k)A(-1);else{const H=n.findIndex(P=>String(P.value)===String(e));A(H>=0?H:0)}},[k,n,e]),r.useEffect(()=>{if(!k||!g)return;const H=()=>{const P=X.current;if(!P)return;const U=P.getBoundingClientRect(),se=Math.max(h||0,U.width),he=Math.max(8,U.right-se),V=U.bottom;B({position:"fixed",top:V,left:he,minWidth:se,zIndex:2e3})};return H(),window.addEventListener("resize",H),window.addEventListener("scroll",H,!0),()=>{window.removeEventListener("resize",H),window.removeEventListener("scroll",H,!0)}},[k,g,h]);const be=()=>{c||I(!k)},_=H=>{a(H.value),I(!1),X.current?.focus()},J=H=>{if(!c)switch(H.key){case"Enter":case" ":H.preventDefault(),k?x>=0&&_(n[x]):I(!0);break;case"Escape":H.preventDefault(),I(!1),X.current?.focus();break;case"ArrowDown":H.preventDefault(),k?A(P=>P<n.length-1?P+1:0):I(!0);break;case"ArrowUp":H.preventDefault(),k?A(P=>P>0?P-1:n.length-1):I(!0);break;case"Home":H.preventDefault(),k&&A(0);break;case"End":H.preventDefault(),k&&A(n.length-1);break;case"Tab":I(!1);break}},Q=(H,P)=>{const U=H.icon&&us[H.icon]?us[H.icon]:Ti,se=H.color?Ra(H.color):"var(--text-secondary)",he=P?.hideLabel===!0;return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`taxonomyDropdownIcon ${mr.taxonomyDropdownIcon}`,style:{color:se},children:t.jsx(U,{size:16})}),!he&&t.jsx("span",{className:`taxonomyDropdownLabel ${mr.taxonomyDropdownLabel}`,children:H.label})]})},ie=k?t.jsx("div",{ref:ce,id:`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,className:`taxonomyDropdownPanel ${mr.taxonomyDropdownPanel} ${g?mr.taxonomyDropdownPanelPortal:""} ${b}`,role:"listbox","aria-labelledby":l,"aria-label":m,style:g?M:void 0,children:n.map((H,P)=>{const U=String(H.value)===String(e),se=P===x;return t.jsx("div",{className:`taxonomyDropdownOption ${mr.taxonomyDropdownOption} ${U?`taxonomyDropdownOptionSelected ${mr.taxonomyDropdownOptionSelected}`:""} ${se?`taxonomyDropdownOptionHighlighted ${mr.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":U,onClick:()=>_(H),onMouseEnter:()=>A(P),style:(()=>{const he=H.color,V=Ra(he),Ce=!V||V.startsWith("var("),Se=Ce?"#8b5cf6":V,ve=Ce?"20":"30",ge=Ce?"05":"10";return{"--option-color":V||"var(--text-primary)","--option-border":`${Se}${ve}`,"--option-bg":`${Se}${ge}`}})(),children:Q(H)},String(H.value))})}):null;return t.jsxs("div",{ref:ue,className:`taxonomyDropdown ${mr.taxonomyDropdown} ${k?`taxonomyDropdownActive ${mr.taxonomyDropdownActive}`:""} ${i}`,children:[t.jsxs("button",{ref:X,type:"button",className:`taxonomyDropdownButton ${mr.taxonomyDropdownButton} ${k?`taxonomyDropdownOpen ${mr.taxonomyDropdownOpen}`:""}`,onClick:be,onKeyDown:J,disabled:c,role:"combobox","aria-haspopup":"listbox","aria-expanded":k,"aria-controls":`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,"aria-labelledby":l,"aria-label":m,style:(()=>{if(!oe)return{};const H=oe.color,P=Ra(H),U=!P||P.startsWith("var("),se=U?"#8b5cf6":P,he=U?"30":"50",V=U?"05":"10";return{"--field-color":P||"var(--text-primary)","--field-border":`${se}${he}`,"--field-bg":`${se}${V}`}})(),children:[t.jsx("span",{className:`taxonomyDropdownButtonContent ${mr.taxonomyDropdownButtonContent}`,children:oe?Q(oe,{hideLabel:y}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`taxonomyDropdownIcon ${mr.taxonomyDropdownIcon}`,children:t.jsx(Ti,{size:16})}),t.jsx("span",{className:`taxonomyDropdownLabel ${mr.taxonomyDropdownLabel}`,children:s})]})}),!v&&t.jsx(fd,{size:16,className:`taxonomyDropdownChevron ${mr.taxonomyDropdownChevron} ${k?`taxonomyDropdownChevronOpen ${mr.taxonomyDropdownChevronOpen}`:""}`})]}),g?ie?Ii.createPortal(ie,document.body):null:ie]})}function Vg({task:e,disabled:n=!1,actionDisabled:a,statusDisabled:s,compressed:o=!1,shortLabels:c=!1,showLabel:i=!0,onSetStatus:l,onArchiveTask:m,onUnarchiveTask:y,archiveActionMode:v="auto"}){const b=e?.status||"task",h=v==="auto"?!!e&&(b==="done"||b==="cancelled")?"archive":"none":v,k=a??n,I=s??n,x=Pc.map(A=>({...A,label:(o||c)&&A.shortLabel||A.label}));return t.jsxs("div",{className:`${p.statusActionsGroup} ${o?p.statusActionsGroupCompact:""}`,children:[h==="archive"&&t.jsx("button",{type:"button",className:`${p.actionBtn} ${p.archiveTaskBtn}`,onClick:()=>e&&!k&&m?.(e),disabled:k,title:"Archive Now","aria-label":"Archive task",children:t.jsx(Jy,{size:o?12:16})}),h==="unarchive"&&t.jsx("button",{type:"button",className:`${p.actionBtn} ${p.archiveTaskBtn}`,onClick:()=>e&&!k&&y?.(e),disabled:k,title:"Unarchive task","aria-label":"Unarchive task",children:t.jsx(cd,{size:o?12:16})}),t.jsx("div",{className:`${p.statusSelectWrap} ${p.statusTaxonomyDropdownWrap}`,children:t.jsx(Ql,{value:b,options:x,disabled:I||!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:A=>{e&&l?.(e,A)}})})]})}function $P(e){return e==="title"?"Title":e==="description"?"Description":e==="assignee"?"Assigned to":e==="status"?"Status":e==="scheduledDate"?"Scheduled date":e==="dueDate"?"Due date":e==="workstreamId"?"Workstream":e==="initiativeId"?"Initiative":e}function UP(e){return e==="task"?"Task":e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,n=>n.toUpperCase())}function _r(e,n,a){const s=a?.(n,e);if(typeof s=="string")return s;if(e==null||e==="")return"none";if(Array.isArray(e)){const o=e.map(c=>_r(c,n,a)).filter(Boolean);return o.length>0?o.join(", "):"none"}return typeof e=="object"?"updated":n==="status"?UP(String(e)):String(e)}function lh(e){return Array.isArray(e)?e.map((n,a)=>{const s=n&&typeof n=="object"?n:{},o=Number(s.order);return{id:String(s.id||"").trim(),title:String(s.title||"").trim(),isCompleted:!!s.isCompleted,order:Number.isFinite(o)?o:a}}):[]}function qP(e){const n=lh(e?.from),a=lh(e?.to),s=new Map(n.map(i=>[i.id||i.title,i])),o=new Map(a.map(i=>[i.id||i.title,i]));for(const[i,l]of o.entries()){const m=s.get(i);if(!m)return l.title?`Checklist item added: ${l.title}`:"Checklist item added";if(m.isCompleted!==l.isCompleted)return l.title?l.isCompleted?`Checklist item completed: ${l.title}`:`Checklist item reopened: ${l.title}`:l.isCompleted?"Checklist item completed":"Checklist item reopened"}for(const[i,l]of s.entries())if(!o.has(i))return l.title?`Checklist item removed: ${l.title}`:"Checklist item removed";return n.length===a.length&&n.every(i=>o.has(i.id||i.title))&&n.some((l,m)=>{const y=a[m];return(l.id||l.title)!==(y?.id||y?.title)})?"Checklist reordered":"Checklist updated"}function lf(e){return e.split(/[?#]/,1)[0]||e}function dh(e){const n=lf(e).replace(/\\/g,"/"),a=n.split("/").filter(Boolean);return a[a.length-1]||n}function zP(e){return/\.(png|jpe?g|webp|gif)$/i.test(lf(e))}function HP(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(lf(e))}function uh(e){return Array.isArray(e)?e.flatMap((n,a)=>{const s=n&&typeof n=="object"?n:null,o=typeof n=="string"?n:String(s?.path||"").trim(),c=String(s?.fsPath||"").trim(),i=String(s?.assetId||"").trim(),l=String(s?.referenceLabel||"").trim(),m=[s?.displayName,s?.originalFilename,s?.caption,l,c?dh(c):"",o?dh(o):""].map(g=>String(g||"").trim()).find(Boolean)||`Attachment ${a+1}`,y=i||c||o||`${m}:${a}`,v=[o,c,String(s?.originalFilename||"").trim(),String(s?.displayName||"").trim(),l].filter(Boolean),b=v.some(g=>zP(g))?"image":l.startsWith("D-")||v.some(g=>HP(g))?"document":"attachment";return[{key:y,label:m,kind:b}]}):[]}function GP(e,n){return n===1?e:e==="image"?"images":e==="document"?"documents":"attachments"}function Du(e){if(e.length===0)return"attachments";const n=e.reduce((s,o)=>(s[o.kind]+=1,s),{image:0,document:0,attachment:0}),a=Object.entries(n).filter(([,s])=>s>0).map(([s,o])=>o===1?s:`${o} ${GP(s,o)}`);return a.length===1?a[0]:e.length<=3&&a.length<=2?a.join(" and "):`${e.length} attachments`}function bi(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function VP(e){const n=uh(e?.from),a=uh(e?.to),s=new Map(n.map(m=>[m.key,m])),o=new Map(a.map(m=>[m.key,m])),c=a.filter(m=>!s.has(m.key)),i=n.filter(m=>!o.has(m.key));if(c.length===1&&i.length===0)return`${bi(c[0].kind)} attached: ${c[0].label}`;if(i.length===1&&c.length===0)return`${bi(i[0].kind)} removed: ${i[0].label}`;if(c.length>0&&i.length===0)return`${bi(Du(c))} attached`;if(i.length>0&&c.length===0)return`${bi(Du(i))} removed`;if(c.length===1&&i.length===1)return`${bi(c[0].kind)} replaced: ${i[0].label} -> ${c[0].label}`;if(c.length>0||i.length>0)return`${bi(Du(c))} attached, ${Du(i)} removed`;const l=a.filter(m=>{const y=s.get(m.key);return y&&y.label!==m.label});if(l.length===1&&n.length===1&&a.length===1){const m=s.get(l[0].key);return`${bi(l[0].kind)} renamed: ${m?.label||"Attachment"} -> ${l[0].label}`}return"Attachment details updated"}function Wp(e,n,a){if(e==="checklistItems")return qP(n);if(e==="attachments")return VP(n);const s=$P(e);if(e==="title")return`${s}: updated`;if(e==="description"){const o=_r(n?.from,e,a)!=="none",c=_r(n?.to,e,a)!=="none";return!o&&c?`${s}: added`:o&&!c?`${s}: cleared`:`${s}: updated`}return`${s}: ${_r(n?.from,e,a)} -> ${_r(n?.to,e,a)}`}function Kg(e,n){const a=e.details?.changes||{},s=Object.keys(a);if(e.action==="task-created")return"Task created";if(e.action==="task-comment-added")return"Comment added";if(e.action==="task-archived")return"Task marked done";if(e.action==="task-cancelled")return"Task cancelled";if(e.action==="task-unarchived")return"Task restored";if(e.action==="task-status-changed"&&a.status)return`Status changed: ${_r(a.status.from,"status",n)} -> ${_r(a.status.to,"status",n)}`;if(e.action==="task-schedule-changed")return a.scheduledDate?`Scheduled date changed: ${_r(a.scheduledDate.from,"scheduledDate",n)} -> ${_r(a.scheduledDate.to,"scheduledDate",n)}`:a.dueDate?`Due date changed: ${_r(a.dueDate.from,"dueDate",n)} -> ${_r(a.dueDate.to,"dueDate",n)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&a.workstreamId)return`Workstream changed: ${_r(a.workstreamId.from,"workstreamId",n)} -> ${_r(a.workstreamId.to,"workstreamId",n)}`;if(e.action==="task-relationship-changed"&&a.initiativeId)return`Initiative changed: ${_r(a.initiativeId.from,"initiativeId",n)} -> ${_r(a.initiativeId.to,"initiativeId",n)}`;if(e.action==="task-attachments-changed")return a.attachments?Wp("attachments",a.attachments,n):"Attachments updated";if(s.length===1){const o=s[0],c=a[o];return Wp(o,c,n)}return s.length>1?`${s.length} fields updated`:"Task updated"}function rm(e){const n=Date.parse(String(e.timestamp||""));return Number.isFinite(n)?n:null}function KP(e){const n=e.details?.changes||{},a=Object.keys(n);if(e.action==="task-status-changed"&&n.status)return"status";if(e.action==="task-schedule-changed"){if(n.scheduledDate)return"scheduledDate";if(n.dueDate)return"dueDate"}if(e.action==="task-relationship-changed"){if(n.workstreamId)return"workstreamId";if(n.initiativeId)return"initiativeId"}return e.action==="task-attachments-changed"&&n.attachments?"attachments":a.length===1?a[0]:null}function df(e){const n=new Map,a=new Set,s=o=>{if(o.type==="event"&&o.event.action==="task-comment-added")return;const c=o.type==="comment"?`comment:${String(o.comment.id||o.id).replace(/^comment:/,"")}`:`event:${String(o.event.id||o.id).replace(/^event:/,"")}`;n.set(c,{...o,id:c}),o.type==="comment"&&a.add(String(o.comment.id||o.id).replace(/^comment:/,""))};return Array.isArray(e.activity)&&e.activity.forEach(s),Array.isArray(e.comments)&&e.comments.forEach(o=>{const c=String(o.id||"").trim();!c||a.has(c)||s({id:`comment:${c}`,type:"comment",timestamp:o.timestamp,comment:o})}),[...n.values()].sort((o,c)=>{const i=rm(o),l=rm(c);return i!==null&&l!==null&&i!==l?i-l:i!==null&&l===null?-1:i===null&&l!==null?1:String(o.id||"").localeCompare(String(c.id||""))})}function ZP(e){const n=df(e);return n.length===0?null:[...n].sort((a,s)=>{const o=rm(a),c=rm(s);return o!==null&&c!==null&&o!==c?c-o:o!==null&&c===null?-1:o===null&&c!==null?1:String(s.id||"").localeCompare(String(a.id||""))})[0]||null}function YP(e,n){return e?e.type==="comment"?e.comment.text:Kg(e.event,n):""}const{MessageSquare:JP,User:XP,Bot:QP,Gauge:eE,ClipboardList:tE,HelpCircle:nE,File:aE}=us,rE=({task:e,searchQuery:n="",copiedId:a=null,taxonomies:s=[],types:o=[],priorities:c=[],categories:i=[],assigneeOptions:l=[],taskWorkstream:m=null,taskInitiative:y=null,isOverlay:v=!1,isArchived:b=!1,readOnlyMode:g=null,isRecentlyChanged:h=!1,onClick:k,onCopyId:I,onToggleInProgress:x,onToggleReview:A,onToggleComplete:M,onToggleCancel:B,onSetStatus:ue,onArchiveTask:X,onUnarchive:ce,onDelete:oe,deleteActionTitle:be,onOpenTaskById:_,compressed:J=!1,showStatusLabel:Q=!0})=>{const ie=cg(e),H=ie.label||(ie.isProvisional?"Pending":""),P=ie.isProvisional,U=!!ie.label,se=em(m)||m?.id||"",he=Dg(y)||y?.id||"",V=c.find(ne=>String(ne.value)===String(e.priority)),Ce=V?V.label.toLowerCase().replace(/\s+/g,"-"):String(e.priority),Se=i.find(ne=>ne.value===e.category||ne.label===e.category),ve=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),ge=Number.isFinite(ve)?Math.max(1,Math.min(5,Math.round(ve))):3,Te={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},Le={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},Ie=Te[ge],Oe=`var(--complexity-${Le[ge]})`,z=rS(e.priority,Ce),T=!!p[`priorityItem_${z}`],w=Xu(e.assignee),j=ad(e.assignee,l),F=pt.useMemo(()=>{const ne=String(e.assignee||"").trim();return l.find(tt=>String(tt.value||"").trim()===ne)||null},[l,e.assignee]),ee=w!=="unassigned"&&typeof F?.avatarUrl=="string"?F.avatarUrl.trim():"",N=w==="agent"?"var(--color-violet-500, #8b5cf6)":w==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",C=pt.useMemo(()=>ZP(e),[e]),$=g||(e.isDeleted?"deleted":b?"archived":null),K=$!==null,te=pt.useCallback((ne,tt)=>{const rt=String(tt||"").trim();if(rt){if(ne==="assignee")return ad(rt,l);if(ne==="workstreamId"&&rt===m?.id)return se||m.id;if(ne==="initiativeId"&&rt===y?.id)return he||y.id}},[l,he,y,m,se]),L=pt.useMemo(()=>YP(C,te),[te,C]),re=pt.useMemo(()=>df(e).length,[e]),fe=[Zt.taskItem,e.status==="on-hold"?Zt.onHold:"",e.status==="in-progress"?Zt.inProgress:"",e.status==="review"?Zt.readyForReview:"",e.status==="done"?Zt.completed:"",e.status==="cancelled"?Zt.cancelled:"",h?Zt.taskItemRecentlyChanged:"",p[`priorityItem_${z}`]||"",v?Zt.kanbanCardOverlay:"",b?Zt.archived:"",J?Zt.compressed:""].filter(Boolean).join(" "),xe=Ra(V?.color),le=o.find(ne=>ne.value===e.type),we=Ra(le?.color)||Mb(e.type),Re=ne=>{const tt=typeof ne=="string"?ne:ne.path,rt=typeof ne=="string"?"":(ne.fsPath||"").trim(),Pt=typeof ne=="string"?"":(ne.displayName||"").trim(),yt=typeof ne=="string"?"":(ne.originalFilename||"").trim(),Rt=typeof ne=="string"?"":(ne.caption||"").trim();return[rt,yt,Pt,Rt,tt].some(Dt=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(Dt))},Xe=ne=>{const tt=typeof ne=="string"?ne:ne.path,rt=tt.includes("/api/taskforce/documents/"),Pt=typeof ne=="string"?"":(ne.displayName||"").trim();if(rt&&typeof ne!="string")return AP({displayName:ne.displayName,originalFilename:ne.originalFilename,fsPath:ne.fsPath,assetId:ne.assetId||null});const yt=typeof ne=="string"?"":(ne.caption||"").trim();if(yt)return yt;if(Pt)return Pt;const Rt=typeof ne=="string"?"":(ne.originalFilename||"").trim();return Rt||tt.split("?")[0].split("#")[0].split("/").pop()||"Context file"},ze=ne=>{const tt=typeof ne=="string"?ne:ne.path,rt=typeof ne=="string"?"":(ne.fsPath||"").trim(),Pt=typeof ne=="string"?"":(ne.caption||"").trim(),yt=typeof ne=="string"?"":(ne.originalFilename||"").trim(),Rt=[];if(rt&&Rt.push(rt),yt&&Rt.push(yt),Pt&&Rt.push(Pt),tt.includes("/api/taskforce/context-link?path="))try{const Dt=new URL(tt,"http://localhost").searchParams.get("path");Dt&&Rt.push(Dt)}catch{}Rt.push(tt);for(const Tt of Rt){const d=Tt.split("?")[0].split("#")[0].split("/").pop()||"",Me=d.lastIndexOf(".");if(Me<=0||Me===d.length-1)continue;const We=d.slice(Me+1);if(We)return We.slice(0,5).toUpperCase()}return"FILE"},lt={"--task-change-glow-color":xe||`var(--priority-${z})`,...xe?{borderLeftColor:xe,[`--priority-${z}`]:xe}:{},...!T&&xe?{borderLeft:`4px solid ${xe}`}:{}},wt=ne=>ne.replace(/\b\w/g,tt=>tt.toUpperCase()),$e=kd(s,[e]),ft=e.checklistItems||[],gt=ft.length,at=gt>0?ft.filter(ne=>ne.isCompleted).length:0,dt=(ne,tt)=>{ne.stopPropagation(),I?.(ne,tt)};return t.jsxs("div",{className:fe,onClick:()=>k?.(e),style:lt,"data-task-card":"true",children:[t.jsxs("div",{className:Zt.taskHeader,children:[t.jsxs("div",{className:Zt.taskReferenceCluster,children:[y?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:Zt.taskReferenceText,children:he}),t.jsx("span",{className:Zt.taskReferenceDivider,children:"/"})]}):null,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:Zt.taskReferenceText,children:se}),t.jsx("span",{className:Zt.taskReferenceDivider,children:"/"})]}):null,H?t.jsx(qu,{copied:U&&a===ie.label,onClick:ne=>dt(ne,ie.label),disabled:!U,title:U?"Copy task reference":"Task reference pending sync",className:b?Zt.archiveBadge:"",label:Mu(H,n)}):null,P?t.jsx("span",{className:p.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),t.jsx("div",{className:Zt.taskActions,onClick:ne=>ne.stopPropagation(),children:K?ce||oe?t.jsxs(t.Fragment,{children:[ce&&t.jsx("button",{type:"button",className:p.actionBtn,onClick:()=>ce(e.id),title:$==="deleted"?"Restore deleted task":"Restore archived task",children:t.jsx(cd,{size:16})}),oe&&t.jsx("button",{type:"button",className:`${p.actionBtn} ${p.deleteBtn}`,onClick:()=>oe(e.id),title:be||($==="deleted"?"Delete Permanently":"Move to Trash"),children:t.jsx(Bc,{size:16})})]}):null:t.jsx(Vg,{task:e,compressed:J,shortLabels:!0,showLabel:Q,onSetStatus:(ne,tt)=>{if(ue){ue(ne,tt);return}if(tt==="in-progress"){x?.(ne);return}if(tt==="review"){A?.(ne);return}if(tt==="done"){M?.(ne);return}tt==="cancelled"&&B?.(ne)},onArchiveTask:X})})]}),t.jsxs("div",{className:Zt.taskContent,children:[K&&t.jsx("div",{className:`${Zt.taskMeta} ${Zt.taskMetaCompact}`}),t.jsxs("div",{children:[t.jsxs("div",{className:Zt.taskTitle,style:J?{fontSize:"13px",lineHeight:"1.4"}:{},children:[$==="archived"&&"✓ ",$==="deleted"&&"Deleted: ",Mu(e.title,n)]}),e.description&&!K&&!J&&t.jsx("div",{className:Zt.taskDescription,children:t.jsx(Dp,{onTaskIdClick:_,children:e.description})})]}),e.attachments&&e.attachments.length>0&&!K&&!J&&t.jsxs("div",{className:Zt.attachmentThumbnails,children:[t.jsx("div",{className:Zt.attachmentImageRow,children:(e.attachments||[]).map((ne,tt)=>{const rt=typeof ne=="string"?ne:ne.path;return Re(ne)?t.jsx("div",{className:Zt.attachmentThumbnail,onClick:Pt=>{Pt.stopPropagation(),!Bp(typeof ne=="string"?{path:rt}:ne,{taskId:e.id,taskReferenceLabel:H})&&window.open(rt,"_blank")},children:t.jsx("img",{src:rt,alt:`Attachment ${tt}`})},tt):null})}),t.jsx("div",{className:Zt.attachmentDocumentList,children:(e.attachments||[]).map((ne,tt)=>{const rt=typeof ne=="string"?ne:ne.path,Pt=typeof ne=="string"?void 0:ne.fsPath,yt=Xe(ne);if(Re(ne))return null;const Rt=ze(ne);return t.jsxs("button",{type:"button",className:Zt.contextDocThumb,onClick:Tt=>{Tt.stopPropagation(),!Lp(ne,Pt)&&window.open(rt,"_blank")},title:yt,style:{"--context-doc-accent":Db(Rt)},children:[t.jsxs("span",{className:Zt.contextDocMain,children:[t.jsx("span",{className:Zt.contextDocIcon,"aria-hidden":"true",children:t.jsx(aE,{size:13})}),t.jsx("span",{className:Zt.contextDocText,children:t.jsx("span",{className:Zt.contextDocName,children:yt})})]}),t.jsx("span",{className:Zt.contextDocType,children:Rt})]},tt)})})]}),e.status==="cancelled"&&e.canceledReason&&!J&&t.jsxs("div",{className:Zt.taskCancellationReason,children:[t.jsx("strong",{children:"Cancellation Reason:"})," ",Mu(e.canceledReason,n)]}),L&&!K&&!J&&t.jsxs("div",{className:Zt.taskLatestComment,children:[t.jsx("strong",{children:"Latest Activity:"})," ",Mu(L.length>120?L.substring(0,120)+"...":L,n)]}),!K&&$e.length>0&&!J&&t.jsx("div",{className:`${Zt.taskSpecialists} ${Zt.taxonomiesList}`,children:$e.map(ne=>{const tt=e.taxonomies?.[ne.id];return tt?(Array.isArray(tt)?tt:[tt]).map(Pt=>{const yt=ne.options.find(Me=>Me.value===Pt);if(!yt)return null;const Rt=us[yt.icon||"Layers"]||bp,Tt=Ra(yt.color)||"var(--text-primary)",Dt=ne.status==="retired"?`${ne.label} (Retired)`:ne.label,d=yt.status==="retired"?`${yt.label} (Retired)`:yt.label;return t.jsx("span",{className:p.specialistBadge,style:{borderColor:`${Tt}50`,backgroundColor:`${Tt}15`,color:Tt},title:`${Dt}: ${wt(d)}`,children:t.jsx(Rt,{size:10})},`${ne.id}-${Pt}`)}):null})}),t.jsx("div",{className:Zt.taskMeta,children:K?t.jsx("span",{children:e.category}):t.jsx(t.Fragment,{children:t.jsxs("div",{className:Zt.taskMetaRow,style:J?{marginBottom:0}:void 0,children:[t.jsxs("div",{className:Zt.taskMetaBadgeGroup,children:[(()=>{const ne=Ra(Se?.color),tt=Se?.icon||"Folder",rt=us[tt]||Ni;return t.jsx("span",{className:p.metaBadge,title:wt(e.category),style:{color:ne||"var(--text-secondary)",backgroundColor:ne?`${ne}15`:"var(--bg-tertiary)",borderColor:ne?`${ne}40`:"transparent"},children:t.jsx(rt,{size:14})})})(),t.jsx("span",{className:`${p.metaBadge} ${p[`type_${e.type}`]||""}`,title:wt(e.type||Mr),style:{color:`var(--type-color, ${we})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${we}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${we}), transparent 75%)`},children:le?.icon?(()=>{const ne=us[le.icon]||nE;return t.jsx(ne,{size:14})})():hP(e.type,14)}),V&&t.jsx("span",{className:p.metaBadge,style:{color:xe||"var(--text-secondary)",backgroundColor:xe?`${xe}15`:"var(--bg-tertiary)",borderColor:xe?`${xe}40`:"var(--border-color)"},title:`${V.label}`,children:(()=>{const ne=V.icon||"AlertCircle",tt=us[ne]||Xy;return t.jsx(tt,{size:14})})()}),re>0&&t.jsxs("span",{className:p.metaBadge,title:`${re} activity items`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[t.jsx(JP,{size:14}),t.jsx("span",{children:re})]}),gt>0&&t.jsxs("span",{className:p.metaBadge,title:`${at}/${gt} checklist items complete`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[t.jsx(tE,{size:14}),t.jsx("span",{children:`${at}/${gt}`})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsxs("span",{className:p.metaBadge,title:`AI-estimated complexity: ${Ie} (${ge}/5)`,style:{color:Oe,backgroundColor:`color-mix(in srgb, ${Oe}, transparent 88%)`,borderColor:`color-mix(in srgb, ${Oe}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[t.jsx(eE,{size:14}),!J&&t.jsx("span",{children:Ie})]}),t.jsx("span",{className:`${Zt.assigneeAvatarIndicator} ${w==="unassigned"?Zt.assigneeAvatarEmpty:""}`,title:`Assigned to: ${j}`,"aria-label":w==="unassigned"?"Unassigned":`Assigned to ${j}`,style:{"--assignee-avatar-color":N},children:ee?t.jsx("img",{src:ee,alt:"",className:Zt.assigneeAvatarImage}):w==="agent"?t.jsx(QP,{size:J?18:20}):w==="member"?t.jsx(XP,{size:J?18:20}):null})]})]})})})]})]})},pd=pt.memo(rE),sm="168px";function Zg(){return t.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:He("standalone.filtersCaps")})}function Ai({label:e,options:n,selected:a,onChange:s,variant:o="label"}){return t.jsx(xi,{label:e,options:n,selected:a,onChange:s,variant:o,containerStyle:{flex:`0 0 ${sm}`,maxWidth:sm}})}function Yg({onClick:e}){return t.jsxs("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[t.jsx(Ei,{size:12})," ",He("standalone.clearFilters")]})}function mh({label:e,options:n,selected:a,onChange:s,allLabel:o,title:c}){const[i,l]=pt.useState(!1),m=pt.useRef(null),y=n.find(g=>g.value===a),v=y?.selectedLabel||y?.label||o;pt.useEffect(()=>{const g=h=>{m.current&&!m.current.contains(h.target)&&l(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const b=g=>{s(g),l(!1)};return t.jsxs("div",{className:p.filterContainer,ref:m,style:{flex:`0 0 ${sm}`,maxWidth:sm},children:[t.jsxs("button",{type:"button",className:`${p.filterButton} ${a?p.filterActive:""}`,onClick:()=>l(g=>!g),title:c||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":i,children:[t.jsx("span",{children:v}),t.jsx(fd,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&t.jsxs("div",{className:`${p.filterDropdown} ${p.appScrollbar} tf-scrollbar`,role:"listbox","aria-label":e,children:[t.jsxs("button",{type:"button",className:p.filterOption,onClick:()=>b(""),"aria-selected":!a,children:[t.jsx(po,{size:14,style:{opacity:a?0:1}}),t.jsx("span",{style:{fontWeight:a?500:600},children:o})]}),t.jsx("div",{className:p.filterDivider}),n.map(g=>{const h=g.value===a;return t.jsxs("button",{type:"button",className:p.filterOption,onClick:()=>b(g.value),"aria-selected":h,children:[t.jsx(po,{size:14,style:{opacity:h?1:0}}),t.jsx("span",{style:{fontWeight:h?600:500},children:g.label})]},g.value)})]})]})}function Jg({scope:e,onScopeChange:n,className:a,labelClassName:s}){return t.jsxs("div",{className:a,children:[t.jsx("span",{className:s,children:"Scope"}),t.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 c=e===o.value;return t.jsx("button",{type:"button",className:`${p.taskScopeTab} ${c?p.taskScopeTabActive:""}`,onClick:()=>n(o.value),role:"tab","aria-selected":c,"aria-pressed":c,title:`Show ${o.label.toLowerCase()} tasks`,children:o.label},o.value)})})]})}function Xg({onClick:e,disabled:n=!1,className:a,title:s="Permanently delete all deleted tasks",children:o="Delete All Permanently"}){return t.jsxs("button",{type:"button",className:a,onClick:e,disabled:n,title:s,children:[t.jsx(Bc,{size:14}),o]})}const{Search:ph,ClipboardList:sE,ChevronRight:oE,ChevronDown:iE,Folder:cE,Archive:lE,RotateCcw:dE,X:uE,Plus:mE,ArrowUpDown:pE,Trash2:fE}=us,Qg=r.forwardRef((e,n)=>{const{tasks:a,archivedTasks:s,categories:o,types:c,priorities:i,taxonomyDisplayLabels:l,assigneeOptions:m=[],workstreams:y=[],initiatives:v=[],searchQuery:b,filterCategories:g,filterTypes:h,filterPriorities:k,filterStatus:I,filterAssignees:x=[],filterTaxonomies:A,sortBy:M,sortOrder:B,showArchive:ue,taskScope:X,collapsedCategories:ce,loadingTasks:oe,filteredTasks:be,filteredArchive:_,groupedTasks:J,filteredDeletedTasks:Q=[],groupedDeletedTasks:ie={},copiedId:H,recentlyChangedTaskIds:P=[],showTaskCardStatusLabel:U=!0,onSearchChange:se,onFilterCategoriesChange:he,onFilterTypesChange:V,onFilterPrioritiesChange:Ce,onFilterStatusChange:Se,onFilterAssigneesChange:ve,onTaxonomyFilterChange:ge,onSortByChange:Te,onSortOrderChange:Le,onShowArchiveChange:Ie,onTaskScopeChange:Oe,onClearFilters:z,onToggleCategory:T,onEditTask:w,onOpenTaskById:j,onCopyId:F,onToggleInProgress:ee,onToggleReview:N,onToggleComplete:C,onToggleCancel:$,onSetStatus:K,onArchiveTask:te,onBulkArchive:L,onUnarchive:re,onDelete:fe,onDeleteAllDeleted:xe,onFetchArchive:le,onAddTaskToCategory:we,supplementalTasks:Re=[],taxonomies:Xe}=e,ze=new Set(P),lt=pt.useMemo(()=>new Map(y.map(de=>[de.id,de])),[y]),wt=pt.useMemo(()=>new Map(v.map(de=>[de.id,de])),[v]),$e=pt.useCallback(de=>{const Be=de.workstreamId&&lt.get(de.workstreamId)||null,St=Be?.initiativeId&&wt.get(Be.initiativeId)||null;return{taskWorkstream:Be,taskInitiative:St}},[wt,lt]),ft=[...a,...s,...Re],gt=!!Oe,at=Oe,dt=X??(ue?"archived":"open"),ne=gt?dt==="archived"?_:dt==="deleted"?Q:be:be,tt=gt?dt==="archived"?{Archived:_}:dt==="deleted"?ie:J:J,rt=gt?dt==="deleted"?"deleted":dt==="archived"?"archived":null:null,Pt=b?He("taskList.noMatchingTasks"):dt==="archived"?"No archived tasks found.":dt==="deleted"?"No deleted tasks found.":He("taskList.noActiveTasks"),yt=o.filter(de=>!de.disabled),Rt=o.filter(de=>de.disabled&&ft.some(Be=>Be.category===de.value)),Tt=[...yt,...Rt.filter(de=>!yt.some(Be=>Be.value===de.value))].map(de=>({value:de.value,label:de.disabled?`${de.label} (Legacy)`:de.label})),Dt=c.filter(de=>de.status!=="retired"),d=c.filter(de=>de.status==="retired"&&ft.some(Be=>Be.type===de.value)),Me=[...Dt,...d.filter(de=>!Dt.some(Be=>Be.value===de.value))].map(de=>({value:de.value,label:de.status==="retired"?`${de.label} (Retired)`:de.label})),Qe=kd(Xe,ft).filter(de=>de.filterEnabled!==!1).map(de=>({...de,options:of(de,ft)})),ot=pt.useMemo(()=>[{value:"created",label:He("taskList.sortCreated")},{value:"updated",label:He("taskList.sortUpdated")},{value:"priority",label:He("taskList.sortPriority")},...Wg(Xe,ft)],[ft,He,Xe]);return t.jsxs("div",{className:p.viewTab,ref:n,children:[t.jsxs("div",{className:p.filterBar,children:[t.jsxs("div",{className:p.searchContainer,children:[t.jsx(ph,{size:16,className:p.searchIcon}),t.jsx("input",{type:"text",className:p.searchInput,placeholder:He("taskList.searchPlaceholder"),value:b,onChange:de=>se(de.target.value)}),b&&t.jsx("button",{className:p.clearSearchBtn,onClick:()=>se(""),title:He("taskList.clearSearchTitle"),children:t.jsx(uE,{size:14})})]}),t.jsxs("div",{className:p.filterRow,children:[t.jsx(xi,{label:l?.category||He("taskList.categoryLabel"),options:Tt,selected:g,onChange:he,variant:"value"}),t.jsx(xi,{label:l?.type||He("taskList.typeLabel"),options:Me,selected:h,onChange:V,variant:"value"})]}),t.jsxs("div",{className:p.filterRow,children:[t.jsx(xi,{label:l?.priority||He("taskList.priorityLabel"),options:i,selected:k,onChange:Ce,variant:"value"}),t.jsx(xi,{label:He("taskList.statusLabel"),options:mo,selected:I,onChange:Se,variant:"value"}),t.jsx(xi,{label:He("taskList.assigneeLabel"),options:m,selected:x,onChange:de=>ve?.(de),variant:"value"})]}),Qe.map(de=>t.jsx(xi,{label:de.status==="retired"?`${de.label} (Retired)`:de.label,options:de.options.map(Be=>({...Be,label:Be.status==="retired"?`${Be.label} (Retired)`:Be.label})),selected:A[de.id]||[],onChange:Be=>ge(de.id,Be),variant:"value"},de.id)),t.jsxs("div",{className:p.filterRow,children:[t.jsxs("div",{className:p.sortLabel,children:[t.jsx(pE,{size:14,style:{marginRight:"4px"}})," ",He("taskList.sortByLabel")]}),t.jsx("select",{value:M,onChange:de=>Te(de.target.value),className:`${p.filterSelect} ${p.filterSelectSort} `,children:ot.map(de=>t.jsx("option",{value:de.value,children:de.label},de.value))}),t.jsx("button",{className:`${p.resetFiltersBtn} ${p.sortDirectionBtnWidget}`,onClick:Le,title:He(B==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:B==="desc"?t.jsx($h,{size:14}):t.jsx(Uh,{size:14})}),t.jsx("button",{className:p.resetFiltersBtn,onClick:z,title:He("taskList.resetFiltersTitle"),children:t.jsx(dE,{size:14})})]}),t.jsxs("div",{className:`${p.filterRow} ${p.archiveRow} `,children:[dt==="open"?t.jsxs("button",{className:`${p.bulkArchiveBtn} ${a.some(de=>de.status==="done"||de.status==="cancelled")?"":p.disabledBtn} `,onClick:()=>a.some(de=>de.status==="done"||de.status==="cancelled")&&L(),disabled:!a.some(de=>de.status==="done"||de.status==="cancelled"),title:a.some(de=>de.status==="done"||de.status==="cancelled")?He("taskList.archiveAllTitle"):He("taskList.noTasksToArchiveTitle"),children:[t.jsx(lE,{size:12}),t.jsx("span",{children:He("taskList.archiveFinished")})]}):dt==="deleted"&&xe?t.jsx(Xg,{className:`${p.bulkArchiveBtn} ${p.taskToolbarAction} ${p.bulkDeleteBtn} ${Q.length===0?p.disabledBtn:""}`,onClick:()=>Q.length>0&&xe(),disabled:Q.length===0,title:Q.length>0?"Empty trash":"Trash is already empty",children:"Empty Trash"}):t.jsx("div",{}),gt?t.jsx(Jg,{scope:dt,onScopeChange:de=>{at?.(de),de==="archived"?(Ie(!0),le()):ue&&Ie(!1)},className:`${p.archiveToggle} ${p.taskScopeToggle}`}):t.jsxs("label",{className:p.archiveToggle,children:[t.jsx("input",{type:"checkbox","aria-label":"Archived",checked:ue,onChange:de=>{Ie(de.target.checked),de.target.checked&&le()}}),t.jsx("span",{children:"Include Archive"})]})]})]}),oe&&a.length===0?t.jsx("div",{className:p.loading,children:t.jsx(Va,{size:24,className:p.spinner})}):ne.length===0&&!oe?t.jsxs("div",{className:p.emptyState,children:[b?t.jsx(ph,{size:48}):dt==="deleted"?t.jsx(fE,{size:48}):t.jsx(sE,{size:48}),t.jsx("p",{children:Pt})]}):t.jsx("div",{className:p.taskList,style:{opacity:oe?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(tt).map(([de,Be])=>{if(Be.length===0)return null;const St=ce[de];return t.jsxs("div",{className:p.categoryGroup,children:[t.jsx("div",{className:p.categoryHeader,onClick:()=>T(de),children:t.jsxs("div",{className:p.categoryTitle,children:[St?t.jsx(oE,{size:16}):t.jsx(iE,{size:16}),(()=>{const vt=o.find(en=>en.label===de),$t=vt?.icon&&Uc[vt.icon]?Uc[vt.icon]:cE,Ze=Ra(vt?.color)||"var(--color-purple, #8b5cf6)";return t.jsx($t,{size:16,className:p.categoryTitleIcon,style:{color:Ze}})})(),de,t.jsxs("span",{className:p.categoryCount,children:["(",Be.length,")"]}),we&&t.jsx("button",{className:p.kanbanQuickAdd,onClick:vt=>{vt.stopPropagation(),we(de)},title:He("taskList.addTaskToCategoryTitle",{category:de}),style:{marginLeft:"auto"},disabled:rt!==null,children:t.jsx(mE,{size:14})})]})}),!St&&t.jsx("div",{className:p.categoryItems,children:Be.map(vt=>(()=>{const{taskWorkstream:$t,taskInitiative:Ze}=$e(vt);return t.jsx(pd,{task:vt,taskWorkstream:$t,taskInitiative:Ze,searchQuery:b,copiedId:H,taxonomies:Xe,types:c,priorities:i,assigneeOptions:m,onClick:w,onOpenTaskById:j,onCopyId:F,onToggleInProgress:ee,onToggleReview:N,onToggleComplete:C,onToggleCancel:$,onSetStatus:K,onArchiveTask:te,onUnarchive:rt?re:void 0,onDelete:rt?fe:void 0,categories:o,isRecentlyChanged:ze.has(vt.id),readOnlyMode:rt,showStatusLabel:U},vt.id)})())})]},de)})}),!gt&&ue&&_.length>0&&t.jsxs("div",{className:p.archiveList,children:[t.jsx("div",{className:p.archiveHeader,children:"Archived"}),_.map(de=>(()=>{const{taskWorkstream:Be,taskInitiative:St}=$e(de);return t.jsx(pd,{task:de,taskWorkstream:Be,taskInitiative:St,searchQuery:b,copiedId:H,isArchived:!0,types:c,assigneeOptions:m,onClick:w,onCopyId:F,onSetStatus:K,onUnarchive:re,onDelete:fe,deleteActionTitle:"Delete Permanently",categories:o,showStatusLabel:U},de.id)})())]})]})});Qg.displayName="TaskList";const hE="_formNotice_1stb0_1",gE="_assigneeIndicator_1stb0_12",yE="_assigneeIndicatorAgent_1stb0_20",kE="_assigneeIndicatorUser_1stb0_24",SE="_assigneeIndicatorUnassigned_1stb0_28",vE="_markdownPreview_1stb0_32",bE="_error_1stb0_83",wE="_keyboardHint_1stb0_92",xE="_taskFormLifecycle_1stb0_110",_E="_taskFormMetaDivider_1stb0_115",CE="_taskFormMetaGrid_1stb0_122",AE="_compactMetaSection_1stb0_128",IE="_createWorkstreamRow_1stb0_134",TE="_createWorkstreamDropdown_1stb0_140",NE="_compactMetaGrid_1stb0_145",RE="_compactMetaField_1stb0_151",jE="_compactMetaFieldHint_1stb0_165",PE="_formFieldsetReset_1stb0_169",EE="_formLayout_1stb0_176",ME="_formLayoutWithSidebar_1stb0_183",DE="_formMainColumn_1stb0_191",LE="_activitySidebar_1stb0_198",BE="_activitySidebarHeader_1stb0_208",WE="_activitySidebarTitle_1stb0_215",FE="_activitySidebarCount_1stb0_224",OE="_taskFormDateRow_1stb0_246",$E="_taskFormDateLabel_1stb0_253",UE="_taskFormDateValue_1stb0_261",qE="_taskFormMetaStack_1stb0_269",zE="_taskFormMetaActor_1stb0_275",HE="_taskFormDateWarning_1stb0_287",GE="_taskFormDateError_1stb0_293",VE="_helpHeader_1stb0_299",KE="_helpClose_1stb0_310",ZE="_markdownHelp_1stb0_324",YE="_helpGrid_1stb0_333",JE="_helpGridItem_1stb0_339",XE="_settingsHint_1stb0_351",QE="_sectionBlock_1stb0_357",eM="_softSectionSurface_1stb0_367",tM="_stackedList_1stb0_374",nM="_stackedListSpaced_1stb0_379",aM="_checklistRow_1stb0_383",rM="_checklistRowDragging_1stb0_392",sM="_checklistHandleBtn_1stb0_396",oM="_checklistCheckboxBtn_1stb0_419",iM="_checklistCheckboxBtnChecked_1stb0_439",cM="_checklistItemText_1stb0_444",lM="_checklistItemTextCompleted_1stb0_450",dM="_checklistRemoveBtn_1stb0_455",uM="_specialistChip_1stb0_522",mM="_specialistChipActive_1stb0_545",pM="_commentPanel_1stb0_626",fM="_activitySidebarPanel_1stb0_635",hM="_commentThread_1stb0_643",gM="_emptyComments_1stb0_663",yM="_comment_1stb0_626",kM="_activityEvent_1stb0_681",SM="_activityEventSystem_1stb0_687",vM="_commentAi_1stb0_691",bM="_commentUser_1stb0_695",wM="_commentHeader_1stb0_699",xM="_activityEventHeader_1stb0_716",_M="_commentAuthor_1stb0_723",CM="_commentTime_1stb0_731",AM="_commentText_1stb0_735",IM="_activityEventText_1stb0_775",TM="_activityEventChanges_1stb0_781",NM="_activityEventChange_1stb0_781",RM="_commentInputArea_1stb0_795",jM="_commentInput_1stb0_795",PM="_sendCommentBtn_1stb0_827",EM="_taxonomyFieldsGrid_1stb0_853",MM="_markdownPreviewContainer_1stb0_860",DM="_descriptionSurface_1stb0_865",qe={formNotice:hE,assigneeIndicator:gE,assigneeIndicatorAgent:yE,assigneeIndicatorUser:kE,assigneeIndicatorUnassigned:SE,markdownPreview:vE,error:bE,keyboardHint:wE,taskFormLifecycle:xE,taskFormMetaDivider:_E,taskFormMetaGrid:CE,compactMetaSection:AE,createWorkstreamRow:IE,createWorkstreamDropdown:TE,compactMetaGrid:NE,compactMetaField:RE,compactMetaFieldHint:jE,formFieldsetReset:PE,formLayout:EE,formLayoutWithSidebar:ME,formMainColumn:DE,activitySidebar:LE,activitySidebarHeader:BE,activitySidebarTitle:WE,activitySidebarCount:FE,taskFormDateRow:OE,taskFormDateLabel:$E,taskFormDateValue:UE,taskFormMetaStack:qE,taskFormMetaActor:zE,taskFormDateWarning:HE,taskFormDateError:GE,helpHeader:VE,helpClose:KE,markdownHelp:ZE,helpGrid:YE,helpGridItem:JE,settingsHint:XE,sectionBlock:QE,softSectionSurface:eM,stackedList:tM,stackedListSpaced:nM,checklistRow:aM,checklistRowDragging:rM,checklistHandleBtn:sM,checklistCheckboxBtn:oM,checklistCheckboxBtnChecked:iM,checklistItemText:cM,checklistItemTextCompleted:lM,checklistRemoveBtn:dM,specialistChip:uM,specialistChipActive:mM,commentPanel:pM,activitySidebarPanel:fM,commentThread:hM,emptyComments:gM,comment:yM,activityEvent:kM,activityEventSystem:SM,commentAi:vM,commentUser:bM,commentHeader:wM,activityEventHeader:xM,commentAuthor:_M,commentTime:CM,commentText:AM,activityEventText:IM,activityEventChanges:TM,activityEventChange:NM,commentInputArea:RM,commentInput:jM,sendCommentBtn:PM,taxonomyFieldsGrid:EM,markdownPreviewContainer:MM,descriptionSurface:DM};function up({label:e,value:n,options:a,onChange:s,type:o="priority",hideLabel:c=!1,showSelectedLabel:i=!0}){const l=a.find(m=>String(m.value)===String(n));return t.jsxs("div",{className:p.field,children:[!c&&t.jsxs("div",{className:p.labelRow,children:[t.jsx("label",{className:p.label,children:e}),i&&l&&t.jsx("span",{className:p.levelLabel,style:{color:Ra(l.color)||(o==="priority"?`var(--priority-${n})`:o==="complexity"?`var(--complexity-${n})`:"var(--text-secondary)"),backgroundColor:(Ra(l.color)?`${Ra(l.color)}25`:void 0)||(o==="priority"?`color-mix(in srgb, var(--priority-${n}), transparent 85%)`:o==="complexity"?`color-mix(in srgb, var(--complexity-${n}), transparent 85%)`:"rgba(255,255,255,0.05)")},children:l.label})]}),t.jsx("div",{className:p.levelSelect,children:a.map((m,y)=>{const v=a.findIndex(h=>String(h.value)===String(n)),b=y<=v,g=String(m.value)===String(n);return t.jsx("button",{type:"button",className:`${p.levelOption} ${b?p.levelOptionFilled:""} ${b?p[`levelOption_${o}_${m.value}`]:""} ${g?p.levelOptionSelected:""}`,onClick:()=>s(m.value),title:m.label,style:{opacity:b?1:.15,backgroundColor:b?Ra(m.color)||(o==="priority"?`var(--priority-${m.value})`:o==="complexity"?`var(--complexity-${m.value})`:"var(--text-primary)"):void 0,color:b?o==="priority"&&String(m.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:b&&(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 fh=new Map;function LM(e){const n=e instanceof Date?e:new Date(e);return Number.isNaN(n.getTime())?null:n}function BM(e,n){const a=Object.entries(n).sort(([s],[o])=>s.localeCompare(o));return JSON.stringify([e,a])}function Lc(e,n,a){const s=LM(e);if(!s)return"";const o=a??mg(),c=BM(o,n);let i=fh.get(c);return i||(i=new Intl.DateTimeFormat(o,n),fh.set(c,i)),i.format(s)}const WM="D-";function FM(e){return gd(WM,e)}const ey=[".png",".jpg",".jpeg",".webp",".gif",".pdf",".txt",".md",".csv",".json",".doc",".docx",".html",".js",".ts",".tsx",".css",".py",".java",".go",".rs",".sh"].join(","),OM=new Set(["image/png","image/jpeg","image/webp"]),$M=new Set(ey.split(",").map(e=>e.trim().toLowerCase())),UM=10*1024*1024,qM=3500;function ty(e){const n=e.trim().toLowerCase(),a=n.lastIndexOf(".");return a===-1?"":n.slice(a)}function mp(e){if(e.length===0)return"";const n=e.slice(0,3).join(", "),a=e.length-3;return a>0?`${n}, +${a} more`:n}function zM(e){return`${e.name.trim().toLowerCase()}::${e.size}::${e.lastModified}`}function HM(e){return new Promise((n,a)=>{const s=new FileReader;s.onload=()=>n(String(s.result||"")),s.onerror=()=>a(s.error||new Error("Failed to read file")),s.readAsDataURL(e)})}function Kl(e){return/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(e)}function GM(e){const n=e.types;if(!n)return null;for(const a of Array.from(n)){const s=String(a||"").trim().toLowerCase();if(OM.has(s))return s}return null}function hh(e,n){const a=e.includes("?")?"&":"?";return`${e}${a}download=1&filename=${encodeURIComponent(n)}`}function gh(e){return typeof e=="string"?e.split("/").pop()||"Context file":e.displayName||e.originalFilename||e.caption||e.fsPath||e.path.split("/").pop()||"Context file"}function VM(e){const n=typeof e=="string"?[e]:[e.originalFilename,e.displayName,e.caption,e.fsPath,e.path];for(const s of n){if(!s)continue;const o=ty(s);if(o)return o.replace(".","").slice(0,5).toUpperCase()}const a=typeof e=="string"?e:e.path;return/^https?:\/\//i.test(a)?"LINK":"FILE"}function ny(e){const{ownerType:n="task",ownerId:a,ownerReferenceLabel:s,workspaceId:o,attachments:c,onAddAttachment:i,onRemoveAttachment:l,onUpdateAttachmentCaption:m}=e,y=r.useRef(null),[v,b]=r.useState(!1),[g,h]=r.useState(null),[k,I]=r.useState(""),[x,A]=r.useState(null),[M,B]=r.useState(null),[ue,X]=r.useState(!1),[ce,oe]=r.useState(!1),[be,_]=r.useState(0),J=r.useRef(new Set),Q=r.useRef(new Set),ie=N=>(N||"").trim(),H=(N,C)=>{const $=[],K=ie(N),te=ie(C);return K&&$.push(`path:${K}`),te&&$.push(`fs:${te}`),$},P=r.useMemo(()=>{const N=new Set;return c.forEach(C=>{if(typeof C=="string"){H(C).forEach($=>N.add($));return}H(C.path,C.fsPath).forEach($=>N.add($))}),N},[c]);r.useEffect(()=>{J.current=new Set(P)},[P]);const U=(N,C)=>C.some($=>N.has($)),se=(N,C)=>C.forEach($=>N.add($)),he=String(o||"").trim(),V=String(a||"").trim(),Ce=n==="initiative"?"initiative":n==="workstream"?"workstream":"task",Se={ownerType:n,ownerId:V||null,taskId:n==="task"&&V||null},ve=(N="application/json")=>{const C={"Content-Type":N};return he&&(C["x-taskforce-workspace-id"]=he),C},ge=(N,C=!0,$=J.current)=>{const K=N.trim();if(!K||!/^https?:\/\//i.test(K))return"invalid";const L=K,re=H(L);if(U($,re))return"duplicate";const fe=K.split(/[\\/]/).pop()||K;return i({path:L,caption:fe,timestamp:new Date().toISOString()}),se($,re),C&&I(""),A(null),"added"};r.useEffect(()=>{if(!M)return;const N=window.setTimeout(()=>{B(null)},qM);return()=>window.clearTimeout(N)},[M]);const Te=async N=>{if(N.length===0)return;h(null),B(null);const C=N,$=[],K=[],te=[],L=[],re=new Set(Q.current);C.forEach(we=>{const Re=ty(we.name);if(!$M.has(Re)){$.push(we.name);return}if(we.size>UM){K.push(we.name);return}const Xe=zM(we);if(re.has(Xe)){te.push(we.name);return}re.add(Xe),L.push({file:we,fingerprint:Xe})});const fe=[];if($.length>0&&fe.push(`${$.length} unsupported file${$.length===1?"":"s"} skipped: ${mp($)}.`),K.length>0&&fe.push(`${K.length} file${K.length===1?"":"s"} over 10 MB skipped: ${mp(K)}.`),te.length>0&&fe.push(`${te.length} local duplicate file${te.length===1?"":"s"} skipped before upload: ${mp(te)}.`),L.length===0){fe.length>0&&B(fe.join(" ")),y.current&&(y.current.value="");return}b(!0);const xe=new Set(J.current);let le=0;try{for(const{file:Re,fingerprint:Xe}of L){let ze=null;const lt=await fetch("/api/taskforce/context-upload/init",{method:"POST",headers:ve(),body:JSON.stringify({originalName:Re.name,mimeType:Re.type||"application/octet-stream",size:Re.size,...Se,workspaceId:he||null})});if(lt.ok){const $e=await lt.json();if($e?.success&&typeof $e?.uploadUrl=="string"&&typeof $e?.path=="string"){if(!(await fetch($e.uploadUrl,{method:String($e.method||"PUT"),headers:$e.headers||{"Content-Type":Re.type||"application/octet-stream"},body:Re})).ok)throw new Error(`Upload failed for ${Re.name}`);const gt=await fetch("/api/taskforce/context-upload/finalize",{method:"POST",headers:ve(),body:JSON.stringify({relativePath:$e.relativePath,mimeType:Re.type||"application/octet-stream",originalName:Re.name,size:Re.size,...Se,workspaceId:he||null})});if(!gt.ok){const at=await gt.json().catch(()=>({}));throw new Error(at?.error||`Upload failed for ${Re.name}`)}ze=await gt.json().catch(()=>null)}else $e?.success&&typeof $e?.path=="string"&&(ze=$e)}if(!ze){const $e=await HM(Re),ft=await fetch("/api/taskforce/context-upload",{method:"POST",headers:ve(),body:JSON.stringify({file:$e,originalName:Re.name,...Se,workspaceId:he||null})});if(!ft.ok)throw new Error(`Upload failed for ${Re.name}`);ze=await ft.json()}if(!ze?.success||!ze?.path)throw new Error(`Upload failed for ${Re.name}`);const wt=H(ze.path,ze.fsPath);if(U(xe,wt)){le+=1;continue}i({path:ze.path,fsPath:ze.fsPath,caption:typeof ze.caption=="string"&&ze.caption.trim().length>0?ze.caption:Re.name,displayName:typeof ze.displayName=="string"?ze.displayName:void 0,originalFilename:typeof ze.originalFilename=="string"?ze.originalFilename:Re.name,assetId:typeof ze.assetId=="string"?ze.assetId:void 0,referenceNumber:typeof ze.referenceNumber=="number"?ze.referenceNumber:null,referenceLabel:typeof ze.referenceLabel=="string"?ze.referenceLabel:void 0,taskId:n==="task"&&typeof ze.taskId=="string"?ze.taskId:null,timestamp:new Date().toISOString()}),Wv({workspaceId:he||"default",ownerType:n,ownerId:V||null,taskId:n==="task"&&V||null,reason:"upload"}),se(xe,wt),Q.current.add(Xe)}const we=[...fe];le>0&&we.push(`${le} duplicate file${le===1?"":"s"} skipped.`),B(we.length>0?we.join(" "):null),J.current=xe}catch(we){h(we instanceof Error?we.message:"Failed to upload context file")}finally{b(!1),y.current&&(y.current.value="")}},Le=async N=>{!N||N.length===0||await Te(Array.from(N))},Ie=async()=>{if(h(null),B(null),!navigator.clipboard||typeof navigator.clipboard.read!="function"){h("Clipboard image paste is not available in this browser.");return}try{const N=await navigator.clipboard.read(),C=[];for(const $ of N){const K=GM($);if(!K)continue;const te=await $.getType(K),L=K.toLowerCase()==="image/png"?"png":K.toLowerCase()==="image/webp"?"webp":"jpg";C.push(new globalThis.File([te],`pasted-image-${Date.now()}.${L}`,{type:K}))}if(C.length===0){h("Clipboard does not currently contain a supported image.");return}await Te(C)}catch(N){h(N?.message||"Failed to read an image from the clipboard.")}},Oe=N=>{const C=new Set,$=N.dataTransfer.getData("text/uri-list")||"",K=N.dataTransfer.getData("text/plain")||"",te=`${$}
4
+ ${K}`.split(`
5
+ `).map(L=>L.trim()).filter(L=>!!L&&!L.startsWith("#"));for(const L of te){if(/^file:\/\//i.test(L)){try{const re=new URL(L),fe=decodeURIComponent(re.pathname||"").trim();fe&&C.add(fe)}catch{}continue}C.add(L)}return Array.from(C)},z=N=>{if(N.preventDefault(),N.stopPropagation(),oe(!1),_(0),h(null),A(null),B(null),N.dataTransfer.files&&N.dataTransfer.files.length>0){Le(N.dataTransfer.files);return}const C=Oe(N);if(C.length===0){A("Drop a file or URL.");return}const $=new Set(J.current);let K=0,te=0,L=0;C.forEach(fe=>{const xe=ge(fe,!1,$);xe==="duplicate"&&(K+=1),xe==="added"&&(te+=1),xe==="invalid"&&(L+=1)});const re=[];K>0&&re.push(`${K} duplicate link${K===1?"":"s"} skipped.`),L>0&&re.push(`${L} local path${L===1?"":"s"} skipped. Upload files to attach them, or drop an http(s) URL to link.`),B(re.length>0?re.join(" "):te>0?null:M),J.current=$},T=N=>{N.preventDefault(),N.stopPropagation(),_(C=>C+1),oe(!0)},w=N=>{N.preventDefault(),N.stopPropagation(),_(C=>{const $=Math.max(0,C-1);return $===0&&oe(!1),$})},j=N=>{N.preventDefault(),N.stopPropagation(),N.dataTransfer.dropEffect="copy"},F=c.filter(N=>{const C=typeof N=="string"?N:N.path;return Kl(C)}),ee=c.filter(N=>{const C=typeof N=="string"?N:N.path;return!Kl(C)});return t.jsxs("div",{className:p.specialistSection,children:[t.jsxs("div",{className:p.toggleHeading,onClick:()=>X(!ue),title:ue?"Hide context documents":"Show context documents",children:[t.jsxs("label",{className:p.label,children:["Context Documents ",c.length>0&&`(${c.length})`]}),ue?t.jsx(fd,{size:14}):t.jsx(Wc,{size:14})]}),ue&&t.jsxs(t.Fragment,{children:[t.jsxs("p",{className:p.settingsHint,children:["Upload files into ",Ce," context storage, or add an external http(s) URL."]}),t.jsxs("div",{className:p.contextUploadPanel,children:[t.jsxs("div",{className:p.contextUploadActions,children:[t.jsxs("button",{type:"button",className:p.secondaryHeaderBtn,onClick:()=>y.current?.click(),disabled:v,children:[v?t.jsx(Va,{size:12,className:p.spinner}):t.jsx(Xm,{size:12}),v?"Uploading...":"Upload File"]}),t.jsxs("button",{type:"button",className:p.secondaryHeaderBtn,onClick:()=>{Ie()},disabled:v,children:[t.jsx(nd,{size:12}),"Paste Image from Clipboard"]})]}),t.jsx("input",{ref:y,type:"file",accept:ey,multiple:!0,className:p.hiddenInput,onChange:N=>{Le(N.target.files)}}),g&&t.jsx("div",{className:p.error,children:g}),t.jsxs("div",{className:p.contextLinkRow,children:[t.jsx("input",{type:"text",className:p.input,placeholder:"Add external URL (https://...)",value:k,onChange:N=>{I(N.target.value),x&&A(null),M&&B(null)}}),t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:()=>{if(!k.trim()){A("Enter an http(s) URL to link.");return}const N=ge(k,!0);if(N==="invalid"){A("Only external http(s) URLs can be linked here. Upload files to attach them.");return}N==="duplicate"?B(`Link already exists in ${Ce} context.`):N==="added"&&B(null)},children:"Add URL"})]}),t.jsxs("div",{className:`${p.contextDropzone} ${ce?p.contextDropzoneActive:""}`,onDragEnter:T,onDragLeave:w,onDragOver:j,onDrop:z,children:[t.jsx(Xm,{size:14}),t.jsx("span",{children:"Drop files or URLs here"})]})]}),M&&t.jsx("div",{className:p.contextNotice,children:M}),x&&t.jsx("div",{className:p.error,children:x}),F.length>0&&t.jsx("div",{className:p.attachmentGrid,children:c.map((N,C)=>{const $=typeof N=="string"?N:N.path;if(!Kl($))return null;const K=typeof N=="string"?void 0:N.fsPath,te=typeof N=="string"?"":N.caption||"",L=gh(N),re=Kl($),fe=/^https?:\/\//i.test($),xe=n==="task"&&Hg(N);return t.jsxs("div",{className:p.attachmentCard,children:[t.jsxs("div",{className:p.attachmentPreviewContainer,children:[re?t.jsx("img",{src:$,alt:te||`Context file ${C}`,onClick:()=>{n==="task"&&Bp(N,{taskId:V,taskReferenceLabel:s})||window.open($,"_blank")},onError:le=>{le.target.style.display="none",le.target.parentElement.classList.add(p.brokenImage)}}):t.jsxs("button",{type:"button",className:p.contextFileLink,onClick:()=>{Lp(N,K)||window.open($,"_blank")},title:"Open file",children:[t.jsx(Xm,{size:16}),t.jsx("span",{children:te||K||$.split("/").pop()||"Context file"})]}),t.jsxs("div",{className:p.brokenImagePlaceholder,children:[t.jsx(Fc,{size:16}),t.jsx("span",{children:"Preview unavailable"})]}),t.jsxs("div",{className:p.attachmentActions,children:[xe&&t.jsx("button",{type:"button",className:p.attachmentActionBtn,onClick:le=>{le.stopPropagation(),Bp(N,{taskId:V,taskReferenceLabel:s})},title:"Annotate",children:t.jsx(Qy,{size:12})}),K&&t.jsx("button",{type:"button",className:p.attachmentActionBtn,onClick:le=>{le.stopPropagation(),navigator.clipboard.writeText(K)},title:`Copy path: ${K}`,children:t.jsx(nd,{size:12})}),!fe&&t.jsx("button",{type:"button",className:p.attachmentActionBtn,onClick:le=>{le.stopPropagation(),window.open(hh($,te||L),"_blank")},title:"Download",children:t.jsx(If,{size:12})}),t.jsx("button",{type:"button",className:p.attachmentActionBtn,onClick:le=>{le.stopPropagation(),l(C)},title:"Delete",children:t.jsx(Bc,{size:12})})]})]}),t.jsx("input",{type:"text",className:p.attachmentCaptionInput,placeholder:"Add a label...",value:te,onChange:le=>m(C,le.target.value)})]},C)})}),ee.length>0&&t.jsx("div",{className:p.documentAttachmentList,children:c.map((N,C)=>{const $=typeof N=="string"?N:N.path;if(Kl($))return null;const K=typeof N=="string"?void 0:N.fsPath,te=typeof N=="string"?"":N.caption||"",L=gh(N),re=VM(N),fe=typeof N=="string"?"":FM(N),xe=/^https?:\/\//i.test($);return t.jsxs("div",{className:p.documentAttachmentItem,children:[t.jsxs("div",{className:p.documentAttachmentRow,children:[t.jsxs("button",{type:"button",className:p.documentAttachmentLink,onClick:()=>{Lp(N,K)||window.open($,"_blank")},title:L,children:[t.jsxs("span",{className:p.documentAttachmentMain,children:[t.jsx("span",{className:p.documentAttachmentIcon,"aria-hidden":"true",children:t.jsx(ek,{size:13})}),t.jsxs("span",{className:p.documentAttachmentText,children:[t.jsx("span",{className:p.documentAttachmentName,children:L}),fe&&t.jsx("span",{className:p.taskIdBadge,children:fe})]})]}),t.jsx("span",{className:p.documentAttachmentType,children:re})]}),t.jsxs("div",{className:p.documentAttachmentActions,children:[K&&t.jsx("button",{type:"button",className:p.documentAttachmentActionBtn,onClick:()=>{navigator.clipboard.writeText(K)},title:`Copy path: ${K}`,children:t.jsx(nd,{size:12})}),!xe&&t.jsx("button",{type:"button",className:p.documentAttachmentActionBtn,onClick:()=>{window.open(hh($,te||L),"_blank")},title:"Download",children:t.jsx(If,{size:12})}),t.jsx("button",{type:"button",className:p.documentAttachmentActionBtn,onClick:()=>l(C),title:"Delete",children:t.jsx(Bc,{size:12})})]})]}),t.jsx("input",{type:"text",className:p.documentAttachmentCaptionInput,placeholder:"Add a label...",value:te,onChange:le=>m(C,le.target.value)})]},C)})})]})]})}function KM(e){const{taskId:n,taskReferenceLabel:a,workspaceId:s,apiBaseUrl:o,contextFiles:c,onAddContextFile:i,onRemoveContextFile:l,onUpdateContextCaption:m}=e;return t.jsx(ny,{ownerType:"task",ownerId:n,ownerReferenceLabel:a,workspaceId:s,apiBaseUrl:o,attachments:c,onAddAttachment:i,onRemoveAttachment:l,onUpdateAttachmentCaption:m})}function ZM({id:e,item:n,onToggle:a,onRemove:s}){const{attributes:o,listeners:c,setNodeRef:i,transform:l,transition:m,isDragging:y}=Qh({id:e}),v={transform:Hp.Transform.toString(l),transition:m,opacity:y?.88:1};return t.jsxs("div",{ref:i,style:v,className:`${qe.checklistRow} ${y?qe.checklistRowDragging:""}`.trim(),children:[t.jsx("button",{type:"button",className:qe.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...o,...c,children:t.jsx(ak,{size:14})}),t.jsx("button",{type:"button",className:`${qe.checklistCheckboxBtn} ${n.isCompleted?qe.checklistCheckboxBtnChecked:""}`.trim(),onClick:a,title:n.isCompleted?"Mark incomplete":"Mark complete","aria-label":n.isCompleted?"Mark checklist item incomplete":"Mark checklist item complete",children:n.isCompleted?t.jsx(po,{size:14,strokeWidth:2.1}):null}),t.jsx("span",{className:`${qe.checklistItemText} ${n.isCompleted?qe.checklistItemTextCompleted:""}`.trim(),children:n.title}),t.jsx("button",{type:"button",className:qe.checklistRemoveBtn,onClick:s,title:"Remove checklist item","aria-label":"Remove checklist item",children:t.jsx(Ei,{size:15,strokeWidth:1.9})})]})}function Lu(e,n){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return a?`rgba(${parseInt(a[1],16)}, ${parseInt(a[2],16)}, ${parseInt(a[3],16)}, ${n})`:""}function ay(e){const{editingTaskId:n,error:a,title:s,description:o,category:c,type:i,priority:l,complexity:m,manualComplexityEnabled:y=!1,assignee:v,scheduledDate:b,dueDate:g,workstreamInput:h="",checklistItems:k,comments:I,newCommentText:x,contextFiles:A,currentWorkspaceId:M,apiBaseUrl:B,descriptionFocused:ue,showMarkdownHelp:X,showChecklist:ce=!1,checklistEnabled:oe=!0,formTaxonomies:be,onTaxonomyChange:_,onOpenSettings:J,categories:Q,types:ie,priorities:H,taxonomyDisplayLabels:P,assigneeOptions:U,taxonomies:se,workstreams:he=[],initiatives:V=[],copiedId:Ce,onTitleChange:Se,onDescriptionChange:ve,onCategoryChange:ge,onTypeChange:Te,onPriorityChange:Le,onComplexityChange:Ie,onAssigneeChange:Oe,onScheduledDateChange:z,onDueDateChange:T,onWorkstreamInputChange:w=()=>{},onChecklistItemsChange:j,onNewCommentTextChange:F,onDescriptionFocusedChange:ee,onShowMarkdownHelpChange:N,onShowChecklistChange:C=()=>{},onSubmit:$,onAddComment:K,onAddContextFile:te,onRemoveContextFile:L,onUpdateContextCaption:re,onCopyId:fe,onToggleInProgress:xe,onToggleReview:le,onToggleComplete:we,onToggleCancel:Re,onSetStatus:Xe,onArchiveTask:ze,onUnarchive:lt,onOpenTaskById:wt,currentTask:$e,commentsEndRef:ft}=e,gt=qs($e),at=pt.useMemo(()=>Ab(se,be),[se,be]),dt=pt.useMemo(()=>{const pe=Q.find(Ot=>Ot.value===Dc),et={value:Dc,label:pe?.label||dm,icon:pe?.icon||"HelpCircle",color:pe?.color||"var(--text-secondary)"},Ae=Q.find(Ot=>Ot.value===c),Ye=Q.filter(Ot=>!Ot.disabled||Ot.value===Ae?.value).filter(Ot=>Ot.value!==Dc).map(Ot=>({value:Ot.value,label:Ot.disabled?`${Ot.label} (Legacy)`:Ot.label,icon:Ot.icon,color:Ot.color}));return[et,...Ye]},[Q,c]),ne=pt.useMemo(()=>{const pe=ie.find(Ae=>Ae.value===i);return ie.filter(Ae=>Ae.status!=="retired"||Ae.value===pe?.value).map(Ae=>({value:Ae.value,label:Ae.status==="retired"?`${Ae.label} (Retired)`:Ae.label,icon:Ae.icon||"Box",color:Ae.color||"violet-500"}))},[ie,i]),tt=pe=>pe&&Lc(pe,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,rt=tt($e?.createdAt),Pt=tt($e?.updatedAt||$e?.createdAt),yt=tt($e?.completedAt),Rt=pt.useMemo(()=>{const pe=new Date,et=pe.getFullYear(),Ae=String(pe.getMonth()+1).padStart(2,"0"),Nt=String(pe.getDate()).padStart(2,"0");return`${et}-${Ae}-${Nt}`},[]),Tt=!!(g&&b&&g<b),Dt=!!(g&&g<Rt&&(!$e||$e.status!=="done"&&$e.status!=="cancelled")),d=k.filter(pe=>pe.isCompleted).length,[Me,We]=pt.useState(""),[Qe,ot]=pt.useState(!1),de=!!$e?.isArchived,Be=!!$e?.isDeleted,St=pt.useMemo(()=>he.map(pe=>{const et=em(pe);return{value:et||pe.id,label:et?`${et} · ${pe.title}`:pe.title,icon:"Folder",color:"var(--text-secondary)"}}),[he]),vt=pt.useMemo(()=>St.some(pe=>String(pe.value)===String(h||"").trim()),[h,St]);pt.useEffect(()=>{if(n){Qe&&ot(!1);return}if(h.trim()){if(vt&&Qe){ot(!1);return}!vt&&!Qe&&ot(!0)}},[n,vt,Qe,h]);const $t=de||Be,Ze=pt.useRef(null),en=Kh(_p(Xh,{activationConstraint:{distance:6}}));pt.useLayoutEffect(()=>{const pe=Ze.current;if(!pe)return;const et=()=>{pe.scrollTop=0;const Nt=pe.parentElement;Nt&&(typeof Nt.scrollTo=="function"?Nt.scrollTo({top:0,left:0,behavior:"auto"}):Nt.scrollTop=0)};et();const Ae=window.requestAnimationFrame(et);return()=>window.cancelAnimationFrame(Ae)},[n,$e?.id]);const Lt=()=>{const pe=Me.trim();if(!pe)return;const et=new Date().toISOString();j([...k,{id:`checklist-draft-${et}-${k.length}`,taskId:n||"",title:pe,isCompleted:!1,order:k.length,createdAt:et,updatedAt:et}]),We("")},bt=pt.useCallback(pe=>{const{active:et,over:Ae}=pe;if(!Ae||et.id===Ae.id)return;const Nt=k.findIndex(yn=>yn.id===et.id),Ye=k.findIndex(yn=>yn.id===Ae.id);if(Nt<0||Ye<0)return;const Ot=new Date().toISOString(),dn=Tk(k,Nt,Ye).map((yn,on)=>({...yn,order:on,updatedAt:Ot}));j(dn)},[k,j]),W=pe=>{const et=String(pe||"").trim(),Ae=pe.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!Ae||Ae==="ai"||et.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${Ae.split(" ").map(Ye=>Ye.charAt(0).toUpperCase()+Ye.slice(1)).join(" ")}`},ke=PS(U,v),Ne=Xu(v),ae=ad(v,ke),Pe=pt.useMemo(()=>new Map(ke.map(pe=>[String(pe.value),pe])),[ke]),Ge=Pe.get(String(v||"unassigned")),De=$e?.assigneeActor?.color||Ge?.color,it=pt.useMemo(()=>{const pe=[$e?.assigneeActor,$e?.createdByActor].filter(Boolean);return new Map(pe.map(et=>[String(et.id),et]))},[$e?.assigneeActor,$e?.createdByActor]),Ut=pt.useMemo(()=>new Map(he.map(pe=>[pe.id,em(pe)||pe.id])),[he]),Gt=pt.useMemo(()=>new Map(V.map(pe=>[pe.id,Dg(pe)||pe.id])),[V]),nn=pt.useMemo(()=>df({activity:$e?.activity,comments:I}),[I,$e?.activity]),Ft=(pe,et)=>{const Ae=String(et||"").trim();if(Ae){if(pe==="assignee")return ad(Ae,ke);if(pe==="workstreamId")return Ut.get(Ae);if(pe==="initiativeId")return Gt.get(Ae)}},Wt=pt.useCallback((pe,et,Ae)=>{if(Ae&&Ae.trim())return Ae.trim();const Nt=String(pe||"").trim();if(!Nt)return et==="ai"?"AI Agent":He("taskForm.you");const Ye=it.get(Nt);if(Ye?.label)return Ye.label;const Ot=Pe.get(Nt)||Pe.get(Nt.toLowerCase());return Ot?.label?Ot.label:et==="ai"?W(Nt):ad(Nt,ke)||Nt},[it,Pe,W,ke]),Vt=pt.useCallback(({actorId:pe,actorType:et,actorProfile:Ae,fallbackKind:Nt})=>{const Ye=String(pe||"").trim(),Ot=Ye.toLowerCase(),dn=it.get(Ye),yn=Pe.get(Ye)||Pe.get(Ot),on=Ae||dn||yn||null,rn=et==="system"?"system":et==="ai"||on?.kind==="ai"?"agent":et==="human"||on?.kind==="human"?"member":yn?.kind==="agent"?"agent":yn?.kind==="member"?"member":Nt||(Ot===""||Ot==="user"||Ot==="human"?"member":"agent"),kt=rn==="system"?"System":Wt(Ye,rn==="agent"?"ai":"human",on?.label||null),zt=on?.color,Ln=String(on?.icon||(rn==="agent"?"Bot":rn==="member"?"User":"ClipboardList")),Et=Uc[Ln]||(rn==="agent"?wp:rn==="member"?_i:tk);return{kind:rn,label:kt,color:zt,ActorIcon:Et}},[it,Pe,Wt]),an=pt.useMemo(()=>{const pe=nn[nn.length-1];if(!pe)return null;if(pe.type==="comment"){const Ae=pe.comment;return Wt(Ae.author,Ae.actor?.kind==="ai"?"ai":Ae.actor?.kind==="human"?"human":null,Ae.actor?.label||null)}const et=pe.event;return Wt(et.actor,et.actorType,et.actorProfile?.label||null)},[Wt,nn]),Kt=pt.useMemo(()=>{if(!$e?.completedAt)return null;for(const et of nn){if(et.type!=="event")continue;const Ae=et.event,Nt=Ae.details?.changes?.status?.to;if(Nt==="done"||Nt==="cancelled")return Wt(Ae.actor,Ae.actorType,Ae.actorProfile?.label||null)}return an},[$e?.completedAt,an,Wt,nn]),Kn=$e?.createdByActor?.label||Wt($e?.createdBy||null,$e?.createdByActor?.kind==="ai"?"ai":$e?.createdByActor?.kind==="human"?"human":null,$e?.createdByActor?.label||null),Fn=an,Jn=nn.length;pt.useLayoutEffect(()=>{if(!n)return;const pe=ft.current;if(!pe)return;const et=pe.parentElement,Ae=()=>{if(typeof pe.scrollIntoView=="function"){pe.scrollIntoView({block:"end"});return}et&&(et.scrollTop=et.scrollHeight)};Ae();const Nt=window.requestAnimationFrame(Ae);return()=>window.cancelAnimationFrame(Nt)},[Jn,ft,$e?.id,n]);const _n=n?t.jsxs("aside",{className:qe.activitySidebar,"aria-label":He("taskForm.commentsSectionTitle"),children:[t.jsxs("div",{className:qe.activitySidebarHeader,children:[t.jsx("h2",{className:qe.activitySidebarTitle,children:He("taskForm.commentsSectionTitle")}),t.jsx("span",{className:qe.activitySidebarCount,children:Jn})]}),t.jsxs("div",{className:`${qe.commentPanel} ${qe.activitySidebarPanel}`.trim(),children:[t.jsxs("div",{className:qe.commentThread,children:[Jn===0&&t.jsx("div",{className:qe.emptyComments,children:He("taskForm.noComments")}),nn.map(pe=>{if(pe.type==="comment"){const kt=pe.comment,zt=Vt({actorId:kt.author,actorType:kt.actor?.kind==="ai"?"ai":kt.actor?.kind==="human"?"human":null,actorProfile:kt.actor}),Ln=zt.kind==="agent"?"agent":"member",{ActorIcon:Et}=zt,On=zt.color,kn=zt.label,Jt=On&&Lu(On,.35)?{background:`linear-gradient(135deg, ${Lu(On,.18)} 0%, ${Lu(On,.1)} 100%)`,borderColor:Lu(On,.35)}:void 0;return t.jsxs("div",{className:`${qe.comment} ${Ln==="agent"?qe.commentAi:qe.commentUser}`,children:[t.jsxs("div",{className:qe.commentHeader,children:[t.jsx("span",{className:qe.commentAuthor,style:On?{color:On}:void 0,children:t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:12,strokeWidth:1.5})," ",kn]})}),t.jsx("span",{className:qe.commentTime,children:Lc(kt.timestamp,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),t.jsx("div",{className:qe.commentText,style:Jt,children:t.jsx(Dp,{onTaskIdClick:wt,children:kt.text})})]},kt.id)}const et=pe.event,Ae=Vt({actorId:et.actor,actorType:et.actorType,actorProfile:et.actorProfile,fallbackKind:"system"}),{ActorIcon:Nt}=Ae,Ye=Ae.color,Ot=Ae.label,dn=Ae.kind,yn=Object.entries(et.details?.changes||{}),on=KP(et),rn=yn.length>1&&on?yn.filter(([kt])=>kt!==on):yn.length>1?yn:[];return t.jsxs("div",{className:`${qe.comment} ${qe.activityEvent} ${dn==="system"?qe.activityEventSystem:""}`,children:[t.jsxs("div",{className:`${qe.commentHeader} ${qe.activityEventHeader}`,children:[t.jsx("span",{className:qe.commentAuthor,style:Ye?{color:Ye}:void 0,children:t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:12,strokeWidth:1.5})," ",Ot]})}),t.jsx("span",{className:qe.commentTime,children:Lc(et.createdAt,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),t.jsxs("div",{className:qe.activityEventText,children:[t.jsx("div",{children:Kg(et,Ft)}),rn.length>0&&t.jsx("div",{className:qe.activityEventChanges,children:rn.map(([kt,zt])=>t.jsx("div",{className:qe.activityEventChange,children:Wp(kt,zt,Ft)},kt))})]})]},pe.id)}),t.jsx("div",{ref:ft})]}),t.jsxs("div",{className:qe.commentInputArea,children:[t.jsx("textarea",{className:qe.commentInput,placeholder:He("taskForm.commentPlaceholder"),value:x,onChange:pe=>F(pe.target.value),onKeyDown:pe=>{pe.key==="Enter"&&!pe.shiftKey&&(pe.preventDefault(),K())},rows:1}),t.jsx("button",{type:"button",className:qe.sendCommentBtn,onClick:K,disabled:!x.trim(),"aria-label":"Send comment",title:"Send comment",children:t.jsx(nk,{size:16})})]})]})]}):null;return t.jsxs("form",{ref:Ze,onSubmit:$,className:`${p.form} ${p.appScrollbar} tf-scrollbar`,children:[a&&t.jsx("div",{className:qe.error,children:a}),$t&&t.jsx("div",{className:`${qe.formNotice} tf-text-helper`,children:Be?"Deleted tasks are read-only. Restore the task to make changes.":"Archived tasks are read-only. Unarchive the task to make changes."}),t.jsxs("fieldset",{disabled:$t,className:`${qe.formFieldsetReset} ${n?qe.formLayoutWithSidebar:qe.formLayout}`.trim(),children:[t.jsxs("div",{className:qe.formMainColumn,children:[t.jsxs("div",{className:p.field,children:[t.jsxs("div",{className:p.labelRow,children:[t.jsx("label",{className:p.label,children:"Title"}),v&&t.jsx("span",{title:`Assigned to: ${ae}`,className:[qe.assigneeIndicator,Ne==="agent"?qe.assigneeIndicatorAgent:Ne==="member"?qe.assigneeIndicatorUser:qe.assigneeIndicatorUnassigned].join(" "),style:De?{color:De}:void 0,children:Ne==="agent"?t.jsx(wp,{size:20}):Ne==="member"?t.jsx(_i,{size:20}):t.jsx(Ti,{size:20})})]}),t.jsx("input",{type:"text",value:s,onChange:pe=>Se(pe.target.value),placeholder:"What needs to be done?",className:p.input,required:!0,maxLength:255,autoFocus:!0})]}),t.jsxs("div",{className:p.field,children:[t.jsxs("div",{className:p.labelRow,children:[t.jsx("label",{className:p.label,children:"Description"}),t.jsx("button",{type:"button",className:p.helpLink,onClick:()=>N(!X),title:"Markdown Help",tabIndex:-1,children:t.jsx(Ti,{size:14})})]}),X&&t.jsxs("div",{className:qe.markdownHelp,children:[t.jsxs("div",{className:qe.helpHeader,children:[t.jsx("span",{children:"Markdown Guide"}),t.jsx("button",{onClick:()=>N(!1),className:qe.helpClose,children:t.jsx(Ei,{size:12})})]}),t.jsxs("div",{className:qe.helpGrid,children:[t.jsx("div",{children:t.jsx("code",{children:"**bold**"})}),t.jsx("div",{children:t.jsx("code",{children:"_italic_"})}),t.jsx("div",{children:t.jsx("code",{children:"- list"})}),t.jsx("div",{children:t.jsx("code",{children:"1. list"})}),t.jsx("div",{className:qe.helpGridItem,children:t.jsx("code",{children:"`inline code`"})}),t.jsxs("div",{className:qe.helpGridItem,children:[t.jsx("code",{children:"```"}),t.jsx("br",{}),t.jsx("code",{children:"code block"}),t.jsx("br",{}),t.jsx("code",{children:"```"})]}),t.jsx("div",{children:t.jsx("code",{children:"[link](url)"})})]})]}),ue||!o?t.jsx("textarea",{className:`${p.textarea} ${qe.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",value:o,onChange:pe=>ve(pe.target.value),onFocus:()=>ee(!0),onBlur:()=>ee(!1),rows:9,autoFocus:ue}):t.jsx("div",{className:`${p.textarea} ${qe.descriptionSurface} ${qe.markdownPreview} ${qe.markdownPreviewContainer}`,onClick:()=>ee(!0),children:t.jsx(Dp,{onTaskIdClick:wt,children:o})})]}),t.jsxs("div",{className:qe.compactMetaSection,children:[t.jsxs("div",{className:qe.compactMetaGrid,children:[t.jsxs("div",{className:`${p.field} ${qe.compactMetaField}`,children:[t.jsx("label",{id:"category-label",className:p.label,children:P?.category||"Category"}),t.jsx(Ql,{value:c,options:dt,onChange:pe=>ge(String(pe)),required:!0,ariaLabelledBy:"category-label"})]}),t.jsxs("div",{className:`${p.field} ${qe.compactMetaField}`,children:[t.jsx("label",{id:"type-label",className:p.label,children:P?.type||"Type"}),t.jsx(Ql,{value:i,options:ne,onChange:pe=>Te(String(pe)),ariaLabelledBy:"type-label"})]}),t.jsxs("div",{className:`${p.field} ${qe.compactMetaField}`,children:[t.jsx("label",{htmlFor:"task-form-scheduled-date",className:p.label,children:He("taskForm.scheduledLabel")}),t.jsx("input",{id:"task-form-scheduled-date",type:"date",value:b,onChange:pe=>z(pe.target.value),className:`${p.input} ${p.taskFormDateInput}`})]}),t.jsxs("div",{className:`${p.field} ${qe.compactMetaField}`,children:[t.jsx("label",{id:"assignee-label",className:p.label,children:"Assigned To"}),t.jsx(Ql,{value:v||"unassigned",options:ke,onChange:pe=>Oe(String(pe)),ariaLabelledBy:"assignee-label"})]}),t.jsx("div",{className:qe.compactMetaField,children:t.jsx(up,{label:P?.priority||"Priority",options:H,value:l,onChange:Le,type:"priority",showSelectedLabel:!1})}),t.jsxs("div",{className:`${p.field} ${qe.compactMetaField}`,children:[t.jsx("label",{htmlFor:"task-form-due-date",className:p.label,children:He("taskForm.dueLabel")}),t.jsx("input",{id:"task-form-due-date",type:"date",value:g,onChange:pe=>T(pe.target.value),className:`${p.input} ${p.taskFormDateInput}`}),Tt&&t.jsx("span",{className:`${qe.taskFormDateWarning} ${qe.compactMetaFieldHint}`,children:He("taskForm.dueBeforeScheduled")}),Dt&&t.jsx("span",{className:`${qe.taskFormDateError} ${qe.compactMetaFieldHint}`,children:He("taskForm.overdue")})]}),y&&t.jsx("div",{className:qe.compactMetaField,children:t.jsx(up,{label:"Complexity",options:[{value:1,label:"Tiny",color:"#10b981",icon:"Gauge"},{value:2,label:"Low",color:"#14b8a6",icon:"Gauge"},{value:3,label:"Medium",color:"#3b82f6",icon:"Gauge"},{value:4,label:"High",color:"#8b5cf6",icon:"Gauge"},{value:5,label:"Epic",color:"#d946ef",icon:"Gauge"}],value:m,onChange:Ie,type:"general"})})]}),!n&&t.jsxs("div",{className:qe.createWorkstreamRow,children:[t.jsx("label",{className:p.label,children:"Attach to workstream"}),t.jsxs("div",{className:p.pathInputGroup,children:[Qe?t.jsx("input",{type:"text",className:p.input,value:h,onChange:pe=>w(pe.target.value),placeholder:"Type a workstream name or reference","aria-label":"Attach to workstream"}):t.jsx(Ql,{value:h,options:St,onChange:pe=>w(String(pe)),placeholder:"Select workstream...",ariaLabel:"Attach to workstream",className:qe.createWorkstreamDropdown}),t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:()=>{if(Qe){ot(!1),vt||w("");return}ot(!0)},"aria-label":Qe?"Use workstream dropdown":"Enter workstream by name",title:Qe?"Use workstream dropdown":"Enter workstream by name",children:t.jsx(Cs,{size:14})})]})]})]}),t.jsxs("div",{className:qe.sectionBlock,children:[t.jsx("div",{className:qe.taxonomyFieldsGrid,children:at.map(pe=>{if(pe.id==="approach"&&pe.isSystem)return null;const et=be[pe.id],Ae=Array.isArray(et)?et.map(Ye=>String(Ye)):et!=null&&et!==""?[String(et)]:[],Nt=pe.options.filter(Ye=>Ye.status!=="retired"||Ae.includes(String(Ye.value)));return t.jsxs("div",{className:p.field,children:[t.jsx("label",{className:p.label,children:pe.label}),pe.description&&t.jsx("div",{className:`${qe.settingsHint} tf-text-helper`,children:pe.description}),pe.widgetType==="level"?t.jsx(up,{label:pe.label,options:Nt.map(Ye=>({...Ye,label:Ye.status==="retired"?`${Ye.label} (Retired)`:Ye.label})),value:be[pe.id]||"",onChange:Ye=>_(pe.id,Ye),type:"general",hideLabel:!0}):pe.multiSelect?t.jsx("div",{className:`${p.dropdownList} ${qe.softSectionSurface}`,children:Nt.map(Ye=>{const Ot=String(Ye.value),dn=Ae.includes(Ot);return t.jsxs("button",{type:"button",className:`${qe.specialistChip} ${dn?qe.specialistChipActive:""}`,onClick:()=>{const yn=dn?Ae.filter(on=>on!==Ot):[...Ae,Ot];_(pe.id,yn)},title:dn?"Click to remove":"Click to add",children:[dn&&t.jsx(po,{size:12}),Ye.status==="retired"?`${Ye.label} (Retired)`:Ye.label]},Ot)})}):t.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 Ye=pe.options.find(yn=>String(yn.value)===String(be[pe.id])),Ot=Ye?.icon&&us[Ye.icon]?us[Ye.icon]:Ti,dn=Ye?.color||"var(--text-secondary)";return t.jsx("div",{className:p.fieldIcon,style:{color:Ra(dn)},children:t.jsx(Ot,{size:16})})})(),t.jsxs("select",{value:be[pe.id]||"",onChange:Ye=>_(pe.id,Ye.target.value),className:`${p.select} ${p.field_dynamic}`,required:pe.isRequired,children:[t.jsxs("option",{value:"",children:["Select ",pe.label,"..."]}),Nt.map(Ye=>t.jsx("option",{value:Ye.value,children:Ye.status==="retired"?`${Ye.label} (Retired)`:Ye.label},Ye.value))]})]})]},pe.id)})}),oe&&t.jsxs("div",{className:p.specialistSection,children:[t.jsxs("div",{className:p.toggleHeading,onClick:()=>C(!ce),title:ce?"Hide checklist":"Show checklist",children:[t.jsxs("label",{className:p.label,children:["Checklist"," ",k.length>0&&`(${d}/${k.length})`]}),ce?t.jsx(fd,{size:14}):t.jsx(Wc,{size:14})]}),ce&&t.jsxs("div",{className:`${p.dropdownList} ${qe.stackedList} ${qe.stackedListSpaced}`,children:[t.jsxs("div",{className:p.pathInputGroup,children:[t.jsx("input",{type:"text",className:p.input,placeholder:"Add checklist item",value:Me,onChange:pe=>We(pe.target.value),onKeyDown:pe=>{pe.key==="Enter"&&(pe.preventDefault(),Lt())}}),t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:Lt,disabled:!Me.trim(),children:"Add"})]}),k.length>0?t.jsx(Zh,{sensors:en,collisionDetection:Nk,onDragEnd:bt,children:t.jsx(Yh,{items:k.map(pe=>pe.id),strategy:Jh,children:k.map((pe,et)=>t.jsx(ZM,{id:pe.id||`checklist-${et}`,item:pe,onToggle:()=>{const Ae=new Date().toISOString();j(k.map((Nt,Ye)=>Ye===et?{...Nt,isCompleted:!Nt.isCompleted,updatedAt:Ae}:Nt))},onRemove:()=>j(k.filter((Ae,Nt)=>Nt!==et).map((Ae,Nt)=>({...Ae,order:Nt})))},pe.id||`checklist-${et}`))})}):t.jsx("div",{className:`${qe.settingsHint} tf-text-helper`,children:"No checklist items yet."})]})]})]}),t.jsxs("div",{children:[t.jsx(KM,{taskId:n,taskReferenceLabel:gt,workspaceId:M,apiBaseUrl:B,contextFiles:A,onAddContextFile:te,onRemoveContextFile:L,onUpdateContextCaption:re}),t.jsx("div",{className:`${qe.taskFormLifecycle} ${qe.taskFormMetaDivider}`,children:t.jsx("div",{className:qe.taskFormMetaGrid,children:$e&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:qe.taskFormDateRow,children:[t.jsx("span",{className:qe.taskFormDateLabel,children:He("taskForm.createdLabel")}),t.jsxs("span",{className:qe.taskFormMetaStack,children:[t.jsx("span",{className:qe.taskFormDateValue,children:rt||He("taskForm.emptyValue")}),t.jsx("span",{className:qe.taskFormMetaActor,children:Kn?`by ${Kn}`:He("taskForm.emptyValue")})]})]}),t.jsxs("div",{className:qe.taskFormDateRow,children:[t.jsx("span",{className:qe.taskFormDateLabel,children:He("taskForm.updatedLabel")}),t.jsxs("span",{className:qe.taskFormMetaStack,children:[t.jsx("span",{className:qe.taskFormDateValue,children:Pt||He("taskForm.emptyValue")}),t.jsx("span",{className:qe.taskFormMetaActor,children:Fn?`by ${Fn}`:He("taskForm.emptyValue")})]})]}),t.jsxs("div",{className:qe.taskFormDateRow,children:[t.jsx("span",{className:qe.taskFormDateLabel,children:He("taskForm.completedLabel")}),t.jsxs("span",{className:qe.taskFormMetaStack,children:[t.jsx("span",{className:qe.taskFormDateValue,children:yt||He("taskForm.emptyValue")}),t.jsx("span",{className:qe.taskFormMetaActor,children:Kt?`by ${Kt}`:He("taskForm.emptyValue")})]})]})]})})})]})]}),_n,t.jsxs("div",{className:qe.keyboardHint,children:["Press ",t.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function ry({editingTaskId:e,loading:n,autoSaveState:a="idle",title:s,handleSubmit:o,resetForm:c,handleCopyId:i,copiedId:l,tasks:m,currentTask:y,currentTaskWorkstream:v,currentTaskInitiative:b,workstreamInput:g="",onWorkstreamInputChange:h,onSetWorkstreamForCurrentTask:k,handleToggleInProgress:I,handleToggleReview:x,handleToggleComplete:A,handleToggleCancel:M,handleSetStatus:B,handleArchiveTask:ue,handleUnarchiveTask:X,handleRestoreDeletedTask:ce,handlePermanentlyDeleteDeletedTask:oe}){const[be,_]=pt.useState(!1),J=y??(e&&m.find(Se=>Se.id===e)||null),Q=!!J?.isArchived,ie=!!J?.isDeleted,H=cg(J),P=H.label||(H.isProvisional?"Pending":""),U=H.isProvisional,se=!!H.label,he=v?em(v)||v.id:"",V=b?xs(b)||b.id:"";pt.useEffect(()=>{v&&_(!1)},[v?.id]);const Ce=pt.useCallback(()=>{g.trim()&&k?.()},[k,g]);return t.jsx("div",{className:p.stickyActionHeader,children:e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:p.taskHierarchyHeader,children:[t.jsxs("div",{className:p.taskHierarchyBadgeRow,children:[b?t.jsxs(t.Fragment,{children:[t.jsx(qu,{copied:l===V,onClick:Se=>i(Se,V),disabled:n,title:"Copy initiative reference",label:V}),t.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}):null,v?t.jsxs(t.Fragment,{children:[t.jsx(qu,{copied:l===he,onClick:Se=>i(Se,he),disabled:n,title:"Copy workstream reference",label:he}),t.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:`${p.taskIdBadge} ${p.taskHierarchyAddBtn}`,onClick:()=>{h?.(""),_(Se=>!Se)},disabled:n||Q||ie,title:"Attach to workstream","aria-label":"Attach to workstream",children:t.jsx(Cs,{size:13})}),t.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}),P?t.jsx(qu,{copied:se&&l===H.label,onClick:Se=>i(Se,H.label),disabled:n||!se,title:se?He("actionHeader.copyTaskIdTitle"):"Task reference pending sync",label:P}):null,U?t.jsx("span",{className:p.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),be&&!v?t.jsxs("div",{className:p.taskHierarchyEditor,children:[t.jsx("input",{type:"text",className:`${p.input} ${p.taskHierarchyInput}`,value:g,onChange:Se=>h?.(Se.target.value),placeholder:"WS-123","aria-label":"Attach workstream reference",onKeyDown:Se=>{Se.key==="Enter"&&(Se.preventDefault(),Ce()),Se.key==="Escape"&&(Se.preventDefault(),h?.(""),_(!1))}}),t.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:Ce,disabled:!g.trim()||n,title:"Attach workstream","aria-label":"Attach workstream",children:t.jsx(po,{size:14})}),t.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>{h?.(""),_(!1)},disabled:n,title:"Cancel workstream attach","aria-label":"Cancel workstream attach",children:t.jsx(Ei,{size:14})})]}):null]}),t.jsx("div",{className:p.taskSaveStatusCenter,children:t.jsx("div",{className:`${p.taskSaveStatus} ${a==="error"?p.taskSaveStatusError:""}`,"aria-live":"polite",children:a==="saving"?t.jsxs(t.Fragment,{children:[t.jsx(Va,{size:14,className:p.spinner}),t.jsx("span",{children:"Saving…"})]}):a==="saved"?t.jsx("span",{children:"Saved"}):a==="error"?t.jsx("span",{children:"Save failed"}):null})}),t.jsx("div",{className:p.editActionsGroup,children:ie&&J?.deletedRecordId?t.jsxs(t.Fragment,{children:[ce&&t.jsx("button",{type:"button",className:p.actionBtn,onClick:()=>ce(J.deletedRecordId||""),disabled:n,title:"Restore deleted task",children:t.jsx(cd,{size:16})}),oe&&t.jsx("button",{type:"button",className:`${p.actionBtn} ${p.deleteBtn}`,onClick:()=>oe(J.deletedRecordId||""),disabled:n,title:"Permanently delete deleted task",children:t.jsx(Bc,{size:16})})]}):t.jsx(Vg,{task:J,disabled:n,statusDisabled:n||Q,archiveActionMode:Q?"unarchive":"auto",onSetStatus:(Se,ve)=>{if(B){B(Se,ve);return}if(ve==="in-progress"){I(Se);return}if(ve==="review"){x(Se);return}if(ve==="done"){A(Se);return}ve==="cancelled"&&M(Se)},onArchiveTask:ue,onUnarchiveTask:Se=>X?.(Se.id)})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:c,disabled:n,className:p.secondaryHeaderBtn,title:He("actionHeader.clearFormTitle"),children:[t.jsx(cd,{size:16}),He("actionHeader.clear")]}),t.jsxs("button",{type:"button",onClick:Se=>o(Se),disabled:n||!s.trim(),className:p.primaryUpdateBtn,title:He("actionHeader.addTaskTitle"),children:[n?t.jsx(Va,{size:16,className:p.spinner}):t.jsx(Cs,{size:16}),He("actionHeader.addTask")]})]})})}const YM="_topNoticeLayer_1m6a1_1",JM="_topNotice_1m6a1_1",XM="_topNoticeMessage_1m6a1_32",QM="_topNoticeSuccess_1m6a1_38",eD="_topNoticeError_1m6a1_44",tD="_topNoticeInfo_1m6a1_50",nD="_topNoticeDismiss_1m6a1_56",wi={topNoticeLayer:YM,topNotice:JM,topNoticeMessage:XM,topNoticeSuccess:QM,topNoticeError:eD,topNoticeInfo:tD,topNoticeDismiss:nD};function sy({notice:e,onDismiss:n}){if(!e)return null;const a=e.tone==="error"?wi.topNoticeError:e.tone==="success"?wi.topNoticeSuccess:wi.topNoticeInfo,s=e.tone==="error"?"alert":"status";return t.jsx("div",{className:wi.topNoticeLayer,children:t.jsxs("div",{className:`${wi.topNotice} ${a}`,role:s,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?t.jsx(Fc,{size:14}):e.tone==="success"?t.jsx(po,{size:14}):t.jsx(rk,{size:14}),t.jsx("span",{className:wi.topNoticeMessage,children:e.message}),n&&t.jsx("button",{type:"button",className:wi.topNoticeDismiss,onClick:n,"aria-label":"Dismiss notice",title:"Dismiss notice",children:t.jsx(Ei,{size:14})})]})})}const aD=pt.lazy(()=>Uo(()=>import("./TaskSettings-DZX4jk7e.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.TaskSettings})));function rD(e){const{activeTab:n,setActiveTab:a,isOpen:s,setIsOpen:o,currentTheme:c,setCurrentTheme:i,saveSettings:l,pathSaved:m,keyShortcut:y,setKeyShortcut:v,jsonBackupEnabled:b,setJsonBackupEnabled:g,mcpHostRoot:h,setMcpHostRoot:k,settingsSection:I,setSettingsSection:x,projectRoot:A,projectName:M,mcpScriptPath:B,serverHostRoot:ue,showFolderBrowser:X,setShowFolderBrowser:ce,folders:oe,files:be,currentBrowsePath:_,fetchFolders:J,browserTarget:Q,setBrowserTarget:ie,handleSelectPath:H,handleAddPath:P,handleRemovePath:U,tasks:se,loadingTasks:he,archivedTasks:V,deletedTasks:Ce,activeCategories:Se,activeTypes:ve,priorities:ge,taxonomyDisplayLabels:Te,approaches:Le,taxonomies:Ie,searchQuery:Oe,setSearchQuery:z,filterCategories:T,setFilterCategories:w,filterTypes:j,setFilterTypes:F,filterPriorities:ee,setFilterPriorities:N,filterStatus:C,setFilterStatus:$,filterAssignees:K,setFilterAssignees:te,assigneeOptions:L,filterTaxonomies:re,setFilterTaxonomies:fe,sortBy:xe,setSortBy:le,sortOrder:we,toggleSortOrder:Re,showArchive:Xe,setShowArchive:ze,taskScope:lt,setTaskScope:wt,clearFilters:$e,filteredTasks:ft,filteredArchive:gt,groupedTasks:at,collapsedCategories:dt,setCollapsedCategories:ne,handleEdit:tt,handleDelete:rt,handleCopyId:Pt,handleToggleComplete:yt,handleToggleCancel:Rt,handleToggleInProgress:Tt,handleToggleReview:Dt,handleArchiveTask:d,handleBulkArchive:Me,handleUnarchive:We,handleRestoreDeletedTask:Qe,handlePermanentlyDeleteDeletedTask:ot,handleEmptyDeletedTasks:de,fetchArchive:Be,editingTaskId:St,loading:vt,error:$t,title:Ze,setTitle:en,description:Lt,setDescription:bt,checklistItems:W,setChecklistItems:ke,category:Ne,setCategory:ae,type:Pe,setType:Ge,priority:De,setPriority:it,complexity:Ut,setComplexity:Gt,manualComplexityEnabled:nn,checklistDropdownEnabled:Ft,showTaskCardStatusLabel:Wt,approach:Vt,setApproach:an,assignee:Kt,setAssignee:Kn,scheduledDate:Fn,setScheduledDate:Jn,dueDate:_n,setDueDate:pe,workstreamInput:et,setWorkstreamInput:Ae,formTaxonomies:Nt,setFormTaxonomies:Ye,comments:Ot,newCommentText:dn,setNewCommentText:yn,attachments:on,setAttachments:rn,setAttachmentsDirty:kt,descriptionFocused:zt,setDescriptionFocused:Ln,showMarkdownHelp:Et,setShowMarkdownHelp:On,showChecklist:kn,setShowChecklist:Jt,showComments:Dr,setShowComments:Rn,handleSubmit:Xn,resetForm:In,handleAddComment:Yt,handleSetWorkstreamForCurrentTask:jn,handleOpenTaskById:ln,autoSaveState:ga,unsavedModalOpen:la,setUnsavedModalOpen:Za,pendingNavigation:fn,handleNavigation:Cr,handleClose:Lr,scheduleWarningPrompt:ya,confirmScheduleWarning:Bn,cancelScheduleWarning:Ar,uiNotice:ka,clearNotice:ja,taskReturnTrail:Qn,clearReturnToParentTask:Tn,returnToPreviousTask:Br,copiedId:_t,recentlyChangedTaskIds:Sa,tasksScrollRef:da,setTasksScrollPos:va,currentTask:$n,currentTaskWorkstream:Pa,currentTaskInitiative:wn,exportEnvironment:Un,setExportEnvironment:ba,exportWorkflowsPath:un,setExportWorkflowsPath:Ea,exportResult:Qt,exportingResource:qn,availableWorkflows:Cn,onExportWorkflows:Ya,availableEnvironments:Ja,handleUpdateCategory:Mn,handleRemoveCategory:cn,handleSaveCategory:hn,handleUpdateCategoryIcon:ua,handleUpdateCategoryColor:ea,handleSaveType:pr,handleRemoveType:fr,handleUpdateTaxonomies:Xt,handleUpdatePriorities:ms,pathValidation:zn,validatePaths:Xa,getCategoryPaths:Vr,commentsEndRef:ma,currentWorkspaceId:qa,settingsModel:Wr,onHeaderMouseDown:wa,isDragging:Hn}=e,Ir=r.useRef(null),[Pn,ps]=pt.useState(0);r.useLayoutEffect(()=>{if(n==="tasks"&&da.current&&Pn>0){const Ve=setTimeout(()=>{da.current&&(da.current.scrollTop=Pn)},50);return()=>clearTimeout(Ve)}},[n,Pn,se]);const ta=Ve=>{le(Ve)},Tr=()=>{Cr(()=>{if(n==="add"||n==="settings"){if(n==="add"&&Br())return;n==="add"&&Qn.length>0&&Tn(),n==="add"&&In(),a("tasks")}else e.onClose?e.onClose():Lr()})},hr=()=>{Za(!1),fn?(n==="add"&&In(),fn()):a("tasks")},Fr=async()=>{await Xn({preventDefault:()=>{}}),Za(!1),fn&&fn()},pa=(Ve,Bt)=>{Ye(Dn=>({...Dn,[Ve]:Bt})),Ve==="approach"&&typeof Bt=="string"&&an(Bt)},gr=r.useCallback(Ve=>{In(),ae(Ve),Cr(()=>{a("add")})},[In,ae,a,Cr]),xa=pt.useMemo(()=>Ce.map(Ve=>({...Ve.taskSnapshot,isDeleted:!0,deletedRecordId:Ve.id})),[Ce]),Ma=pt.useMemo(()=>new globalThis.Map(Ce.map(Ve=>[Ve.taskId,Ve])),[Ce]),Qa=pt.useMemo(()=>{const Ve=Oe.toLowerCase(),Bt=Se.every(Mt=>T.includes(Mt.value)),Dn=ve.every(Mt=>j.includes(Mt.value)),sn=Array.from(new Set(ee.map(Mt=>Number(Mt)).filter(Mt=>Number.isFinite(Mt)))),Zn=ge.map(Mt=>Number(Mt.value)).filter(Mt=>Number.isFinite(Mt)).every(Mt=>sn.includes(Mt)),Zr=["task","in-progress","review","done","cancelled","on-hold"].every(Mt=>C.includes(Mt)),Yr=L.length>0&&L.every(Mt=>K.includes(Mt.value)),Yn=kd(Ie,xa);return xa.filter(Mt=>{const mn=qs(Mt).toLowerCase(),Da=!Ve||Mt.title.toLowerCase().includes(Ve)||(Mt.description?.toLowerCase()||"").includes(Ve)||Mt.id.toLowerCase().includes(Ve)||mn.includes(Ve),yr=Bt||T.includes(Mt.category),kr=Zn||sn.includes(Zu(Mt.priority)),er=Dn||j.includes(Mt.type||Mr),fs=Zr||C.includes(Mt.status),Nr=Yr||K.includes(Mt.assignee||"unassigned"),Jr=Object.entries(re).every(([tr,ra])=>{const Ts=Yn.find(jt=>jt.id===tr);if(!Ts||of(Ts,xa).every(jt=>ra.includes(jt.value)))return!0;const Ct=Mt.taxonomies?.[tr];return Ct?Array.isArray(Ct)?Ct.some(jt=>ra.includes(jt)):ra.includes(Ct):ra.includes("")});return Da&&yr&&kr&&er&&fs&&Nr&&Jr}).sort((Mt,mn)=>nm(Mt,mn,xe,we,Ie))},[Se,ve,V,L,xa,K,T,ee,C,re,j,ge,Oe,xe,we,Ie,se]),Kr=pt.useMemo(()=>{const Ve={};return Qa.forEach(Bt=>{const sn=Se.find(_a=>_a.value===Bt.category||_a.label===Bt.category)?.label||Bt.category||"General";Ve[sn]||(Ve[sn]=[]),Ve[sn].push(Bt)}),Ve},[Se,Qa]),Or=lt==="archived"?gt.length:lt==="deleted"?Qa.length:ft.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:Ir,className:`${At.modal} ${p.coreModal} ${n==="settings"?At.settingsViewModal:""}`,"data-theme":c,children:[t.jsxs("div",{className:"tf-modal-header",onMouseDown:wa,style:{cursor:wa?Hn?"grabbing":"grab":"default"},children:[t.jsxs("div",{className:`tf-modal-title ${pn.headerTitleWidget}`,children:["Taskforce",M&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:p.projectSlash,children:"/"}),t.jsx("span",{className:p.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:M})]}),t.jsx("span",{className:p.taskCountBadge,title:`${lt.charAt(0).toUpperCase()+lt.slice(1)} tasks`,children:Or})]}),t.jsxs("div",{className:At.headerActions,children:[n==="tasks"&&t.jsx(t.Fragment,{children:t.jsx("button",{className:"tf-control-icon",onClick:()=>{Cr(()=>{In(),a("add")})},title:"Add New Task",children:t.jsx(Cs,{size:18})})}),t.jsx("button",{className:`tf-control-icon ${n==="settings"?"tf-control-icon-active":""}`,onClick:()=>{n!=="settings"&&Cr(()=>{a("settings")})},title:"Settings",children:t.jsx(qh,{size:18})}),t.jsx("button",{className:"tf-control-icon",onClick:Tr,title:n==="tasks"?"Close":"Back to Tasks",children:n==="tasks"?t.jsx(Ei,{size:20}):t.jsx(sk,{size:20})})]})]}),t.jsx(sy,{notice:ka,onDismiss:ja}),n==="add"&&t.jsx(ry,{editingTaskId:St,loading:vt,autoSaveState:ga,title:Ze,currentTask:$n,currentTaskWorkstream:Pa,currentTaskInitiative:wn,workstreamInput:et,onWorkstreamInputChange:Ae,onSetWorkstreamForCurrentTask:jn,handleSubmit:Xn,resetForm:In,handleCopyId:Pt,copiedId:_t,tasks:se,handleToggleInProgress:Tt,handleToggleReview:Dt,handleToggleComplete:yt,handleToggleCancel:Rt,handleArchiveTask:d,handleUnarchiveTask:Ve=>{if($n?.isDeleted){const Bt=Ma.get(Ve);Bt&&Qe(Bt.id);return}We(Ve)},handleRestoreDeletedTask:Ve=>{Qe(Ve)},handlePermanentlyDeleteDeletedTask:Ve=>{ot(Ve)}}),n==="tasks"&&t.jsx(Qg,{ref:da,tasks:se,archivedTasks:V,categories:Se,types:ve,priorities:ge,taxonomyDisplayLabels:Te,taxonomies:Ie,searchQuery:Oe,filterCategories:T,filterTypes:j,filterPriorities:ee,filterStatus:C,filterAssignees:K,assigneeOptions:L,filterTaxonomies:re,sortBy:xe,sortOrder:we,showArchive:Xe,taskScope:lt,collapsedCategories:dt,loadingTasks:he,filteredTasks:ft,filteredArchive:gt,groupedTasks:at,filteredDeletedTasks:Qa,groupedDeletedTasks:Kr,copiedId:_t,recentlyChangedTaskIds:Sa,showTaskCardStatusLabel:Wt,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:z,onFilterCategoriesChange:Ve=>w(Ve),onFilterTypesChange:Ve=>F(Ve),onFilterPrioritiesChange:N,onFilterStatusChange:$,onFilterAssigneesChange:Ve=>te(Ve),onTaxonomyFilterChange:(Ve,Bt)=>fe(Dn=>({...Dn,[Ve]:Bt})),onSortByChange:ta,onSortOrderChange:Re,onShowArchiveChange:ze,onTaskScopeChange:wt,onClearFilters:$e,onToggleCategory:Ve=>ne(Bt=>({...Bt,[Ve]:!Bt[Ve]})),onEditTask:tt,onOpenTaskById:ln,onCopyId:Pt,onToggleInProgress:Tt,onToggleReview:Dt,onToggleComplete:yt,onToggleCancel:Rt,onArchiveTask:d,onBulkArchive:Me,onUnarchive:Ve=>{const Bt=Ma.get(Ve);if(Bt){Qe(Bt.id);return}We(Ve)},onDelete:Ve=>{const Bt=Ma.get(Ve);if(Bt){ot(Bt.id);return}rt(Ve)},onDeleteAllDeleted:()=>{de()},onFetchArchive:Be,onAddTaskToCategory:gr,supplementalTasks:xa}),n==="add"&&t.jsx(ay,{editingTaskId:St,error:$t,title:Ze,description:Lt,checklistItems:W,category:Ne,type:Pe,priority:De,complexity:Ut,manualComplexityEnabled:nn,approach:Vt,assignee:Kt,scheduledDate:Fn,dueDate:_n,workstreamInput:et,formTaxonomies:Nt,onTaxonomyChange:pa,taxonomies:Ie,comments:Ot,newCommentText:dn,contextFiles:on,currentWorkspaceId:qa,apiBaseUrl:"",descriptionFocused:zt,showMarkdownHelp:Et,showChecklist:kn,checklistEnabled:Ft,showComments:Dr,categories:Se,types:ve,priorities:ge,taxonomyDisplayLabels:Te,assigneeOptions:L,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:_t,onTitleChange:en,onDescriptionChange:bt,onChecklistItemsChange:ke,onCategoryChange:ae,onTypeChange:Ge,onPriorityChange:it,onComplexityChange:Gt,onApproachChange:Ve=>{an(Ve),Ye(Bt=>({...Bt,approach:Ve}))},onAssigneeChange:Kn,onScheduledDateChange:Jn,onDueDateChange:pe,onWorkstreamInputChange:Ae,onNewCommentTextChange:yn,onDescriptionFocusedChange:Ln,onShowMarkdownHelpChange:On,onShowChecklistChange:Jt,onShowCommentsChange:Rn,onOpenSettings:Ve=>{Cr(()=>{x(Ve),a("settings")})},onSubmit:Xn,commentsEndRef:ma,onAddComment:()=>Yt(dn),onOpenTaskById:ln,onAddContextFile:Ve=>{kt(!0),rn(Bt=>[...Bt,Ve])},onRemoveContextFile:async Ve=>{kt(!0),rn(Bt=>Bt.filter((Dn,sn)=>sn!==Ve))},onUpdateContextCaption:(Ve,Bt)=>{kt(!0),rn(Dn=>Dn.map((sn,_a)=>_a!==Ve?sn:typeof sn=="string"?{path:sn,caption:Bt,timestamp:new Date().toISOString()}:{...sn,caption:Bt}))},onCopyId:Pt,onToggleInProgress:Tt,onToggleReview:Dt,onToggleComplete:yt,onToggleCancel:Rt,onArchiveTask:d,onUnarchive:Ve=>{if($n?.isDeleted){const Bt=Ma.get(Ve);Bt&&Qe(Bt.id);return}We(Ve)},currentTask:$n}),n==="settings"&&t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(aD,{settingsModel:Wr,onSectionChange:x})})]}),X&&Ii.createPortal(t.jsx("div",{className:En.overlay,children:t.jsxs("div",{className:En.browser,children:[t.jsxs("div",{className:En.header,children:[t.jsxs("div",{className:En.pathInfo,children:[t.jsx(Ni,{size:14}),t.jsx("span",{children:_||"Project Root"})]}),t.jsxs("div",{className:En.actions,children:[_&&t.jsx("button",{className:p.helpLink,onClick:()=>{const Ve=_.split("/").filter(Boolean);Ve.pop(),J(Ve.length?Ve.join("/")+"/":"")},children:"Back"}),t.jsx("button",{className:p.helpLink,onClick:()=>ce(!1),children:"Close"})]})]}),t.jsxs("div",{className:En.list,children:[Q&&typeof Q=="object"&&t.jsxs("div",{className:`${En.item} ${En.itemCurrent}`,onClick:()=>H(_),children:[t.jsx(po,{size:14})," Select Current: ./",_||"(root)"]}),oe.map(Ve=>t.jsxs("div",{className:En.item,onClick:()=>J(_+Ve+"/"),children:[t.jsx(Ni,{size:14})," ",Ve,"/"]},Ve)),be.map(Ve=>t.jsxs("div",{className:`${En.item} ${En.itemFile}`,onClick:()=>H(_+Ve),children:[t.jsx(xp,{size:14})," ",Ve]},Ve)),oe.length===0&&be.length===0&&t.jsx("div",{className:`${En.item} ${En.empty}`,children:"No items found"})]})]})}),document.body),la&&t.jsx("div",{className:`${At.overlay} ${At.unsavedOverlay}`,children:t.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${At.modal} ${At.unsavedModal}`,"data-theme":c,children:[t.jsx("div",{className:`tf-modal-header ${At.unsavedHeader}`,children:t.jsxs("div",{className:`tf-modal-title ${At.unsavedTitle}`,children:[t.jsx(Fc,{size:20}),"Unsaved Changes"]})}),t.jsx("div",{className:`${At.form} ${At.unsavedContent}`,children:t.jsx("p",{className:At.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),t.jsxs("div",{className:`${At.formActions} ${At.unsavedActions}`,children:[t.jsx("button",{className:p.cancelBtn,onClick:()=>Za(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),t.jsx("button",{className:p.destructiveBtn,onClick:hr,title:"Discard unsaved changes and leave",children:"Discard"}),t.jsxs("button",{className:p.submitBtn,onClick:Fr,disabled:vt,title:"Save changes and leave",children:[vt?t.jsx(Va,{size:16,className:p.spinner}):t.jsx(zh,{size:16}),"Save"]})]})]})}),ya&&t.jsx("div",{className:`${At.overlay} ${At.unsavedOverlay}`,children:t.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${At.modal} ${At.unsavedModal}`,"data-theme":c,children:[t.jsx("div",{className:`tf-modal-header ${At.unsavedHeader}`,children:t.jsxs("div",{className:`tf-modal-title ${At.unsavedTitle}`,children:[t.jsx(Fc,{size:20}),"Date Warning"]})}),t.jsxs("div",{className:`${At.form} ${At.unsavedContent}`,children:[t.jsx("p",{className:At.unsavedText,children:"Due date is before scheduled date."}),t.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",ya.dueDate," · Scheduled: ",ya.scheduledDate]})]}),t.jsxs("div",{className:`${At.formActions} ${At.unsavedActions}`,children:[t.jsx("button",{className:p.cancelBtn,onClick:Ar,children:"Go Back"}),t.jsx("button",{className:p.submitBtn,onClick:Bn,children:"Save Anyway"})]})]})})]})}const sD="_accountMenuWrap_1mocf_1",oD="_avatarBtn_1mocf_5",iD="_avatarBadge_1mocf_9",cD="_avatarImage_1mocf_24",lD="_avatarIcon_1mocf_30",dD="_accountMenu_1mocf_1",uD="_accountMenuItem_1mocf_48",mD="_accountMenuItemActive_1mocf_68",pD="_accountMenuSection_1mocf_73",fD="_accountMenuSectionLabel_1mocf_79",hD="_accountMenuMeta_1mocf_88",gD="_accountMenuHint_1mocf_93",yD="_accountIdentityEmail_1mocf_99",kD="_accountIdentityBlock_1mocf_104",SD="_accountIdentityMetaLine_1mocf_109",vD="_accountIdentityMetaAction_1mocf_116",bD="_accountIdentityMetaValue_1mocf_125",wD="_accountIdentityMetaLabel_1mocf_130",xD="_accountMenuError_1mocf_159",_D="_accountHubCard_1mocf_165",CD="_profileAvatarEditor_1mocf_172",AD="_profileEditLayout_1mocf_178",ID="_profileFieldStack_1mocf_185",TD="_profileFieldLabel_1mocf_191",mt={accountMenuWrap:sD,avatarBtn:oD,avatarBadge:iD,avatarImage:cD,avatarIcon:lD,accountMenu:dD,accountMenuItem:uD,accountMenuItemActive:mD,accountMenuSection:pD,accountMenuSectionLabel:fD,accountMenuMeta:hD,accountMenuHint:gD,accountIdentityEmail:yD,accountIdentityBlock:kD,accountIdentityMetaLine:SD,accountIdentityMetaAction:vD,accountIdentityMetaValue:bD,accountIdentityMetaLabel:wD,accountMenuError:xD,accountHubCard:_D,profileAvatarEditor:CD,profileEditLayout:AD,profileFieldStack:ID,profileFieldLabel:TD},ND="_authBlockedBanner_1virb_1",RD="_loginView_1virb_10",jD="_loginCard_1virb_20",PD="_loginCloseBtn_1virb_34",ED="_loginLogo_1virb_56",MD="_authBrandRow_1virb_62",DD="_setupHeaderRow_1virb_68",LD="_runtimeIconBadge_1virb_75",BD="_loginTitle_1virb_94",WD="_loginTitleAccent_1virb_105",FD="_loginSubtitle_1virb_109",OD="_loginError_1virb_115",$D="_loginField_1virb_121",UD="_loginFieldLabel_1virb_126",qD="_loginInput_1virb_133",zD="_loginPrimaryBtn_1virb_149",HD="_authPrimaryActions_1virb_154",GD="_registerConsent_1virb_159",VD="_registerConsentLink_1virb_167",KD="_authModeSwitch_1virb_177",ZD="_authModeSwitchLink_1virb_184",YD="_authModeLinks_1virb_199",JD="_authSecondaryActions_1virb_207",XD="_authModeLink_1virb_199",QD="_optionGrid_1virb_236",eL="_optionGroup_1virb_242",tL="_optionRow_1virb_247",nL="_inlineHint_1virb_254",aL="_actionRowEnd_1virb_260",rL="_oauthProviders_1virb_267",sL="_oauthDivider_1virb_274",oL="_oauthButtons_1virb_290",iL="_oauthButton_1virb_290",me={authBlockedBanner:ND,loginView:RD,loginCard:jD,loginCloseBtn:PD,loginLogo:ED,authBrandRow:MD,setupHeaderRow:DD,runtimeIconBadge:LD,loginTitle:BD,loginTitleAccent:WD,loginSubtitle:FD,loginError:OD,loginField:$D,loginFieldLabel:UD,loginInput:qD,loginPrimaryBtn:zD,authPrimaryActions:HD,registerConsent:GD,registerConsentLink:VD,authModeSwitch:KD,authModeSwitchLink:ZD,authModeLinks:YD,authSecondaryActions:JD,authModeLink:XD,optionGrid:QD,optionGroup:eL,optionRow:tL,inlineHint:nL,actionRowEnd:aL,oauthProviders:rL,oauthDivider:sL,oauthButtons:oL,oauthButton:iL};function cL(e={x:0,y:0}){const[n,a]=r.useState(e),[s,o]=r.useState(!1),[c,i]=r.useState({x:0,y:0}),[l,m]=r.useState(0),y=r.useRef(null),v=r.useCallback(h=>{const k=h.target;if(!(k.closest("button")||k.closest("input")||k.closest("select")||k.closest("textarea")||k.closest('[role="button"]')||k.closest(".no-drag"))){if(y.current){const I=y.current.getBoundingClientRect();m(I.top-n.y)}o(!0),i({x:h.clientX-n.x,y:h.clientY-n.y})}},[n]),b=r.useCallback(h=>{if(s){let k=h.clientX-c.x,I=h.clientY-c.y;I<-l&&(I=-l),a({x:k,y:I})}},[s,c,l]),g=r.useCallback(()=>{o(!1)},[]);return r.useEffect(()=>(s?(window.addEventListener("mousemove",b),window.addEventListener("mouseup",g)):(window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",g)),()=>{window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",g)}),[s,b,g]),{position:n,isDragging:s,handleMouseDown:v,modalRef:y,setPosition:a}}function As({isOpen:e,onClose:n,title:a,children:s,footer:o,size:c="md",theme:i=Ku,className:l,headerActions:m,draggable:y=!1,isSettings:v=!1,closeOnOverlayClick:b=!0}){const g=r.useRef(null),{position:h,isDragging:k,handleMouseDown:I,modalRef:x}=cL();if(r.useEffect(()=>{const M=B=>{B.key==="Escape"&&e&&n()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e,n]),r.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const A={sm:At.modalSizeSm,md:At.modalSizeMd,mdWide:At.modalSizeMdWide,lg:At.modalSizeLg,xl:At.modalSizeXl,full:At.modalSizeFull};return Ii.createPortal(t.jsx("div",{className:`${At.overlay} ${l||""} ${At.overlayHighZ}`,ref:g,onClick:M=>{b&&M.target===g.current&&n()},children:t.jsxs("div",{ref:x,className:`tf-surface-modal tf-modal-shell ${At.modal} tf-scrollbar-scope ${A[c]} ${y?At.draggableModal:""} ${v?At.settingsViewModal:""}`,"data-theme":i,style:{transform:y?`translate(${h.x}px, ${h.y}px)`:void 0,transition:k?"none":"transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s ease-out"},children:[t.jsxs("div",{className:`tf-modal-header ${y?At.draggableHeader:""}`,onMouseDown:y?I:void 0,style:{cursor:y?k?"grabbing":"grab":"default"},children:[t.jsx("div",{className:"tf-modal-title",children:a}),t.jsxs("div",{className:At.headerActions,children:[m,t.jsx("button",{className:"tf-control-icon",onClick:n,title:"Close",children:t.jsx(Ei,{size:20})})]})]}),t.jsx("div",{className:At.modalContent,children:s}),o&&t.jsx("div",{className:`${At.formActions} ${At.modalFooter}`,children:o})]})}),document.body)}const lL="_modalBody_1mute_1",dL="_mutedText_1mute_5",uL="_sectionText_1mute_10",mL="_sectionTextSpaced_1mute_15",pL="_sectionTextTop_1mute_20",fL="_errorText_1mute_25",hL="_inlineFieldLabel_1mute_29",gL="_wrapRow_1mute_35",yL="_actionRowEnd_1mute_42",kL="_modalActionsEnd_1mute_50",SL="_memberRow_1mute_56",vL="_memberTitle_1mute_62",bL="_memberActions_1mute_66",wL="_selectRole_1mute_73",xL="_selectPermission_1mute_77",_L="_inviteRow_1mute_81",CL="_listHeading_1mute_85",AL="_auditList_1mute_90",IL="_auditPager_1mute_96",TL="_labelFixed_1mute_103",ht={modalBody:lL,mutedText:dL,sectionText:uL,sectionTextSpaced:mL,sectionTextTop:pL,errorText:fL,inlineFieldLabel:hL,wrapRow:gL,actionRowEnd:yL,modalActionsEnd:kL,memberRow:SL,memberTitle:vL,memberActions:bL,selectRole:wL,selectPermission:xL,inviteRow:_L,listHeading:CL,auditList:AL,auditPager:IL,labelFixed:TL};function NL({isOpen:e,theme:n,onClose:a,onConfirm:s}){return t.jsx(As,{isOpen:e,onClose:a,title:"New Workspace",size:"sm",theme:n,draggable:!0,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:p.cancelBtn,onClick:a,children:"Cancel"}),t.jsx("button",{type:"button",className:p.submitBtn,onClick:s,children:"Start Setup"})]}),children:t.jsx("div",{className:`${At.form} ${ht.modalBody}`,children:t.jsx("p",{className:ht.sectionText,children:"Create and configure a new workspace."})})})}const RL=new Set(["active","trialing","grace"]),yh={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."},Bu={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 Pi(e){return String(e||"").trim()}function oy(e){return Pi(e).toLowerCase()}function jL(e){return Pi(e).toLowerCase()}function PL(e){return!!(Pi(e?.stripeCustomerId)||Pi(e?.stripeSubscriptionId))}function EL(e){const n=Pi(e?.trialEnd||e?.effectiveUntil);if(n){const a=new Date(n);if(!Number.isNaN(a.getTime()))return a.getTime()<=Date.now()?"Your trial end date has passed. Billing status is updating.":`Your trial is active through ${a.toLocaleString()}.`}return"Your trial is active. Continue to Taskforce or manage billing anytime."}function ML(e){return RL.has(oy(e))}function Fp(e,n){const a=oy(e?.entitlementState),s=jL(e?.gate||n),o=Pi(e?.billingConflictCode).toUpperCase(),c=Pi(e?.message),i=ML(a),l=PL(e);return o==="CHECKOUT_SESSION_EXPIRED"?{entitlementState:a||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:yh.CHECKOUT_SESSION_EXPIRED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:l,markCurrentPlan:!1}:o==="CHECKOUT_SESSION_SUPERSEDED"?{entitlementState:a||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:yh.CHECKOUT_SESSION_SUPERSEDED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:l,markCurrentPlan:!1}:a==="trialing"?{entitlementState:a,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:EL(e),primaryAction:l?"manage_billing":"none",primaryLabel:l?"Manage Billing":null,showManageBilling:l,markCurrentPlan:!0}:i?{entitlementState:a||null,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:c||null,primaryAction:"none",primaryLabel:null,showManageBilling:l,markCurrentPlan:!0}:a==="suspended"?{entitlementState:a,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access is suspended because billing needs attention. Update billing to restore access.",primaryAction:l?"manage_billing":"open_plans",primaryLabel:l?"Manage Billing":"Open Plans",showManageBilling:l,markCurrentPlan:!1}:a==="canceled"?{entitlementState:a,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access has ended. Choose a plan to reactivate your workspace.",primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:l,markCurrentPlan:!1}:a==="pending_plan_selection"||e?.planSelectionRequired===!0||s==="plan_selection_required"?{entitlementState:a||"pending_plan_selection",gate:s||"plan_selection_required",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:c||Bu.planSelectionRequired,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:a==="checkout_pending"||s==="checkout_pending"?{entitlementState:a||"checkout_pending",gate:s||"checkout_pending",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:c||Bu.checkoutPending,primaryAction:"open_plans",primaryLabel:"Open Plans",showManageBilling:l,markCurrentPlan:!1}:s==="misconfigured"?{entitlementState:a||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Bu.misconfigured,primaryAction:"none",primaryLabel:null,showManageBilling:!1,markCurrentPlan:!1}:s==="missing_entitlement"?{entitlementState:a||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Bu.missingEntitlement,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:{entitlementState:a||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:c?"error":"info",message:c||null,primaryAction:"none",primaryLabel:null,showManageBilling:l,markCurrentPlan:!1}}const Op=12,DL=new Set(["12345678","123456789","1234567890","admin123","changeme","letmein","letmein123","password","password1","password12","password123","password1234","qwerty","qwerty123","welcome","welcome123"]),LL=e=>String(e||"").trim().toLowerCase().replace(/[^a-z0-9]/g,"");function BL(e){const n=new Set,a=String(e?.email||"").trim().toLowerCase(),s=String(e?.displayName||"").trim().toLowerCase();if(a.includes("@")){const o=a.split("@")[0]||"",c=o.replace(/[^a-z0-9]/g,"");c.length>=4&&n.add(c);for(const i of o.split(/[^a-z0-9]+/))i.length>=4&&n.add(i)}for(const o of s.split(/[^a-z0-9]+/))o.length>=4&&n.add(o);return[...n]}function iy(){return[`Use at least ${Op} characters.`,"Avoid common passwords or obvious patterns.","Do not include your email or display name."]}function cy(e,n){const a=String(e||"");if(!a)return{ok:!1,code:"PASSWORD_REQUIRED",message:"Password is required."};if(a.length<Op)return{ok:!1,code:"PASSWORD_TOO_SHORT",message:`Password must be at least ${Op} characters.`};const s=LL(a);return DL.has(s)?{ok:!1,code:"PASSWORD_TOO_COMMON",message:"Choose a less common password."}:BL(n).some(c=>s.includes(c))?{ok:!1,code:"PASSWORD_CONTAINS_PERSONAL_INFO",message:"Password cannot contain your email or display name."}:{ok:!0}}function WL({isOpen:e,theme:n,runtimeMode:a,authRequiredForApi:s,isAuthenticated:o,hasAuthIdentity:c,authIdentityLabel:i,billingLoading:l,billingError:m,billingActionError:y,billingNotice:v,billingActionBusy:b,billingIntervalChoice:g,accountProfileSummary:h,currentWorkspaceId:k,canOpenTeamManagement:I,canManageWorkspaceSync:x,workspaceCloudSyncEnabled:A,syncStatusLabel:M,workspaceSyncError:B,syncControlBusy:ue,cloudAuthEnabled:X,availableAuthProviders:ce,onFetchLoginMethods:oe,onUnlinkLoginMethod:be,onAddPassword:_,onLinkProvider:J,onClose:Q,onOpenWorkspaceAudit:ie,onBillingIntervalChange:H,onRefreshBilling:P,onUpdateInterval:U,onManageBilling:se,onStartCheckout:he,onToggleWorkspaceSync:V,onOpenHelp:Ce}){const Se=Fp(h),ve=iy(),ge=Se.message,Te=Se.primaryLabel||"Start Checkout",Le=String(h?.planName||h?.planId||"n/a").trim()||"n/a",Ie=()=>{if(Se.primaryAction==="manage_billing"){se();return}he()},[Oe,z]=r.useState([]),[T,w]=r.useState(!1),[j,F]=r.useState(null),[ee,N]=r.useState(null),[C,$]=r.useState(null),[K,te]=r.useState(!1),[L,re]=r.useState(""),[fe,xe]=r.useState(!1),[le,we]=r.useState(null),[Re,Xe]=r.useState(!1);r.useEffect(()=>{!e||!o||!X||(w(!0),F(null),oe().then(at=>{w(!1),at.success&&at.methods?z(at.methods):F(at.error||"Failed to load login methods.")}))},[e,o,X,oe]);const ze=async at=>{N(at),$(null);const dt=await be(at);N(null),dt.success?z(ne=>ne.filter(tt=>tt.provider!==at)):$(dt.error||"Unlink failed.")},lt=async()=>{const at=cy(L);if(!at.ok){we(at.message||"Password does not meet the password policy.");return}xe(!0),we(null);const dt=await _(L);if(xe(!1),!dt.success)we(dt.error||"Failed to add password.");else{Xe(!0),re(""),te(!1);const ne=await oe();ne.success&&ne.methods&&z(ne.methods)}},wt={password:"Email & Password",google:"Google",github:"GitHub",apple:"Apple"},$e=new Set(Oe.map(at=>at.provider)),ft=$e.has("password"),gt=ce.filter(at=>at!=="password"&&!$e.has(at));return t.jsx(As,{isOpen:e,onClose:Q,title:"Account Hub",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${At.form} ${ht.modalBody}`,children:[t.jsx("p",{className:ht.mutedText,children:"Manage sign in, profile, and workspace controls from one place."}),t.jsxs("div",{className:mt.accountHubCard,children:[t.jsx("strong",{children:"Authentication"}),t.jsx("p",{className:ht.sectionText,children:a==="cloud"?s?o?"Signed in. API access is enabled.":"Cloud mode requires sign in before app usage.":"Cloud runtime with optional authentication.":"Local runtime allows guest usage without sign in."}),t.jsx("p",{className:ht.sectionTextSpaced,children:o?c?t.jsxs(t.Fragment,{children:["Signed in as ",t.jsx("span",{className:mt.accountIdentityEmail,children:i})]}):"Signed in":"Signed in as: not signed in"}),a==="cloud"&&s&&!o&&t.jsx("p",{className:ht.sectionTextTop,children:"Use the `/login` screen to sign in."})]}),o&&X&&t.jsxs("div",{className:mt.accountHubCard,children:[t.jsx("strong",{children:"Login Methods"}),T&&t.jsx("p",{className:ht.sectionText,children:"Loading..."}),j&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:j}),C&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:C}),Re&&t.jsx("p",{className:ht.sectionText,style:{color:"var(--color-success, #4ade80)"},children:"Password login added."}),!T&&Oe.length>0&&t.jsx("div",{style:{marginTop:8,display:"grid",gap:6},children:Oe.map(at=>t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsxs("span",{className:ht.sectionText,children:[t.jsx("strong",{children:wt[at.provider]||at.provider}),at.providerEmail?t.jsxs(t.Fragment,{children:[" · ",t.jsx("span",{className:mt.accountMenuMeta,children:at.providerEmail})]}):null]}),Oe.length>1&&t.jsx("button",{className:p.cancelBtn,style:{fontSize:11,padding:"2px 8px"},disabled:ee===at.provider,onClick:()=>ze(at.provider),children:ee===at.provider?"Removing…":"Remove"})]},at.provider))}),!T&&!ft&&!K&&t.jsx("div",{className:ht.actionRowEnd,children:t.jsx("button",{className:p.cancelBtn,onClick:()=>{te(!0),Xe(!1),we(null)},children:"Add Password Login"})}),K&&t.jsxs("div",{style:{marginTop:10,display:"grid",gap:6},children:[t.jsxs("label",{className:mt.accountMenuMeta,style:{display:"block"},children:["New password",t.jsx("input",{type:"password",className:p.input,placeholder:"Use 12+ characters",value:L,onChange:at=>re(at.target.value),disabled:fe,style:{marginTop:4,display:"block",width:"100%"},autoComplete:"new-password"})]}),t.jsx("p",{className:mt.accountMenuMeta,style:{margin:0},children:ve.join(" ")}),le&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:le}),t.jsxs("div",{className:ht.actionRowEnd,children:[t.jsx("button",{className:p.cancelBtn,onClick:()=>{te(!1),re(""),we(null)},disabled:fe,children:"Cancel"}),t.jsx("button",{className:p.submitBtn,onClick:lt,disabled:fe||!L,children:fe?"Saving…":"Save Password"})]})]}),!T&&gt.length>0&&t.jsxs("div",{style:{marginTop:10},children:[t.jsx("p",{className:mt.accountMenuMeta,style:{marginBottom:6},children:"Link another account:"}),t.jsx("div",{className:me.oauthButtons,children:gt.map(at=>t.jsx("button",{className:me.oauthButton,onClick:()=>J(at),children:wt[at]||at},at))})]})]}),t.jsxs("div",{className:mt.accountHubCard,children:[t.jsx("strong",{children:"Profile & Account"}),t.jsx("p",{className:ht.sectionText,children:"Profile editing and account preferences will live here."})]}),t.jsxs("div",{className:mt.accountHubCard,children:[t.jsx("strong",{children:"Billing"}),o?a!=="cloud"?t.jsx("p",{className:ht.sectionText,children:"Billing remains cloud-backed in local runtime and uses your connected cloud account."}):t.jsxs(t.Fragment,{children:[l&&t.jsx("p",{className:ht.sectionTextSpaced,children:"Loading billing status..."}),m&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:m}),y&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:y}),v&&t.jsx("p",{className:ht.errorText,children:v}),ge&&t.jsx("p",{className:ht.sectionText,children:ge}),t.jsxs("p",{className:ht.sectionTextSpaced,children:["Plan: ",t.jsx("code",{children:Le})," · ","Entitlement: ",t.jsx("code",{children:String(h?.entitlementState||"n/a")})]}),t.jsxs("p",{className:ht.sectionText,children:["Stripe status: ",t.jsx("code",{children:String(h?.stripeStatus||"n/a")}),h?.effectiveUntil?` · Effective until ${new Date(h.effectiveUntil).toLocaleString()}`:""]}),t.jsx("div",{className:ht.wrapRow,children:t.jsxs("label",{className:`${mt.accountMenuMeta} ${ht.inlineFieldLabel}`,children:["Interval",t.jsxs("select",{className:p.input,value:g,onChange:at=>H(at.target.value==="year"?"year":"month"),disabled:b,children:[t.jsx("option",{value:"month",children:"Monthly"}),t.jsx("option",{value:"year",children:"Yearly"})]})]})}),t.jsxs("div",{className:ht.actionRowEnd,children:[t.jsx("button",{className:p.cancelBtn,onClick:P,disabled:b||l,children:"Refresh Billing"}),t.jsx("button",{className:p.cancelBtn,onClick:U,disabled:b||!h?.stripeSubscriptionId,children:"Update Interval"}),t.jsx("button",{className:p.cancelBtn,onClick:se,disabled:b||!h?.stripeCustomerId,children:"Manage Billing"}),t.jsx("button",{className:p.submitBtn,onClick:Ie,disabled:b||Se.primaryAction==="manage_billing"&&!h?.stripeCustomerId,children:b?"Working...":Te})]})]}):t.jsx("p",{className:ht.sectionText,children:"Sign in to manage subscription billing."})]}),t.jsxs("div",{className:mt.accountHubCard,children:[t.jsx("strong",{children:"Workspace Audit Log"}),t.jsx("p",{className:ht.sectionText,children:"Audit entries are workspace-scoped for the active workspace, not global account history."}),t.jsxs("p",{className:ht.sectionText,children:["Active workspace: ",t.jsx("code",{children:k})]}),t.jsx("div",{className:ht.actionRowEnd,children:t.jsx("button",{className:p.cancelBtn,onClick:ie,disabled:!I,children:"Open Workspace Audit"})})]}),t.jsxs("div",{className:mt.accountHubCard,children:[t.jsx("strong",{children:"Workspace Cloud Sync"}),t.jsx("p",{className:ht.sectionText,children:x?A?`Enabled · ${M}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),B&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:B}),t.jsx("div",{className:ht.actionRowEnd,children:t.jsx("button",{className:p.cancelBtn,disabled:!x||ue,onClick:()=>V(!A),children:A?"Disable Sync":"Enable Sync"})})]}),t.jsxs("div",{className:`${At.formActions} ${ht.modalActionsEnd}`,children:[t.jsx("button",{className:p.cancelBtn,onClick:Ce,children:"Help & Tutorial"}),t.jsx("button",{className:p.submitBtn,onClick:Q,children:"Close"})]})]})})}var kh=(e,n,a,s,o,c)=>{if(c===0)e.rect(n,a,s,o);else{let i=s-c,l=o-c;e.translate(n,a),e.arc(c,c,c,Math.PI,Math.PI*1.5),e.lineTo(i,0),e.arc(i,c,c,Math.PI*1.5,Math.PI*2),e.lineTo(s,l),e.arc(i,l,c,Math.PI*2,Math.PI*.5),e.lineTo(c,o),e.arc(c,l,c,Math.PI*.5,Math.PI),e.closePath(),e.translate(-n,-a)}},FL=(e,n,a,s,o,c)=>{e.fillStyle=c;let i=s/3,l=o/3;e.fillRect(n,a,1,o),e.fillRect(i+n,a,1,o),e.fillRect(i*2+n,a,1,o),e.fillRect(i*3+n,a,1,o),e.fillRect(i*4+n,a,1,o),e.fillRect(n,a,s,1),e.fillRect(n,l+a,s,1),e.fillRect(n,l*2+a,s,1),e.fillRect(n,l*3+a,s,1),e.fillRect(n,l*4+a,s,1)},OL=e=>!!e.match(/^\s*data:([a-z]+\/[a-z]+(;[a-z-]+=[a-z-]+)?)?(;base64)?,[a-z0-9!$&',()*+;=\-._~:@/?%\s]*\s*$/i),ly=(e,n)=>new Promise((a,s)=>{let o=new Image;o.addEventListener("load",()=>a(o)),o.addEventListener("error",s),!OL(e)&&n&&(o.crossOrigin=n),o.src=e}),$L=e=>new Promise((n,a)=>{let s=new FileReader;s.addEventListener("load",o=>{try{if(!o?.target?.result)throw Error("No image data");n(ly(o.target.result))}catch(c){a(c)}}),s.readAsDataURL(e)}),UL=typeof File<"u",Sh=e=>Math.PI/180*e,vh={x:.5,y:.5},qL=class{constructor(e){this.imageState=vh,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 n=e??this.config.border;return Array.isArray(n)?n:[n,n]}getDimensions(){let{width:e,height:n,rotate:a,border:s}=this.config,o={width:0,height:0},[c,i]=this.getBorders(s);return this.isVertical()?(o.width=n,o.height=e):(o.width=e,o.height=n),o.width+=c*2,o.height+=i*2,{canvas:o,rotate:a,width:e,height:n,border:s}}getXScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.width/this.config.height,n=this.imageState.width/this.imageState.height;return Math.min(1,e/n)}getYScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.height/this.config.width,n=this.imageState.height/this.imageState.width;return Math.min(1,e/n)}getCroppingRect(e){if(!this.imageState.width||!this.imageState.height)return{x:0,y:0,width:1,height:1};let n=e||{x:this.imageState.x,y:this.imageState.y},a=1/this.config.scale*this.getXScale(),s=1/this.config.scale*this.getYScale(),o={x:n.x-a/2,y:n.y-s/2,width:a,height:s},c=0,i=1-o.width,l=0,m=1-o.height;return(this.config.disableBoundaryChecks||a>1||s>1)&&(c=-o.width,i=1,l=-o.height,m=1),{...o,x:Math.max(c,Math.min(o.x,i)),y:Math.max(l,Math.min(o.y,m))}}getInitialSize(e,n){let a,s,o=this.getDimensions();return o.height/o.width>n/e?(a=o.height,s=a/n*e):(s=o.width,a=s/e*n),{height:a,width:s}}async loadImage(e){let n;if(UL&&e instanceof File)n=await $L(e);else if(typeof e=="string")n=await ly(e,this.config.crossOrigin);else throw Error("Invalid image source");let a={...this.getInitialSize(n.width,n.height),resource:n,x:.5,y:.5};return this.imageState=a,a}clearImage(){this.imageState=vh}calculatePosition(e=this.imageState,n){let[a,s]=this.getBorders(n);if(!e.width||!e.height)throw Error("Image dimension is unknown.");let o=this.getCroppingRect(),c=e.width*this.config.scale,i=e.height*this.config.scale,l=-o.x*c,m=-o.y*i;return this.isVertical()?(l+=s,m+=a):(l+=a,m+=s),{x:l,y:m,height:i,width:c}}paint(e){e.save(),e.scale(this.pixelRatio,this.pixelRatio),e.translate(0,0),e.fillStyle="rgba("+this.config.color.slice(0,4).join(",")+")";let n=this.config.borderRadius,a=this.getDimensions(),[s,o]=this.getBorders(a.border),c=a.canvas.height,i=a.canvas.width;n=Math.max(n,0),n=Math.min(n,i/2-s,c/2-o),e.beginPath(),kh(e,s,o,i-s*2,c-o*2,n),e.rect(i,0,-i,c),e.fill("evenodd"),this.config.borderColor&&(e.strokeStyle="rgba("+this.config.borderColor.slice(0,4).join(",")+")",e.lineWidth=1,e.beginPath(),kh(e,s+.5,o+.5,i-s*2-1,c-o*2-1,n),e.stroke()),this.config.showGrid&&FL(e,s,o,i-s*2,c-o*2,this.config.gridColor),e.restore()}paintImage(e,n,a,s=this.pixelRatio){if(!n.resource)return;let o=this.calculatePosition(n,a);e.save(),e.translate(e.canvas.width/2,e.canvas.height/2),e.rotate(this.config.rotate*Math.PI/180),e.translate(-(e.canvas.width/2),-(e.canvas.height/2)),this.isVertical()&&e.translate((e.canvas.width-e.canvas.height)/2,(e.canvas.height-e.canvas.width)/2),e.scale(s,s),e.globalCompositeOperation="destination-over",e.drawImage(n.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(),n=this.imageState;if(!n.resource)throw Error("No image resource available, please report this to: https://github.com/mosch/react-avatar-editor/issues");e.x*=n.resource.width,e.y*=n.resource.height,e.width*=n.resource.width,e.height*=n.resource.height;let a=document.createElement("canvas");this.isVertical()?(a.width=Math.round(e.height),a.height=Math.round(e.width)):(a.width=Math.round(e.width),a.height=Math.round(e.height));let s=a.getContext("2d");if(!s)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return s.translate(a.width/2,a.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(a.width/2),-(a.height/2)),this.isVertical()&&s.translate((a.width-a.height)/2,(a.height-a.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,a.width,a.height)),s.drawImage(n.resource,-e.x,-e.y),a}getImageScaledToCanvas(){let e=this.getDimensions(),n=this.imageState,a=document.createElement("canvas");if(this.isVertical()?(a.width=e.height,a.height=e.width):(a.width=e.width,a.height=e.height),!n.resource)return a;let s=a.getContext("2d");if(!s)return a;let o=this.calculatePosition(n,0);return s.save(),s.translate(a.width/2,a.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(a.width/2),-(a.height/2)),this.isVertical()&&s.translate((a.width-a.height)/2,(a.height-a.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,a.width,a.height)),s.drawImage(n.resource,o.x,o.y,o.width,o.height),s.restore(),a}calculateDragPosition(e,n,a,s){let o=a-e,c=s-n;if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let i=this.imageState.width*this.config.scale,l=this.imageState.height*this.config.scale,{x:m,y}=this.getCroppingRect();m*=i,y*=l;let v=this.config.rotate;v%=360,v=v<0?v+360:v;let b=Math.cos(Sh(v)),g=Math.sin(Sh(v)),h=m+o*b+c*g,k=y+-o*g+c*b,I=1/this.config.scale*this.getXScale(),x=1/this.config.scale*this.getYScale();return{x:h/i+I/2,y:k/l+x/2}}},bh=()=>{},zL=()=>{let e=!1;try{let n=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",bh,n),window.removeEventListener("test",bh,n)}catch{e=!1}return e},dy=r.forwardRef((e,n)=>{let{scale:a=1,rotate:s=0,border:o=25,borderRadius:c=0,width:i=200,height:l=200,color:m=[0,0,0,.5],showGrid:y=!1,gridColor:v="#666",disableBoundaryChecks:b=!1,disableHiDPIScaling:g=!1,disableCanvasRotation:h=!0,image:k,position:I,backgroundColor:x,crossOrigin:A,onLoadStart:M,onLoadFailure:B,onLoadSuccess:ue,onImageReady:X,onImageChange:ce,onMouseUp:oe,onMouseMove:be,onPositionChange:_,borderColor:J,style:Q}=e,ie=r.useRef(null),H=r.useRef(new qL({width:i,height:l,border:o,borderRadius:c,scale:a,rotate:s,color:m,backgroundColor:x,borderColor:J,showGrid:y,gridColor:v,disableBoundaryChecks:b,disableHiDPIScaling:g,disableCanvasRotation:h,crossOrigin:A})),P=r.useRef(!1),U=r.useRef(void 0),se=r.useRef(void 0),[he,V]=r.useState(!1),[Ce,Se]=r.useState(!1),[ve,ge]=r.useState(H.current.getImageState()),Te=r.useRef(oe);Te.current=oe;let Le=r.useRef(be);Le.current=be;let Ie=r.useRef(_);Ie.current=_,r.useEffect(()=>{H.current.updateConfig({width:i,height:l,border:o,borderRadius:c,scale:a,rotate:s,color:m,backgroundColor:x,borderColor:J,showGrid:y,gridColor:v,disableBoundaryChecks:b,disableHiDPIScaling:g,disableCanvasRotation:h,crossOrigin:A})},[i,l,o,c,a,s,m,x,J,y,v,b,g,h,A]);let Oe=r.useCallback(()=>{if(!ie.current)throw Error("No canvas found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return ie.current},[]),z=r.useCallback(()=>{let te=Oe().getContext("2d");if(!te)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return te},[Oe]),T=r.useCallback(async te=>{Se(!0),M?.();try{let L=await H.current.loadImage(te);P.current=!1,V(!1),ge(L),X?.(),ue?.(L)}catch{B?.()}finally{Se(!1)}},[M,X,ue,B]),w=r.useCallback(()=>{let te=Oe();z().clearRect(0,0,te.width,te.height),H.current.clearImage(),ge(H.current.getImageState())},[Oe,z]),j=r.useCallback(()=>{let te=z(),L=Oe();te.clearRect(0,0,L.width,L.height),H.current.paint(te),H.current.paintImage(te,ve,o)},[z,Oe,ve,o,i,l,c,a,s,m,x,J,y,v,b,g,h,A]),F=r.useCallback(te=>{te.preventDefault(),P.current=!0,U.current=void 0,se.current=void 0,V(!0)},[]),ee=r.useCallback(()=>{P.current=!0,U.current=void 0,se.current=void 0,V(!0)},[]);r.useImperativeHandle(n,()=>({getImage:()=>H.current.getImage(),getImageScaledToCanvas:()=>H.current.getImageScaledToCanvas(),getCroppingRect:()=>H.current.getCroppingRect()}),[]),r.useEffect(()=>{let te=z();k&&T(k),H.current.paint(te);let L=xe=>{if(!P.current)return;xe.cancelable&&xe.preventDefault();let le="targetTouches"in xe?xe.targetTouches[0].pageX:xe.clientX,we="targetTouches"in xe?xe.targetTouches[0].pageY:xe.clientY,Re=U.current,Xe=se.current;if(U.current=le,se.current=we,Re!==void 0&&Xe!==void 0){let ze=H.current.getImageState();if(ze.width&&ze.height){let lt=H.current.calculateDragPosition(le,we,Re,Xe);Ie.current?.(lt);let wt={...ze,...lt};H.current.setImageState(wt),ge(wt)}}Le.current?.(xe)},re=()=>{P.current&&(P.current=!1,V(!1),Te.current?.())},fe=zL()?{passive:!1}:!1;return document.addEventListener("mousemove",L,fe),document.addEventListener("mouseup",re,fe),document.addEventListener("touchmove",L,fe),document.addEventListener("touchend",re,fe),()=>{document.removeEventListener("mousemove",L,!1),document.removeEventListener("mouseup",re,!1),document.removeEventListener("touchmove",L,!1),document.removeEventListener("touchend",re,!1)}},[]),r.useEffect(()=>{k?T(k):!k&&ve.x!==.5&&ve.y!==.5&&w()},[k,i,l,x]),r.useEffect(()=>{j()},[j]),r.useEffect(()=>{if(!Ce)return;let te=ie.current;if(!te)return;let L=te.getContext("2d");if(!L)return;let re,fe=performance.now(),xe=le=>{let we=(le-fe)/1e3,Re=.03+Math.sin(we*2.5)*.02+.02;L.save(),L.clearRect(0,0,te.width,te.height),L.fillStyle=`rgba(255,255,255,${Re})`,L.fillRect(0,0,te.width,te.height),L.restore(),re=requestAnimationFrame(xe)};return re=requestAnimationFrame(xe),()=>cancelAnimationFrame(re)},[Ce]);let N=r.useRef({image:k,width:i,height:l,position:I,scale:a,rotate:s,imageX:ve.x,imageY:ve.y});r.useEffect(()=>{let te=N.current;(te.image!==k||te.width!==i||te.height!==l||te.position!==I||te.scale!==a||te.rotate!==s||te.imageX!==ve.x||te.imageY!==ve.y)&&(ce?.(),N.current={image:k,width:i,height:l,position:I,scale:a,rotate:s,imageX:ve.x,imageY:ve.y})},[k,i,l,I,a,s,ve.x,ve.y,ce]);let C=H.current.getDimensions(),$=H.current.getPixelRatio(),K={width:C.canvas.width,height:C.canvas.height,cursor:he?"grabbing":"grab",touchAction:"none",maxWidth:"none",maxHeight:"none"};return pt.createElement("canvas",{width:C.canvas.width*$,height:C.canvas.height*$,onMouseDown:F,onTouchStart:ee,style:{...K,...Q},ref:ie})});dy.displayName="AvatarEditor";const HL="_avatarManagerBody_1bfwv_1",GL="_editorPanel_1bfwv_7",VL="_editorFrame_1bfwv_13",KL="_gifPreviewImage_1bfwv_21",ZL="_emptyPreview_1bfwv_28",YL="_controlPanel_1bfwv_41",JL="_zoomField_1bfwv_47",XL="_zoomSlider_1bfwv_52",QL="_actionGrid_1bfwv_57",e1="_fileInput_1bfwv_63",t1="_messageStack_1bfwv_67",ws={avatarManagerBody:HL,editorPanel:GL,editorFrame:VL,gifPreviewImage:KL,emptyPreview:ZL,controlPanel:YL,zoomField:JL,zoomSlider:XL,actionGrid:QL,fileInput:e1,messageStack:t1},pp=512,n1=48,Wu=512;function wh(e,n,a){return new Promise(s=>{e.toBlob(s,n,a)})}function a1(e,n){const a=String(e).trim()||"avatar",s=a.lastIndexOf(".");return s<=0?`${a}${n}`:`${a.slice(0,s)}${n}`}async function r1(e,n){const a=e.getImageScaledToCanvas(),s=document.createElement("canvas");s.width=Wu,s.height=Wu;const o=s.getContext("2d");if(!o)throw new Error("Image editing requires a 2D canvas context.");o.drawImage(a,0,0,Wu,Wu);const i=await wh(s,"image/webp",.9)||await wh(s,"image/jpeg",.9);if(!i)throw new Error("Unable to prepare profile photo.");const l=i.type||"image/jpeg",m=l==="image/webp"?".webp":".jpg";return new File([i],a1(n,m),{type:l,lastModified:Date.now()})}function s1({isOpen:e,theme:n,title:a="Edit Photo",currentImageUrl:s,editorImageUrl:o="",fallbackInitial:c,accept:i,busy:l,hasPendingImage:m,canRemove:y,error:v,notice:b,onClose:g,onApplyImage:h,onRemoveImage:k,onDiscardPendingImage:I}){const x=r.useRef(null),A=r.useRef(null),[M,B]=r.useState(null),[ue,X]=r.useState(""),[ce,oe]=r.useState(1.1),[be,_]=r.useState(null),[J,Q]=r.useState(null);r.useEffect(()=>{e||(B(null),X(""),oe(1.1),_(null),Q(null))},[e]),r.useEffect(()=>{if(!M){X("");return}const ve=URL.createObjectURL(M);return X(ve),()=>URL.revokeObjectURL(ve)},[M]);const ie=ue||o||s,H=M?.name||"avatar",P=String(c||"").trim().charAt(0).toUpperCase(),U=be||v,se=J||b,he=r.useCallback(ve=>{if(_(null),Q(null),!!ve){if(!ve.type.startsWith("image/")){_("Profile photo must be an image file.");return}ve.type==="image/gif"&&Q("Animated GIFs will upload without repositioning."),B(ve),oe(1.1)}},[]),V=r.useCallback(async()=>{_(null);const ve=x.current;if(M?.type==="image/gif"){await h(M)&&g();return}if(!ve||!ie){_("Choose a profile photo first.");return}try{const ge=await r1(ve,H);await h(ge,M)&&g()}catch(ge){_(ge instanceof Error?ge.message:"Unable to prepare profile photo.")}},[ie,h,g,M,H]),Ce=M?.type==="image/gif"||!!ie,Se=r.useMemo(()=>t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:p.secondaryButton,onClick:g,disabled:l,children:"Cancel"}),t.jsx("button",{type:"button",className:p.primaryUpdateBtn,onClick:()=>{V()},disabled:l||!Ce,children:l?"Applying...":"Apply Photo"})]}),[l,Ce,V,g]);return t.jsx(As,{isOpen:e,onClose:g,title:a,size:"md",theme:n,draggable:!0,footer:Se,children:t.jsxs("div",{className:ws.avatarManagerBody,children:[t.jsxs("div",{className:ws.editorPanel,children:[t.jsx("div",{className:`tf-surface-inset ${ws.editorFrame}`,children:M?.type==="image/gif"&&ue?t.jsx("img",{src:ue,alt:"",className:ws.gifPreviewImage}):ie?t.jsx(dy,{ref:x,image:ie,width:pp,height:pp,border:n1,borderRadius:pp/2,scale:ce,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}):t.jsx("div",{className:ws.emptyPreview,"aria-hidden":"true",children:P})}),t.jsxs("div",{className:ws.controlPanel,children:[t.jsx("input",{ref:A,type:"file","aria-label":"Choose profile photo",accept:i,className:ws.fileInput,onChange:ve=>he(ve.target.files?.[0]||null),disabled:l}),t.jsxs("div",{className:ws.actionGrid,children:[t.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>A.current?.click(),disabled:l,children:[t.jsx(ok,{size:16}),"Choose"]}),m&&I&&t.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:I,disabled:l,children:[t.jsx(cd,{size:16}),"Discard"]}),y&&k&&t.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",onClick:k,disabled:l,children:[t.jsx(Bc,{size:16}),"Remove"]})]}),t.jsxs("label",{className:`tf-field-stack ${ws.zoomField}`,children:[t.jsx("span",{className:"tf-field-label",children:"Zoom"}),t.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:ce,onChange:ve=>oe(Number(ve.target.value)),className:ws.zoomSlider,disabled:l||!ie||M?.type==="image/gif"})]})]})]}),(U||se)&&t.jsxs("div",{className:ws.messageStack,children:[U&&t.jsx("p",{className:"tf-text-error",children:U}),se&&!U&&t.jsx("p",{className:"tf-text-helper",children:se})]})]})})}const o1="_editableAvatarButton_1ga39_1",i1="_editableAvatarImage_1ga39_47",c1="_editableAvatarFallback_1ga39_54",l1="_editableAvatarBadge_1ga39_65",Fu={editableAvatarButton:o1,editableAvatarImage:i1,editableAvatarFallback:c1,editableAvatarBadge:l1};function d1({label:e,imageUrl:n,fallback:a,accentColor:s,size:o=52,width:c,height:i,radius:l,editBadgeSize:m,editIconSize:y=16,disabled:v=!1,className:b="",onClick:g}){const h=String(n||"").trim(),k=c??o,I=i??o,x=typeof l=="number"?`${l}px`:l,A=typeof m=="number"?`${m}px`:m;return t.jsxs("button",{type:"button",className:`${Fu.editableAvatarButton} ${b}`.trim(),"aria-label":e,title:e,onClick:g,disabled:v,style:{"--editable-avatar-size":`${o}px`,"--editable-avatar-width":`${k}px`,"--editable-avatar-height":`${I}px`,...x?{"--editable-avatar-radius":x}:{},...A?{"--editable-avatar-badge-size":A}:{},...s?{"--editable-avatar-accent":s}:{}},children:[h?t.jsx("img",{src:h,alt:"",className:Fu.editableAvatarImage}):t.jsx("span",{className:Fu.editableAvatarFallback,children:a}),t.jsx("span",{className:Fu.editableAvatarBadge,"aria-hidden":"true",children:t.jsx(ik,{size:y})})]})}function u1({isOpen:e,theme:n,onClose:a,onSave:s,displayName:o,email:c,avatarDisplayUrl:i,accountBadgeInitial:l,saveBusy:m,avatarBusy:y,saveError:v,saveNotice:b,onDisplayNameChange:g,onOpenAvatarManager:h}){return t.jsx(As,{isOpen:e,onClose:a,title:"Edit Profile",size:"sm",theme:n,draggable:!0,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:p.secondaryButton,onClick:a,disabled:m||y,children:"Cancel"}),t.jsx("button",{type:"button",className:p.primaryUpdateBtn,onClick:s,disabled:m||y||!o.trim(),children:m?"Saving...":"Save Profile"})]}),children:t.jsxs("div",{className:`${At.form} ${ht.modalBody}`,children:[t.jsxs("div",{className:mt.profileEditLayout,children:[t.jsx("div",{className:mt.profileAvatarEditor,children:t.jsx(d1,{label:"Edit profile photo",imageUrl:i,fallback:l,disabled:m||y,onClick:h})}),t.jsxs("div",{className:mt.profileFieldStack,children:[t.jsxs("label",{className:mt.profileFieldLabel,children:[t.jsx("span",{children:"Display name"}),t.jsx("input",{className:p.input,type:"text",value:o,onChange:k=>g(k.target.value),placeholder:"Display name",disabled:m})]}),t.jsxs("label",{className:mt.profileFieldLabel,children:[t.jsx("span",{children:"Email"}),t.jsx("input",{className:p.input,type:"email",value:c,readOnly:!0,disabled:!0})]})]})]}),v&&t.jsx("p",{className:`${me.loginError} ${ht.errorText}`,children:v}),b&&!v&&t.jsx("p",{className:ht.errorText,children:b})]})})}function m1({isOpen:e,theme:n,onClose:a,onOpenSettings:s}){return t.jsx(As,{isOpen:e,onClose:a,title:"Quick Start",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${At.form} ${ht.modalBody}`,children:[t.jsx("p",{className:ht.mutedText,children:"Use this quick guide to get productive in Taskforce dashboard mode."}),t.jsxs("div",{children:[t.jsx("strong",{children:"1. Capture work"}),t.jsxs("p",{className:ht.sectionText,children:["Click ",t.jsx("code",{children:"Add Task"}),", write a short title, and save."]})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"2. Plan the board"}),t.jsxs("p",{className:ht.sectionText,children:["Use ",t.jsx("code",{children:"Sort"}),", ",t.jsx("code",{children:"Group"}),", and ",t.jsx("code",{children:"Filters"})," in the header."]})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"3. Execute and stage"}),t.jsxs("p",{className:ht.sectionText,children:["Move tasks through ",t.jsx("code",{children:"Task"}),", ",t.jsx("code",{children:"In Progress"}),", ",t.jsx("code",{children:"Review"}),", and ",t.jsx("code",{children:"Done"}),"."]})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"4. Archive finished work"}),t.jsx("p",{className:ht.sectionText,children:"Archive completed/cancelled tasks to keep active board signal high."})]}),t.jsxs("div",{className:`${At.formActions} ${ht.modalActionsEnd}`,children:[t.jsx("button",{className:p.cancelBtn,onClick:s,children:"Open Settings"}),t.jsx("button",{className:p.submitBtn,onClick:a,children:"Close Tutorial"})]})]})})}function p1({prompt:e,theme:n,onClose:a,onConfirm:s}){return t.jsx(As,{isOpen:!!e,onClose:a,title:"Date Warning",size:"sm",theme:n,draggable:!1,closeOnOverlayClick:!1,children:t.jsxs("div",{className:`${p.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[t.jsx("p",{className:"tf-text-body",children:"Due date is before scheduled date."}),e&&t.jsxs("p",{className:"tf-text-helper",children:["Due: ",e.dueDate," · Scheduled: ",e.scheduledDate]}),t.jsxs("div",{className:p.formActions,children:[t.jsx("button",{className:p.cancelBtn,onClick:a,children:"Go Back"}),t.jsx("button",{className:p.submitBtn,onClick:s,children:"Save Anyway"})]})]})})}function f1({isOpen:e,theme:n,onClose:a,onConfirm:s}){return t.jsx(As,{isOpen:e,onClose:a,title:"Cloud Sync Warning",size:"sm",theme:n,draggable:!1,closeOnOverlayClick:!1,children:t.jsxs("div",{className:`${p.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[t.jsx("p",{className:"tf-text-body",children:"Turning on cloud sync can renumber task, document, and image references to match the cloud workspace."}),t.jsxs("p",{className:"tf-text-helper",children:["Labels like ",t.jsx("code",{children:"T-12"}),", ",t.jsx("code",{children:"D-4"}),", and ",t.jsx("code",{children:"IMG-2"})," may change. Plain file attachments are not renumbered."]}),t.jsxs("div",{className:p.formActions,children:[t.jsx("button",{className:p.cancelBtn,onClick:a,children:"Go Back"}),t.jsx("button",{className:p.submitBtn,onClick:s,children:"Enable Sync Anyway"})]})]})})}const h1="_syncStatusModal_4pd1g_1",g1="_syncStatusTop_4pd1g_6",y1="_syncStatusMetaHeader_4pd1g_15",k1="_syncStatusHeaderInfo_4pd1g_22",S1="_syncToggle_4pd1g_43",v1="_syncStatusBadge_4pd1g_47",b1="_syncToggleControl_4pd1g_75",w1="_syncToggleControlEnabled_4pd1g_91",x1="_syncToggleControlDisabled_4pd1g_98",_1="_syncToggleControlBusy_4pd1g_102",C1="_syncToggleControlBlocked_4pd1g_107",A1="_syncToggleInput_4pd1g_112",I1="_syncToggleState_4pd1g_125",T1="_syncToggleStateOn_4pd1g_136",N1="_syncToggleStateOff_4pd1g_141",R1="_syncToggleThumb_4pd1g_146",j1="_syncStatusSummaryValue_4pd1g_173",P1="_syncStatusSummaryCompact_4pd1g_180",E1="_syncStatusRepairBanner_4pd1g_190",M1="_syncStatusRepairHeader_4pd1g_200",D1="_syncStatusRepairBadge_4pd1g_207",L1="_syncStatusRepairMeta_4pd1g_216",B1="_syncStatusRepairText_4pd1g_223",W1="_syncStatusLabel_4pd1g_257",F1="_syncStatusSectionHeader_4pd1g_265",O1="_syncStatusCompactGrid_4pd1g_278",$1="_syncStatusCompactItem_4pd1g_284",U1="_syncStatusValue_4pd1g_295",q1="_syncStatusValueError_4pd1g_325",z1="_syncStatusActions_4pd1g_329",H1="_syncStatusPanel_4pd1g_336",G1="_syncStatusPanelHeader_4pd1g_346",V1="_syncStatusPanelMeta_4pd1g_353",K1="_syncStatusEventsList_4pd1g_375",Z1="_syncStatusEventItem_4pd1g_384",Y1="_syncStatusEventItemError_4pd1g_391",J1="_syncStatusEventItemMuted_4pd1g_396",X1="_syncStatusEventLine_4pd1g_401",Q1="_syncStatusSecondaryActions_4pd1g_411",e2="_syncStatusPrimaryActions_4pd1g_425",t2="_syncStatusPrimaryActionSlot_4pd1g_432",n2="_syncStatusActionPlaceholder_4pd1g_440",st={syncStatusModal:h1,syncStatusTop:g1,syncStatusMetaHeader:y1,syncStatusHeaderInfo:k1,syncToggle:S1,syncStatusBadge:v1,syncToggleControl:b1,syncToggleControlEnabled:w1,syncToggleControlDisabled:x1,syncToggleControlBusy:_1,syncToggleControlBlocked:C1,syncToggleInput:A1,syncToggleState:I1,syncToggleStateOn:T1,syncToggleStateOff:N1,syncToggleThumb:R1,syncStatusSummaryValue:j1,syncStatusSummaryCompact:P1,syncStatusRepairBanner:E1,syncStatusRepairHeader:M1,syncStatusRepairBadge:D1,syncStatusRepairMeta:L1,syncStatusRepairText:B1,syncStatusLabel:W1,syncStatusSectionHeader:F1,syncStatusCompactGrid:O1,syncStatusCompactItem:$1,syncStatusValue:U1,syncStatusValueError:q1,syncStatusActions:z1,syncStatusPanel:H1,syncStatusPanelHeader:G1,syncStatusPanelMeta:V1,syncStatusEventsList:K1,syncStatusEventItem:Z1,syncStatusEventItemError:Y1,syncStatusEventItemMuted:J1,syncStatusEventLine:X1,syncStatusSecondaryActions:Q1,syncStatusPrimaryActions:e2,syncStatusPrimaryActionSlot:t2,syncStatusActionPlaceholder:n2};function a2({isOpen:e,theme:n,currentWorkspaceLabel:a,syncStatusMeta:s,workspaceCloudSyncEnabled:o,syncControlBusy:c,canManageWorkspaceSync:i,workspaceSyncSummary:l,workspaceSyncRecommendedAction:m,workspaceSyncRepairBusy:y,referenceMismatchCount:v,syncStageLabel:b,workspaceSyncPendingChanges:g,formattedLastSyncTime:h,formattedLastPullTime:k,formattedLastPushTime:I,syncLastError:x,workspaceSyncDiagnostics:A,activeReferenceMismatchSummaries:M,syncDiagnosticsSummary:B,syncEventRows:ue,syncEventsListRef:X,workspaceSyncRepairQueued:ce,workspaceSyncBusy:oe,workspaceSyncCopied:be,runtimeMode:_,isAuthenticated:J,onClose:Q,onToggleWorkspaceSync:ie,onRepairSync:H,onCopyReport:P,onOpenLogin:U,onRetrySync:se}){return t.jsx(As,{isOpen:e,onClose:Q,title:"Sync Manager",size:"mdWide",theme:n,draggable:!0,children:t.jsxs("div",{className:`${At.form} ${st.syncStatusModal}`,style:{gap:"10px"},children:[t.jsxs("div",{className:st.syncStatusTop,children:[t.jsx("div",{className:st.syncStatusHeaderInfo,children:t.jsxs("div",{className:st.syncStatusMetaHeader,children:[t.jsx("div",{className:st.syncStatusBadge,style:{borderColor:s.border,background:s.background,color:s.color},children:s.label}),t.jsxs("span",{className:st.syncStatusLabel,children:["Workspace: ",t.jsx("code",{children:a})]})]})}),t.jsx("label",{className:st.syncToggle,children:t.jsxs("span",{className:[st.syncToggleControl,o?st.syncToggleControlEnabled:st.syncToggleControlDisabled,c?st.syncToggleControlBusy:"",i?"":st.syncToggleControlBlocked].filter(Boolean).join(" "),children:[t.jsx("input",{className:st.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:o,disabled:!i||c,onChange:he=>ie(he.target.checked)}),t.jsx("span",{className:`${st.syncToggleState} ${st.syncToggleStateOn}`,children:"On"}),t.jsx("span",{className:`${st.syncToggleState} ${st.syncToggleStateOff}`,children:"Off"}),t.jsx("span",{className:st.syncToggleThumb})]})})]}),t.jsxs("div",{className:st.syncStatusSummaryCompact,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Health"}),t.jsx("span",{className:st.syncStatusSummaryValue,children:l})]}),t.jsxs("div",{className:st.syncStatusSummaryCompact,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Next Step"}),t.jsx("span",{className:st.syncStatusSummaryValue,children:m})]}),y&&t.jsxs("div",{className:st.syncStatusRepairBanner,children:[t.jsxs("div",{className:st.syncStatusRepairHeader,children:[t.jsxs("div",{className:st.syncStatusRepairBadge,children:[t.jsx(Va,{size:13,className:p.spinner}),t.jsx("span",{children:"Repair In Progress"})]}),t.jsx("span",{className:st.syncStatusRepairMeta,children:"Advanced recovery mode"})]}),t.jsx("span",{className:st.syncStatusRepairText,children:v>0?`Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again, including ${v} detected reference mismatch${v===1?"":"es"}. The panel may stay busy for a while during large repairs.`:"Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again. The panel may stay busy for a while during large repairs."})]}),t.jsx("div",{className:st.syncStatusSectionHeader,children:t.jsx("span",{className:st.syncStatusLabel,children:"Current Session"})}),t.jsxs("div",{className:st.syncStatusCompactGrid,children:[t.jsxs("div",{className:st.syncStatusCompactItem,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Stage"}),t.jsx("span",{className:st.syncStatusValue,children:b})]}),t.jsxs("div",{className:st.syncStatusCompactItem,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Local Changes"}),t.jsx("span",{className:st.syncStatusValue,children:g})]}),t.jsxs("div",{className:st.syncStatusCompactItem,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Last Successful"}),t.jsx("span",{className:st.syncStatusValue,children:h})]})]}),t.jsx("div",{className:st.syncStatusSectionHeader,children:t.jsx("span",{className:st.syncStatusLabel,children:"Activity"})}),t.jsxs("div",{className:st.syncStatusCompactGrid,children:[t.jsxs("div",{className:st.syncStatusCompactItem,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Last Pull"}),t.jsx("span",{className:st.syncStatusValue,children:k})]}),t.jsxs("div",{className:st.syncStatusCompactItem,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Last Push"}),t.jsx("span",{className:st.syncStatusValue,children:I})]})]}),x!=="None"&&t.jsxs("div",{className:st.syncStatusPanel,style:{background:"rgba(239, 68, 68, 0.05)",borderColor:"rgba(239, 68, 68, 0.2)"},children:[t.jsxs("div",{className:st.syncStatusSectionHeader,style:{marginTop:0},children:[t.jsx(Fc,{size:12,color:"#fda4af"}),t.jsxs("span",{className:st.syncStatusLabel,style:{color:"#fda4af"},children:["Last Error (",A.lastErrorAt?new Date(A.lastErrorAt).toLocaleTimeString():"Recent",")"]})]}),t.jsx("span",{className:`${st.syncStatusValue} ${st.syncStatusValueError}`,children:x})]}),v>0&&t.jsxs("div",{className:st.syncStatusPanel,style:{background:"rgba(250, 204, 21, 0.08)",borderColor:"rgba(250, 204, 21, 0.22)"},children:[t.jsxs("div",{className:st.syncStatusPanelHeader,children:[t.jsx("span",{className:st.syncStatusLabel,style:{color:"#fde68a"},children:"Identifier Integrity"}),t.jsxs("span",{className:st.syncStatusPanelMeta,children:[v," mismatch",v===1?"":"es"," detected"]})]}),t.jsx("span",{className:st.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."}),M.length>0&&t.jsx("div",{style:{marginTop:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:M.map(he=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",padding:"8px 10px",borderRadius:"8px",background:"rgba(15, 23, 42, 0.18)",border:"1px solid rgba(250, 204, 21, 0.16)"},children:[t.jsx("span",{className:st.syncStatusValue,style:{fontSize:"12px",wordBreak:"break-all"},children:he.pathLabel}),he.refsLabel?t.jsx("span",{className:st.syncStatusPanelMeta,children:he.refsLabel}):null]},he.key))})]}),t.jsxs("div",{className:st.syncStatusPanel,children:[t.jsxs("div",{className:st.syncStatusPanelHeader,children:[t.jsx("span",{className:st.syncStatusLabel,children:"Local Sync Diagnostics"}),t.jsx("span",{className:st.syncStatusPanelMeta,style:{fontSize:"10px"},children:"AI profiles & metadata"})]}),t.jsx("div",{className:st.syncStatusCompactGrid,style:{gridTemplateColumns:"repeat(2, 1fr)"},children:B.map(he=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"8px"},children:[t.jsx("span",{className:st.syncStatusLabel,style:{fontSize:"9px",textTransform:"capitalize"},children:he.label}),t.jsx("span",{className:st.syncStatusValue,style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:he.value})]},he.label))})]}),t.jsxs("div",{className:st.syncStatusPanel,children:[t.jsx("div",{className:st.syncStatusPanelHeader,children:t.jsx("span",{className:st.syncStatusLabel,children:"Recent Events"})}),t.jsx("div",{ref:X,className:st.syncStatusEventsList,style:{height:"120px"},children:ue.map(he=>t.jsx("div",{className:[st.syncStatusEventItem,he.tone==="error"?st.syncStatusEventItemError:"",he.tone==="muted"?st.syncStatusEventItemMuted:""].filter(Boolean).join(" "),style:{padding:"6px 8px",borderRadius:"6px"},children:t.jsx("span",{className:st.syncStatusEventLine,style:{fontSize:"11px"},children:he.text})},he.key))})]}),t.jsxs("div",{className:`${At.formActions} ${st.syncStatusActions}`,children:[t.jsxs("div",{className:st.syncStatusSecondaryActions,children:[t.jsx("button",{className:p.cancelBtn,onClick:H,disabled:y,title:y?"Repair is running now.":ce?"Repair is queued and will start when the current sync finishes.":oe?"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?t.jsxs(t.Fragment,{children:[t.jsx(Va,{size:14,className:p.spinner}),t.jsx("span",{style:{marginLeft:"6px"},children:"Repairing..."})]}):ce?"Repair Queued":"Repair"}),t.jsxs("button",{className:p.cancelBtn,onClick:P,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[t.jsx(nd,{size:14}),t.jsx("span",{style:{marginLeft:"6px"},children:be?"Copied":"Copy Report"})]})]}),t.jsxs("div",{className:st.syncStatusPrimaryActions,children:[t.jsx("div",{className:st.syncStatusPrimaryActionSlot,children:_==="local"&&!J?t.jsx("button",{className:p.submitBtn,onClick:U,children:"Sign In / Register"}):t.jsx("div",{className:st.syncStatusActionPlaceholder,"aria-hidden":"true"})}),t.jsx("div",{className:st.syncStatusPrimaryActionSlot,children:t.jsx("button",{className:p.submitBtn,onClick:se,disabled:oe,children:oe?t.jsxs(t.Fragment,{children:[t.jsx(Va,{size:14,className:p.spinner}),"Syncing..."]}):t.jsxs(t.Fragment,{children:[t.jsx(ck,{size:14}),"Sync"]})})})]})]})]})})}function r2({isOpen:e,theme:n,teamPlanMode:a,teamMgmtError:s,teamManagementTab:o,teamUsersLoading:c,teamUsers:i,teamActionBusyUserId:l,teamInviteFeedback:m,teamInviteEmail:y,teamInviteRole:v,teamInvitePermissionMode:b,teamInviteBusy:g,pendingInvites:h,teamAuditLoading:k,teamAuditEvents:I,teamAuditPage:x,teamAuditPages:A,teamAuditHasMore:M,onClose:B,onOpenMembersTab:ue,onOpenInvitesTab:X,onOpenAuditTab:ce,onMemberRoleChange:oe,onMemberPermissionChange:be,onToggleMemberDisabled:_,onRevokeInvite:J,onRemoveMember:Q,onInviteEmailChange:ie,onInviteRoleChange:H,onInvitePermissionModeChange:P,onSubmitInvite:U,onLoadAuditPrevious:se,onLoadAuditNext:he}){return t.jsx(As,{isOpen:e,onClose:B,title:"Team Management",size:"md",theme:n,draggable:!0,children:t.jsxs("div",{className:`${At.form} ${ht.modalBody}`,children:[a==="personal"&&t.jsx("p",{className:me.loginError,children:"Team management is only available in TEAM accounts."}),s&&t.jsx("p",{className:me.loginError,children:s}),t.jsxs("div",{className:`${p.settingsTabs} tf-scrollbar tf-scrollbar--track-transparent tf-scrollbar--compact`,children:[t.jsx("button",{className:`${p.settingsTabBtn} ${o==="members"?p.settingsTabBtnActive:""}`,onClick:ue,children:"Members"}),t.jsx("button",{className:`${p.settingsTabBtn} ${o==="invites"?p.settingsTabBtnActive:""}`,onClick:X,children:"Invites"}),t.jsx("button",{className:`${p.settingsTabBtn} ${o==="audit"?p.settingsTabBtnActive:""}`,onClick:ce,children:"Audit Log"})]}),o==="members"&&t.jsxs("div",{className:mt.accountHubCard,children:[c&&t.jsx("p",{className:ht.mutedText,children:"Loading members..."}),!c&&i.length===0&&t.jsx("p",{className:ht.mutedText,children:"No users found."}),!c&&i.map(V=>t.jsxs("div",{className:ht.memberRow,children:[t.jsx("div",{className:ht.memberTitle,children:V.displayName||V.email}),t.jsxs("div",{className:mt.accountMenuMeta,children:[V.email," · ",V.status,V.disabled?" · deactivated":""]}),t.jsxs("div",{className:ht.memberActions,children:[t.jsxs("select",{className:`${p.input} ${ht.selectRole}`,value:V.role,onChange:Ce=>oe(V.userId,Ce.target.value),disabled:l===V.userId,children:[t.jsx("option",{value:"owner",children:"Owner"}),t.jsx("option",{value:"admin",children:"Admin"}),t.jsx("option",{value:"member",children:"Member"})]}),V.role==="member"&&t.jsxs("select",{className:`${p.input} ${ht.selectPermission}`,value:V.permissionMode,onChange:Ce=>be(V.userId,Ce.target.value),disabled:l===V.userId,children:[t.jsx("option",{value:"read-write",children:"Read / Write"}),t.jsx("option",{value:"read-only",children:"Read Only"})]}),t.jsx("button",{className:p.cancelBtn,disabled:l===V.userId,onClick:()=>_(V.userId,!V.disabled),children:V.disabled?"Reactivate":"Deactivate"}),V.status==="invited"&&t.jsx("button",{className:p.cancelBtn,disabled:l===V.userId,onClick:()=>J(V.userId),children:"Revoke Invite"}),t.jsx("button",{className:p.cancelBtn,disabled:l===V.userId,onClick:()=>Q(V.userId),children:"Remove"})]})]},V.userId))]}),o==="invites"&&t.jsxs("div",{className:mt.accountHubCard,children:[m&&t.jsx("p",{className:ht.sectionText,children:m}),t.jsxs("div",{className:p.pathInputGroup,children:[t.jsx("label",{className:`${p.label} ${ht.labelFixed}`,children:"Email"}),t.jsx("input",{className:p.input,value:y,onChange:V=>ie(V.target.value),placeholder:"name@company.com"})]}),t.jsxs("div",{className:p.pathInputGroup,children:[t.jsx("label",{className:`${p.label} ${ht.labelFixed}`,children:"Role"}),t.jsxs("select",{className:`${p.input} ${ht.selectRole}`,value:v,onChange:V=>H(V.target.value==="admin"?"admin":"member"),children:[t.jsx("option",{value:"member",children:"Member"}),t.jsx("option",{value:"admin",children:"Admin"})]}),v==="member"&&t.jsxs("select",{className:`${p.input} ${ht.selectPermission}`,value:b,onChange:V=>P(V.target.value==="read-only"?"read-only":"read-write"),children:[t.jsx("option",{value:"read-write",children:"Read / Write"}),t.jsx("option",{value:"read-only",children:"Read Only"})]}),t.jsx("button",{className:p.submitBtn,disabled:g||!y.trim()||a!=="team",onClick:U,children:g?"Sending...":"Send Invite"})]}),t.jsxs("div",{className:ht.inviteRow,children:[t.jsx("div",{className:ht.listHeading,children:"Pending Invites"}),h.length===0&&t.jsx("p",{className:ht.mutedText,children:"No pending invites."}),h.map(V=>t.jsxs("div",{className:ht.memberRow,children:[t.jsx("div",{className:ht.memberTitle,children:V.displayName||V.email}),t.jsxs("div",{className:mt.accountMenuMeta,children:[V.email," · ",V.role]})]},V.userId))]})]}),o==="audit"&&t.jsxs("div",{className:mt.accountHubCard,children:[k&&t.jsx("p",{className:ht.mutedText,children:"Loading audit entries..."}),!k&&I.length===0&&t.jsx("p",{className:ht.mutedText,children:"No audit events for this workspace."}),!k&&t.jsx("div",{className:ht.auditList,children:I.map(V=>t.jsxs("div",{className:ht.memberRow,children:[t.jsx("div",{className:mt.accountMenuMeta,children:new Date(V.createdAt).toLocaleString()}),t.jsx("div",{className:ht.memberTitle,children:V.action}),t.jsxs("div",{className:mt.accountMenuMeta,children:[V.actorUserId," (",V.actorRole,")"]})]},V.id))}),t.jsxs("div",{className:ht.auditPager,children:[t.jsx("button",{className:p.cancelBtn,disabled:k||x===0,onClick:se,children:"Previous"}),t.jsxs("span",{className:mt.accountMenuMeta,children:["Page ",x+1," of ",A]}),t.jsx("button",{className:p.cancelBtn,disabled:k||!M||x+1>=A,onClick:he,children:"Next"})]})]}),t.jsx("div",{className:`${At.formActions} ${ht.modalActionsEnd}`,children:t.jsx("button",{className:p.cancelBtn,onClick:B,children:"Close"})})]})})}const uy=e=>{const n=e.status||"task";return n==="done"||n==="cancelled"?"completed":n},s2=(e,n,a)=>{if(uy(e)===n)return null;const o={status:n};return n==="task"||n==="on-hold"?(o.inProgress=!1,o.readyForReview=!1,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):n==="in-progress"?(o.inProgress=!0,o.readyForReview=!1,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):n==="review"?(o.inProgress=!1,o.readyForReview=!0,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):n==="done"||n==="completed"?(o.status="done",o.inProgress=!1,o.readyForReview=!1,o.completed=!0,o.cancelled=!1,o.completedAt=a,o):(n==="cancelled"&&(o.status="cancelled"),o)},o2=({targetTasks:e,overTaskId:n,isBelowOverItem:a})=>{if(!n)return e.length;const s=e.findIndex(o=>o.id===n);return s<0?e.length:s+(a?1:0)},my=(e,n=new Map)=>{const a=new Map(n);return e.forEach((s,o)=>{a.set(s.id,{...a.get(s.id)||{},orderInDay:o})}),a},uf=e=>Array.from(e.entries()).map(([n,a])=>({taskId:n,updates:a})),py=({sourceColumnId:e,targetColumnId:n,sourceTasks:a,updates:s})=>!e||e===n?s:my(a,s),i2=({activeTask:e,sourceColumnId:n,targetTasks:a,sourceTasks:s,insertAt:o})=>{const c=[...a];c.splice(o,0,e);let i=new Map;return c.forEach((l,m)=>{if(l.id===e.id){i.set(l.id,{...i.get(l.id)||{},...e.scheduledDate?{scheduledDate:null,scheduledWeekKey:null}:{},orderInDay:m});return}i.set(l.id,{...i.get(l.id)||{},orderInDay:m})}),i=py({sourceColumnId:n,targetColumnId:"backlog",sourceTasks:s,updates:i}),uf(i)},c2=({activeTask:e,targetTasks:n,insertAt:a})=>{const s=[...n];return s.splice(a,0,e),uf(my(s))},l2=({activeTask:e,sourceColumnId:n,targetColumnId:a,targetTasks:s,sourceTasks:o,insertAt:c,scheduledDate:i,scheduledWeekKey:l})=>{const m=[...s];m.splice(c,0,e);let y=new Map;return m.forEach((v,b)=>{if(v.id===e.id){y.set(v.id,{...y.get(v.id)||{},scheduledDate:i,scheduledWeekKey:l,orderInDay:b});return}y.set(v.id,{...y.get(v.id)||{},orderInDay:b})}),y=py({sourceColumnId:n,targetColumnId:a,sourceTasks:o,updates:y}),uf(y)},d2=({activeTask:e,sourceColumnId:n,targetColumnId:a,targetTasks:s,sourceTasks:o,overTaskId:c,isBelowOverItem:i,scheduleDates:l,parseToIsoWeekKey:m,todayDate:y})=>{const v=["mon","tue","wed","thu","fri","sat","sun"];if(!(a==="backlog"||a==="expired"||v.includes(a)))return null;const g=o2({targetTasks:s,overTaskId:c,isBelowOverItem:i});if(a==="expired")return n!=="expired"?null:{kind:"updates",updates:c2({activeTask:e,targetTasks:s,insertAt:g})};if(a==="backlog")return{kind:"updates",updates:i2({activeTask:e,sourceColumnId:n,targetTasks:s,sourceTasks:o,insertAt:g})};if(!v.includes(a))return null;const h=l[a];return h?!(e.status==="done"||e.status==="cancelled")&&h<y?{kind:"blocked",reason:"Only completed work can be scheduled in the past."}:{kind:"updates",updates:l2({activeTask:e,sourceColumnId:n,targetColumnId:a,targetTasks:s,sourceTasks:o,insertAt:g,scheduledDate:h,scheduledWeekKey:m(h)}),selectedDate:h}:null},zu="expired::";function u2({tasks:e,columns:n,groupBy:a,searchQuery:s,copiedId:o,taxonomies:c,types:i,priorities:l,approaches:m,assigneeOptions:y=[],onUpdateTask:v,onTaskClick:b,onOpenTaskById:g,onCopyId:h,onToggleInProgress:k,onToggleReview:I,onToggleComplete:x,onToggleCancel:A,onSetStatus:M,onArchiveTask:B,onUnarchive:ue,onDelete:X,allTasks:ce=[],onAddTaskToColumn:oe,emptyColumnMode:be="show",filterCategories:_=[],filterTypes:J=[],filterPriorities:Q=[],filterStatus:ie=[],filterAssignees:H=[],filtersReady:P=!0,scheduleFilteredTaskIds:U,categories:se=[],compressed:he=!1,readOnlyMode:V=null,recentlyChangedTaskIds:Ce=[],scheduleDates:Se,onScheduleDaySelected:ve,persistedScrollLeft:ge,onScrollLeftChange:Te,sortBy:Le="created",sortOrder:Ie="desc",planningDropTargets:Oe=null,onAssignTaskToWorkstream:z,onAssignWorkstreamToInitiative:T,showTaskCardStatusLabel:w=!0,workstreams:j=[],initiatives:F=[]}){const[ee,N]=r.useState(null),[C,$]=r.useState(!1),[K,te]=r.useState(!1),L=r.useMemo(()=>new Set(Ce),[Ce]),re=r.useMemo(()=>new Map(j.map(W=>[W.id,W])),[j]),fe=r.useMemo(()=>new Map(F.map(W=>[W.id,W])),[F]),xe=r.useCallback(W=>{const ke=W.workstreamId&&re.get(W.workstreamId)||null,Ne=ke?.initiativeId&&fe.get(ke.initiativeId)||null;return{taskWorkstream:ke,taskInitiative:Ne}},[fe,re]),le=r.useMemo(()=>new Set(e.map(W=>W.id)),[e]),we=r.useCallback(W=>W.startsWith(zu)?W.slice(zu.length):W,[]),Re=r.useCallback(W=>le.has(we(W)),[le,we]),Xe=r.useMemo(()=>new Set(U||[]),[U]),ze=r.useRef(null),lt=r.useCallback(W=>{const ke=W?.data?.current||{},Ne=String(W?.id||"");let ae=String(ke.taskId||""),Pe=String(ke.workstreamId||"");!ae&&Ne&&Re(Ne)&&(ae=we(Ne)),!Pe&&Ne.startsWith("planning-workstream:")&&(Pe=Ne.slice(20));let Ge=String(ke.type||"");return Ge||(ae?Ge="task-card":Pe&&(Ge="planning-workstream")),{activeId:Ne,type:Ge,taskId:ae,workstreamId:Pe}},[we,Re]),wt=Kh(_p(Xh,{activationConstraint:{distance:10}}),_p(Ek,{coordinateGetter:Pk})),$e=uy,ft=r.useMemo(()=>{const W=new Date,ke=W.getFullYear(),Ne=String(W.getMonth()+1).padStart(2,"0"),ae=String(W.getDate()).padStart(2,"0");return`${ke}-${Ne}-${ae}`},[]),gt=r.useMemo(()=>{const W=ae=>{const Pe=ae.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!Pe)return null;const Ge=new Date(Date.UTC(Number(Pe[1]),Number(Pe[2])-1,Number(Pe[3]))),De=Ge.getUTCDay()||7;Ge.setUTCDate(Ge.getUTCDate()+4-De);const it=new Date(Date.UTC(Ge.getUTCFullYear(),0,1)),Ut=Math.ceil(((Ge.getTime()-it.getTime())/864e5+1)/7);return`${Ge.getUTCFullYear()}-W${String(Ut).padStart(2,"0")}`};return{dates:{...(()=>{const ae=new Date,Pe=ae.getDay(),Ge=Pe===0?-6:1-Pe,De=new Date(ae);De.setDate(ae.getDate()+Ge);const it=nn=>{const Ft=nn.getFullYear(),Wt=String(nn.getMonth()+1).padStart(2,"0"),Vt=String(nn.getDate()).padStart(2,"0");return`${Ft}-${Wt}-${Vt}`},Ut={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((nn,Ft)=>{const Wt=new Date(De);Wt.setDate(De.getDate()+Ft),Ut[nn]=it(Wt)}),Ut})(),...Se||{}},parseToIsoWeekKey:W}},[Se]),at=W=>{const ke=W.scheduledDate||null;return ke?new Map([[gt.dates.mon,"mon"],[gt.dates.tue,"tue"],[gt.dates.wed,"wed"],[gt.dates.thu,"thu"],[gt.dates.fri,"fri"],[gt.dates.sat,"sat"],[gt.dates.sun,"sun"]]).get(ke)||"__offweek":"backlog"},dt=r.useMemo(()=>{if(a==="schedule")return[];const W=new Set(n.map(Pe=>String(Pe.value))),ke=new Set(n.map(Pe=>Pe.label)),Ne=[],ae=Pe=>{const Ge=a==="status"?$e(Pe):Pe[a],De=String(Ge??"");if(!De||W.has(De)||ke.has(De))return null;if(a==="category"){const it=se.find(Ut=>Ut.value===De||Ut.label===De);return{value:De,label:it?.label||De,icon:it?.icon||"Folder",color:it?.color}}if(a==="type"){const it=i?.find(Ut=>Ut.value===De||Ut.label===De);return{value:De,label:it?.label||De,icon:it?.icon||"CheckSquare",color:it?.color}}if(a==="priority"){const it=l?.find(Ut=>Number(Ut.value)===Number(De));return{value:Number.isFinite(Number(De))?Number(De):De,label:it?.label||De,icon:it?.icon||"Flag",color:it?.color}}if(a==="complexity")return{value:Number.isFinite(Number(De))?Number(De):De,label:De,icon:"Gauge"};if(a==="status")return{value:De,label:De,icon:"Circle"};if(a==="assignee"){const it=y.find(Ut=>Ut.value===De);return{value:De,label:it?.label||De,icon:it?.icon==="HelpCircle"?"Circle":it?.icon,color:it?.color}}return{value:De,label:De}};for(const Pe of e){const Ge=ae(Pe);Ge&&(Ne.push(Ge),W.add(String(Ge.value)),ke.add(Ge.label))}return Ne},[y,se,a,n,l,e,i]),ne=r.useMemo(()=>[...n,...dt],[dt,n]),tt=r.useMemo(()=>{const W=new Map;for(const ke of ne)W.set(String(ke.value),ke),W.has(ke.label)||W.set(ke.label,ke);return W},[ne]),rt=r.useMemo(()=>{const W={};return ne.forEach(Ne=>{W[String(Ne.value)]=0}),(ce.length>0?ce:e).forEach(Ne=>{let ae="";if(a==="status")ae=$e(Ne);else if(a==="schedule")ae=at(Ne);else{const Ge=Ne[a];ae=String(Ge??"")}const Pe=tt.get(ae);if(Pe&&W[String(Pe.value)]++,a==="schedule"){const Ge=Ne.status==="done"||Ne.status==="cancelled";Ne.scheduledDate&&!Ge&&Ne.scheduledDate<ft&&tt.has("expired")&&(W.expired=(W.expired||0)+1)}}),W},[ce,e,ne,a,tt,ft]),Pt=r.useMemo(()=>{const W={};if(ne.forEach(ke=>{W[String(ke.value)]=[]}),e.forEach(ke=>{let Ne="";if(a==="status")Ne=$e(ke);else if(a==="schedule")Ne=at(ke);else{const Pe=ke[a];Ne=String(Pe??"")}const ae=tt.get(Ne);if(ae){if(a==="schedule"&&String(ae.value)==="backlog"&&!Xe.has(ke.id))return;W[String(ae.value)].push(ke)}if(a==="schedule"){const Pe=ke.status==="done"||ke.status==="cancelled";ke.scheduledDate&&!Pe&&ke.scheduledDate<ft&&W.expired&&W.expired.push(ke)}}),a==="schedule"){const ke=(ae,Pe)=>{const Ge=typeof ae.orderInDay=="number"?ae.orderInDay:Number.MAX_SAFE_INTEGER,De=typeof Pe.orderInDay=="number"?Pe.orderInDay:Number.MAX_SAFE_INTEGER;return Ge!==De?Ge-De:String(ae.createdAt||"").localeCompare(String(Pe.createdAt||""))},Ne=(ae,Pe)=>nm(ae,Pe,Le,Ie,c);Object.keys(W).forEach(ae=>{if(ae==="backlog"||ae==="expired"){W[ae].sort(Ne);return}W[ae].sort(ke)})}return W},[e,ce,ne,a,tt,Xe,ft,Le,Ie]),yt=ee?we(ee):null,Rt=yt?e.find(W=>W.id===yt):null,Tt=r.useRef(null),Dt=r.useRef(null),d=r.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),Me=r.useRef(-1),We=(W,ke)=>P?a==="category"?!_.includes(String(W)):a==="type"?!J.includes(String(W)):a==="priority"?!Q.some(Ne=>Number(Ne)===Number(W)):a==="status"?String(W)==="completed"?!ie.includes("done")&&!ie.includes("cancelled"):!ie.includes(String(W)):a==="assignee"?!H.includes(String(W)):!1:!1,Qe=r.useMemo(()=>{let ae=0;return ne.forEach((Pe,Ge)=>{const De=Pt[String(Pe.value)]||[],it=We(Pe.value,Pe.label),Ut=a!=="schedule"&&be==="hide"&&De.length===0;if(it||Ut)return;const Gt=be==="collapse"&&De.length===0;ae+=Gt?72:320,ae+=4}),ae},[ne,Pt,be,a,_,J,Q,ie,H,P]),ot=r.useCallback(W=>{if(!Te)return;const ke=Math.max(0,Math.round(W));ke!==Me.current&&(Me.current=ke,Te(ke))},[Te]);r.useEffect(()=>{const W=Tt.current,ke=Dt.current;if(!W||!ke)return;let Ne=!1,ae=!1;const Pe=()=>{!W||ae||(Ne=!0,W.scrollLeft=ke.scrollLeft,ot(ke.scrollLeft),setTimeout(()=>Ne=!1,0))},Ge=()=>{!ke||Ne||(ae=!0,ke.scrollLeft=W.scrollLeft,ot(W.scrollLeft),setTimeout(()=>ae=!1,0))};return ke.addEventListener("scroll",Pe),W.addEventListener("scroll",Ge),()=>{ke.removeEventListener("scroll",Pe),W.removeEventListener("scroll",Ge)}},[ot]);const de=r.useRef(!1);r.useEffect(()=>{if(de.current)return;if(typeof ge!="number"||!Number.isFinite(ge)){de.current=!0;return}const W=Tt.current,ke=Dt.current;if(!W||!ke)return;const Ne=Math.max(0,W.scrollWidth-W.clientWidth),ae=Math.min(Math.max(0,ge),Ne);W.scrollLeft=ae,ke.scrollLeft=ae,de.current=!0},[ge,Qe]),r.useEffect(()=>{const W=()=>{const ke=Tt.current;if(!ke){te(!1);return}te(ke.scrollWidth>ke.clientWidth+4)};return W(),window.addEventListener("resize",W),()=>{window.removeEventListener("resize",W)}},[Qe,ne.length,Pt]),r.useEffect(()=>{const W=Ne=>{const ae=d.current;if(ae.pointerId===null||ae.pointerId!==Ne.pointerId)return;const Pe=Ne.clientX-ae.startX,Ge=Ne.clientY-ae.startY;if(!ae.didPan){if(Math.abs(Pe)<7||Math.abs(Pe)<Math.abs(Ge))return;ae.didPan=!0,$(!0),document.body.style.userSelect="none"}const De=ae.startScrollLeft-Pe;Tt.current&&(Tt.current.scrollLeft=De),Dt.current&&(Dt.current.scrollLeft=De),Ne.preventDefault()},ke=()=>{const Ne=d.current;Ne.pointerId!==null&&(Ne.pointerId=null,Ne.didPan=!1,C&&($(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",W),window.addEventListener("pointerup",ke),window.addEventListener("pointercancel",ke),()=>{window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",ke),window.removeEventListener("pointercancel",ke),document.body.style.userSelect=""}},[C]);const Be=W=>{!K||W.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(d.current.pointerId=W.pointerId,d.current.startX=W.clientX,d.current.startY=W.clientY,d.current.startScrollLeft=Tt.current?.scrollLeft||0,d.current.didPan=!1)},St=W=>{N(W.active.id)},vt=W=>{const ke=lt(W.active),Ne=String(W.over?.data?.current?.type||"");ke.type==="task-card"&&Ne.startsWith("planning-")?ze.current=`${String(W.over?.id||"")}:${Ne}`:ze.current&&(ze.current=null)},$t=W=>{const{active:ke,over:Ne}=W;ze.current=null,N(null);const ae=lt(ke),Pe=ae.type,Ge=String(Ne?.data?.current?.type||""),De=ae.taskId,it=ae.workstreamId,Ut=String(Ne?.data?.current?.workstreamId||""),Gt=String(Ne?.data?.current?.initiativeId||"");if(Pe==="task-card"){if(Ge==="planning-workstream-target"&&De&&Ut){z?.(De,Ut);return}if(Ge==="planning-task-unlink"&&De){z?.(De,null);return}}if(Pe==="planning-workstream"){if(Ge==="planning-initiative-target"&&it&&Gt){T?.(it,Gt);return}if(Ge==="planning-workstream-unlink"&&it){T?.(it,null);return}return}const nn=String(ke.id),Ft=Ne?String(Ne.id):null,Wt=we(nn);Ft&&we(Ft);const Vt=e.find(pe=>pe.id===Wt);if(!Vt||!Ft)return;const an=Ze(nn),Kn=String(ke?.data?.current?.sortable?.containerId||"")||an,Jn=String(Ne?.data?.current?.sortable?.containerId||"")||Ze(Ft);if(!Jn)return;const _n=tt.get(Jn)||ne.find(pe=>String(pe.value)===Jn||pe.label===Jn);if(_n){if(a==="schedule"){const Ae=String(_n.value),Nt=Ft&&Re(Ft)?we(Ft):null,Ye=Ne?.rect,dn=ke.rect.current.translated||ke.rect.current.initial,yn=!!(Ye&&dn&&dn.top+dn.height/2>Ye.top+Ye.height/2),on=(Pt[Ae]||[]).filter(zt=>zt.id!==Wt),rn=(Pt[String(Kn)]||[]).filter(zt=>zt.id!==Wt),kt=d2({activeTask:Vt,sourceColumnId:Kn,targetColumnId:Ae,targetTasks:on,sourceTasks:rn,overTaskId:Nt,isBelowOverItem:yn,scheduleDates:gt.dates,parseToIsoWeekKey:gt.parseToIsoWeekKey,todayDate:ft});if(!kt)return;if(kt.kind==="blocked"){window.alert(kt.reason);return}kt.updates.forEach(({taskId:zt,updates:Ln})=>v(zt,Ln)),kt.selectedDate&&ve?.(kt.selectedDate);return}let pe=_n.value;if(a==="status"){const Ae=String(pe),Nt=s2(Vt,Ae,new Date().toISOString());Nt&&v(Vt.id,Nt);return}(a==="priority"||a==="complexity")&&(pe=Number(pe));const et=Vt[a];if(String(et??"")!==String(pe??"")){const Ae={[a]:pe};v(Vt.id,Ae)}}},Ze=W=>{if(tt.has(W)){const ae=tt.get(W);return ae?String(ae.value):W}if(a==="schedule"&&W.startsWith(zu))return"expired";const ke=we(W),Ne=e.find(ae=>ae.id===ke);if(Ne){let ae="";a==="status"?ae=$e(Ne):a==="schedule"?ae=at(Ne):ae=String(Ne[a]??"");const Pe=tt.get(ae);return Pe?String(Pe.value):null}return null},en={sideEffects:Mk({styles:{active:{opacity:"0"}}})},Lt=W=>{try{const ke=jk(W);if(ke.length>0){const Ne=ke.find(Ut=>String(Ut.id).startsWith("planning-"));if(Ne)return[Ne];const ae=W.pointerCoordinates;if(!ae)return[ke[0]];const Pe=ke.filter(Ut=>{const Gt=String(Ut.id);return Re(Gt)&&Gt!==ee});if(Pe.length===0){const Gt=ke.filter(Wt=>{const Vt=String(Wt.id);return!Re(Vt)}).find(Wt=>!!Ze(String(Wt.id)))||null,nn=Gt?Ze(String(Gt.id)):null,Ft=(W.droppableContainers||[]).filter(Wt=>{const Vt=String(Wt.id);return!Re(Vt)||Vt===ee?!1:nn?Ze(Vt)===nn:!0});if(Ft.length>0){const Wt=Rf({...W,droppableContainers:Ft});if(Wt.length>0)return[Wt[0]]}return Gt?[Gt]:[ke[0]]}const Ge=Pe;let De=Ge[0],it=Number.POSITIVE_INFINITY;for(const Ut of Ge){const Gt=W.droppableRects?.get(Ut.id);if(!Gt)continue;const nn=Gt.left+Gt.width/2,Ft=Gt.top+Gt.height/2,Wt=ae.x-nn,Vt=ae.y-Ft,an=Wt*Wt+Vt*Vt;an<it&&(it=an,De=Ut)}return[De]}return Rf(W)}catch(ke){return console.error("[TaskKanban] collision detection error",ke),[]}},bt={searchQuery:s,copiedId:o,taxonomies:c,types:i,priorities:l,approaches:m,assigneeOptions:y,onCopyId:h,onToggleInProgress:k,onToggleReview:I,onToggleComplete:x,onToggleCancel:A,onSetStatus:M,onArchiveTask:B,onUnarchive:ue,onDelete:X,onOpenTaskById:g,categories:se,readOnlyMode:V,changedTaskIdSet:L,resolveTaskHierarchy:xe,groupBy:a,showStatusLabel:w};return t.jsxs(Zh,{sensors:wt,collisionDetection:Lt,onDragStart:St,onDragOver:vt,onDragEnd:$t,onDragCancel:W=>{ze.current=null,N(null)},children:[Oe,t.jsxs("div",{className:p.kanbanWrapper,children:[t.jsx("div",{ref:Dt,className:`${p.kanbanTopScroll} tf-scrollbar`,children:t.jsx("div",{className:p.kanbanTopScrollSpacer,style:{width:`${Qe}px`}})}),t.jsx("div",{className:p.kanbanContainer,ref:Tt,children:ne.map(W=>{const ke=Pt[String(W.value)]||[],Ne=We(W.value,W.label),ae=a!=="schedule"&&be==="hide"&&ke.length===0,Pe=a==="schedule",Ge=Pe&&ne.some(Vt=>String(Vt.value)==="backlog"),De=Pe&&String(W.value)==="backlog",it=Pe&&String(W.value)==="expired",Ut=Pt.backlog||[],nn=be==="collapse"&&Ut.length===0?72:320,Ft=De?0:it?Ge?nn+4:0:void 0,Wt=De?6:it?5:void 0;return Ne||ae?null:t.jsx(m2,{id:String(W.value),title:W.label,color:W.color,icon:W.icon,tasks:ke,activeId:ee,activeTaskId:yt,totalCount:rt[String(W.value)],onAddTask:()=>oe?.(a,W.value),onTaskClick:b,commonCardProps:bt,collapseEmpty:be==="collapse",compressed:he,onHeaderPointerDown:Be,isHeaderPanning:C,headerPanEnabled:K,stickyLeft:Ft,stickyZIndex:Wt,isPast:!!W.isPast,isSelected:!!W.isSelected,isWeekend:!!W.isWeekend,disableSorting:!1,scheduleDate:a==="schedule"?gt.dates[String(W.value)]:void 0,onScheduleDaySelected:ve},String(W.value))})})]}),Ii.createPortal(t.jsx(Rk,{dropAnimation:en,children:Rt?(()=>{const{taskWorkstream:W,taskInitiative:ke}=xe(Rt);return t.jsx(pd,{task:Rt,taskWorkstream:W,taskInitiative:ke,isOverlay:!0,...bt,isArchived:Rt.isArchived,categories:se,compressed:he,isRecentlyChanged:L.has(Rt.id)})})():null}),document.body)]})}function m2({id:e,title:n,color:a,icon:s,tasks:o,activeId:c=null,activeTaskId:i=null,totalCount:l,onAddTask:m,onTaskClick:y,commonCardProps:v,collapseEmpty:b,compressed:g,onHeaderPointerDown:h,isHeaderPanning:k=!1,headerPanEnabled:I=!1,stickyLeft:x,stickyZIndex:A,isPast:M=!1,isSelected:B=!1,isWeekend:ue=!1,disableSorting:X=!1,scheduleDate:ce,onScheduleDaySelected:oe}){const{setNodeRef:be}=hd({id:e,data:{type:"Column"}}),_=b&&o.length===0,J=i?o.filter(U=>U.id!==i):o,Q=typeof x=="number",ie=r.useRef(null),H=U=>e==="expired"?`${zu}${U}`:U,P=U=>{if(!ce||!oe)return;const se=U.target;se&&(se.closest('[data-task-card="true"]')||se.closest(`.${p.kanbanCardWrapper}`)||oe(ce))};return t.jsxs("div",{ref:be,className:`${p.kanbanColumn} ${_?p.kanbanColumnCollapsed:""} ${Q?p.kanbanColumnSticky:""} ${M?p.kanbanColumnPast:""} ${B?p.kanbanColumnSelectedDay:""} ${ue?p.kanbanColumnWeekend:""}`,style:Q?{left:`${x}px`,zIndex:A??4}:void 0,onClick:P,children:[t.jsxs("div",{className:`${p.kanbanHeader} ${I?p.kanbanHeaderDraggable:""} ${k?p.kanbanHeaderPanning:""}`,style:{borderTopColor:Ra(a)||"var(--color-purple)"},onPointerDown:h,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const U=s&&Uc[s]?Uc[s]:Ni,se=Ra(a)||"var(--color-purple)";return t.jsx(U,{size:16,style:{color:se}})})(),!_&&t.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!_||l>0)&&t.jsx("span",{className:p.kanbanCount,children:_?l:`${o.length} / ${l}`}),!v.readOnlyMode&&t.jsx("button",{className:"tf-control-icon tf-control-icon-compact",onClick:U=>{U.stopPropagation(),m()},title:`Add task to ${n}`,"aria-label":`Add task to ${n}`,"data-no-header-pan":"true",children:t.jsx(Cs,{size:14})})]})]}),t.jsx("div",{className:p.kanbanDroppable,children:t.jsx("div",{className:`${p.kanbanDroppableScroll} ${p.appScrollbar} tf-scrollbar`,ref:ie,children:X?J.map(U=>t.jsx("div",{className:p.kanbanCardWrapper,children:(()=>{const{taskWorkstream:se,taskInitiative:he}=v.resolveTaskHierarchy?.(U)||{};return t.jsx(pd,{task:U,taskWorkstream:se,taskInitiative:he,onClick:y,...v,isArchived:U.isArchived,readOnlyMode:v.readOnlyMode||null,compressed:g,isRecentlyChanged:!1})})()},U.id)):t.jsx(Yh,{id:e,items:J.map(U=>H(U.id)),strategy:Jh,children:J.map(U=>t.jsx(p2,{sortableId:H(U.id),task:U,onClick:y,commonCardProps:v,compressed:g,isRecentlyChanged:v.changedTaskIdSet?.has(U.id)},H(U.id)))})})})]})}function p2({sortableId:e,task:n,onClick:a,commonCardProps:s,compressed:o,isRecentlyChanged:c=!1}){const i=!!s?.readOnlyMode,{attributes:l,listeners:m,setNodeRef:y,transform:v,transition:b,isDragging:g}=Qh({id:e,disabled:i,data:{type:"task-card",taskId:n.id}}),h={transform:Hp.Transform.toString(v),transition:b,opacity:g?0:1,pointerEvents:g?"none":"auto"},k=s?.groupBy==="schedule",I=!k&&c;return t.jsx("div",{ref:y,style:h,...i?{}:l,...i?{}:m,className:`${p.kanbanCardWrapper} ${I?p.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:x,taskInitiative:A}=s.resolveTaskHierarchy?.(n)||{};return t.jsx(pd,{task:n,taskWorkstream:x,taskInitiative:A,onClick:a,...s,isArchived:n.isArchived,readOnlyMode:s?.readOnlyMode||null,compressed:o,isRecentlyChanged:k?!1:c})})()})}function f2(e,n,a){const s=String(n);if(e==="category"){const o=a.categories.find(c=>String(c.value)===s||c.label===s);return o?{category:o.label}:{}}if(e==="type")return{type:s};if(e==="priority")return Number.isFinite(Number(n))?{priority:Number(n)}:{};if(e==="complexity")return Number.isFinite(Number(n))?{complexity:Number(n)}:{};if(e==="approach"){const o=a.approaches.find(c=>String(c.value)===s||c.label===s);return o?{approach:o.value,taxonomyApproach:o.value}:{}}return e==="assignee"?s.trim().length>0?{assignee:s}:{}:e==="status"?s==="completed"?{status:"done"}:s==="task"||s==="on-hold"||s==="in-progress"||s==="review"||s==="done"||s==="cancelled"?{status:s}:{}:e==="schedule"?s==="backlog"||s==="expired"?{}:{scheduledDate:s}:{}}function h2(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 g2(e){const n=e.runtimeMode==="local"&&e.isAuthenticated;if(n){const a=h2(e.retryBlockedReason||e.pullBlockedReason||e.pushBlockedReason||null);return{actionable:n,status:e.workspaceSyncStatus,syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:a?.summary||e.workspaceSyncSummary,recommendedAction:a?.recommendedAction||e.workspaceSyncRecommendedAction,lastError:e.workspaceSyncError}}return{actionable:n,status:"off",syncEnabledLabel:"no",summary:"Sign in to enable workspace sync controls on this device.",recommendedAction:"Sign in to manage workspace sync for this workspace.",lastError:"Sign in to enable workspace sync controls on this device."}}function om(e,n){return e==="deleted"?!1:e==="archived"?n:!n}function y2(e,n,a){const s=n.filter(l=>om(a,!!l.isArchived)),o=a==="deleted"?[]:e.filter(l=>om(a,!!l.isArchived)).map(l=>({...l,workstreams:s.filter(m=>m.initiativeId===l.id)})),c=s.filter(l=>!l.initiativeId),i=[...o.flatMap(l=>l.workstreams),...c];return{initiatives:o,standaloneWorkstreams:c,visibleWorkstreams:i,initiativeById:new Map(o.map(l=>[l.id,l])),workstreamById:new Map(i.map(l=>[l.id,l]))}}function fy(e){return typeof e.occurredAt=="string"&&e.occurredAt.trim().length>0?e.occurredAt:"unknown-time"}function k2(e){return typeof e.eventType=="string"&&e.eventType.trim().length>0?e.eventType.trim():"sync"}function S2(e){const n=mm(e.details),a=n?n.source:null;return typeof a=="string"?a.trim():""}function xh(e){const n=String(e||"").trim();switch(n){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 n.length>0?n.replace(/-/g," "):"blocked"}}function _h(e){const n=String(e||"").trim();switch(n){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 n.length>0?n.replace(/-/g," "):"sync"}}function v2(e){const n=fy(e),a=mm(e.details),s=S2(e);return s==="retry.blocked"?`${n} manual retry blocked: ${xh(a?.reason)} during ${_h(a?.phase)}`:s==="repair.started"?`${n} manual repair started: ${_h(a?.repairPhase)} selected`:s==="repair.blocked"?`${n} manual repair blocked: ${xh(a?.reason)}`:null}function qc(e,n=0){const a=String(e.id??"").trim();return a?`id:${a}`:[String(e.occurredAt||"").trim()||"unknown-time",String(e.eventType||"").trim()||"sync",String(e.status||"").trim()||"unknown-status",String(e.statusCode??""),String(e.changeCount??""),String(e.requestMs??""),String(e.errorMessage||"").trim(),Ov(e.details),String(n)].join("|")}function b2(e,n,a=15){const s=new Map;for(const[o,c]of e.entries())s.set(qc(c,o),c);for(const[o,c]of n.entries())s.set(qc(c,o),c);return Array.from(s.values()).sort((o,c)=>String(c.occurredAt||"").localeCompare(String(o.occurredAt||""))).slice(0,Math.max(1,a))}function w2(e,n){if(e.length!==n.length)return!1;for(let a=0;a<e.length;a+=1)if(qc(e[a],a)!==qc(n[a],a))return!1;return!0}function hy(e){const n=v2(e);if(n)return n;const a=fy(e),s=k2(e),o=e.status==="error"?"failed":"succeeded",c=Number(e.changeCount),i=Number.isFinite(c)?` (${Math.max(0,Math.floor(c))} change${Math.floor(c)===1?"":"s"})`:"",l=Number(e.requestMs),m=Number.isFinite(l)?` in ${Math.max(0,Math.floor(l))}ms`:"",y=Number(e.statusCode),v=Number.isFinite(y)?` [${Math.floor(y)}]`:"",b=typeof e.errorMessage=="string"&&e.errorMessage.trim().length>0?`: ${e.errorMessage.trim()}`:"";return`${a} ${s} ${o}${i}${m}${v}${b}`}function $p(e){if(!e)return"Never";const n=new Date(e);return Number.isNaN(n.getTime())?"Never":n.toLocaleString()}function x2(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 gy(e,n,a){if(n)return"Repairing";if(a&&e==="error")return"Recovering";switch(e){case"provision-local":return"Initial cloud upload";case"attach-cloud":return"Initial cloud pull";case"active":return"Active";case"error":return"Error";default:return"Idle"}}function _2(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:$p(e.aiProfileSnapshotLastFetchAt)},{label:"AI snapshot fetch error",value:e.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:e.aiProfileSnapshotLastSkipReason||"None"}]}function C2({syncRecentEvents:e,syncRecentEventsError:n,syncRecentEventsLoading:a}){return a&&e.length===0?[{key:"loading",text:"Loading recent sync events...",tone:"muted"}]:n?[{key:"error",text:n,tone:"error"}]:e.length===0?[{key:"empty",text:"No recent sync events recorded.",tone:"muted"}]:e.map((s,o)=>({key:qc(s,o),text:hy(s),tone:s.status==="error"?"error":"default"}))}function yy(e){const n=[];for(const a of e){if(String(a.errorMessage||"").toLowerCase().includes("reference number mismatch")){n.push(a);continue}if(String(a.status||"").toLowerCase()==="success")break}return n}function A2(e){return yy(e).length}function I2(e){return yy(e).map((n,a)=>{const s=n.details&&typeof n.details=="object"?n.details:null,o=String(s?.path||"").trim(),c=String(s?.referenceLabel||"").trim(),i=String(s?.taskTitle||s?.existingTaskTitle||"").trim(),l=Number(s?.existingReferenceNumber),m=Number(s?.incomingReferenceNumber),y=o||i||c||`Mismatch ${a+1}`,v=Number.isFinite(l)||Number.isFinite(m)?`Existing ${Number.isFinite(l)?l:"?"} vs incoming ${Number.isFinite(m)?m:"?"}`:c?`Both claimed ${c}`:null;return{key:qc(n,a),pathLabel:y,refsLabel:v}})}function T2({currentWorkspaceId:e,syncStatusLabel:n,workspaceSyncSummary:a,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:c,formattedLastPushTime:i,workspaceSyncDiagnostics:l,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:v,referenceMismatchCount:b,syncRecentEvents:g}){const h=["Taskforce Sync Manager",`Workspace ID: ${e}`,`Status: ${n}`,`Summary: ${a}`,`Recommended action: ${s}`,`Last successful sync: ${o}`,`Last pull from cloud: ${c}`,`Last push to cloud: ${i}`,`Last error at: ${$p(l.lastErrorAt)}`,`Pending local changes: ${m}`,`Last error: ${y}`,`Sync stage: ${v}`,`Push blocked reason: ${l.pushBlockedReason||"None"}`,`Pull blocked reason: ${l.pullBlockedReason||"None"}`,`Retry blocked reason: ${l.retryBlockedReason||"None"}`,`Repair active: ${l.repairActive?"Yes":"No"}`,`Push in flight: ${l.pushInFlight?"Yes":"No"}`,`Pull in flight: ${l.pullInFlight?"Yes":"No"}`,`Retry pending: ${l.retryPending?"Yes":"No"}`,`AI profile snapshot: ${l.aiProfileSnapshotCount}`,`AI profile raw response: ${l.aiProfileSnapshotRawCount}`,`Last pushed AI profiles tracked: ${l.lastPushedAiProfileCount}`,`AI profile watermarks tracked: ${l.lastPushedAiProfileWatermarkCount}`,`AI snapshot last fetch: ${$p(l.aiProfileSnapshotLastFetchAt)}`,`AI snapshot fetch error: ${l.aiProfileSnapshotLastFetchError||"None"}`,`AI snapshot skip reason: ${l.aiProfileSnapshotLastSkipReason||"None"}`,`Document snapshot: ${l.documentSnapshotCount}`,`Asset snapshot: ${l.assetSnapshotCount}`,`Reference mismatches detected: ${b}`,`Queued full AI sync: ${l.forceFullAiProfilePushQueued?"Yes":"No"}`],k=g.map(I=>hy(I));return[...h,"","Recent sync events",...k.length>0?k:["No recent sync events recorded."]].join(`
6
+ `)}const Ch="/api/taskforce/account/profile-summary",N2=9e4,Nc=new Map;function Ou(){return typeof performance<"u"?performance.now():Date.now()}function ky(e,n){const a=String(e||"").trim();if(!a)return"";const s=String(n||"").trim();return s?`${a}::${s}`:a}function Ah(e,n){Nc.delete(ky(e,n?.identityKey))}async function R2(e,n){const a=String(e||"").trim(),s=ky(e,n?.identityKey);if(!s||!a)return null;const o=n?.force===!0,c=Date.now(),i=Nc.get(s);if(!o&&i?.payload!==void 0&&c-i.fetchedAt<N2)return Ht("account_profile_summary_cache_hit",{url:a,cacheKey:s,ageMs:c-i.fetchedAt}),i.payload;if(!o&&i?.promise)return Ht("account_profile_summary_request_reused",{url:a,cacheKey:s}),i.promise;const l=Ou(),m=(async()=>{const y=await fetch(a,{method:"GET",credentials:"include"});if(!y.ok)throw new Error(String((await y.json().catch(()=>({})))?.error||"Failed to load account summary."));const b=await y.json().catch(()=>({}))||null;return Nc.set(s,{payload:b,fetchedAt:Date.now(),promise:null}),Ht("account_profile_summary_loaded",{url:a,cacheKey:s,durationMs:Math.round(Ou()-l),fromCache:!1}),b})().catch(y=>{const v=i?.payload??null;if(v)return Nc.set(s,{payload:v,fetchedAt:i?.fetchedAt??Date.now(),promise:null}),Ht("account_profile_summary_failed",{url:a,cacheKey:s,durationMs:Math.round(Ou()-l),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!0}),v;throw Nc.delete(s),Ht("account_profile_summary_failed",{url:a,cacheKey:s,durationMs:Math.round(Ou()-l),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!1}),y});return Nc.set(s,{payload:i?.payload??null,fetchedAt:i?.fetchedAt??0,promise:m}),m}const j2=1024,P2=5*1024*1024,E2=[.9,.82,.74,.66,.58],M2=[.9,.82,.74,.66,.58],D2=[1,.85,.7,.55,.4],L2=new Set(["image/png","image/jpeg","image/webp"]);function B2(e,n){const a=document.createElement("canvas");return a.width=Math.max(1,Math.round(e)),a.height=Math.max(1,Math.round(n)),a}async function W2(e){const n=URL.createObjectURL(e);try{const a=await new Promise((s,o)=>{const c=new Image;c.onload=()=>s(c),c.onerror=()=>o(new Error("Failed to load image.")),c.src=n});return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,source:a}}finally{URL.revokeObjectURL(n)}}async function F2(e){const n=B2(e.width,e.height),a=n.getContext("2d");if(!a)throw new Error("Image optimization requires a 2D canvas context.");return a.drawImage(e.image.source,0,0,n.width,n.height),await new Promise((s,o)=>{n.toBlob(c=>{if(c){s(c);return}o(new Error("Failed to encode resized image."))},e.type,e.quality)})}const O2={loadImage:W2,renderToBlob:F2};function Ih(e,n){return e==="image/png"?".png":e==="image/jpeg"?".jpg":e==="image/webp"?".webp":(n.includes(".")?n.slice(n.lastIndexOf(".")):"")||".img"}function Th(e,n){const a=String(e||"").trim();if(!a)return`avatar${n}`;const s=a.lastIndexOf(".");return s<=0?`${a}${n}`:`${a.slice(0,s)}${n}`}function $2(e){const n=e==="image/jpeg"?"image/jpeg":"image/webp";return Array.from(new Set([n,"image/webp","image/jpeg"]))}function U2(e){return e==="image/webp"?E2:e==="image/jpeg"?M2:[void 0]}async function q2(e,n,a=O2){const s=Number.isFinite(n?.maxBytes)&&(n?.maxBytes||0)>0?Math.floor(n?.maxBytes):P2,o=Number.isFinite(n?.maxDimension)&&(n?.maxDimension||0)>0?Math.floor(n?.maxDimension):j2;if(e.size<=s)return{file:e,optimized:!1,exceededLimit:!1};if(!L2.has(e.type))return{file:e,optimized:!1,exceededLimit:!0};const c=await a.loadImage(e),i=Math.max(c.width,c.height,1),l=Math.min(1,o/i);let m=null;for(const v of D2){const b=Math.min(1,l*v),g=Math.max(1,Math.round(c.width*b)),h=Math.max(1,Math.round(c.height*b));for(const k of $2(e.type))for(const I of U2(k)){const x=await a.renderToBlob({image:c,width:g,height:h,type:k,quality:I});if((!m||x.size<m.size)&&(m=x),x.size<=s)return{file:new File([x],Th(e.name,Ih(x.type||k,e.name)),{type:x.type||k,lastModified:e.lastModified}),optimized:!0,exceededLimit:!1}}}if(!m)return{file:e,optimized:!1,exceededLimit:!0};const y=new File([m],Th(e.name,Ih(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 Up="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Sy="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Nh="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function z2({projectName:e,currentWorkspaceId:n,brandLabel:a="TaskForce",runtimeMode:s="local",theme:o=Ku,meta:c,actions:i}){const l=sg(o)?Sy:Up,m=String(e||"").trim(),y=String(n||"").trim().toLowerCase(),v=!!(m&&(s!=="cloud"||y&&y!=="default"));return t.jsxs("div",{className:`${p.header} ${pn.standaloneHeader}`,children:[t.jsxs("div",{className:`${p.headerTitle} ${pn.standaloneTitle}`,children:[t.jsx("img",{src:l,alt:"Taskforce Logo",className:p.brandIcon,onError:b=>{const g=b.currentTarget;g.src!==Nh?g.src=Nh:g.style.display="none"}}),t.jsx("span",{children:a}),s==="cloud"&&t.jsx("span",{className:p.brandCloudSuffix,children:"HQ"}),v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:p.projectSlash,children:"/"}),t.jsx("span",{className:p.projectName,title:n?`Workspace ID: ${n}`:void 0,children:m})]}),c]}),t.jsx("div",{className:p.headerActions,style:{gap:"16px"},children:i})]})}function H2({value:e,placeholder:n,active:a=!1,onChange:s,onClear:o,clearTitle:c}){return t.jsxs("div",{className:p.searchContainer,style:{width:"240px"},children:[t.jsx(lk,{size:16,className:p.searchIcon}),t.jsx("input",{type:"text",className:`${p.searchInput} ${a?p.searchActive:""}`,placeholder:n,value:e,onChange:i=>s(i.target.value)}),e&&o&&t.jsx("button",{className:p.clearSearchBtn,onClick:o,title:c,children:t.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function Rh({label:e,value:n,options:a,onChange:s,trailingAction:o,width:c}){return t.jsxs("div",{className:p.groupByContainer,style:c?{width:c}:void 0,children:[t.jsx("span",{className:p.groupByLabel,children:e}),t.jsx("select",{className:`${p.select} ${p.groupBySelect}`,value:n,onChange:i=>s(i.target.value),children:a.map(i=>t.jsx("option",{value:i.value,children:i.label},String(i.value)))}),o]})}function fp({actions:e}){return t.jsx(t.Fragment,{children:e.map(n=>t.jsx("button",{className:`tf-control-icon ${n.active?"tf-control-icon-active":""} ${n.className||""}`.trim(),onClick:n.onClick,title:n.title,disabled:n.disabled,"aria-disabled":n.ariaDisabled,children:n.icon},n.key))})}function jh(){return t.jsx("div",{className:p.headerDivider})}function G2({icon:e,label:n,onClick:a,disabled:s=!1}){return t.jsxs("button",{className:p.primaryUpdateBtn,onClick:a,disabled:s,children:[e," ",n]})}function mf({children:e}){return t.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 V2(){return t.jsx(mf,{children:t.jsx("div",{"aria-hidden":"true",style:{minHeight:"32px",flex:1}})})}function K2({categoryFilterOptions:e,typeFilterOptions:n,priorities:a,taxonomyDisplayLabels:s,filterCategories:o,setFilterCategories:c,filterTypes:i,setFilterTypes:l,filterPriorities:m,setFilterPriorities:y,filterStatus:v,setFilterStatus:b,filterAssignees:g,setFilterAssignees:h,assigneeOptions:k,initiativeFilterOptions:I=[],selectedInitiativeId:x="",setSelectedInitiativeId:A=()=>{},workstreamFilterOptions:M=[],selectedWorkstreamId:B="",setSelectedWorkstreamId:ue=()=>{},taskScope:X,setTaskScope:ce,showArchive:oe,setShowArchive:be,fetchArchive:_,onDeleteAllDeleted:J,clearFilters:Q}){return t.jsxs(t.Fragment,{children:[t.jsx(Zg,{}),t.jsx(Ai,{label:s?.category||He("standalone.categoryLabel"),options:e,selected:o,onChange:ie=>c(ie),variant:"value"}),t.jsx(Ai,{label:s?.type||He("standalone.typeLabel"),options:n,selected:i,onChange:ie=>l(ie),variant:"value"}),t.jsx(Ai,{label:s?.priority||He("standalone.priorityLabel"),options:a,selected:m,onChange:ie=>y(ie),variant:"value"}),t.jsx(Ai,{label:He("standalone.statusLabel"),options:mo,selected:v,onChange:ie=>b(ie),variant:"value"}),t.jsx(Ai,{label:He("standalone.assigneeLabel"),options:k,selected:g,onChange:ie=>h(ie),variant:"value"}),t.jsx("div",{className:p.headerDivider,style:{height:"16px",margin:"0 8px"}}),t.jsx(mh,{label:"Initiative",options:I,selected:x,onChange:A,allLabel:"All Initiatives",title:"Filter by initiative"}),t.jsx(mh,{label:"Workstream",options:M,selected:B,onChange:ue,allLabel:"All Workstreams",title:"Filter by workstream"}),t.jsx(Jg,{scope:X,onScopeChange:ie=>{ce(ie),ie==="archived"?(be(!0),_()):oe&&be(!1)},className:p.groupByContainer,labelClassName:p.groupByLabel}),t.jsx("div",{style:{flex:1}}),X==="deleted"&&J&&t.jsx(Xg,{onClick:J,className:`${p.bulkArchiveBtn} ${p.taskToolbarAction} ${p.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),t.jsx(Yg,{onClick:Q})]})}function Z2(e){return t.jsx(mf,{children:t.jsx(K2,{...e})})}const Hu=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],Gu=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function Y2({typeFilters:e,setTypeFilters:n,attachmentFilters:a,setAttachmentFilters:s,clearFilters:o}){return t.jsxs(mf,{children:[t.jsx(Zg,{}),t.jsx(Ai,{label:"Attachment",options:Gu,selected:a,onChange:c=>s(c),variant:"value"}),t.jsx(Ai,{label:"Type",options:Hu,selected:e,onChange:c=>n(c),variant:"value"}),t.jsx("div",{style:{flex:1}}),t.jsx(Yg,{onClick:o})]})}const J2="_drawerBody_126ut_1",X2="_paneShell_126ut_9",Q2="_collapsedPaneShell_126ut_18",eB="_collapsedPaneHeader_126ut_27",tB="_collapsedPaneLabel_126ut_39",nB="_treePane_126ut_49",aB="_treePaneSplit_126ut_59",rB="_detailPane_126ut_63",sB="_paneHeader_126ut_73",oB="_paneHeaderLabel_126ut_87",iB="_paneContent_126ut_96",cB="_sectionTitle_126ut_105",lB="_sectionHeaderRow_126ut_113",dB="_sectionGroup_126ut_120",uB="_treeList_126ut_145",mB="_treeChildren_126ut_151",pB="_treeRow_126ut_159",fB="_treeRowDetailOpen_126ut_171",hB="_treeRowDropReady_126ut_177",gB="_treeRowDropActive_126ut_181",yB="_treeRowDropMode_126ut_187",kB="_treeChevron_126ut_187",SB="_rowButton_126ut_188",vB="_detailsButton_126ut_189",bB="_treeRowDragging_126ut_193",wB="_rowContent_126ut_234",xB="_rowTopRow_126ut_244",_B="_referenceBadgeButton_126ut_253",CB="_referenceBadgeStatic_126ut_259",AB="_rowTitle_126ut_280",IB="_rowMeta_126ut_294",TB="_detailsButtonActive_126ut_322",NB="_unlinkZone_126ut_329",RB="_unlinkZoneActive_126ut_340",jB="_emptyPanel_126ut_346",PB="_emptyPanelTitle_126ut_355",EB="_emptyPanelText_126ut_361",MB="_sectionNote_126ut_367",DB="_detailHero_126ut_374",LB="_detailReferenceRow_126ut_381",BB="_detailTitle_126ut_386",WB="_detailDescription_126ut_393",FB="_detailActionRow_126ut_404",OB="_metricGrid_126ut_411",$B="_metricCard_126ut_418",UB="_editorCard_126ut_423",qB="_editorField_126ut_430",zB="_editorLabel_126ut_436",HB="_editorHint_126ut_442",GB="_editorSubActions_126ut_447",VB="_editorActions_126ut_452",KB="_metricValue_126ut_458",ZB="_metricLabel_126ut_465",YB="_progressTrack_126ut_472",JB="_progressFill_126ut_480",XB="_listCard_126ut_486",QB="_sectionDropReady_126ut_495",eW="_sectionDropActive_126ut_500",tW="_sectionDropMode_126ut_506",nW="_attachReferenceRow_126ut_510",aW="_listItem_126ut_521",rW="_listItemButton_126ut_530",sW="_detailCardButton_126ut_539",oW="_listItemText_126ut_547",iW="_listItemTitle_126ut_554",cW="_listItemMeta_126ut_568",lW="_detailChildCard_126ut_573",dW="_detailChildCardTopRow_126ut_585",uW="_taskStatusIcon_126ut_594",Ee={drawerBody:J2,paneShell:X2,collapsedPaneShell:Q2,collapsedPaneHeader:eB,collapsedPaneLabel:tB,treePane:nB,treePaneSplit:aB,detailPane:rB,paneHeader:sB,paneHeaderLabel:oB,paneContent:iB,sectionTitle:cB,sectionHeaderRow:lB,sectionGroup:dB,treeList:uB,treeChildren:mB,treeRow:pB,treeRowDetailOpen:fB,treeRowDropReady:hB,treeRowDropActive:gB,treeRowDropMode:yB,treeChevron:kB,rowButton:SB,detailsButton:vB,treeRowDragging:bB,rowContent:wB,rowTopRow:xB,referenceBadgeButton:_B,referenceBadgeStatic:CB,rowTitle:AB,rowMeta:IB,detailsButtonActive:TB,unlinkZone:NB,unlinkZoneActive:RB,emptyPanel:jB,emptyPanelTitle:PB,emptyPanelText:EB,sectionNote:MB,detailHero:DB,detailReferenceRow:LB,detailTitle:BB,detailDescription:WB,detailActionRow:FB,metricGrid:OB,metricCard:$B,editorCard:UB,editorField:qB,editorLabel:zB,editorHint:HB,editorSubActions:GB,editorActions:VB,metricValue:KB,metricLabel:ZB,progressTrack:YB,progressFill:JB,listCard:XB,sectionDropReady:QB,sectionDropActive:eW,sectionDropMode:tW,attachReferenceRow:nW,listItem:aW,listItemButton:rW,detailCardButton:sW,listItemText:oW,listItemTitle:iW,listItemMeta:cW,detailChildCard:lW,detailChildCardTopRow:dW,taskStatusIcon:uW},ed=332,Us=392,hp=56;function vy(e,n,a,s,o){return(e?hp:ed)+(n?a?hp:Us:0)+(s?o?hp:Us:0)}function gp(e){return e?e.split(/[-_\s]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"No status"}function Vu({label:e,entityType:n,interactive:a=!0}){const[s,o]=pt.useState(!1),c=pt.useCallback(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),window.setTimeout(()=>o(!1),1200)}catch{o(!1)}},[e]);return a?t.jsx(Fg,{copied:s,label:e,onClick:c,title:`Copy ${n} reference`,ariaLabel:s?`Copied ${n} reference`:`Copy ${n} reference`,className:Ee.referenceBadgeButton,children:e}):t.jsx("span",{className:`${p.taskIdBadge} ${Ee.referenceBadgeStatic}`.trim(),children:t.jsx("span",{children:e})})}function yp({rowId:e,rowType:n,referenceLabel:a,title:s,meta:o,active:c,detailOpen:i=!1,canExpand:l=!1,expanded:m=!1,onToggleExpand:y,onToggleScope:v,onToggleDetails:b}){const{active:g}=lm(),h=String(g?.data?.current?.type||""),k=n==="workstream"&&h==="task-card",I=n==="initiative"&&h==="planning-workstream",x=n==="workstream"?"planning-workstream-target":"planning-initiative-target",{setNodeRef:A,isOver:M}=hd({id:`${x}:${e}`,data:n==="workstream"?{type:x,workstreamId:e}:{type:x,initiativeId:e}}),B=n==="workstream",{attributes:ue,listeners:X,setNodeRef:ce,transform:oe,isDragging:be}=Dk({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!B}),_=B&&oe?{transform:Hp.Translate.toString(oe)}:void 0,J=k||I;return t.jsxs("div",{ref:A,style:_,className:`${Ee.treeRow} ${i?Ee.treeRowDetailOpen:""} ${J?Ee.treeRowDropReady:""} ${M?Ee.treeRowDropActive:""} ${be?Ee.treeRowDragging:""} ${J?Ee.treeRowDropMode:""}`,children:[l?t.jsx("button",{type:"button",className:Ee.treeChevron,onClick:y,title:m?"Collapse workstreams":"Expand workstreams",children:m?t.jsx(Hh,{size:15}):t.jsx(dk,{size:15})}):t.jsx("span",{className:Ee.treeChevron,"aria-hidden":"true",children:t.jsx(Wc,{size:14})}),t.jsxs("div",{className:Ee.rowContent,children:[t.jsxs("div",{className:Ee.rowTopRow,children:[a?t.jsx(Vu,{label:a,entityType:n}):t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:`${Ee.detailsButton} ${c?Ee.detailsButtonActive:""}`,onClick:v,title:c?"Clear board scope":"Scope board to this item",children:t.jsx(Gh,{size:14})})]}),t.jsxs("button",{type:"button",ref:B?ce:void 0,className:Ee.rowButton,onClick:b,...B?ue:{},...B?X:{},children:[t.jsx("span",{className:Ee.rowTitle,children:s}),t.jsx("span",{className:Ee.rowMeta,children:o})]})]})]})}function kp({label:e,onExpand:n}){return t.jsx("div",{className:`${Ee.paneShell} ${Ee.collapsedPaneShell}`.trim(),children:t.jsxs("div",{className:Ee.collapsedPaneHeader,children:[t.jsx("button",{type:"button",className:"tf-control-icon",onClick:n,title:`Expand ${e}`,children:t.jsx(Wc,{size:16})}),t.jsx("span",{className:Ee.collapsedPaneLabel,children:e})]})})}function mW({targetType:e,label:n}){const{active:a}=lm(),s=String(a?.data?.current?.type||""),o=e==="task"&&s==="task-card"||e==="workstream"&&s==="planning-workstream",{setNodeRef:c,isOver:i}=hd({id:e==="task"?"planning-task-unlink":"planning-workstream-unlink",data:{type:e==="task"?"planning-task-unlink":"planning-workstream-unlink"}});return o?t.jsx("div",{ref:c,className:`${Ee.unlinkZone} ${i?Ee.unlinkZoneActive:""}`,children:n}):null}function pW({initiatives:e,standaloneWorkstreams:n,activeInitiativeId:a,activeWorkstreamId:s,expandedInitiativeIds:o,detail:c,secondaryPane:i,onCreateInitiative:l,onCreateWorkstream:m,onToggleInitiative:y,onSelectInitiative:v,onSelectWorkstream:b,onOpenInitiativeDetails:g,onOpenWorkstreamDetails:h}){const{active:k}=lm(),x=String(k?.data?.current?.type||"")==="planning-workstream",{setNodeRef:A,isOver:M}=hd({id:"planning-workstream-unlink",data:{type:"planning-workstream-unlink"}});return t.jsxs(t.Fragment,{children:[t.jsx(mW,{targetType:"task",label:"Drop here to make task standalone"}),t.jsxs("div",{className:Ee.sectionGroup,children:[t.jsxs("div",{className:Ee.sectionHeaderRow,children:[t.jsx("div",{className:Ee.sectionTitle,children:"Initiatives"}),t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create initiative","aria-label":"Create initiative",onClick:l,children:t.jsx(Cs,{size:15})})]}),t.jsx("div",{className:Ee.treeList,children:e.length===0?t.jsxs("div",{className:Ee.emptyPanel,children:[t.jsx("div",{className:Ee.emptyPanelTitle,children:"No initiatives yet"}),t.jsxs("div",{className:Ee.emptyPanelText,children:["Initiatives give larger efforts a clear home without crowding the task board. Use the ",t.jsx("code",{children:"+"})," action above to create the first one."]})]}):e.map(B=>{const ue=o.has(B.id),X=`${B.workstreamCount||0} workstreams • ${B.taskCount} tasks${B.isArchived?" • archived":""}`;return t.jsxs("div",{children:[t.jsx(yp,{rowId:B.id,rowType:"initiative",referenceLabel:xs(B),title:B.title,meta:X,active:a===B.id&&!s,detailOpen:c?.type==="initiative"&&c.item.id===B.id,canExpand:B.workstreams.length>0,expanded:ue,onToggleExpand:()=>y(B.id),onToggleScope:()=>v(B.id),onToggleDetails:()=>{if(c?.type==="initiative"&&c.item.id===B.id){g("");return}g(B.id)}}),ue&&B.workstreams.length>0&&t.jsx("div",{className:Ee.treeChildren,children:B.workstreams.map(ce=>t.jsx(yp,{rowId:ce.id,rowType:"workstream",referenceLabel:uo(ce),title:ce.title,meta:`${ce.taskCount} tasks • ${ce.progressPercent}% complete${ce.isArchived?" • archived":""}`,active:s===ce.id,detailOpen:c?.type==="workstream"&&c.item.id===ce.id||i?.kind==="detail"&&i.detail.item.id===ce.id,onToggleScope:()=>b(ce.id,B.id),onToggleDetails:()=>{if(i?.kind==="detail"&&i.detail.item.id===ce.id){h("");return}if(c?.type==="workstream"&&c.item.id===ce.id){h("");return}h(ce.id)}},ce.id))})]},B.id)})})]}),t.jsxs("div",{ref:A,className:`${Ee.sectionGroup} ${x?Ee.sectionDropReady:""} ${M?Ee.sectionDropActive:""}`.trim(),children:[t.jsxs("div",{className:Ee.sectionHeaderRow,children:[t.jsx("div",{className:Ee.sectionTitle,children:"Workstreams"}),t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:m,children:t.jsx(Cs,{size:15})})]}),t.jsx("div",{className:Ee.treeList,children:n.length===0?t.jsxs("div",{className:Ee.emptyPanel,children:[t.jsx("div",{className:Ee.emptyPanelTitle,children:"No standalone workstreams yet"}),t.jsxs("div",{className:Ee.emptyPanelText,children:["Smaller projects can still use workstreams without needing initiative-level structure. Use the ",t.jsx("code",{children:"+"})," action above to add one."]})]}):n.map(B=>t.jsx(yp,{rowId:B.id,rowType:"workstream",referenceLabel:uo(B),title:B.title,meta:`${B.taskCount} tasks • ${B.progressPercent}% complete${B.isArchived?" • archived":""}`,active:s===B.id,detailOpen:c?.type==="workstream"&&c.item.id===B.id||i?.kind==="detail"&&i.detail.item.id===B.id,onToggleScope:()=>b(B.id,null),onToggleDetails:()=>{if(c?.type==="workstream"&&c.item.id===B.id){h("");return}h(B.id)}},B.id))})]})]})}function Ph({detail:e,currentWorkspaceId:n,onOpenNestedWorkstreamDetails:a,onEdit:s,onArchive:o,onUnarchive:c,onCreateTaskInWorkstream:i,onCreateWorkstreamInInitiative:l,onOpenTaskById:m,onAttachTaskToWorkstreamByReference:y,onAttachWorkstreamToInitiativeByReference:v,onAddPlanningContextFile:b,onRemovePlanningContextFile:g,onUpdatePlanningContextCaption:h}){const[k,I]=pt.useState(""),{active:x}=lm(),A=String(x?.data?.current?.type||""),M=e.type==="workstream"&&A==="task-card",B=e.type==="initiative"&&A==="planning-workstream",ue=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:X,isOver:ce}=hd({id:`${ue}:detail:${e.item.id}`,data:e.type==="initiative"?{type:ue,initiativeId:e.item.id}:{type:ue,workstreamId:e.item.id}}),oe=e.type==="initiative"?"Workstreams":"Tasks",be=e.type==="initiative"?e.item.workstreams:[],_=e.type==="initiative"?"Initiative":"Workstream",J=e.type==="initiative"?xs(e.item):uo(e.item);return pt.useEffect(()=>{I("")},[e.item.id,e.type]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:Ee.detailHero,children:[J?t.jsx("div",{className:Ee.detailReferenceRow,children:t.jsx(Vu,{label:J,entityType:e.type})}):null,t.jsx("h3",{className:Ee.detailTitle,children:e.item.title}),t.jsx("p",{className:Ee.detailDescription,children:e.item.description?.trim()||(e.type==="initiative"?"A top-level planning container that groups related workstreams.":"A coordination lane that groups related tasks and keeps execution organized.")}),t.jsx("div",{className:Ee.progressTrack,"aria-label":`${e.item.progressPercent}% complete`,children:t.jsx("div",{className:Ee.progressFill,style:{width:`${e.item.progressPercent}%`}})}),t.jsxs("div",{className:Ee.detailActionRow,children:[t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:s,children:t.jsxs("span",{children:["Edit ",_]})}),e.item.isArchived?t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:c,children:t.jsx("span",{children:"Unarchive"})}):t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:o,children:t.jsx("span",{children:"Archive"})})]})]}),t.jsxs("div",{className:Ee.metricGrid,children:[t.jsxs("div",{className:Ee.metricCard,children:[t.jsx("span",{className:Ee.metricValue,children:e.item.taskCount}),t.jsx("span",{className:Ee.metricLabel,children:"Tasks in scope"})]}),t.jsxs("div",{className:Ee.metricCard,children:[t.jsx("span",{className:Ee.metricValue,children:e.item.completedTaskCount}),t.jsx("span",{className:Ee.metricLabel,children:"Done / terminal"})]}),t.jsxs("div",{className:Ee.metricCard,children:[t.jsx("span",{className:Ee.metricValue,children:e.item.ownerLabel||"Unassigned"}),t.jsx("span",{className:Ee.metricLabel,children:"Owner"})]}),t.jsxs("div",{className:Ee.metricCard,children:[t.jsx("span",{className:Ee.metricValue,children:(e.item.commentCount||0)+(e.item.attachmentCount||0)}),t.jsx("span",{className:Ee.metricLabel,children:"Context items"})]})]}),t.jsxs("div",{ref:X,className:`${Ee.listCard} ${M||B?Ee.sectionDropReady:""} ${ce?Ee.sectionDropActive:""} ${M||B?Ee.sectionDropMode:""}`.trim(),children:[t.jsxs("div",{className:Ee.sectionHeaderRow,children:[t.jsx("div",{className:Ee.sectionTitle,children:oe}),e.type==="initiative"?t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream in this initiative","aria-label":"Create workstream in this initiative",onClick:()=>l?.(e.item.id),children:t.jsx(Cs,{size:15})}):t.jsx("button",{type:"button",className:"tf-control-icon",title:"Create task in this workstream","aria-label":"Create task in this workstream",onClick:()=>i?.(e.item.id),children:t.jsx(Cs,{size:15})})]}),t.jsxs("div",{className:Ee.attachReferenceRow,children:[t.jsx("input",{type:"text",className:p.input,placeholder:e.type==="initiative"?"Paste workstream reference (e.g. WS-123)":"Paste task reference (e.g. T-123)",value:k,onChange:Q=>I(Q.target.value)}),t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:()=>{const Q=k.trim();Q&&(e.type==="initiative"?v?.(e.item.id,Q):y?.(e.item.id,Q),I(""))},children:"Attach"})]}),e.type==="initiative"?be.length>0?be.map(Q=>t.jsx("button",{type:"button",className:`${Ee.listItemButton} ${Ee.detailCardButton}`.trim(),onClick:()=>a?.(Q.id),children:t.jsxs("div",{className:`${Ee.listItem} ${Ee.detailChildCard}`.trim(),children:[t.jsx("div",{className:Ee.detailChildCardTopRow,children:Q.referenceNumber?t.jsx(Vu,{label:uo(Q),entityType:"workstream"}):t.jsx("span",{"aria-hidden":"true"})}),t.jsxs("div",{className:Ee.listItemText,children:[t.jsx("span",{className:Ee.listItemTitle,children:Q.title}),t.jsxs("span",{className:Ee.listItemMeta,children:[Q.taskCount," tasks • ",Q.progressPercent,"% complete"]})]})]})},Q.id)):t.jsxs("div",{className:Ee.emptyPanel,children:[t.jsx("div",{className:Ee.emptyPanelTitle,children:"No workstreams yet"}),t.jsx("div",{className:Ee.emptyPanelText,children:"Add the first workstream to break the initiative into clearer lanes of execution."})]}):e.item.tasks&&e.item.tasks.length>0?[...e.item.tasks].sort((Q,ie)=>{const H=sd(Q.status).value==="done",P=sd(ie.status).value==="done";return H===P?0:H?1:-1}).map(Q=>{const ie=Q.referenceNumber?`T-${Q.referenceNumber}`:"",H=sd(Q.status),P=Uc[H.icon||"Square"],U=Ra(H.color)||"var(--text-secondary)";return t.jsx("button",{type:"button",className:`${Ee.listItemButton} ${Ee.detailCardButton}`.trim(),onClick:()=>m?.(Q.id),children:t.jsxs("div",{className:`${Ee.listItem} ${Ee.detailChildCard}`.trim(),children:[t.jsxs("div",{className:Ee.detailChildCardTopRow,children:[ie?t.jsx(Vu,{label:ie,entityType:"task"}):t.jsx("span",{"aria-hidden":"true"}),t.jsx("span",{className:Ee.taskStatusIcon,style:{color:U},"aria-label":H.shortLabel||gp(Q.status),title:H.shortLabel||gp(Q.status),children:P?t.jsx(P,{size:18,strokeWidth:2.4}):null})]}),t.jsxs("div",{className:Ee.listItemText,children:[t.jsx("span",{className:Ee.listItemTitle,children:Q.title}),t.jsx("span",{className:Ee.listItemMeta,children:gp(Q.status)})]})]})},Q.id)}):t.jsxs("div",{className:Ee.sectionNote,children:["No tasks are linked to this workstream yet. Use the ",t.jsx("code",{children:"+"})," action above to add the first one."]})]}),t.jsx("div",{className:Ee.listCard,children:t.jsx(ny,{ownerType:e.type,ownerId:e.item.id,ownerReferenceLabel:J,workspaceId:n,attachments:e.item.attachments||[],onAddAttachment:Q=>b?.(e.type,e.item.id,Q),onRemoveAttachment:Q=>g?.(e.type,e.item.id,Q),onUpdateAttachmentCaption:(Q,ie)=>h?.(e.type,e.item.id,Q,ie)})})]})}function Eh({editor:e,draftTitle:n,draftDescription:a,draftOwner:s,draftInitiativeId:o,assigneeOptions:c,draftInitiativeSummary:i,onChangeDraftTitle:l,onChangeDraftDescription:m,onChangeDraftOwner:y,onChangeDraftInitiativeId:v,onCancel:b,onSubmit:g,isSubmitting:h,onAssignInitiativeToWorkstream:k}){const I=e.entityType==="initiative"?"Initiative":"Workstream",x=h?e.mode==="create"?`Creating ${I}...`:`Saving ${I}...`:e.mode==="create"?`Create ${I}`:`Save ${I}`,A=pt.useCallback(M=>{M.preventDefault(),g()},[g]);return t.jsxs("form",{className:Ee.editorCard,onSubmit:A,children:[t.jsxs("div",{className:Ee.editorField,children:[t.jsx("label",{className:Ee.editorLabel,children:"Title"}),t.jsx("input",{className:p.input,disabled:h,value:n,onChange:M=>l(M.target.value),placeholder:e.entityType==="initiative"?"Q3 Product Launch":"Content Production"})]}),t.jsxs("div",{className:Ee.editorField,children:[t.jsx("label",{className:Ee.editorLabel,children:"Description"}),t.jsx("textarea",{className:p.textarea,disabled:h,value:a,onChange:M=>m(M.target.value),placeholder:e.entityType==="initiative"?"Describe the broader outcome this initiative is meant to achieve.":"Describe the lane of work this workstream will coordinate.",rows:5})]}),e.entityType==="workstream"&&t.jsxs("div",{className:Ee.editorField,children:[t.jsx("label",{className:Ee.editorLabel,children:"Initiative"}),i&&t.jsxs("div",{className:Ee.editorHint,children:["Current: ",i.title]}),t.jsxs("div",{className:p.pathInputGroup,children:[t.jsx("input",{type:"text",className:p.input,disabled:h,placeholder:"Paste initiative reference (e.g. IN-123)",value:o,onChange:M=>v(M.target.value)}),e.mode==="edit"&&t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,disabled:h,onClick:()=>k?.(e.targetId),children:"Set Initiative"})]}),e.mode==="edit"&&t.jsx("div",{className:Ee.editorSubActions,children:t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,disabled:h,onClick:()=>k?.(e.targetId,null),children:"Clear Initiative"})})]}),t.jsxs("div",{className:Ee.editorField,children:[t.jsx("label",{className:Ee.editorLabel,children:"Owner"}),t.jsxs("select",{className:`${p.select} ${p.groupBySelect}`,disabled:h,value:s,onChange:M=>y(M.target.value),children:[t.jsx("option",{value:"",children:"Unassigned"}),c.map(M=>t.jsx("option",{value:M.value,children:M.label},M.value))]})]}),t.jsxs("div",{className:Ee.editorActions,children:[t.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:b,disabled:h,children:"Cancel"}),t.jsx("button",{type:"submit",className:p.primaryUpdateBtn,disabled:h,children:x})]})]})}function fW({open:e,leftOffset:n=0,initiatives:a,standaloneWorkstreams:s,activeInitiativeId:o,activeWorkstreamId:c,expandedInitiativeIds:i,detail:l,editor:m,secondaryPane:y,currentWorkspaceId:v,assigneeOptions:b,draftInitiativeSummary:g,draftTitle:h,draftDescription:k,draftOwner:I,draftInitiativeId:x,onChangeDraftTitle:A,onChangeDraftDescription:M,onChangeDraftOwner:B,onChangeDraftInitiativeId:ue,onCollapseTreePane:X,onExpandTreePane:ce,onCollapsePrimaryPane:oe,onExpandPrimaryPane:be,onCollapseSecondaryPane:_,onExpandSecondaryPane:J,onBackFromSecondary:Q,treeCollapsed:ie,primaryCollapsed:H,secondaryCollapsed:P,onCancelEditor:U,onSubmitEditor:se,isSubmittingEditor:he,onCreateInitiative:V,onCreateWorkstream:Ce,onToggleInitiative:Se,onSelectInitiative:ve,onSelectWorkstream:ge,onOpenInitiativeDetails:Te,onOpenWorkstreamDetails:Le,onOpenNestedWorkstreamDetails:Ie,onEditInitiative:Oe,onEditWorkstream:z,onArchiveInitiative:T,onUnarchiveInitiative:w,onArchiveWorkstream:j,onUnarchiveWorkstream:F,onCreateTaskInWorkstream:ee,onCreateWorkstreamInInitiative:N,onAssignInitiativeToWorkstream:C,onOpenTaskById:$,onAttachTaskToWorkstreamByReference:K,onAttachWorkstreamToInitiativeByReference:te,onAddPlanningContextFile:L,onRemovePlanningContextFile:re,onUpdatePlanningContextCaption:fe}){const xe=!!(l||m),le=!!y,we=vy(ie,xe,H,le,P),Re=m?m.entityType==="initiative"?m.mode==="create"?"New Initiative":"Edit Initiative":m.mode==="create"?"New Workstream":"Edit Workstream":l?.type==="initiative"?"Initiative":"Workstream",Xe=y?.kind==="editor"?y.editor.mode==="create"?"New Workstream":"Edit Workstream":"Workstream";return t.jsx("aside",{style:{position:"absolute",top:0,left:e?`${n}px`:`${n-we-24}px`,bottom:0,width:`${we}px`,minWidth:`${we}px`,borderRight:"1px solid var(--border-color)",background:"var(--bg-secondary)",boxSizing:"border-box",display:"flex",flexDirection:"column",zIndex:35,overflow:"hidden",pointerEvents:e?"auto":"none",transition:"left 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"left"},children:t.jsxs("div",{className:Ee.drawerBody,children:[ie?t.jsx(kp,{label:"Planning",onExpand:ce}):t.jsxs("div",{className:`${Ee.paneShell} ${p.appScrollbar} tf-scrollbar ${Ee.treePane} ${xe&&!H?Ee.treePaneSplit:""}`.trim(),style:{flex:`0 0 ${ed}px`,width:`${ed}px`,minWidth:`${ed}px`,maxWidth:`${ed}px`},children:[t.jsxs("div",{className:Ee.paneHeader,children:[t.jsx("span",{className:Ee.paneHeaderLabel,children:"Planning"}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:X,children:t.jsx(Mc,{size:16})})]}),t.jsx("div",{className:Ee.paneContent,children:t.jsx(pW,{initiatives:a,standaloneWorkstreams:s,activeInitiativeId:o,activeWorkstreamId:c,expandedInitiativeIds:i,detail:l,secondaryPane:y,onCreateInitiative:V,onCreateWorkstream:Ce,onToggleInitiative:Se,onSelectInitiative:ve,onSelectWorkstream:ge,onOpenInitiativeDetails:Te,onOpenWorkstreamDetails:Le})})]}),xe&&(H?t.jsx(kp,{label:Re,onExpand:be}):t.jsxs("div",{className:`${Ee.paneShell} ${p.appScrollbar} tf-scrollbar ${Ee.detailPane}`.trim(),style:{flex:`0 0 ${Us}px`,width:`${Us}px`,minWidth:`${Us}px`,maxWidth:`${Us}px`},children:[t.jsxs("div",{className:Ee.paneHeader,children:[t.jsx("span",{className:Ee.paneHeaderLabel,children:Re}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:oe,children:t.jsx(Mc,{size:16})})]}),t.jsx("div",{className:Ee.paneContent,children:m?t.jsx(Eh,{editor:m,draftTitle:h,draftDescription:k,draftOwner:I,draftInitiativeId:x,assigneeOptions:b,draftInitiativeSummary:g,onChangeDraftTitle:A,onChangeDraftDescription:M,onChangeDraftOwner:B,onChangeDraftInitiativeId:ue,onCancel:U,onSubmit:se,isSubmitting:he,onAssignInitiativeToWorkstream:C}):l?t.jsx(Ph,{detail:l,currentWorkspaceId:v,onOpenNestedWorkstreamDetails:l.type==="initiative"?Ie:void 0,onCreateTaskInWorkstream:l.type==="workstream"?ee:void 0,onCreateWorkstreamInInitiative:l.type==="initiative"?N:void 0,onOpenTaskById:l.type==="workstream"?$:void 0,onAttachTaskToWorkstreamByReference:l.type==="workstream"?K:void 0,onAttachWorkstreamToInitiativeByReference:l.type==="initiative"?te:void 0,onEdit:()=>l.type==="initiative"?Oe(l.item.id):z(l.item.id),onArchive:()=>l.type==="initiative"?T(l.item.id):j(l.item.id),onUnarchive:()=>l.type==="initiative"?w(l.item.id):F(l.item.id),onAddPlanningContextFile:L,onRemovePlanningContextFile:re,onUpdatePlanningContextCaption:fe}):null})]})),le&&(P?t.jsx(kp,{label:Xe,onExpand:J}):t.jsxs("div",{className:`${Ee.paneShell} ${p.appScrollbar} tf-scrollbar ${Ee.detailPane}`.trim(),style:{flex:`0 0 ${Us}px`,width:`${Us}px`,minWidth:`${Us}px`,maxWidth:`${Us}px`},children:[t.jsxs("div",{className:Ee.paneHeader,children:[t.jsx("span",{className:Ee.paneHeaderLabel,children:Xe}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:_,children:t.jsx(Mc,{size:16})})]}),t.jsx("div",{className:Ee.paneContent,children:y?.kind==="editor"?t.jsx(Eh,{editor:y.editor,draftTitle:h,draftDescription:k,draftOwner:I,draftInitiativeId:x,assigneeOptions:b,draftInitiativeSummary:g,onChangeDraftTitle:A,onChangeDraftDescription:M,onChangeDraftOwner:B,onChangeDraftInitiativeId:ue,onCancel:Q,onSubmit:se,isSubmitting:he,onAssignInitiativeToWorkstream:C}):y?t.jsx(Ph,{detail:y.detail,currentWorkspaceId:v,onCreateTaskInWorkstream:ee,onOpenTaskById:$,onAttachTaskToWorkstreamByReference:K,onEdit:()=>z(y.detail.item.id),onArchive:()=>j(y.detail.item.id),onUnarchive:()=>F(y.detail.item.id),onAddPlanningContextFile:L,onRemovePlanningContextFile:re,onUpdatePlanningContextCaption:fe}):null})]}))]})})}const hW={"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"}},od="annotated_attachments.workspace_access",id="documents.workspace_access",im="workflows.workspace_access",cm="agents.workspace_access",Mh="initiatives.workspace_access",gW=Object.entries(hW).reduce((e,[n,a])=>(e[n]={key:n,enabled:!!a.enabled,description:String(a.description||""),owner:String(a.owner||""),removalMilestone:String(a.removalMilestone||"")},e),{});function yW(e){const n=String(e||"").trim();return n&&gW[n]||null}function kW(e){const n=yW(e);return n?n.enabled?{featureKey:e,allowed:!0,source:"app_gate",code:"OK"}:{featureKey:e,allowed:!1,source:"app_gate",code:"APP_GATE_DISABLED"}:{featureKey:e,allowed:!0,source:"none",code:"OK"}}function Zl(e){return kW(e.featureKey)}const SW=["tasks","docs","annotate","workflows","agents"];function vW(e){const n=e?.featureAccess||{},a={tasks:{id:"tasks",label:"Tasks",featureKey:null,enabled:!0,fallbackModuleId:"tasks"},docs:{id:"docs",label:"Documents",featureKey:id,enabled:n[id]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:"Image Notes",featureKey:od,enabled:n[od]?.allowed??!1,fallbackModuleId:"tasks"},workflows:{id:"workflows",label:"Workflows",featureKey:im,enabled:n[im]?.allowed??!1,fallbackModuleId:"tasks"},agents:{id:"agents",label:"Agents",featureKey:cm,enabled:n[cm]?.allowed??!1,fallbackModuleId:"tasks"}};return SW.map(s=>a[s])}function bW(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 Dh(e,n){const a=n.find(s=>s.id===e);return a?a.enabled?a.id:a.fallbackModuleId:"tasks"}const wW="_weekLabel_vet2o_1",xW="_sectionTitle_vet2o_6",_W="_calendarHeader_vet2o_11",CW="_monthLabel_vet2o_18",AW="_weekdayGrid_vet2o_23",IW="_weekdayLabel_vet2o_30",TW="_calendarGrid_vet2o_36",NW="_calendarDay_vet2o_42",RW="_calendarDayDot_vet2o_55",jW="_jumpRow_vet2o_67",PW="_displaySection_vet2o_73",EW="_toggleLabel_vet2o_79",MW="_expiredSummary_vet2o_87",DW="_actionButton_vet2o_95",Ua={weekLabel:wW,sectionTitle:xW,calendarHeader:_W,monthLabel:CW,weekdayGrid:AW,weekdayLabel:IW,calendarGrid:TW,calendarDay:NW,calendarDayDot:RW,jumpRow:jW,displaySection:PW,toggleLabel:EW,expiredSummary:MW,actionButton:DW},Lh=["mon","tue","wed","thu","fri","sat","sun"],LW={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function Ec(e){const n=e.getFullYear(),a=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${a}-${s}`}function td(e){const n=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const a=new Date(Number(n[1]),Number(n[2])-1,Number(n[3]));return Number.isNaN(a.getTime())?null:a}function qp(e,n){const a=e.getDay(),s=n==="sunday"?-a:a===0?-6:1-a,o=new Date(e);return o.setHours(0,0,0,0),o.setDate(o.getDate()+s),o}function BW(e,n){return n==="sunday"?{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}[e]:{mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6}[e]}function by(e,n){const a=new Date(e);return a.setDate(e.getDate()+n),a}function WW(e){const n=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),s=a.getUTCDay()||7;a.setUTCDate(a.getUTCDate()+4-s);const o=new Date(Date.UTC(a.getUTCFullYear(),0,1)),c=Math.ceil(((a.getTime()-o.getTime())/864e5+1)/7);return`${a.getUTCFullYear()}-W${String(c).padStart(2,"0")}`}const zp=320;function FW({open:e,onClose:n,scheduleSelectedDate:a,setScheduleSelectedDate:s,scheduleCalendarMonth:o,setScheduleCalendarMonth:c,scheduleShowWeekends:i,setScheduleShowWeekends:l,scheduleShowBacklog:m,setScheduleShowBacklog:y,scheduleOnlyExpired:v,setScheduleOnlyExpired:b,expiredScheduledCount:g,overdueDueCount:h,expiredLeafCandidates:k,expiredRecoveryCandidates:I,onMoveExpiredToSelectedWeek:x,onMoveExpiredToBacklog:A,scheduleBulkBusy:M,globalWeekStartsOn:B,resolvedLocale:ue,todayDateOnly:X,scheduleBaseTasks:ce,scheduleWeekStart:oe,scheduleWeekLabel:be}){const _=pt.useMemo(()=>{const[P,U]=o.split("-"),se=Number(P),he=Number(U);if(!Number.isInteger(se)||!Number.isInteger(he)||he<1||he>12){const V=td(a)||new Date;return new Date(V.getFullYear(),V.getMonth(),1)}return new Date(se,he-1,1)},[o,a]),J=pt.useMemo(()=>Lc(_,{month:"long",year:"numeric"},ue),[_,ue]),Q=pt.useMemo(()=>{const P=qp(_,B);return Array.from({length:42},(U,se)=>by(P,se))},[_,B]),ie=pt.useMemo(()=>{const P=new Map;for(const U of ce){const se=U.scheduledDate||"";if(!se)continue;const V=!(U.status==="done"||U.status==="cancelled")&&se<X,Ce=P.get(se);Ce?(Ce.count+=1,V&&(Ce.hasExpired=!0)):P.set(se,{count:1,hasExpired:V})}return P},[ce,X]),H=pt.useMemo(()=>B==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[B]);return t.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:`${zp}px`,minWidth:`${zp}px`},children:[t.jsxs("div",{className:"tf-sidebar-header",children:[t.jsxs("div",{className:"tf-sidebar-title",children:[t.jsx(uk,{size:16}),t.jsx("span",{children:"Schedule Controls"})]}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:n,title:"Hide Schedule Sidebar",children:t.jsx(Wc,{size:16})})]}),t.jsxs("div",{className:Ua.weekLabel,children:["Week of ",be]}),t.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[t.jsxs("div",{className:Ua.calendarHeader,children:[t.jsx("button",{className:"tf-control-icon",onClick:()=>{const P=new Date(_);P.setMonth(_.getMonth()-1),c(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:t.jsx(Mc,{size:14})}),t.jsx("div",{className:Ua.monthLabel,children:J}),t.jsx("button",{className:"tf-control-icon",onClick:()=>{const P=new Date(_);P.setMonth(_.getMonth()+1),c(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:t.jsx(Wc,{size:14})})]}),t.jsx("div",{className:Ua.weekdayGrid,children:H.map(P=>t.jsx("div",{className:Ua.weekdayLabel,children:P},P))}),t.jsx("div",{className:Ua.calendarGrid,children:Q.map(P=>{const U=Ec(P),se=P.getMonth()!==_.getMonth(),he=qp(P,B),V=Ec(he)===Ec(oe),Ce=U===a,Se=U===X,ve=U<X,ge=ie.get(U),Te=!!ge,Le=!!ge?.hasExpired;return t.jsxs("button",{onClick:()=>{s(U),c(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},className:Ua.calendarDay,style:{"--calendar-day-border":Ce?"1px solid #2563eb":Se?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":Ce?"rgba(59,130,246,0.22)":Se?"rgba(245,158,11,0.16)":V?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":se?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":Ce||Se?700:500,"--calendar-day-opacity":ve?.42:1},title:`${Se?`${U} (Today)`:U}`+(Te?` • ${ge?.count} scheduled`:"")+(Le?" • includes expired":""),children:[P.getDate(),Te&&t.jsx("span",{className:Ua.calendarDayDot,style:{"--calendar-dot-background":Le?"#ef4444":"#3b82f6","--calendar-dot-opacity":se?.6:.95}})]},U)})}),t.jsx("div",{className:Ua.jumpRow,children:t.jsx("button",{className:"tf-control-icon",onClick:()=>{const P=new Date;s(Ec(P)),c(`${P.getFullYear()}-${String(P.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),t.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${Ua.displaySection}`,children:[t.jsx("div",{className:Ua.sectionTitle,children:"Display"}),t.jsxs("label",{className:Ua.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:i,onChange:P=>l(P.target.checked)}),"Show weekends"]}),t.jsxs("label",{className:Ua.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:m,onChange:P=>y(P.target.checked)}),"Show backlog"]}),t.jsxs("label",{className:Ua.toggleLabel,children:[t.jsx("input",{type:"checkbox",checked:v,onChange:P=>b(P.target.checked)}),"Only expired/overdue"]})]}),g>0&&t.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[t.jsx("div",{className:Ua.sectionTitle,children:"Expired Tasks"}),t.jsxs("div",{className:Ua.expiredSummary,children:[t.jsxs("span",{children:[g," expired"]}),t.jsxs("span",{children:[h," overdue"]})]}),t.jsx("button",{className:`tf-control-icon ${Ua.actionButton}`,onClick:x,disabled:M||k.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",children:M?"Working...":"Schedule to selected week"}),t.jsx("button",{className:`tf-control-icon ${Ua.actionButton}`,onClick:A,disabled:M||I.length===0,title:"Unschedule expired/overdue tasks back to backlog",children:M?"Working...":"Unschedule to backlog"})]})]})}function wy(e,n){return e&&(n==="owner"||n==="admin")}function OW(e,n,a){return wy(e,n)&&a==="team"}function $W({isOpen:e,workspaceId:n,refreshKeys:a}){const[s,o]=r.useState([]),[c,i]=r.useState(!1),[l,m]=r.useState(null),y=r.useRef(null),v=r.useRef(null);r.useLayoutEffect(()=>{v.current=qW(y.current,v.current)},[s]);const b=r.useCallback(async()=>{const g=await fetch(`/api/taskforce/sync/events?workspace_id=${encodeURIComponent(n)}&limit=15`,{method:"GET",credentials:"include"});if(!g.ok)throw new Error(`Failed to load sync events (${g.status})`);const h=await g.json().catch(()=>({}));return Array.isArray(h?.events)?h.events.filter(k=>k&&typeof k=="object"):[]},[n]);return r.useEffect(()=>{if(!e)return;let g=!1;const h=s.length===0;return h&&i(!0),b().then(k=>{g||(v.current=UW(y.current),o(I=>{const x=I.length===0?k:b2(I,k,15);return w2(I,x)?I:x}),m(null))}).catch(k=>{if(g)return;const I=k instanceof Error&&k.message.trim().length>0?k.message.trim():"Unable to load recent sync events.";m(I),h&&o([])}).finally(()=>{g||h&&i(!1)}),()=>{g=!0}},[e,b,...a]),{syncRecentEvents:s,syncRecentEventsLoading:c,syncRecentEventsError:l,syncEventsListRef:y,loadRecentSyncEvents:b}}function UW(e){return e&&e.scrollTop>8?{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight}:null}function qW(e,n){if(!n||!e)return null;const a=e.scrollHeight-n.scrollHeight;return e.scrollTop=n.scrollTop+Math.max(0,a),null}function zW({currentWorkspaceId:e,syncStatusLabel:n,workspaceSyncSummary:a,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:c,formattedLastPushTime:i,workspaceSyncDiagnostics:l,workspaceSyncPendingChanges:m,syncLastError:y,workspaceSyncPhase:v,referenceMismatchCount:b,syncRecentEvents:g,loadRecentSyncEvents:h,pushNotice:k,resetWorkspaceSyncCursorAndPull:I,workspaceSyncBusy:x}){const[A,M]=r.useState(!1),[B,ue]=r.useState(!1),[X,ce]=r.useState(!1),oe=r.useCallback(async()=>{try{const J=g.length>0?g:await h(),Q=T2({currentWorkspaceId:e,syncStatusLabel:n,workspaceSyncSummary:a,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:c,formattedLastPushTime:i,workspaceSyncDiagnostics:l,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:gy(v,A,x),referenceMismatchCount:b,syncRecentEvents:J});await navigator.clipboard.writeText(Q),ce(!0),window.setTimeout(()=>{ce(!1)},1800),k("Sync details copied to clipboard.","success")}catch{ce(!1),k("Failed to copy sync details.","error")}},[e,c,i,o,h,k,b,y,g,n,l,v,m,s,a,x,A]),be=r.useCallback(async()=>{ue(!1),M(!0);try{await I()}finally{M(!1)}},[I]),_=r.useCallback(()=>{if(!A){if(x){ue(!0);return}be()}},[be,x,A]);return r.useEffect(()=>{B&&(x||A||be())},[be,x,A,B]),{workspaceSyncRepairBusy:A,workspaceSyncRepairQueued:B,workspaceSyncCopied:X,handleCopySyncDetails:oe,handleQueueOrRunRepairSync:_}}function HW({canManageWorkspaceSync:e,workspaceCloudSyncEnabled:n,saveWorkspaceCloudSyncSettings:a}){const[s,o]=r.useState(!1),[c,i]=r.useState(!1),[l,m]=r.useState(!1),[y,v]=r.useState(null),b=r.useCallback(async A=>{if(e){v(null),m(!0);try{const M=await a({enabled:A});M.success||v(M.error||(A?"Failed to enable sync.":"Failed to disable sync."))}finally{m(!1)}}},[e,a]),g=r.useCallback(async A=>{if(A&&!n){i(!0);return}await b(A)},[b,n]),h=r.useCallback(()=>{i(!1)},[]),k=r.useCallback(()=>{i(!1),b(!0)},[b]),I=r.useCallback(()=>{o(!0)},[]),x=r.useCallback(()=>{o(!1)},[]);return{showSyncStatusModal:s,showSyncEnableWarning:c,workspaceSyncToggleBusy:l,workspaceSyncError:y,syncControlBusy:l,openSyncStatusModal:I,closeSyncStatusModal:x,handleWorkspaceSyncToggle:g,cancelSyncEnableWarning:h,confirmSyncEnableWarning:k}}const GW=pt.lazy(()=>Uo(()=>import("./TaskSettings-DZX4jk7e.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.TaskSettings}))),VW=pt.lazy(()=>Uo(()=>import("./AnnotatedAttachmentWorkspace-Z9_whf7F.js"),__vite__mapDeps([7,1,2,3,4,5,8])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),KW=pt.lazy(()=>Uo(()=>import("./DocumentWorkspace-B03MaSkw.js"),__vite__mapDeps([9,1,2,3,4,5,10])).then(e=>({default:e.DocumentWorkspaceShell}))),ZW=pt.lazy(()=>Uo(()=>import("./WorkflowsModule-BA7jcEpH.js"),__vite__mapDeps([11,1,2,3,4,5])).then(e=>({default:e.WorkflowsModule}))),YW=pt.lazy(()=>Uo(()=>import("./AgentsModule-DrLawwNl.js"),__vite__mapDeps([12,1,2,3,4,5])).then(e=>({default:e.AgentsModule})));pt.lazy(()=>Uo(()=>import("./InitiativesModule-9E6ParrY.js"),__vite__mapDeps([13,1,2,3,4,5])).then(e=>({default:e.InitiativesModule})));const JW=pt.lazy(()=>Uo(()=>import("./PlansPage-DRXscYxH.js"),__vite__mapDeps([14,1,2,5,3,4,15])).then(e=>({default:e.PlansPage}))),XW="image/png,image/jpeg,image/webp,image/gif",QW=5*1024*1024,eF=e=>e;function tF(e,n){const a=um(e);if(a)return Ef(a).label.toUpperCase();for(const s of n){const o=String(s||"").trim();if(!o)continue;const c=Yp(o);if(c)return Ef(c).label.toUpperCase();let i=o.toLowerCase();try{i=new URL(o.includes("://")?o:`https://${o}`).hostname.toLowerCase()}catch{i=o.toLowerCase()}if(!(i.includes("localhost")||i.includes("127.0.0.1")||i.includes("::1")))return i.toUpperCase()}return"UNKNOWN"}function Yl(){return typeof performance<"u"?performance.now():Date.now()}function nF(e){const s=eg(),o=tg(),c=r.useMemo(()=>new URLSearchParams(o.search),[o.search]),i=String(c.get("screen")||"").trim().toLowerCase()==="plans",l=r.useCallback(u=>{const S=new URLSearchParams(o.search);S.set("screen","plans");for(const[D,ye]of Object.entries(u||{}))ye==null||String(ye).trim()===""?S.delete(D):S.set(D,String(ye));s(`/?${S.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 S=u.toString();s(`${o.pathname==="/"?"/":o.pathname}${S?`?${S}`:""}${o.hash||""}`)},[o.hash,o.pathname,o.search,s]),{activeTab:y,setActiveTab:v,activeCategories:b,groupBy:g,setGroupBy:h,activeWorkspaceModule:k,setActiveWorkspaceModule:I,emptyColumnMode:x,setEmptyColumnMode:A,zenMode:M,setZenMode:B,filterStatus:ue,setFilterStatus:X,tasks:ce,handleEdit:oe,handleSubmit:be,resetForm:_,handleUpdateTask:J,editingTaskId:Q,loading:ie,error:H,title:P,setTitle:U,description:se,setDescription:he,checklistItems:V,setChecklistItems:Ce,category:Se,setCategory:ve,type:ge,setType:Te,priority:Le,setPriority:Ie,complexity:Oe,setComplexity:z,setStatus:T,approach:w,setApproach:j,assignee:F,setAssignee:ee,scheduledDate:N,setScheduledDate:C,dueDate:$,setDueDate:K,workstreamInput:te,setWorkstreamInput:L,manualComplexityEnabled:re,checklistDropdownEnabled:fe,showTaskCardStatusLabel:xe,formTaxonomies:le,setFormTaxonomies:we,comments:Re,newCommentText:Xe,setNewCommentText:ze,attachments:lt,setAttachments:wt,setAttachmentsDirty:$e,descriptionFocused:ft,setDescriptionFocused:gt,showMarkdownHelp:at,setShowMarkdownHelp:dt,showChecklist:ne,setShowChecklist:tt,showComments:rt,setShowComments:Pt,handleAddComment:yt,handleSetWorkstreamForCurrentTask:Rt,handleOpenTaskById:Tt,taxonomies:Dt,activeTypes:d,priorities:Me,taxonomyDisplayLabels:We,approaches:Qe,copiedId:ot,handleCopyId:de,handleToggleInProgress:Be,handleToggleComplete:St,handleToggleReview:vt,handleToggleCancel:$t,handleArchiveTask:Ze,handleDelete:en,handleUnarchive:Lt,handleRestoreDeletedTask:bt,handlePermanentlyDeleteDeletedTask:W,handleEmptyDeletedTasks:ke,fetchTasks:Ne,searchQuery:ae,setSearchQuery:Pe,filterCategories:Ge,setFilterCategories:De,filterTypes:it,setFilterTypes:Ut,filterPriorities:Gt,setFilterPriorities:nn,filterAssignees:Ft,setFilterAssignees:Wt,hasInitedFilters:Vt,assigneeOptions:an,taskScope:Kt,setTaskScope:Kn,sortBy:Fn,setSortBy:Jn,clearFilters:_n,settingsModel:pe,configLoaded:et,currentTheme:Ae,setCurrentTheme:Nt,pathSaved:Ye,saveSettings:Ot,keyShortcut:dn,setKeyShortcut:yn,globalWeekStartsOn:on,locale:rn,jsonBackupEnabled:kt,setJsonBackupEnabled:zt,mcpHostRoot:Ln,setMcpHostRoot:Et,settingsSection:On,setSettingsSection:kn,runtimeMode:Jt,workspaceSwitchingEnabled:Dr,cloudAuthConfigured:Rn,authRequiredForApi:Xn,authBlocked:In,isAuthenticated:Yt,authUserId:jn,authWorkspaceId:ln,authUserEmail:ga,authUserDisplayName:la,authUserAvatarUrl:Za,authSessionResolved:fn,realtimeSyncEnabled:Cr,realtimeSyncFlagSource:Lr,workspaceCloudSyncEnabled:ya,workspaceSyncPhase:Bn,workspaceSyncStatus:Ar,workspaceSyncSummary:ka,workspaceSyncRecommendedAction:ja,workspaceSyncBusy:Qn,workspaceSyncPendingChanges:Tn,saveWorkspaceCloudSyncSettings:Br,pushNotice:_t,userGlobalSyncStatus:Sa,workspaceLastSuccessfulSyncAt:da,workspaceLastPullAt:va,workspaceLastPushAt:$n,workspaceLastErrorAt:Pa,userGlobalSyncError:wn,workspaceLastErrorMessage:Un,retryWorkspaceCloudSync:ba,resetWorkspaceSyncCursorAndPull:un,getWorkspaceSyncDiagnostics:Ea,currentWorkspaceId:Qt,currentWorkspaceRole:qn,availableWorkspaces:Cn,switchWorkspace:Ya,updateCurrentUserProfile:Ja,resolveCloudAuthUrl:Mn=eF,logout:cn,fetchLoginMethods:hn,unlinkLoginMethod:ua,addPasswordToAccount:ea,beginOAuthLogin:pr,beginOAuthLink:fr,availableAuthProviders:Xt,projectRoot:ms,projectName:zn,mcpScriptPath:Xa,serverHostRoot:Vr,showFolderBrowser:ma,setShowFolderBrowser:qa,folders:Wr,files:wa,currentBrowsePath:Hn,fetchFolders:Ir,browserTarget:Pn,setBrowserTarget:ps,handleSelectPath:ta,handleAddPath:Tr,handleRemovePath:hr,handleUpdateCategory:Fr,handleRemoveCategory:pa,handleSaveCategory:gr,handleUpdateCategoryIcon:xa,handleUpdateCategoryColor:Ma,handleSaveType:Qa,handleRemoveType:Kr,handleUpdateTaxonomies:Or,handleUpdatePriorities:Ve,pathValidation:Bt,exportEnvironment:Dn,setExportEnvironment:sn,exportWorkflowsPath:_a,setExportWorkflowsPath:Zn,exportResult:Is,exportingResource:Zr,availableWorkflows:Yr,onExportWorkflows:Yn,fetchWorkflows:Mt,availableEnvironments:mn,initiativeTemplates:Da,fetchInitiativeTemplates:yr,createInitiativeFromTemplate:kr,uiNotice:er,clearNotice:fs,taskReturnTrail:Nr,clearReturnToParentTask:Jr,returnToPreviousTask:tr,tasksScrollRef:ra,setTasksScrollPos:Ts,commentsEndRef:q,autoSaveState:Je,unsavedModalOpen:Ct,setUnsavedModalOpen:jt,pendingNavigation:Nn,handleNavigation:nr,currentTask:Ca,currentTaskWorkstream:ho,currentTaskInitiative:Ns,scheduleWarningPrompt:qo,confirmScheduleWarning:Gn,cancelScheduleWarning:La}=e,R=rn||mg();r.useEffect(()=>{const u=String(zn||"").trim();document.title=u?`Taskforce - ${u}`:"Taskforce"},[zn]);const E=()=>{jt(!1),Nn?(y==="add"&&_(),Nn()):(y==="add"&&_(),v("tasks"))},je=async()=>{await be({preventDefault:()=>{}}),jt(!1),Nn&&Nn()},[ct,nt]=r.useState(!1),[Y,zs]=r.useState(!1),[ar,Hs]=r.useState(!0),[Ba,Hc]=r.useState(!1),[rr,sr]=r.useState(!0),[Xr,Gc]=r.useState(Ec(new Date)),[Vc,Gs]=r.useState(()=>{const u=new Date;return`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}`}),[zo,Aa]=r.useState(0),[Vs,Ho]=r.useState(!1),[Go,Mi]=r.useState(!1),[Rr,Ks]=r.useState(!1),[go,Kc]=r.useState(!1),[yo,hs]=r.useState(!1),[Vo,Sr]=r.useState(!1),[An,or]=r.useState(""),[jr,Sn]=r.useState(""),[Zc,gs]=r.useState(new Set),[fa,Qr]=r.useState(null),[ko,Wa]=r.useState(null),[vr,ys]=r.useState(null),[Zs,es]=r.useState(null),[Ys,ks]=r.useState(""),[$r,Js]=r.useState(""),[Di,Rs]=r.useState(""),[ts,ns]=r.useState(""),[Yc,ir]=r.useState(!1),vn=r.useRef(new Map),Ia=r.useRef(new Map),[br,Xs]=r.useState(()=>Hu.map(u=>u.value)),[Ur,So]=r.useState(()=>Gu.map(u=>u.value)),[Sd,Li]=r.useState(null),[Fa,Jc]=r.useState(null),[Oa,Qs]=r.useState(null),[js,Ko]=r.useState(null),[fm,vd]=r.useState(0),[vo,hm]=r.useState({}),[Zo,bd]=r.useState(!1),Ps=r.useRef(!1),wd=r.useRef(""),Xc=r.useRef(null),xd=r.useRef(null),Qc=r.useRef(new Set),bo=r.useMemo(()=>{const u={},S=String(Qt||"").trim();return Jt==="cloud"&&S&&S!=="default"&&(u["x-taskforce-workspace-id"]=S),u},[Jt,Qt]),Yo=r.useMemo(()=>`${Jt}:${String(Qt||"default").trim()||"default"}`,[Jt,Qt]),Bi=r.useMemo(()=>`taskforce:annotate-layout:${Yo}`,[Yo]),el=r.useMemo(()=>Jt==="cloud"?fn:et,[fn,et,Jt]);r.useEffect(()=>{Xc.current=Oa},[Oa]),r.useEffect(()=>{xd.current=js},[js]);const Wi=r.useMemo(()=>({[id]:Zl({featureKey:id}),[od]:Zl({featureKey:od}),[im]:Zl({featureKey:im}),[cm]:Zl({featureKey:cm}),[Mh]:Zl({featureKey:Mh})}),[Jt]),eo=r.useMemo(()=>vW({featureAccess:Wi}),[Wi]),na=r.useMemo(()=>Dh(k,eo),[k,eo]),Jo=Wi[id]?.allowed??!1,tl=Wi[od]?.allowed??!1,_d="Documents is not available in this build yet.",Cd="Annotate is not available in this build yet.";r.useEffect(()=>{const u=S=>{const D=S,ye=D.detail?.fsPath,_e=String(D.detail?.assetId||"").trim()||null;if(!(!ye&&!_e)){if(D.preventDefault(),!Jo){_t(_d,"error");return}Li(ye||null),Jc(_e),I("docs")}};return window.addEventListener("taskforce:open-markdown-document",u),()=>{window.removeEventListener("taskforce:open-markdown-document",u)}},[Jo,_d,_t,I]),r.useEffect(()=>{na!==k&&I(na)},[k,na,I]),r.useEffect(()=>{na==="docs"&&Jo||(Li(null),Jc(null))},[Jo,na]),r.useEffect(()=>{if(!(typeof window>"u"))try{const u=window.sessionStorage.getItem(Bi);if(!u)return;const S=JSON.parse(u);S?.annotatedTarget&&typeof S.annotatedTarget=="object"&&Qs(S.annotatedTarget),typeof S?.annotatedSessionId=="string"&&Ko(S.annotatedSessionId.trim()||null)}catch{}},[Bi]),r.useEffect(()=>{if(wd.current===Yo)return;wd.current=Yo,bd(!1);let u=!1;return(async()=>{try{const D=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:bo});if(!D.ok)return;const ye=await D.json().catch(()=>({})),_e=ye?.state&&typeof ye.state=="object"?ye.state:null;if(!_e||u)return;if(typeof _e.scheduleShowWeekends=="boolean"&&zs(_e.scheduleShowWeekends),typeof _e.scheduleShowBacklog=="boolean"&&Hs(_e.scheduleShowBacklog),typeof _e.scheduleOnlyExpired=="boolean"&&Hc(_e.scheduleOnlyExpired),typeof _e.scheduleSidebarOpen=="boolean"&&sr(_e.scheduleSidebarOpen),typeof _e.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(_e.scheduleSelectedDate)&&Gc(_e.scheduleSelectedDate),typeof _e.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(_e.scheduleCalendarMonth)&&Gs(_e.scheduleCalendarMonth),typeof _e.scheduleScrollLeft=="number"&&Number.isFinite(_e.scheduleScrollLeft)&&_e.scheduleScrollLeft>=0&&Aa(_e.scheduleScrollLeft),typeof _e.showFilters=="boolean"&&Ho(_e.showFilters),Array.isArray(_e.documentTypeFilters)&&Xs(_e.documentTypeFilters),Array.isArray(_e.documentAttachmentFilters)&&So(_e.documentAttachmentFilters),typeof _e.planningDrawerOpen=="boolean"&&Ks(_e.planningDrawerOpen),typeof _e.planningTreeCollapsed=="boolean"&&Kc(_e.planningTreeCollapsed),typeof _e.planningPrimaryCollapsed=="boolean"&&hs(_e.planningPrimaryCollapsed),typeof _e.planningSecondaryCollapsed=="boolean"&&Sr(_e.planningSecondaryCollapsed),Array.isArray(_e.planningExpandedInitiativeIds)&&gs(new Set(_e.planningExpandedInitiativeIds.map(qt=>String(qt||"").trim()).filter(Boolean))),_e.planningDrawerDetail&&typeof _e.planningDrawerDetail=="object"&&(_e.planningDrawerDetail.type==="initiative"||_e.planningDrawerDetail.type==="workstream")&&typeof _e.planningDrawerDetail.id=="string"){const qt=_e.planningDrawerDetail.id.trim();Qr(qt?{type:_e.planningDrawerDetail.type,id:qt}:null)}else _e.planningDrawerDetail===null&&Qr(null);typeof _e.planningNestedWorkstreamDetailId=="string"?Wa(_e.planningNestedWorkstreamDetailId.trim()||null):_e.planningNestedWorkstreamDetailId===null&&Wa(null);const ut=_e.annotatedTarget;ut&&typeof ut=="object"&&(Xc.current||Qs(ut)),typeof _e.annotatedSessionId=="string"&&(xd.current||Ko(_e.annotatedSessionId.trim()||null))}catch{}finally{u||bd(!0)}})(),()=>{u=!0}},[Yo,bo]),r.useEffect(()=>{if(!Zo)return;const u=window.setTimeout(async()=>{try{await Xp({stateKey:"layout",workspaceId:Qt,headers:bo,patch:{scheduleShowWeekends:Y,scheduleShowBacklog:ar,scheduleOnlyExpired:Ba,scheduleSidebarOpen:rr,scheduleSelectedDate:Xr,scheduleCalendarMonth:Vc,scheduleScrollLeft:zo,showFilters:Vs,documentTypeFilters:br,documentAttachmentFilters:Ur,planningDrawerOpen:Rr,planningTreeCollapsed:go,planningPrimaryCollapsed:yo,planningSecondaryCollapsed:Vo,planningExpandedInitiativeIds:Array.from(Zc),planningDrawerDetail:fa,planningNestedWorkstreamDetailId:ko,annotatedTarget:Oa,annotatedSessionId:js}})}catch{}},250);return()=>window.clearTimeout(u)},[Zo,Y,ar,Ba,rr,Xr,Vc,zo,Vs,br,Ur,Rr,go,yo,Vo,Zc,fa,ko,Oa,js,bo]),r.useEffect(()=>{if(!(typeof window>"u"))try{window.sessionStorage.setItem(Bi,JSON.stringify({annotatedTarget:Oa,annotatedSessionId:js}))}catch{}},[Bi,js,Oa]),r.useEffect(()=>{g==="schedule"&&sr(!0)},[g]);const{showArchive:Es,setShowArchive:Fi,fetchArchive:Oi,filteredArchive:$i}=e,Ms=r.useMemo(()=>$i.map(u=>({...u,isArchived:!0})),[$i]),sa=r.useMemo(()=>e.archivedTasks.map(u=>({...u,isArchived:!0})),[e.archivedTasks]),qr=r.useMemo(()=>[...e.searchAgnosticTasks,...sa],[sa,e.searchAgnosticTasks]),nl=r.useCallback(u=>{const S=String(u||"").trim();if(!S)return"";const D=qr.find(ye=>ye.id===S);return qs(D)||""},[qr]),Ad=r.useCallback(u=>{const S=String(u||"").trim();if(!S)return"";const D=String(vo[S]||"").trim();if(D)return D;for(const ye of qr)for(const _e of ye.attachments||[]){if(!_e||typeof _e!="object"||String(_e.assetId||"").trim()!==S)continue;const ut=qg({referenceNumber:typeof _e.referenceNumber=="number"?_e.referenceNumber:null,referenceLabel:String(_e.referenceLabel||"").trim()||null});if(ut)return ut}return""},[qr,vo]);r.useEffect(()=>{const u=S=>{const D=S,ye=ih(D.detail,qr);if(ye){if(D.preventDefault(),!tl){_t(Cd,"error");return}Qs(ye),Ko(null),vd(_e=>_e+1),I("annotate")}};return window.addEventListener("taskforce:open-annotated-attachment",u),()=>{window.removeEventListener("taskforce:open-annotated-attachment",u)}},[qr,tl,Cd,_t,I]),r.useEffect(()=>{if(!Oa)return;const u=ih(Oa,qr);u&&(u.taskReferenceLabel===Oa.taskReferenceLabel&&u.imageReferenceLabel===Oa.imageReferenceLabel||Qs(u))},[qr,Oa]),r.useEffect(()=>{const u=Xc.current,S=String(u?.assetId||"").trim();if(!S)return;const D=String(vo[S]||"").trim();D&&D!==String(u?.imageReferenceLabel||"").trim()&&Qs(ye=>!ye||String(ye.assetId||"").trim()!==S?ye:{...ye,imageReferenceLabel:D})},[vo,Oa]),r.useEffect(()=>{if(!el)return;const S=String(Oa?.assetId||"").trim();if(!S||Qc.current.has(S)||String(vo[S]||"").trim())return;let D=!1;Qc.current.add(S);const ye=String(Qt||"default").trim()||"default",_e=new URLSearchParams({workspaceId:ye});return(async()=>{try{const qt=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(S)}?${_e.toString()}`,{method:"GET",credentials:"include",headers:bo});if(!qt.ok)return;const xn=await qt.json().catch(()=>({})),gn=String(xn?.target?.imageReferenceLabel||"").trim();if(!gn||D)return;hm(Bo=>Bo[S]===gn?Bo:{...Bo,[S]:gn})}catch{}finally{Qc.current.delete(S)}})(),()=>{D=!0}},[el,vo,Qt,Oa,bo]);const cr=r.useMemo(()=>e.deletedTasks.map(u=>({...u.taskSnapshot,isDeleted:!0,deletedRecordId:u.id})),[e.deletedTasks]),Xo=r.useMemo(()=>{const u=new Map;return e.deletedTasks.forEach(S=>{u.set(S.taskSnapshot.id,S)}),u},[e.deletedTasks]),Ui=r.useMemo(()=>{const u=cr,S=ae.trim().toLowerCase(),D=b.every(gn=>Ge.includes(gn.value)),ye=d.every(gn=>it.includes(gn.value)),_e=new Set(Gt.map(gn=>String(gn))),ut=Me.every(gn=>_e.has(String(gn.value))),qt=new Set(ue.map(gn=>String(gn))),xn=mo.every(gn=>qt.has(String(gn.value)));return u.filter(gn=>{const Bo=(qs(gn)||gn.id).toLowerCase(),Gm=!S||gn.title.toLowerCase().includes(S)||String(gn.description||"").toLowerCase().includes(S)||gn.id.toLowerCase().includes(S)||Bo.includes(S),Vm=D||Ge.includes(gn.category),xu=ye||it.includes(gn.type||Mr),Km=ut||_e.has(String(gn.priority)),Zm=xn||qt.has(String(gn.status)),Ym=Ft.length===0||Ft.includes(gn.assignee||"unassigned");return Gm&&Vm&&xu&&Km&&Zm&&Ym})},[b,d,cr,Ft,Ge,Gt,ue,it,Me,ae]),Qo=r.useMemo(()=>[...e.tasks,...sa,...cr],[sa,cr,e.tasks]),al=r.useMemo(()=>{const u=b.filter(D=>!D.disabled).map(D=>({value:D.value,label:D.label})),S=b.filter(D=>D.disabled&&Qo.some(ye=>ye.category===D.value)).map(D=>({value:D.value,label:`${D.label} (Legacy)`}));return[...u,...S]},[b,Qo]),rl=r.useMemo(()=>{const u=d.filter(D=>D.status!=="retired").map(D=>({value:D.value,label:D.label})),S=d.filter(D=>D.status==="retired"&&Qo.some(ye=>(ye.type||Mr)===D.value)).map(D=>({value:D.value,label:`${D.label} (Retired)`}));return[...u,...S]},[d,Qo]),to=r.useMemo(()=>Kt==="archived"?Ms:Kt==="deleted"?Ui:Es?[...e.filteredTasks,...Ms]:e.filteredTasks,[Ms,Ui,e.filteredTasks,Es,Kt]),qi=r.useMemo(()=>Kt==="open"?e.tasks.filter(u=>!u.isArchived):to,[to,e.tasks,Kt]),Id=r.useMemo(()=>new Set(to.map(u=>u.id)),[to]),zi=r.useMemo(()=>Kt==="archived"?sa:Kt==="deleted"?cr:Es?[...e.tasks,...sa]:e.tasks,[sa,cr,e.tasks,Es,Kt]),ei=r.useMemo(()=>{const u=new Map;for(const S of sa)u.set(S.id,S);for(const S of cr)u.set(S.id,S);for(const S of e.tasks)u.set(S.id,S);return Array.from(u.values())},[sa,cr,e.tasks]),sl=r.useMemo(()=>{const u=new Map;return ei.forEach(S=>u.set(S.id,S)),u},[ei]),Hi=r.useMemo(()=>{const u=new Map;an.forEach(ye=>{u.set(String(ye.value),ye.label)});const S=String(jn||"").trim(),D=String(la||ga||"").trim();return S&&D&&u.set(S,D),u},[an,la,ga,jn]),xt=r.useMemo(()=>{const u=Kt==="archived"?sa:Kt==="deleted"?cr:e.tasks.filter(It=>!It.isArchived),S=(It,$a)=>({progressPercent:It>0?Math.round($a/It*100):0,taskCount:It,completedTaskCount:$a}),D=Kt==="open"&&e.planningBootstrapTaskSummaries.length>0&&(e.loadingTasks||e.tasks.length===0),ye=new Map;D?e.planningBootstrapTaskSummaries.forEach(It=>{ye.set(It.workstreamId,It)}):u.forEach(It=>{const $a=String(It.workstreamId||"").trim();if(!$a)return;const bs=ye.get($a)||{workstreamId:$a,taskCount:0,completedTaskCount:0,tasks:[]};bs.taskCount+=1,(It.isArchived||It.status==="done"||It.status==="cancelled")&&(bs.completedTaskCount+=1),bs.tasks.push({id:It.id,referenceNumber:It.referenceNumber??null,title:It.title,status:It.status||null}),ye.set($a,bs)});const _e=new Map,ut=new Map,qt=new Map,xn=new Map,gn=It=>{const $a=ye.get(It.id),bs=$a?.tasks||[],_u={id:It.id,referenceNumber:It.referenceNumber??null,title:It.title,description:String(It.description||"").trim()||void 0,ownerLabel:It.ownerId?Hi.get(String(It.ownerId))||String(It.ownerId):null,...S($a?.taskCount||0,$a?.completedTaskCount||0),initiativeId:It.initiativeId||null,commentCount:Array.isArray(It.comments)?It.comments.length:0,attachmentCount:Array.isArray(It.attachments)?It.attachments.length:0,attachments:Array.isArray(It.attachments)?It.attachments:[],isArchived:!!It.isArchived,tasks:bs};if(_e.set(It.id,bs.map(Hl=>Hl.id)),It.initiativeId){ut.set(It.id,It.initiativeId);const Hl=xn.get(It.initiativeId)||[];Hl.push(_u),xn.set(It.initiativeId,Hl)}return _u},Gm=e.workstreams.map(gn).filter(It=>om(Kt,!!It.isArchived)),Vm=e.initiatives.map(It=>{const $a=(xn.get(It.id)||[]).filter(Gl=>om(Kt,!!Gl.isArchived)),bs=$a.reduce((Gl,Jm)=>Gl+Jm.taskCount,0),_u=$a.reduce((Gl,Jm)=>Gl+Jm.completedTaskCount,0);return{id:It.id,referenceNumber:It.referenceNumber??null,title:It.title,description:String(It.description||"").trim()||void 0,ownerLabel:It.ownerId?Hi.get(String(It.ownerId))||String(It.ownerId):null,...S(bs,_u),workstreamCount:$a.length,workstreams:$a,commentCount:Array.isArray(It.comments)?It.comments.length:0,attachmentCount:Array.isArray(It.attachments)?It.attachments.length:0,attachments:Array.isArray(It.attachments)?It.attachments:[],isArchived:!!It.isArchived}}),{initiatives:xu,standaloneWorkstreams:Km,initiativeById:Zm,workstreamById:Ym}=y2(Vm,Gm,Kt);return xu.forEach(It=>{qt.set(It.id,It.workstreams.flatMap($a=>($a.tasks||[]).map(bs=>bs.id)))}),{initiatives:xu,standaloneWorkstreams:Km,workstreamTaskIds:_e,workstreamInitiativeIds:ut,initiativeTaskIds:qt,workstreamById:Ym,initiativeById:Zm}},[sa,Hi,cr,e.initiatives,e.loadingTasks,e.planningBootstrapTaskSummaries,e.tasks,e.workstreams,Kt]),ol=r.useMemo(()=>xt.initiatives.map(u=>{const S=xs(u);return{value:u.id,label:S||u.title}}),[xt.initiatives]),Gi=r.useMemo(()=>{const S=(An?xt.initiativeById.get(An)?.workstreams||[]:xt.initiatives.flatMap(ye=>ye.workstreams)).map(ye=>{const _e=uo(ye);return{value:ye.id,label:_e||ye.title}}),D=An?[]:xt.standaloneWorkstreams.map(ye=>{const _e=uo(ye);return{value:ye.id,label:_e||ye.title}});return[...S,...D]},[xt.initiativeById,xt.initiatives,xt.standaloneWorkstreams,An]),Ss=r.useMemo(()=>jr?new Set(xt.workstreamTaskIds.get(jr)||[]):An?new Set(xt.initiativeTaskIds.get(An)||[]):null,[xt.initiativeTaskIds,xt.workstreamTaskIds,An,jr]),Vi=r.useMemo(()=>{if(!fa)return null;if(fa.type==="initiative"){const S=xt.initiativeById.get(fa.id);return S?{type:"initiative",item:S}:null}const u=xt.workstreamById.get(fa.id)||xt.standaloneWorkstreams.find(S=>S.id===fa.id);return u?{type:"workstream",item:u}:null},[fa,xt.initiativeById,xt.standaloneWorkstreams,xt.workstreamById]),Ki=r.useMemo(()=>{if(!ko)return null;const u=xt.workstreamById.get(ko)||xt.standaloneWorkstreams.find(S=>S.id===ko);return u?{type:"workstream",item:u}:null},[ko,xt.standaloneWorkstreams,xt.workstreamById]),Zi=r.useMemo(()=>Zs?{kind:"editor",editor:Zs}:Ki?{kind:"detail",detail:Ki}:null,[Ki,Zs]),Td=vy(go,!!(Vi||vr),yo,!!Zi,Vo),il=r.useMemo(()=>{if(!ts.trim())return null;const u=xt.initiativeById.get(ts);return u||ip(xt.initiatives,ts)},[ts,xt.initiativeById,xt.initiatives]);r.useEffect(()=>{An&&!xt.initiativeById.has(An)&&or(""),jr&&!xt.workstreamById.has(jr)&&Sn("")},[xt.initiativeById,xt.workstreamById,An,jr]);const wr=r.useMemo(()=>g==="schedule"?qi:to,[g,to,qi]),aa=r.useMemo(()=>{const u=new Date,S=u.getFullYear(),D=String(u.getMonth()+1).padStart(2,"0"),ye=String(u.getDate()).padStart(2,"0");return`${S}-${D}-${ye}`},[]),wo=r.useMemo(()=>g!=="schedule"||!Ba?wr:wr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const D=!!u.scheduledDate&&u.scheduledDate<aa,ye=!!u.dueDate&&u.dueDate<aa;return D||ye}),[g,Ba,wr,aa]),Nd=r.useMemo(()=>!Ss||Ss.size===0?wo:wo.filter(u=>Ss.has(u.id)),[wo,Ss]),Rd=r.useMemo(()=>!Ss||Ss.size===0?zi:zi.filter(u=>Ss.has(u.id)),[zi,Ss]),ti=r.useMemo(()=>g!=="schedule"?[]:wr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const D=!!u.scheduledDate&&u.scheduledDate<aa,ye=!!u.dueDate&&u.dueDate<aa;return D||ye}),[g,wr,aa]),cl=r.useMemo(()=>g!=="schedule"?0:wr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<aa).length,[g,wr,aa]),ll=r.useMemo(()=>g!=="schedule"?0:wr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.dueDate&&u.dueDate<aa).length,[g,wr,aa]),lr=String(jn||"").trim(),jd=r.useMemo(()=>!lr||lr==="anonymous"?0:ce.filter(u=>u.status==="done"||u.status==="cancelled"?!1:String(u.assignee||"").trim()===lr).length,[lr,ce]),Yi=r.useMemo(()=>!lr||lr==="anonymous"?0:ce.filter(u=>u.status==="done"||u.status==="cancelled"||String(u.assignee||"").trim()!==lr?!1:!!u.dueDate&&u.dueDate<aa).length,[lr,ce,aa]),dl=r.useMemo(()=>g!=="schedule"?[]:wr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<aa),[g,wr,aa]),no=ti,[ao,xo]=r.useState(!1),ul=()=>{nr(()=>{tr()||(y==="add"&&Nr.length>0&&Jr(),Mi(!1),y==="add"&&_(),v("tasks"))})};r.useEffect(()=>{y!=="add"&&Mi(!1)},[y]);const ni=r.useCallback((u,S)=>{if(u.status!==S){if(S==="in-progress"){Be(u);return}if(S==="review"){vt(u);return}if(S==="done"){St(u);return}if(S==="cancelled"){$t(u);return}J(u.id,{status:S,completedAt:null})}},[Be,vt,St,$t,J]),Pd=r.useCallback((u,S)=>{_();const D=f2(u,S,{categories:b,approaches:Qe});D.category&&ve(D.category),D.type&&Te(D.type),typeof D.priority=="number"&&Ie(D.priority),typeof D.complexity=="number"&&z(D.complexity),D.approach&&j(D.approach);const ye=D.taxonomyApproach;typeof ye=="string"&&ye.length>0&&we(_e=>({..._e,approach:ye})),D.assignee&&ee(D.assignee),D.status&&T(D.status),D.scheduledDate&&C(D.scheduledDate),v("add")},[_,b,Qe,ve,Te,Ie,z,T,j,ee,C,we,v]);pt.useEffect(()=>{ue&&!ue.includes("done")&&X(u=>[...u,"done"])},[]);const[ml,ai]=r.useState(!1),[as,dr]=r.useState(!1),[_o,ri]=r.useState(!1),[si,Ji]=r.useState(!1),[pl,oi]=r.useState(!1),[Co,fl]=r.useState(!1),[Xi,Qi]=r.useState(""),[gm,ii]=r.useState(!1),[Ed,ec]=r.useState(!1),[Md,ci]=r.useState("members"),[tc,nc]=r.useState(null),[Dd,ac]=r.useState("unknown"),[ym,hl]=r.useState(!1),[km,ro]=r.useState(null),[gl,Pr]=r.useState(null),[Sm,Ld]=r.useState(!1),[yl,vm]=r.useState([]),[bm,rc]=r.useState(null),[sc,kl]=r.useState(""),[Ao,wm]=r.useState("member"),[za,rs]=r.useState("read-write"),[Bd,li]=r.useState(!1),[Sl,Io]=r.useState(null),[Ds,di]=r.useState(0),[ui,oc]=r.useState(!1),[vl,To]=r.useState([]),[mi,bl]=r.useState(!1),[ic,Wd]=r.useState(1),[oa,cc]=r.useState(null),[pi,wl]=r.useState(!1),[Fd,xl]=r.useState(null),[Od,lc]=r.useState(!1),[xm,vs]=r.useState(null),[dc,uc]=r.useState(!1),[_m,_l]=r.useState(null),[so,Cl]=r.useState("month"),[Al,$d]=r.useState(""),[mc,Ta]=r.useState(""),[Na,Ls]=r.useState(null),[ss,Il]=r.useState(!1),[Cm,No]=r.useState(!1),[Ro,zr]=r.useState(null),[Ud,ha]=r.useState(null),qd=25,Tl=r.useRef(null),fi=r.useRef(null),pc=r.useRef({billing:!1,teamManagement:!1}),hi=r.useRef(null);r.useEffect(()=>{hi.current=oa},[oa]),r.useEffect(()=>{if(!as)return;const u=S=>{Tl.current?.contains(S.target)||dr(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[as]);const Am=Jt==="cloud"&&Dr&&Yt,jo=Yt&&(Jt==="cloud"||Rn),Nl=Jt==="local"&&Yt,{showSyncStatusModal:zd,showSyncEnableWarning:Im,workspaceSyncError:Hd,syncControlBusy:Gd,openSyncStatusModal:Tm,closeSyncStatusModal:Rl,handleWorkspaceSyncToggle:Vd,cancelSyncEnableWarning:Nm,confirmSyncEnableWarning:Rm}=HW({canManageWorkspaceSync:Nl,workspaceCloudSyncEnabled:ya,saveWorkspaceCloudSyncSettings:Br}),jm=r.useMemo(()=>{const u=Cn.find(ye=>ye.id===Qt),S=String(u?.name||"").trim();if(S)return S;if(Jt==="local"){const ye=String(zn||"").trim();if(ye)return ye}return String(Qt||"").trim()||"Workspace"},[Cn,Qt,zn,Jt]),fc=wy(jo,tc),oo=OW(jo,tc,Dd),hc=String(la||"").trim(),xr=String(Za||"").trim(),gi=String(ga||"").trim(),gc=hc||gi,Kd=gc.length>0,Pm=gi.length>0,Zd=(gc||gi||"").trim(),yc=Yt&&fn&&Zd.length>0?Zd.charAt(0).toUpperCase():"",Yd=xr,Jd=Yt&&fn&&Yd.length>0,kc=String(mc||xr).trim(),jl=String(oa?.planName||oa?.planId||"").trim(),Pl=jl.length>0,os=String(oa?.workspaceId||ln||Qt||"").trim(),Xd=Jt==="cloud"?"CLOUD":"LOCAL",Qd=e.config?.apiBaseUrl||"",Em=r.useMemo(()=>tF(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]),yi=Rn&&!fn;r.useEffect(()=>{si&&($d(hc),Ta(xr),Ls(null),zr(null),ha(null))},[xr,hc,si]);const Bs=r.useCallback(async u=>{const S=String(u||"").trim();if(!(!S||!Rn))try{await fetch(Mn("/api/taskforce/auth/profile/avatar/discard"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:S})})}catch{}},[Rn,Mn]),eu=r.useCallback(()=>{const u=Na;Ji(!1),oi(!1),zr(null),ha(null),Ls(null),Ta(xr),u&&Bs(u)},[xr,Bs,Na]),tu=r.useCallback(async u=>{if(!u||!Rn)return!1;if(!u.type.startsWith("image/"))return zr("Profile photo must be an image file."),ha(null),!1;Il(!0),zr(null),ha(null);try{const S=await q2(u,{maxBytes:QW});if(S.exceededLimit){const Bo=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(Bo)}const D=S.file,ye=await fetch(Mn("/api/taskforce/auth/profile/avatar/init"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:D.name,mimeType:D.type,size:D.size})}),_e=await ye.json().catch(()=>({}));if(!ye.ok||!_e?.success||typeof _e?.draftId!="string"||typeof _e?.relativePath!="string")throw new Error(_e?.error||"Failed to start avatar upload.");if(!(await fetch(Mn("/api/taskforce/auth/profile/avatar/upload"),{method:"POST",headers:{"Content-Type":D.type||"application/octet-stream","x-taskforce-avatar-draft-id":_e.draftId},credentials:"include",body:D})).ok)throw new Error("Failed to upload avatar.");const qt=await fetch(Mn("/api/taskforce/auth/profile/avatar/finalize"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:_e.draftId,relativePath:_e.relativePath})}),xn=await qt.json().catch(()=>({}));if(!qt.ok||!xn?.success||typeof xn?.draftId!="string")throw new Error(xn?.error||"Failed to finalize avatar upload.");const gn=Na;return Ls(xn.draftId),Ta(typeof xn?.avatarUrl=="string"?xn.avatarUrl:""),ha(null),gn&&gn!==xn.draftId&&Bs(gn),!0}catch(S){return zr(S instanceof Error?S.message:"Failed to upload profile photo."),!1}finally{Il(!1)}},[Rn,Bs,Na,Mn]),Mm=r.useCallback(()=>{if(!Na)return;const u=Na;Ls(null),Ta(xr),ha(null),zr(null),Bs(u)},[xr,Bs,Na]),nu=r.useCallback(()=>{const u=Na;Ls(null),Ta(""),ha(xr?"Profile photo will be removed when you save.":null),zr(null),u&&Bs(u)},[xr,Bs,Na]),au=r.useCallback(async()=>{const u=Al.trim();if(!u){zr("Display name is required."),ha(null);return}No(!0),zr(null),ha(null);const S=await Ja({displayName:u,avatarDraftId:Na,clearAvatar:!Na&&!mc&&!!xr});if(!S.success){zr(S.error||"Failed to update profile."),No(!1);return}ha("Profile updated."),Ls(null),Ta(""),No(!1),oi(!1),Ji(!1)},[xr,Na,mc,Al,Ja]),Er=r.useCallback(()=>{const u={},S=String(os||"").trim();S&&(u["x-taskforce-workspace-id"]=S);const D=tc||qn;return(D==="owner"||D==="admin"||D==="member"||D==="read-only")&&(u["x-taskforce-workspace-role"]=D),u},[qn,os,tc]),El=r.useCallback(u=>{const S=Yt,D=jo;fi.current=Yl(),pc.current={billing:S,teamManagement:D},Ht("account_surface_opened",{surface:u,expectsBilling:S,expectsTeamManagement:D}),!S&&!D&&(Ht("account_surface_ready",{surface:u,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),fi.current=null)},[jo,Yt]),Po=r.useCallback(u=>{const S=pc.current;if(S[u]=!1,S.billing||S.teamManagement)return;const D=fi.current;D!==null&&(Ht("account_surface_ready",{surface:_o?"account_hub":as?"account_menu":"closed",durationMs:Math.round(Yl()-D),teamManagementVisible:oo,billingPlanId:String(oa?.planId||"").trim()||null}),fi.current=null)},[oa?.planId,oo,_o,as]),is=r.useCallback(async u=>{const S=Mn(Ch);if(!Yt)return cc(null),xl(null),nc(null),ac("unknown"),hl(!1),ro(null),Ah(S,{identityKey:jn}),Po("billing"),Po("teamManagement"),null;const D=Yl();wl(!0),xl(null),hl(jo),ro(null);try{const ye=await R2(S,{identityKey:jn,force:u?.force===!0}),_e=ye?.workspaceRole==="owner"||ye?.workspaceRole==="admin"||ye?.workspaceRole==="member"||ye?.workspaceRole==="read-only"?ye.workspaceRole:null,ut=ye?.teamPlanMode==="team"||ye?.teamPlanMode==="personal"?ye.teamPlanMode:"unknown";return cc(ye),nc(_e),ac(ut),ro(null),Ht("account_profile_summary_resolved",{durationMs:Math.round(Yl()-D),planId:String(ye?.planId||"").trim()||null,gate:String(ye?.gate||"").trim()||null,teamManagementAllowed:ye?.teamManagementAllowed===!0}),ye}catch(ye){const _e=ye instanceof Error?ye.message:"Failed to load account summary.",ut=!!hi.current;return xl(_e),ut?ro(null):(nc(null),ac("unknown"),ro(_e)),Ht("account_profile_summary_failed",{durationMs:Math.round(Yl()-D),error:_e,preservedSummary:ut}),hi.current}finally{wl(!1),hl(!1),Po("billing"),Po("teamManagement")}},[jn,jo,Yt,Po,Mn]),Dm=r.useCallback(u=>{cc(u);const S=u?.workspaceRole==="owner"||u?.workspaceRole==="admin"||u?.workspaceRole==="member"||u?.workspaceRole==="read-only"?u.workspaceRole:null,D=u?.teamPlanMode==="team"||u?.teamPlanMode==="personal"?u.teamPlanMode:"unknown";nc(S),ac(D)},[]),Sc=r.useMemo(()=>Fp(oa).allowReturnToApp,[oa]),ru=r.useCallback(async()=>{const u=new URLSearchParams;u.set("screen","plans"),u.set("interval",so);const S=String(oa?.planId||"").trim(),D=String(oa?.planVersionId||"").trim();S&&u.set("planId",S),D&&u.set("planVersionId",D),s(`/?${u.toString()}`)},[oa?.planId,oa?.planVersionId,so,s]),Ml=r.useCallback(async()=>{vs(null),_l(null),lc(!0);try{const u=await fetch(Mn("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),S=await u.json().catch(()=>({}));if(!u.ok){vs(String(S?.error||"Failed to create portal session."));return}const D=String(S?.url||"").trim();if(!D){vs("Portal session did not return a redirect URL.");return}window.location.assign(D)}catch{vs("Failed to open billing portal.")}finally{lc(!1)}},[Mn]),su=r.useCallback(async()=>{vs(null),_l(null),lc(!0);try{const u=String(oa?.planVersionId||"").trim();if(!u){vs("No active plan version is linked to this account.");return}const S=await fetch(Mn("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:u,interval:so})}),D=await S.json().catch(()=>({}));if(!S.ok){vs(String(D?.error||"Failed to update subscription interval."));return}_l("Subscription updated."),Ah(Mn(Ch),{identityKey:jn}),await is()}catch{vs("Failed to update subscription interval.")}finally{lc(!1)}},[oa?.planVersionId,jn,so,is,Mn]);r.useEffect(()=>{!Yt||!fn||is()},[fn,Yt,is]),r.useEffect(()=>{!_o&&!as||is()},[is,_o,as]);const Eo=r.useCallback(async()=>{if(fc){Ld(!0),Pr(null);try{const u=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:Er()}),S=await u.json().catch(()=>({}));if(!u.ok){Pr(S?.error||"Failed to load workspace users.");return}const D=Array.isArray(S?.users)?S.users:[],ye={owner:0,admin:1,member:2,"read-only":3},_e=D.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}));_e.sort((ut,qt)=>{const xn=(ye[ut.role]??99)-(ye[qt.role]??99);return xn!==0?xn:(ut.displayName||ut.email).localeCompare(qt.displayName||qt.email,void 0,{sensitivity:"base"})}),vm(_e)}catch{Pr("Failed to load workspace users.")}finally{Ld(!1)}}},[fc,Er]),Ws=r.useCallback(async u=>{if(!fc)return;const S=Math.max(0,Math.floor(u));oc(!0),Pr(null);try{const D=S*qd,ye=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${qd}&offset=${D}`,{method:"GET",credentials:"include",headers:Er()}),_e=await ye.json().catch(()=>({}));if(!ye.ok){Pr(_e?.error||"Failed to load workspace audit log.");return}const ut=Array.isArray(_e?.events)?_e.events:[];To(ut.map(xn=>({id:String(xn?.id||""),action:String(xn?.action||""),actorUserId:String(xn?.actorUserId||""),actorRole:String(xn?.actorRole||""),createdAt:String(xn?.createdAt||xn?.ts||"")}))),di(S);const qt=Math.max(1,Number(_e?.pages||1));Wd(qt),bl(S+1<qt)}catch{Pr("Failed to load workspace audit log.")}finally{oc(!1)}},[fc,Er]),vc=r.useCallback(async()=>{await Promise.all([Eo(),Ws(Ds)])},[Eo,Ws,Ds]),ou=r.useCallback((u="login")=>{const S=`${o.pathname}${o.search}${o.hash}`,D=!S||S==="/login"||!S.startsWith("/")?"/":S;dr(!1),ri(!1),Rl(),s(`/login?mode=${u}&next=${encodeURIComponent(D)}`)},[Rl,o.hash,o.pathname,o.search,s]),Mo=r.useCallback(u=>{dr(!1),ii(!1);const S=new URLSearchParams({step:"workspace"});u?.intent==="create-workspace"&&S.set("intent","create-workspace"),s(`/setup?${S.toString()}`,{replace:!0})},[s]),Do=r.useCallback(async()=>{if(dc)return;if(uc(!0),!Yt){try{m()}finally{uc(!1)}return}const u=hi.current;if(u&&!Fp(u).allowReturnToApp){uc(!1);return}m(),(async()=>{try{const S=await e.continueAfterCommercialOnboarding();if(!S.success){_t(S.error||"Unable to finish onboarding.","error"),S.destination==="login"&&s("/login",{replace:!0});return}S.destination==="setup"&&Mo()}finally{uc(!1)}})()},[hi,m,Yt,s,Mo,dc,e,_t]),iu=r.useCallback(async u=>{if(!(!u||Co)){Qi(""),fl(!0);try{const S=await Ya(u);if(!S.success){if(S.code==="WORKSPACE_NOT_FOUND"||S.code==="WORKSPACE_ID_REQUIRED"){Mo();return}Qi(S.error||"Failed to switch workspace.");return}await Ne(!0),dr(!1)}finally{fl(!1)}}},[Ya,Co,Ne,Mo]),cu=r.useCallback(async()=>{dr(!1),ec(!0),ci("members"),((await is())?.teamManagementAllowed??oo)&&(await Eo(),await Ws(0))},[oo,is,Ws,Eo]),ki=r.useCallback(async(u,S)=>{Pr(null),rc(u);try{const D=await S(),ye=await D.json().catch(()=>({}));if(!D.ok){Pr(ye?.error||"Team management action failed.");return}await vc()}catch{Pr("Team management action failed.")}finally{rc(null)}},[vc]),Dl=r.useCallback(async()=>{const u=sc.trim();if(u){li(!0),Pr(null),Io(null);try{const S=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...Er()},credentials:"include",body:JSON.stringify({workspaceId:os,email:u,role:Ao,permissionMode:Ao==="member"?za:"read-write"})}),D=await S.json().catch(()=>({}));if(!S.ok){Pr(D?.error||"Failed to send invite.");return}kl(""),D?.inviteEmailSent===!1?Io(`Invite created, but email delivery failed${D?.inviteEmailError?`: ${String(D.inviteEmailError)}`:"."}`):Io("Invite sent."),await vc()}catch{Pr("Failed to send invite.")}finally{li(!1)}}},[Qt,vc,Er,sc,za,Ao]),bc=r.useMemo(()=>ae.trim().length>0,[ae]),lu=r.useMemo(()=>yl.filter(u=>u.status==="invited"),[yl]),Ll=r.useMemo(()=>{const u=Ge.length!==b.length,S=it.length!==d.length,D=Gt.length!==Me.length,ye=ue.length!==mo.length,_e=Ft.length!==an.length,ut=An.length>0,qt=jr.length>0;return u||S||D||ye||_e||ut||qt},[b.length,d.length,an.length,Ft.length,Ge.length,Gt.length,ue.length,it.length,Me.length,An,jr]),du=r.useMemo(()=>br.length!==Hu.length||Ur.length!==Gu.length,[Ur.length,br.length]),uu=na,Fs=r.useMemo(()=>bW(uu),[uu]),wc=r.useMemo(()=>{switch(Fs.filterBar.kind){case"task-filters":return Ll;case"document-filters":return du;default:return!1}},[du,Ll,Fs.filterBar.kind]),xc=bc||Ll,_c=Kt==="archived"?sa.length:Kt==="deleted"?cr.length:ce.length,Bl=Kt==="archived"?Ms.length:Kt==="deleted"?Ui.length:e.filteredTasks.length,Wl=xc?`${Bl}/${_c}`:`${_c}`,Fl=xc?`${Kt.charAt(0).toUpperCase()+Kt.slice(1)} tasks matching current filters`:`${Kt.charAt(0).toUpperCase()+Kt.slice(1)} tasks`,Ol=Jt==="local"&&Yt,Lo=r.useCallback(u=>{if(!u)return"Never";const S=new Date(u);return Number.isNaN(S.getTime())?"Never":S.toLocaleString()},[]),$l=r.useMemo(()=>Lo(da),[Lo,da]),mu=r.useMemo(()=>Lo(va),[Lo,va]),pu=r.useMemo(()=>Lo($n),[Lo,$n]),fu=Hd||Un||wn||"None",cs=Ea(),Hr=r.useMemo(()=>g2({runtimeMode:Jt,isAuthenticated:Yt,workspaceSyncStatus:Ar,workspaceCloudSyncEnabled:ya,workspaceSyncSummary:ka,workspaceSyncRecommendedAction:ja,workspaceSyncError:fu,pushBlockedReason:cs.pushBlockedReason||null,pullBlockedReason:cs.pullBlockedReason||null,retryBlockedReason:cs.retryBlockedReason||null}),[Jt,Yt,Ar,ya,ka,ja,fu,cs.pushBlockedReason,cs.pullBlockedReason,cs.retryBlockedReason]),hu=Hr.lastError,[Ul,gu]=r.useState(Hr.status),ql=r.useMemo(()=>_2(cs),[cs]),{syncRecentEvents:io,syncRecentEventsLoading:yu,syncRecentEventsError:ku,syncEventsListRef:Lm,loadRecentSyncEvents:Bm}=$W({isOpen:zd,workspaceId:Qt,refreshKeys:[$n,va,Pa,Ar]}),Su=Hr.actionable&&Ar==="syncing"&&Bn==="active"&&Tn===0;r.useEffect(()=>{if(!Su){gu(Hr.status);return}const u=window.setTimeout(()=>{gu(Hr.status)},1200);return()=>window.clearTimeout(u)},[Hr.status,Su]);const Wm=r.useMemo(()=>C2({syncRecentEvents:io,syncRecentEventsError:ku,syncRecentEventsLoading:yu}),[io,ku,yu]),vu=r.useMemo(()=>A2(io),[io]),Fm=r.useMemo(()=>I2(io),[io]),Os=r.useMemo(()=>x2(Ul),[Ul]),{workspaceSyncRepairBusy:bu,workspaceSyncRepairQueued:f,workspaceSyncCopied:O,handleCopySyncDetails:G,handleQueueOrRunRepairSync:Z}=zW({currentWorkspaceId:Qt,syncStatusLabel:Os.label,workspaceSyncSummary:Hr.summary,workspaceSyncRecommendedAction:Hr.recommendedAction,formattedLastSyncTime:$l,formattedLastPullTime:mu,formattedLastPushTime:pu,workspaceSyncDiagnostics:cs,workspaceSyncPendingChanges:Tn,syncLastError:hu,workspaceSyncPhase:Bn,referenceMismatchCount:vu,syncRecentEvents:io,loadRecentSyncEvents:Bm,pushNotice:_t,resetWorkspaceSyncCursorAndPull:un,workspaceSyncBusy:Qn}),Ke=r.useMemo(()=>gy(Bn,bu,Qn),[Qn,Bn,bu]),Fe=r.useMemo(()=>td(Xr)||new Date,[Xr]),Ue=r.useMemo(()=>qp(Fe,on),[Fe,on]),tn=r.useMemo(()=>{const u={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return Lh.forEach(S=>{const D=BW(S,on);u[S]=Ec(by(Ue,D))}),u},[Ue,on]),bn=r.useCallback(u=>{const S=td(u);if(!S)return tn.mon;const D=S.getDay();return tn[D===1?"mon":D===2?"tue":D===3?"wed":D===4?"thu":D===5?"fri":D===6?Y?"sat":"fri":Y?"sun":"fri"]||tn.mon},[tn,Y]),Wn=r.useCallback(async()=>{if(!(ao||no.length===0)){xo(!0);try{for(const u of no){const S=u.scheduledDate||u.dueDate||aa,D=bn(S);await J(u.id,{scheduledDate:D,scheduledWeekKey:WW(D),orderInDay:null})}await Ne(!0)}finally{xo(!1)}}},[ao,no,aa,bn,J,Ne]),ia=r.useCallback(async()=>{if(!(ao||ti.length===0)){xo(!0);try{for(const u of ti)await J(u.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await Ne(!0)}finally{xo(!1)}}},[ao,ti,J,Ne]),Ha=r.useMemo(()=>Lc(Ue,{month:"short",day:"numeric",year:"numeric"},R),[Ue,R]),ur=r.useMemo(()=>{const D=(Y?on==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:Lh:["mon","tue","wed","thu","fri"]).map(_e=>{const ut=td(tn[_e])||Ue,qt=tn[_e],xn=_e==="sat"||_e==="sun";return{value:_e,label:`${LW[_e]} ${Lc(ut,{month:"short",day:"numeric"},R)}`,color:xn?"#1e3a8a":"#3b82f6",icon:"Calendar",date:qt,isPast:qt<aa,isSelected:qt===Xr,isWeekend:xn}}),ye=dl.length>0;return[...ar?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...ye?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...D]},[Y,ar,tn,Ue,dl.length,aa,Xr,on,R]),Cc=r.useMemo(()=>{switch(g){case"category":return b;case"type":return(d||[]).map(u=>({...u,icon:u.icon||tm[u.value]?.icon,color:u.color||tm[u.value]?.color}));case"priority":return Me;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 Qe;case"assignee":return an.map(u=>({value:u.value,label:u.label,icon:u.icon==="HelpCircle"?"Circle":u.icon,color:u.color}));case"status":return[...mo.filter(u=>u.value!=="done"&&u.value!=="cancelled"),{value:"completed",label:"Completed",icon:sd("done").icon,color:sd("done").color}];case"schedule":return ur;default:return b}},[g,b,d,Me,Qe,an,ur]),_y=t.jsxs("div",{className:mt.accountMenuWrap,ref:Tl,children:[t.jsx("button",{className:`tf-control-icon ${mt.avatarBtn}`,onClick:()=>{dr(u=>{const S=!u;return S?El("account_menu"):(fi.current=null,pc.current={billing:!1,teamManagement:!1}),S})},title:Yt?"Account":"Account (Not signed in)","aria-label":Yt?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":as,children:t.jsx("span",{className:mt.avatarBadge,"aria-hidden":"true",children:Jd?t.jsx("img",{src:Yd,alt:"",className:mt.avatarImage}):yc||t.jsx(_i,{size:14,className:mt.avatarIcon})})}),as&&t.jsxs("div",{className:mt.accountMenu,role:"menu","aria-label":"Account menu",children:[t.jsxs("div",{className:mt.accountMenuSection,children:[t.jsx("div",{className:mt.accountMenuSectionLabel,children:"Account"}),t.jsx("div",{className:mt.accountMenuHint,children:yi?"Checking sign-in status...":Yt?t.jsx(t.Fragment,{children:Kd?t.jsx(t.Fragment,{children:t.jsxs("span",{className:mt.accountIdentityBlock,children:[t.jsx("span",{className:mt.accountIdentityEmail,children:gc}),Pm&&hc&&t.jsxs("span",{className:mt.accountIdentityMetaLine,children:[t.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Email"}),t.jsx("span",{className:mt.accountIdentityMetaValue,children:gi})]}),pi?t.jsxs("span",{className:mt.accountIdentityMetaLine,children:[t.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:mt.accountIdentityMetaValue,children:"Loading…"})]}):Pl?t.jsxs("button",{"aria-label":`Subscription ${jl}`,className:`${mt.accountIdentityMetaLine} ${mt.accountIdentityMetaAction}`,onClick:()=>{dr(!1),l()},type:"button",children:[t.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:mt.accountIdentityMetaValue,children:jl})]}):Fd?t.jsxs("span",{className:mt.accountIdentityMetaLine,children:[t.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Subscription"}),t.jsx("span",{className:mt.accountIdentityMetaValue,children:"Unavailable"})]}):null,t.jsxs("span",{className:mt.accountIdentityMetaLine,children:[t.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Runtime"}),t.jsx("span",{className:mt.accountIdentityMetaValue,children:Xd})]}),t.jsxs("span",{className:mt.accountIdentityMetaLine,children:[t.jsx("span",{className:mt.accountIdentityMetaLabel,children:"Environment"}),t.jsx("span",{className:mt.accountIdentityMetaValue,children:Em})]})]})}):"Signed in"}):"Not signed in"})]}),Am&&t.jsxs("div",{className:mt.accountMenuSection,children:[t.jsx("div",{className:mt.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),Cn.length===0&&t.jsx("div",{className:mt.accountMenuHint,children:"No workspaces found for this account yet."}),Cn.map(u=>t.jsxs("button",{className:`${mt.accountMenuItem} ${u.id===Qt?mt.accountMenuItemActive:""}`,onClick:()=>iu(u.id),role:"menuitem",disabled:Co||u.id===Qt,title:u.description||u.name,children:[t.jsx(Ni,{size:15}),t.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[t.jsx("span",{children:u.name}),t.jsx("span",{className:mt.accountMenuMeta,children:u.role})]})]},u.id)),t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{Qi(""),ii(!0),dr(!1)},role:"menuitem",disabled:Co,children:[t.jsx(Cs,{size:15}),"Create Workspace"]}),Xi&&t.jsx("div",{className:mt.accountMenuError,children:Xi})]}),ym?t.jsx("div",{className:mt.accountMenuHint,children:"Resolving team management access..."}):oo?t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{cu()},role:"menuitem",children:[t.jsx(mk,{size:15}),"Team Management"]}):km?t.jsx("div",{className:mt.accountMenuHint,children:"Team Management unavailable right now."}):null,Yt&&t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{dr(!1),Ji(!0)},role:"menuitem",children:[t.jsx(_i,{size:15}),"Edit Profile"]}),t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{dr(!1),l()},role:"menuitem",children:[t.jsx(bp,{size:15}),"Plans"]}),t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{dr(!1),El("account_hub"),ri(!0)},role:"menuitem",children:[t.jsx(_i,{size:15}),"Account Hub"]}),t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{dr(!1),ai(!0)},role:"menuitem",children:[t.jsx(Ti,{size:15}),"Help & Tutorial"]}),Jt==="local"&&!Yt&&!yi&&t.jsxs("button",{className:mt.accountMenuItem,onClick:()=>{ou("login")},role:"menuitem",children:[t.jsx(_i,{size:15}),"Sign In / Register"]}),Yt&&t.jsxs("button",{className:mt.accountMenuItem,onClick:async()=>{dr(!1),await cn(),Jt==="cloud"&&s("/login",{replace:!0})},role:"menuitem",children:[t.jsx(pk,{size:15}),"Sign Out"]})]})]}),ff=r.useCallback(()=>{A(u=>u==="show"?"collapse":u==="collapse"?"hide":"show")},[A]),hf=r.useCallback(()=>{_(),I("tasks"),v("add")},[_,v,I]),Cy=r.useCallback(u=>{const S=e.workstreams.find(D=>D.id===u);_(),L(uo(S)||u),I("tasks"),v("add")},[e.workstreams,_,v,I,L]),gf=r.useCallback(u=>{Ps.current=!1,ir(!1),ys(u),hs(!1),es(null),Sr(!1),ks(""),Js(""),Rs("");const S=u.entityType==="workstream"&&An&&xt.initiativeById.get(An)||null;ns(S?xs(S):""),Wa(null)},[xt.initiativeById,An]),yf=r.useCallback((u,S)=>{Ps.current=!1,ir(!1),es(u),Sr(!1),ks(""),Js(""),Rs("");const D=u.entityType==="workstream"&&((S?xt.initiativeById.get(S):null)||An&&xt.initiativeById.get(An))||null;ns(D?xs(D):""),Wa(null)},[xt.initiativeById,An]),Om=r.useCallback(()=>{Ps.current=!1,ir(!1),ys(null),ks(""),Js(""),Rs(""),ns("")},[]),kf=r.useCallback(()=>{Ps.current=!1,ir(!1),es(null),ks(""),Js(""),Rs(""),ns("")},[]),Ay=r.useCallback(async()=>{const u=Zs||vr;if(!u||Ps.current)return;Ps.current=!0,ir(!0);const S=!!Zs,D=Di.trim()||null;try{if(u.entityType==="initiative")if(u.mode==="edit")await e.updateInitiative(u.targetId,{title:Ys.trim()||"Untitled Initiative",description:$r.trim()||null,ownerId:D}),Qr({type:"initiative",id:u.targetId}),Wa(null),_t("Initiative updated","success");else{const ye=await e.createInitiative({title:Ys.trim()||"Untitled Initiative",description:$r.trim()||null,ownerId:D});Qr({type:"initiative",id:ye.id}),Wa(null),_t("Initiative created","success")}else{const ye=ts.trim(),_e=ye.length===0?null:ip(xt.initiatives,ye);if(ye.length>0&&!_e){_t("Initiative not found by that reference.","error");return}const ut={title:Ys.trim()||"Untitled Workstream",description:$r.trim()||null,ownerId:D,initiativeId:_e?.id||null};if(u.mode==="edit")await e.updateWorkstream(u.targetId,ut),S?Wa(u.targetId):(Qr({type:"workstream",id:u.targetId}),Wa(null)),_t("Workstream updated","success");else{const qt=await e.createWorkstream(ut);S?Wa(qt.id):(Qr({type:"workstream",id:qt.id}),Wa(null)),_t("Workstream created","success")}}S?kf():Om()}catch(ye){_t(ye instanceof Error?ye.message:"Failed to save planning item.","error")}finally{Ps.current=!1,ir(!1)}},[Om,kf,$r,ts,Di,Ys,vr,Zs,xt.initiatives,e,_t]),Iy=r.useCallback(u=>{gs(S=>{const D=new Set(S);return D.has(u)?D.delete(u):D.add(u),D})},[]),Ty=r.useCallback(u=>{or(S=>S===u?"":u),Sn("")},[]),Ny=r.useCallback((u,S)=>{Sn(D=>{const ye=D===u?"":u;return or(ye&&S||""),ye})},[]),Ry=r.useCallback(u=>{ys(null),es(null),hs(!1),Sr(!1),Qr(u?{type:"initiative",id:u}:null),Wa(null)},[]),jy=r.useCallback(u=>{ys(null),es(null),hs(!1),Sr(!1),Qr(u?{type:"workstream",id:u}:null),Wa(null)},[]),Py=r.useCallback(u=>{es(null),Sr(!1),Wa(u)},[]),$m=r.useMemo(()=>{const u=new Map;return an.forEach(S=>{u.set(S.label,String(S.value))}),u},[an]),Um=r.useCallback((u,S)=>{if(u==="workstream"&&S){yf({mode:"create",entityType:"workstream"},S);return}if(gf({mode:"create",entityType:u}),u==="workstream"){const D=(S?xt.initiativeById.get(S):null)||(An?xt.initiativeById.get(An):null)||null;ns(D?xs(D):"")}},[gf,yf,xt.initiativeById,An]),Sf=r.useCallback((u,S)=>{if(u==="initiative"){const D=xt.initiativeById.get(S);if(!D)return;ys({mode:"edit",entityType:"initiative",targetId:S}),ks(D.title),Js(D.description||""),Rs(D.ownerLabel&&$m.get(D.ownerLabel)||""),ns("")}else{const D=xt.workstreamById.get(S)||xt.standaloneWorkstreams.find(_e=>_e.id===S);if(!D)return;ys({mode:"edit",entityType:"workstream",targetId:S}),ks(D.title),Js(D.description||""),Rs(D.ownerLabel&&$m.get(D.ownerLabel)||"");const ye=D.initiativeId&&xt.initiativeById.get(D.initiativeId)||null;ns(ye?xs(ye):"")}Wa(null)},[$m,xt.initiativeById,xt.standaloneWorkstreams,xt.workstreamById]),wu=r.useCallback(async(u,S)=>{const D=e.workstreams.find(qt=>qt.id===u);if(!D){_t("Workstream not found.","error");return}const ye=typeof S=="string"?S.trim():S===null?"":ts.trim(),_e=ye.length===0?null:ip(xt.initiatives,ye);if(ye.length>0&&!_e){_t("Initiative not found by that reference.","error");return}const ut=_e?.id||null;if((D.initiativeId||null)===ut){_t(ut?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info");return}try{await e.updateWorkstream(u,{initiativeId:ut}),ns(_e?xs(_e):""),_t(ut?"Initiative set":"Initiative removed","success")}catch{_t("Failed to set initiative.","error")}},[ts,xt.initiatives,e,_t]),qm=r.useCallback(async(u,S)=>{const D=sl.get(u);if(!D){_t("Task not found.","error");return}const ye=S||null;if(xt.initiativeById.has(u)||xt.workstreamById.has(u)){_t("Only execution tasks can be moved into workstreams.","error");return}if(ye&&!xt.workstreamById.has(ye)){_t("Workstream not found.","error");return}if((D.workstreamId||null)===ye){_t(ye?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const _e=await fetch(`/api/taskforce/task/${u}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:ye})});if(!_e.ok){const ut=await _e.json().catch(()=>({}));_t(ut?.error||"Failed to set workstream.","error");return}await _e.json().catch(()=>null),await Ne(!0),_t(ye?"Workstream set":"Workstream removed","success")}catch{_t("Failed to set workstream.","error")}},[Ne,sl,xt.initiativeById,xt.workstreamById,_t]),Ey=r.useCallback(async(u,S)=>{const D=S.trim();if(!D){_t("Enter a task reference.","error");return}const ye=ig(D),_e=ei.find(ut=>ut.id===D||qs(ut)===D||ye!==null&&ut.referenceNumber===ye);if(!_e){_t("Task not found by that reference.","error");return}await qm(_e.id,u)},[qm,ei,_t]),My=r.useCallback(async(u,S)=>{const D=S.trim();if(!D){_t("Enter a workstream reference.","error");return}const ye=xt.initiativeById.get(u);if(!ye){_t("Initiative not found.","error");return}const _e=Mg(D),ut=e.workstreams.find(qt=>qt.id===D||uo(qt)===D||_e!==null&&qt.referenceNumber===_e);if(!ut){_t("Workstream not found by that reference.","error");return}await wu(ut.id,xs(ye))},[wu,xt.initiativeById,e.workstreams,_t]),Ac=r.useCallback((u,S)=>{const D=`${u}:${S}`,ye=vn.current.get(D);if(ye)return ye;const _e=u==="initiative"?e.initiatives.find(ut=>ut.id===S):e.workstreams.find(ut=>ut.id===S);return Array.isArray(_e?.attachments)?_e.attachments:[]},[e.initiatives,e.workstreams]),Ic=r.useCallback((u,S,D)=>{const ye=`${u}:${S}`;vn.current.set(ye,D);const ut=(Ia.current.get(ye)||Promise.resolve()).catch(()=>{}).then(()=>u==="initiative"?e.updateInitiative(S,{attachments:D}):e.updateWorkstream(S,{attachments:D}));Ia.current.set(ye,ut),ut.catch(qt=>{_t(qt instanceof Error?qt.message:"Failed to update planning context.","error")}).finally(()=>{Ia.current.get(ye)===ut&&Ia.current.delete(ye)})},[e,_t]),Dy=r.useCallback((u,S,D)=>{const ye=Ac(u,S);Ic(u,S,[...ye,D])},[Ac,Ic]),Ly=r.useCallback((u,S,D)=>{const ye=Ac(u,S);Ic(u,S,ye.filter((_e,ut)=>ut!==D))},[Ac,Ic]),By=r.useCallback((u,S,D,ye)=>{const ut=Ac(u,S).map((qt,xn)=>xn!==D?qt:typeof qt=="string"?{path:qt,caption:ye,timestamp:new Date().toISOString()}:{...qt,caption:ye});Ic(u,S,ut)},[Ac,Ic]),vf=r.useCallback(u=>{or(u),Sn("")},[]),bf=r.useCallback(u=>{Sn(u),or(u&&xt.workstreamInitiativeIds.get(u)||"")},[xt.workstreamInitiativeIds]),zm=r.useCallback(u=>{const S=Dh(u,eo);if(S!==u){const D=eo.find(ye=>ye.id===u)?.label||"That module";_t(`${D} is not available in this build yet.`,"error");return}I(S)},[_t,I,eo]),wf=r.useCallback(()=>{if(na==="tasks"&&Rr){Ks(!1),Qr(null),Wa(null),ys(null);return}if(na!=="tasks"){I("tasks"),Ks(!0);return}Ks(u=>!u)},[Rr,na,I]),Wy=r.useCallback(u=>{I("tasks"),Tt(u)},[Tt,I]),Fy=r.useCallback((u,S)=>{Qs(u),Ko(S?.sessionId??null),vd(D=>D+1),I("annotate")},[I]),Oy=r.useCallback(({target:u,sessionId:S})=>{Qs(D=>!D&&!u||D&&u&&D.taskId===u.taskId&&D.taskReferenceLabel===u.taskReferenceLabel&&D.assetId===u.assetId&&D.imageReferenceLabel===u.imageReferenceLabel&&D.path===u.path&&D.displayName===u.displayName?D:u),Ko(D=>D===S?D:S)},[]),xf=r.useMemo(()=>[{value:"created",label:He("standalone.sortCreated")},{value:"updated",label:He("standalone.sortUpdated")},{value:"priority",label:He("standalone.sortPriority")},{value:"complexity",label:He("standalone.sortComplexity")},...Wg(Dt,[...e.searchAgnosticTasks,...sa])],[sa,e.searchAgnosticTasks,Dt]),_f=r.useMemo(()=>[{value:"category",label:He("standalone.groupCategory")},{value:"type",label:He("standalone.groupType")},{value:"priority",label:He("standalone.groupPriority")},{value:"complexity",label:He("standalone.groupComplexity")},{value:"assignee",label:He("standalone.groupAssignee")},{value:"status",label:He("standalone.groupStatus")},{value:"schedule",label:He("standalone.groupSchedule")}],[]),Cf=r.useMemo(()=>eo.filter(u=>u.enabled),[eo]),Af=r.useMemo(()=>[{key:"empty-columns",icon:x==="show"?t.jsx(Tf,{size:16}):x==="collapse"?t.jsx(Nf,{size:16}):t.jsx(fk,{size:16}),title:He(x==="show"?"standalone.showEmptyColumns":x==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:ff,active:x!=="show"},{key:"compressed-cards",icon:ct?t.jsx(Hh,{size:16}):t.jsx(hk,{size:16}),title:He(ct?"standalone.expandCards":"standalone.compressCards"),onClick:()=>nt(!ct),active:ct}],[ct,ff,x]),$y=r.useMemo(()=>[{key:"filter-toggle",icon:t.jsx(Gh,{size:16}),title:He("standalone.toggleFilters"),onClick:()=>Ho(!Vs),active:Vs,className:wc?p.filterGlow:""}],[wc,Ho,Vs]),Uy=r.useMemo(()=>{switch(Fs.filterBar.kind){case"task-filters":return t.jsx(Z2,{categoryFilterOptions:al,typeFilterOptions:rl,priorities:Me,taxonomyDisplayLabels:We,filterCategories:Ge,setFilterCategories:De,filterTypes:it,setFilterTypes:Ut,filterPriorities:Gt,setFilterPriorities:nn,filterStatus:ue,setFilterStatus:X,filterAssignees:Ft,setFilterAssignees:Wt,assigneeOptions:an,initiativeFilterOptions:ol,selectedInitiativeId:An,setSelectedInitiativeId:vf,workstreamFilterOptions:Gi,selectedWorkstreamId:jr,setSelectedWorkstreamId:bf,taskScope:Kt,setTaskScope:Kn,showArchive:Es,setShowArchive:Fi,fetchArchive:Oi,onDeleteAllDeleted:()=>{const u=cr.length;u===0||!window.confirm(`Permanently delete ${u} deleted task${u===1?"":"s"}? This cannot be undone.`)||ke()},clearFilters:()=>{_n(),or(""),Sn("")}});case"document-filters":return t.jsx(Y2,{typeFilters:br,setTypeFilters:Xs,attachmentFilters:Ur,setAttachmentFilters:So,clearFilters:()=>{Xs(Hu.map(u=>u.value)),So(Gu.map(u=>u.value))}});default:return t.jsx(V2,{})}},[an,al,_n,cr.length,Ur,br,Ft,Ge,Gt,ue,it,vf,bf,ol,Me,An,jr,So,Xs,Wt,De,nn,X,Ut,or,Sn,Fi,Kn,Es,Kt,We,rl,Gi,Fs.filterBar.kind,Oi,ke]),qy=r.useMemo(()=>[{key:"zen-toggle",icon:t.jsx(gk,{size:16,fill:M?"currentColor":"none"}),title:He(M?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>B(),active:M}],[M,B]),zy=r.useMemo(()=>({search:t.jsx(H2,{value:ae,placeholder:He("standalone.searchPlaceholder"),active:bc,onChange:Pe,onClear:()=>Pe(""),clearTitle:He("standalone.clearSearchTitle")}),sort:t.jsx(Rh,{label:t.jsxs(t.Fragment,{children:[t.jsx(yk,{size:12})," ",He("standalone.sortLabel")]}),value:Fn,options:xf,onChange:u=>Jn(u),trailingAction:t.jsx("button",{className:`tf-control-icon ${p.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?He("standalone.sortDirectionDescTitle"):He("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?t.jsx($h,{size:14}):t.jsx(Uh,{size:14})})}),"divider-primary":t.jsx(jh,{}),grouping:t.jsx(Rh,{label:t.jsxs(t.Fragment,{children:[t.jsx(bp,{size:12})," ",He("standalone.groupLabel")]}),value:g,options:_f,onChange:u=>h(u)}),"divider-secondary":t.jsx(jh,{}),"task-display-actions":t.jsx(fp,{actions:Af})}),[g,_f,zm,bc,e,ae,h,Pe,Jn,Fn,xf,Af,Fs.moduleId]),Hy=r.useMemo(()=>({"add-task":t.jsx(G2,{icon:t.jsx(Cs,{size:16}),label:He("standalone.addTask"),onClick:hf}),"add-document":null}),[hf]),zl=r.useMemo(()=>{const u={tasks:t.jsx(xk,{size:18}),docs:t.jsx(xp,{size:18}),annotate:t.jsx(wk,{size:18}),workflows:t.jsx(bk,{size:18}),agents:t.jsx(wp,{size:18})};return t.jsxs("aside",{className:pn.workspaceToolRail,"aria-label":"Workspace tools",children:[t.jsxs("div",{className:pn.workspaceToolRailMain,children:[t.jsx("button",{type:"button",className:`${pn.workspaceToolButton} ${na==="tasks"&&Rr?pn.workspaceToolButtonActive:""}`.trim(),onClick:wf,title:na==="tasks"&&Rr?"Collapse planning trays":"Planning","aria-label":na==="tasks"&&Rr?"Collapse planning trays":"Planning",children:na==="tasks"&&Rr?t.jsx(Mc,{size:18}):t.jsx(kk,{size:18})}),t.jsx("div",{className:pn.workspaceToolRailDivider}),Cf.map(S=>t.jsx("button",{type:"button",className:`${pn.workspaceToolButton} ${na===S.id?pn.workspaceToolButtonActive:""}`.trim(),onClick:()=>zm(S.id),title:S.label,"aria-label":S.label,children:u[S.id]},S.id))]}),t.jsxs("div",{className:pn.workspaceToolRailBottom,children:[t.jsx("div",{className:pn.workspaceToolRailDivider}),t.jsx("button",{type:"button",className:`${pn.workspaceToolButton} ${y==="settings"?pn.workspaceToolButtonActive:""}`.trim(),onClick:()=>{kn("general"),v("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:t.jsx(qh,{size:18})})]})]})},[y,zm,wf,Rr,na,kn,v,Cf]),Hm=r.useRef(null),Gy=t.jsx(fW,{open:Rr,leftOffset:56,initiatives:xt.initiatives,standaloneWorkstreams:xt.standaloneWorkstreams,activeInitiativeId:An,activeWorkstreamId:jr,expandedInitiativeIds:Zc,detail:Vi,editor:vr,secondaryPane:Zi,currentWorkspaceId:Qt,assigneeOptions:an.map(u=>({value:String(u.value),label:u.label})),draftInitiativeSummary:il,draftTitle:Ys,draftDescription:$r,draftOwner:Di,draftInitiativeId:ts,onChangeDraftTitle:ks,onChangeDraftDescription:Js,onChangeDraftOwner:Rs,onChangeDraftInitiativeId:ns,onCollapseTreePane:()=>Kc(!0),onExpandTreePane:()=>Kc(!1),onCollapsePrimaryPane:()=>hs(!0),onExpandPrimaryPane:()=>hs(!1),onCollapseSecondaryPane:()=>Sr(!0),onExpandSecondaryPane:()=>Sr(!1),onBackFromSecondary:()=>{Ps.current=!1,ir(!1),es(null),Wa(null)},treeCollapsed:go,primaryCollapsed:yo,secondaryCollapsed:Vo,onCancelEditor:Om,onSubmitEditor:Ay,isSubmittingEditor:Yc,onCreateInitiative:()=>Um("initiative"),onCreateWorkstream:()=>Um("workstream"),onCreateTaskInWorkstream:Cy,onCreateWorkstreamInInitiative:u=>Um("workstream",u),onAssignInitiativeToWorkstream:wu,onOpenTaskById:Tt,onAttachTaskToWorkstreamByReference:Ey,onAttachWorkstreamToInitiativeByReference:My,onAddPlanningContextFile:Dy,onRemovePlanningContextFile:Ly,onUpdatePlanningContextCaption:By,onToggleInitiative:Iy,onSelectInitiative:Ty,onSelectWorkstream:Ny,onOpenInitiativeDetails:Ry,onOpenWorkstreamDetails:jy,onOpenNestedWorkstreamDetails:Py,onEditInitiative:u=>Sf("initiative",u),onEditWorkstream:u=>Sf("workstream",u),onArchiveInitiative:u=>{e.archiveInitiative(u).then(()=>{_t("Initiative archived","success")}).catch(S=>{_t(S instanceof Error?S.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:u=>{e.unarchiveInitiative(u).then(()=>{_t("Initiative unarchived","success")}).catch(S=>{_t(S instanceof Error?S.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:u=>{e.archiveWorkstream(u).then(()=>{_t("Workstream archived","success")}).catch(S=>{_t(S instanceof Error?S.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:u=>{e.unarchiveWorkstream(u).then(()=>{_t("Workstream unarchived","success")}).catch(S=>{_t(S instanceof Error?S.message:"Failed to unarchive workstream.","error")})}}),Vy=Fs.headerSections.map(u=>{const S=zy[u];return S?t.jsx(pt.Fragment,{children:S},u):null}).filter(Boolean),Ky=Fs.primaryAction?Hy[Fs.primaryAction]:null;return t.jsxs("div",{className:`${pn.standaloneWrapper} ${M?p.zenModeEnabled:""}`,"data-theme":Ae,children:[t.jsx(z2,{projectName:zn,currentWorkspaceId:Qt,runtimeMode:Jt,theme:Ae,meta:t.jsxs(t.Fragment,{children:[t.jsx("span",{className:p.taskCountBadge,title:Fl,children:Wl}),lr&&lr!=="anonymous"&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:p.taskCountBadge,title:"Tasks assigned to me",children:[t.jsx(_i,{size:13,className:p.taskCountBadgeIcon,"aria-hidden":"true"}),jd]}),t.jsxs("span",{className:`${p.taskCountBadge} ${Yi>0?p.taskCountBadgeAlert:""}`.trim(),title:"Tasks overdue",children:[t.jsx(Sk,{size:13,className:p.taskCountBadgeIcon,"aria-hidden":"true"}),Yi]})]}),Ol&&t.jsx("button",{className:"tf-control-icon",onClick:Tm,title:`Sync manager: ${Os.label} | Last success: ${$l}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${Os.border}`,background:Os.background,color:Os.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:Os.icon==="off"?t.jsx(vk,{size:16}):t.jsx(Vh,{size:16})})]}),actions:t.jsxs(t.Fragment,{children:[i&&t.jsxs(t.Fragment,{children:[Yt&&oa?.stripeCustomerId&&t.jsx("button",{className:"tf-control-icon",onClick:()=>{Ml()},title:"Manage billing",disabled:Od,children:"Manage billing"}),t.jsx("button",{className:"tf-control-icon",onClick:()=>{if(Sc){Do();return}m()},title:Sc?"Continue to Taskforce":"Back",disabled:dc,children:Sc?"Take Me to Taskforce":"Back"})]}),!i&&t.jsxs(t.Fragment,{children:[Vy,Ky]}),t.jsx(fp,{actions:qy}),!i&&t.jsx(fp,{actions:$y}),_y]})}),t.jsx(sy,{notice:er,onDismiss:fs}),In&&t.jsx("div",{className:me.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),!i&&Vs&&Uy,i?t.jsx("div",{className:`${pn.standalonePage} ${pn.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:t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(JW,{...e,currentTheme:Ae,projectName:zn,currentWorkspaceId:Qt,authUserId:jn,apiBaseUrl:Qd,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",resolveCloudAuthUrl:Mn,embedded:!0,shellOwnsScroll:!0,onAccountProfileSummaryChange:Dm,onContinueToTaskforce:Do,continueBusy:dc})})}):na==="docs"&&Jo?t.jsxs("div",{className:`${pn.standalonePage} ${pn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[zl,t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(KW,{tasks:ce,runtimeMode:Jt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:br,attachmentFilters:Ur,onTypeFiltersChange:Xs,onAttachmentFiltersChange:So,requestedDocPath:Sd,requestedDocAssetId:Fa,onRequestedDocHandled:()=>{Li(null),Jc(null)},enableTaskGeneration:!0})})]}):na==="annotate"&&tl?t.jsxs("div",{className:`${pn.standalonePage} ${pn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[zl,t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(VW,{runtimeMode:Jt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:Qt,sessionLoadReady:el,requestedTarget:Oa,requestedSessionId:js,requestedOpenVersion:fm,resolveTaskReferenceLabel:nl,resolveImageReferenceLabel:Ad,onOpenTarget:Fy,onContextChange:Oy,onBackToTask:Wy})})]}):na==="workflows"?t.jsxs("div",{className:`${pn.standalonePage} ${pn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[zl,t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(ZW,{availableWorkflows:Yr,availableEnvironments:mn,exportEnvironment:Dn,exportWorkflowsPath:e.exportWorkflowsPath,exportingResource:Zr,exportResult:Is,onExportEnvironmentChange:e.setExportEnvironment,onExportWorkflows:Yn,onRefreshWorkflows:Mt,onFetchWorkflowTemplate:e.fetchWorkflowTemplate,onFetchWorkflowOverrideNames:e.fetchWorkflowOverrideNames,onSaveWorkflowTemplateDraft:e.saveWorkflowTemplateDraft,onResetWorkflowTemplateDraft:e.resetWorkflowTemplateDraft})})]}):na==="agents"?t.jsxs("div",{className:`${pn.standalonePage} ${pn.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[zl,t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(YW,{workspaceId:Qt,cloudAuthConfigured:Rn,authSessionResolved:fn,isAuthenticated:Yt,cloudAiProfileSeatUsage:oa?.aiProfileSeatUsage??null})})]}):t.jsxs("div",{className:`${pn.standalonePage} ${pn.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:Rr?`${56+Td+6}px`:"62px",paddingRight:g==="schedule"&&rr?`${zp}px`:0},children:[zl,t.jsx("div",{ref:Hm,style:{position:"absolute",inset:0,zIndex:35,pointerEvents:"none"}}),t.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.loadingTasks&&wo.length>0&&t.jsx("div",{className:p.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:t.jsx(Va,{size:14,className:p.spinner})}),t.jsx(u2,{tasks:Nd,allTasks:Rd,columns:Cc,groupBy:g,scheduleDates:tn,searchQuery:ae,filterCategories:Ge,filterTypes:it,filterPriorities:Gt,filterStatus:ue,filterAssignees:Ft,filtersReady:Vt,assigneeOptions:an,scheduleFilteredTaskIds:Array.from(Id),copiedId:ot,taxonomies:Dt,types:d,priorities:Me,onUpdateTask:J,onTaskClick:u=>oe(u),onOpenTaskById:Tt,onCopyId:de,onToggleInProgress:Be,onToggleReview:vt,onToggleComplete:St,onToggleCancel:$t,onSetStatus:ni,onArchiveTask:Ze,onAddTaskToColumn:Pd,showTaskCardStatusLabel:xe,onScheduleDaySelected:u=>{Gc(u);const S=td(u);S&&Gs(`${S.getFullYear()}-${String(S.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:g==="schedule"?zo:void 0,onScrollLeftChange:u=>{g==="schedule"&&Aa(u)},emptyColumnMode:x,categories:b,compressed:ct,readOnlyMode:Kt==="deleted"?"deleted":Kt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:Fn,sortOrder:e.sortOrder,planningDropTargets:Hm.current?Ii.createPortal(Gy,Hm.current):null,onAssignTaskToWorkstream:qm,onAssignWorkstreamToInitiative:wu,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:u=>{if(Kt==="deleted"){const S=Xo.get(u);if(!S)return;bt(S.id);return}Lt(u)},onDelete:u=>{if(Kt==="deleted"){const S=Xo.get(u);if(!S||!window.confirm("Permanently delete this task? This cannot be undone."))return;W(S.id);return}en(u)}},`${g}-${Cc.map(u=>String(u.value)).join("|")}-${tn.mon}`),g==="schedule"&&!rr&&t.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{Qr(null),sr(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:t.jsx(Mc,{size:16})})]}),g==="schedule"&&t.jsx(FW,{open:rr,onClose:()=>sr(!1),scheduleSelectedDate:Xr,setScheduleSelectedDate:Gc,scheduleCalendarMonth:Vc,setScheduleCalendarMonth:Gs,scheduleShowWeekends:Y,setScheduleShowWeekends:zs,scheduleShowBacklog:ar,setScheduleShowBacklog:Hs,scheduleOnlyExpired:Ba,setScheduleOnlyExpired:Hc,expiredScheduledCount:cl,overdueDueCount:ll,expiredLeafCandidates:no,expiredRecoveryCandidates:ti,onMoveExpiredToSelectedWeek:Wn,onMoveExpiredToBacklog:ia,scheduleBulkBusy:ao,globalWeekStartsOn:on,resolvedLocale:R,todayDateOnly:aa,scheduleBaseTasks:qi,scheduleWeekStart:Ue,scheduleWeekLabel:Ha})]}),t.jsxs(As,{isOpen:y==="add",onClose:ul,title:Q?Ca?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:Go?"full":"xl",theme:Ae,headerActions:t.jsx("button",{className:"tf-control-icon",onClick:()=>Mi(u=>!u),title:Go?"Exit full screen":"Enter full screen","aria-label":Go?"Exit full screen":"Enter full screen",children:Go?t.jsx(Nf,{size:18}):t.jsx(Tf,{size:18})}),draggable:!Go,closeOnOverlayClick:!1,children:[t.jsx(ry,{editingTaskId:Q,loading:ie,autoSaveState:Je,title:P,currentTask:Ca,currentTaskWorkstream:ho,currentTaskInitiative:Ns,workstreamInput:te,onWorkstreamInputChange:L,onSetWorkstreamForCurrentTask:Rt,handleSubmit:be,resetForm:_,handleCopyId:de,copiedId:ot,tasks:ce,handleToggleInProgress:Be,handleToggleReview:vt,handleToggleComplete:St,handleToggleCancel:$t,handleSetStatus:ni,handleArchiveTask:Ze,handleUnarchiveTask:u=>{if(Ca?.isDeleted){const S=Xo.get(u);if(!S)return;bt(S.id);return}Lt(u)},handleRestoreDeletedTask:Ca?.deletedRecordId?u=>{bt(u)}:void 0,handlePermanentlyDeleteDeletedTask:Ca?.deletedRecordId?u=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(W(u),_(),v("tasks"))}:void 0}),t.jsx(ay,{editingTaskId:Q,error:H,title:P,description:se,checklistItems:V,category:Se,type:ge,priority:Le,complexity:Oe,manualComplexityEnabled:re,approach:w,assignee:F,scheduledDate:N,dueDate:$,workstreamInput:te,formTaxonomies:le,onTaxonomyChange:(u,S)=>we(D=>({...D,[u]:S})),taxonomies:Dt,comments:Re,newCommentText:Xe,contextFiles:lt,currentWorkspaceId:Qt,apiBaseUrl:Qd,descriptionFocused:ft,showMarkdownHelp:at,showChecklist:ne,checklistEnabled:fe,showComments:rt,categories:b,types:d,priorities:Me,taxonomyDisplayLabels:We,assigneeOptions:an,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:ot,onTitleChange:U,onDescriptionChange:he,onChecklistItemsChange:Ce,onCategoryChange:ve,onTypeChange:Te,onPriorityChange:Ie,onComplexityChange:z,onApproachChange:u=>{j(u),we(S=>({...S,approach:u}))},onAssigneeChange:ee,onScheduledDateChange:C,onDueDateChange:K,onWorkstreamInputChange:L,onNewCommentTextChange:ze,onDescriptionFocusedChange:gt,onShowMarkdownHelpChange:dt,onShowChecklistChange:tt,onShowCommentsChange:Pt,onOpenSettings:u=>{kn(u),v("settings")},onSubmit:be,commentsEndRef:q,onAddComment:()=>yt(Xe),onOpenTaskById:Tt,onAddContextFile:u=>{let S=lt;wt(D=>(S=[...D,u],S)),$e(!0),Q&&J(Q,{attachments:S})},onRemoveContextFile:async u=>{let S=lt;wt(D=>(S=D.filter((ye,_e)=>_e!==u),S)),$e(!0),Q&&J(Q,{attachments:S})},onUpdateContextCaption:(u,S)=>{let D=lt;wt(ye=>(D=ye.map((_e,ut)=>ut!==u?_e:typeof _e=="string"?{path:_e,caption:S,timestamp:new Date().toISOString()}:{..._e,caption:S}),D)),$e(!0),Q&&J(Q,{attachments:D})},onCopyId:de,onToggleInProgress:Be,onToggleReview:vt,onToggleComplete:St,onToggleCancel:$t,onSetStatus:ni,onArchiveTask:Ze,onUnarchive:u=>{if(Ca?.isDeleted){const S=Xo.get(u);if(!S)return;bt(S.id);return}Lt(u)},currentTask:Ca})]}),t.jsx(As,{isOpen:y==="settings",onClose:ul,title:"Settings",size:"xl",theme:Ae,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:t.jsx(r.Suspense,{fallback:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:t.jsx(Va,{size:20,className:p.spinner})}),children:t.jsx(GW,{settingsModel:pe,onSectionChange:kn})})}),t.jsx(p1,{prompt:qo,theme:Ae,onClose:La,onConfirm:Gn}),t.jsx(f1,{isOpen:Im,theme:Ae,onClose:Nm,onConfirm:Rm}),t.jsx(m1,{isOpen:ml,theme:Ae,onClose:()=>ai(!1),onOpenSettings:()=>{ai(!1),v("settings"),kn("general")}}),t.jsx(u1,{isOpen:si,theme:Ae,onClose:eu,onSave:()=>{au()},displayName:Al,email:gi,avatarDisplayUrl:kc,accountBadgeInitial:yc,saveBusy:Cm,avatarBusy:ss,saveError:Ro,saveNotice:Ud,onDisplayNameChange:$d,onOpenAvatarManager:()=>{zr(null),ha(null),oi(!0)}}),t.jsx(s1,{isOpen:pl,theme:Ae,title:"Edit Profile Photo",currentImageUrl:kc,fallbackInitial:yc,accept:XW,busy:ss,hasPendingImage:!!Na,canRemove:!!kc,error:Ro,notice:Ud,onClose:()=>oi(!1),onApplyImage:tu,onRemoveImage:nu,onDiscardPendingImage:Mm}),t.jsx(WL,{isOpen:_o,theme:Ae,runtimeMode:Jt,authRequiredForApi:Xn,isAuthenticated:Yt,hasAuthIdentity:Kd,authIdentityLabel:gc,billingLoading:pi,billingError:Fd,billingActionError:xm,billingNotice:_m,billingActionBusy:Od,billingIntervalChoice:so,accountProfileSummary:oa,currentWorkspaceId:Qt,canOpenTeamManagement:oo,canManageWorkspaceSync:Nl,workspaceCloudSyncEnabled:ya,syncStatusLabel:Os.label,workspaceSyncError:Hd,syncControlBusy:Gd,cloudAuthEnabled:Rn,availableAuthProviders:Xt,onFetchLoginMethods:hn,onUnlinkLoginMethod:ua,onAddPassword:ea,onLinkProvider:u=>fr(u),onClose:()=>ri(!1),onOpenWorkspaceAudit:()=>{ri(!1),cu(),ci("audit")},onBillingIntervalChange:Cl,onRefreshBilling:()=>{is()},onUpdateInterval:()=>{su()},onManageBilling:()=>{Ml()},onStartCheckout:()=>{ru()},onToggleWorkspaceSync:u=>{Vd(u)},onOpenHelp:()=>{ri(!1),ai(!0)}}),t.jsx(r2,{isOpen:Ed,theme:Ae,teamPlanMode:Dd,teamMgmtError:gl,teamManagementTab:Md,teamUsersLoading:Sm,teamUsers:yl,teamActionBusyUserId:bm,teamInviteFeedback:Sl,teamInviteEmail:sc,teamInviteRole:Ao,teamInvitePermissionMode:za,teamInviteBusy:Bd,pendingInvites:lu,teamAuditLoading:ui,teamAuditEvents:vl,teamAuditPage:Ds,teamAuditPages:ic,teamAuditHasMore:mi,onClose:()=>ec(!1),onOpenMembersTab:()=>{ci("members"),Eo()},onOpenInvitesTab:()=>ci("invites"),onOpenAuditTab:()=>{ci("audit"),Ws(Ds)},onMemberRoleChange:(u,S)=>{ki(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...Er()},credentials:"include",body:JSON.stringify({workspaceId:os,role:S})}))},onMemberPermissionChange:(u,S)=>{ki(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...Er()},credentials:"include",body:JSON.stringify({workspaceId:os,mode:S})}))},onToggleMemberDisabled:(u,S)=>{ki(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...Er()},credentials:"include",body:JSON.stringify({workspaceId:os,disabled:S})}))},onRevokeInvite:u=>{ki(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...Er()},credentials:"include",body:JSON.stringify({workspaceId:os})}))},onRemoveMember:u=>{ki(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}?workspaceId=${encodeURIComponent(os)}`,{method:"DELETE",headers:Er(),credentials:"include"}))},onInviteEmailChange:kl,onInviteRoleChange:wm,onInvitePermissionModeChange:rs,onSubmitInvite:()=>{Dl()},onLoadAuditPrevious:()=>{Ws(Ds-1)},onLoadAuditNext:()=>{Ws(Ds+1)}}),t.jsx(NL,{isOpen:gm,theme:Ae,onClose:()=>ii(!1),onConfirm:()=>Mo({intent:"create-workspace"})}),t.jsx(a2,{isOpen:zd,theme:Ae,currentWorkspaceLabel:jm,syncStatusMeta:Os,workspaceCloudSyncEnabled:ya,syncControlBusy:Gd,canManageWorkspaceSync:Nl,workspaceSyncSummary:Hr.summary,workspaceSyncRecommendedAction:Hr.recommendedAction,workspaceSyncRepairBusy:bu,referenceMismatchCount:vu,syncStageLabel:Ke,workspaceSyncPendingChanges:Tn,formattedLastSyncTime:$l,formattedLastPullTime:mu,formattedLastPushTime:pu,syncLastError:hu,workspaceSyncDiagnostics:cs,activeReferenceMismatchSummaries:Fm,syncDiagnosticsSummary:ql,syncEventRows:Wm,syncEventsListRef:Lm,workspaceSyncRepairQueued:f,workspaceSyncBusy:Qn,workspaceSyncCopied:O,runtimeMode:Jt,isAuthenticated:Yt,onClose:Rl,onToggleWorkspaceSync:u=>{Vd(u)},onRepairSync:Z,onCopyReport:()=>{G()},onOpenLogin:()=>{ou("login")},onRetrySync:()=>{ba()}}),Ct&&Ii.createPortal(t.jsx("div",{className:`${At.overlay} ${At.unsavedOverlay}`,style:{zIndex:2e3},children:t.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${At.modal} ${At.unsavedModal}`,"data-theme":Ae,children:[t.jsx("div",{className:`tf-modal-header ${At.unsavedHeader}`,children:t.jsxs("div",{className:`tf-modal-title ${At.unsavedTitle}`,children:[t.jsx(Fc,{size:20}),"Unsaved Changes"]})}),t.jsx("div",{className:`${At.form} ${At.unsavedContent}`,children:t.jsx("p",{className:At.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),t.jsxs("div",{className:`${At.formActions} ${At.unsavedActions}`,children:[t.jsx("button",{className:p.cancelBtn,onClick:()=>jt(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),t.jsx("button",{className:p.destructiveBtn,onClick:E,title:"Discard unsaved changes and leave",children:"Discard"}),t.jsxs("button",{className:p.submitBtn,onClick:je,disabled:ie,title:"Save changes and leave",children:[ie?t.jsx(Va,{size:16,className:p.spinner}):t.jsx(zh,{size:16}),"Save"]})]})]})}),document.body),ma&&Ii.createPortal(t.jsx("div",{className:En.overlay,children:t.jsxs("div",{className:En.browser,children:[t.jsxs("div",{className:En.header,children:[t.jsxs("div",{className:En.pathInfo,children:[t.jsx(Ni,{size:14}),t.jsx("span",{children:Hn||"Project Root"})]}),t.jsxs("div",{className:En.actions,children:[Hn&&t.jsx("button",{className:p.helpLink,onClick:()=>{const u=Hn.split("/").filter(Boolean);u.pop(),Ir(u.length?u.join("/")+"/":"")},children:"Back"}),t.jsx("button",{className:p.helpLink,onClick:()=>qa(!1),children:"Close"})]})]}),t.jsxs("div",{className:En.list,children:[Pn&&typeof Pn=="object"&&t.jsxs("div",{className:`${En.item} ${En.itemFile} ${En.itemCurrent}`,onClick:()=>ta(Hn),children:[t.jsx(po,{size:14})," Select Current: ./",Hn||"(root)"]}),Wr.map(u=>t.jsxs("div",{className:En.item,onClick:()=>Ir(Hn+u+"/"),children:[t.jsx(Ni,{size:14})," ",u,"/"]},u)),wa.map(u=>t.jsxs("div",{className:`${En.item} ${En.itemFile}`,onClick:()=>ta(Hn+u),children:[t.jsx(xp,{size:14})," ",u]},u)),Wr.length===0&&wa.length===0&&t.jsx("div",{className:`${En.item} ${En.empty}`,children:"No items found"})]})]})}),document.body)]})}function aF(e){const n=e.setupState,a=e.runtimeMode,s=e.isAuthenticated,o=!!(n&&a==="cloud"&&s&&n.globalSetupState==="missing"),c=!!(n&&a==="local"&&n.globalSetupState==="missing"),i=!!(n&&a==="cloud"&&s&&n.workspaceSetupState==="missing"),l=!!(n&&a==="local"&&n.workspaceSetupState==="missing"),m=!!(n&&(n.forceSetup||n.forceGlobalSetup||n.forceWorkspaceSetup||o||i||c||l));if(!m)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const y=!!(n&&(n.forceSetup||n.forceGlobalSetup||o||c)),v=!!(n&&(n.forceSetup||n.forceWorkspaceSetup||i||l)),b=!!(y&&n?.globalSetupState==="missing"),g=!!(v&&n?.workspaceSetupState==="missing"),h=!!(y&&n?.globalSetupState==="unreadable"),k=!!(v&&n?.workspaceSetupState==="unreadable"),I=h||k;return{setupGateActive:m,needsGlobalSetup:b,needsWorkspaceSetup:g,hasSetupReadError:I,phase:I?"setup-read-error":b?"needs-global-setup":g?"needs-workspace-setup":"ready"}}const Sp="/taskforce/assets/taskforce-BxLPokNB.png";function Bh(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function vp(e){return(Array.isArray(e)?e:[]).map(n=>String(n.label||n.value||"").trim()).filter(Boolean).join(", ")}function Wh(e={}){const n=new URLSearchParams;n.set("screen","plans");for(const[a,s]of Object.entries(e)){const o=String(s||"").trim();o&&n.set(a,o)}return`/?${n.toString()}`}function Fh({config:e={},initialTaskId:n,onTaskCountChange:a,onHeaderMouseDown:s,isDragging:o,onClose:c,mode:i="standalone"}){const l=tg(),m=r.useMemo(()=>new URLSearchParams(l.search),[l.search]),y=String(m.get("planId")||"").trim(),v=String(m.get("planVersionId")||"").trim(),b=String(m.get("interval")||"").trim(),g=l.pathname==="/pricing",h=l.pathname==="/plans",k=l.pathname==="/"&&String(m.get("screen")||"").trim().toLowerCase()==="plans",I=Wh({gate:"plan_selection_required"}),x=eg(),[A,M]=r.useState(""),[B,ue]=r.useState(""),[X,ce]=r.useState(""),[oe,be]=r.useState(""),[_,J]=r.useState("login"),[Q,ie]=r.useState(""),[H,P]=r.useState(!1),[U,se]=r.useState(null),[he,V]=r.useState(null),[Ce,Se]=r.useState(null),[ve,ge]=r.useState(!1),[Te,Le]=r.useState(""),[Ie,Oe]=r.useState(""),[z,T]=r.useState(null),[w,j]=r.useState(null),[F,ee]=r.useState("unknown"),[N,C]=r.useState(!1),[$,K]=r.useState([]),[te,L]=r.useState(null),[re,fe]=r.useState(null),[xe,le]=r.useState(null),[we,Re]=r.useState(!1),[Xe,ze]=r.useState(0),[lt,wt]=r.useState(0),[$e,ft]=r.useState(()=>Date.now()),[gt,at]=r.useState("core"),[dt,ne]=r.useState(!1),[tt,rt]=r.useState(null),[Pt,yt]=r.useState(null),[Rt,Tt]=r.useState(""),[Dt,d]=r.useState(""),[Me,We]=r.useState("local"),[Qe,ot]=r.useState("details"),[de,Be]=r.useState([]),[St,vt]=r.useState(""),[$t,Ze]=r.useState(!1),[en,Lt]=r.useState(null),[bt,W]=r.useState(!1),[ke,Ne]=r.useState(null),[ae,Pe]=r.useState(!1),Ge=r.useRef(!1),De=r.useMemo(()=>Lg(),[]),[it,Ut]=r.useState(De),[Gt,nn]=r.useState(()=>De.find(q=>q.isDefaultStarter)?.id||De[0]?.id||""),[Ft,Wt]=r.useState(()=>Bh(De.find(q=>q.isDefaultStarter)||De[0]||null)),[Vt,an]=r.useState(!1),[Kt,Kn]=r.useState(null),[Fn,Jn]=r.useState(!1),[_n,pe]=r.useState(null),[et,Ae]=r.useState(!1),Nt=aw({config:e,initialTaskId:n,onTaskCountChange:a,onClose:c}),{runtimeMode:Ye,workspaceSwitchingEnabled:Ot,currentWorkspaceId:dn,cloudAuthConfigured:yn,authRequiredForApi:on,authBlocked:rn,isAuthenticated:kt,hasBetaAccess:zt,authSessionResolved:Ln,setupState:Et,runtimeCapabilities:On,refreshSetupContext:kn,retryBootstrapChecks:Jt,createWorkspace:Dr,saveWorkspaceProfile:Rn,fetchWorkspaces:Xn,applyWorkspaceSyncStateSnapshot:In,workspaceCloudSyncEnabled:Yt,workspaceSyncPhase:jn,workspaceSyncSetupIntent:ln,workspaceSyncSummary:ga,workspaceSyncRecommendedAction:la,workspaceSyncBusy:Za,workspaceLastErrorMessage:fn,retryWorkspaceCloudSync:Cr,settingsModel:Lr,fetchTasks:ya,bootstrapState:Bn,loginWithCredentials:Ar,beginOAuthLogin:ka,availableAuthProviders:ja,registerWithCredentials:Qn,requestEmailVerification:Tn,confirmEmailVerification:Br,requestPasswordReset:_t,confirmPasswordReset:Sa,inspectInviteAcceptance:da,acceptInviteWithToken:va,joinInviteWithToken:$n,authUserEmail:Pa,currentTheme:wn,logout:Un}=Nt,ba=r.useCallback(async(q,Je)=>{const Ct=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:q,stateKey:"workspace-sync",patch:Je})}),jt=await Ct.json().catch(()=>({}));if(!Ct.ok||jt?.success===!1)throw new Error(jt?.error||`Failed to configure workspace sync (${Ct.status})`);return jt},[]),un=r.useMemo(()=>it.find(q=>q.id===Gt)||it.find(q=>q.isDefaultStarter)||it[0]||null,[Gt,it]);sg(wn);const Ea=Up,Qt=r.useMemo(()=>{const q=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return q?q.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),qn=Ye==="cloud"||On?.runtimeMode==="cloud",Cn=!qn&&yn&&!!Qt,Ya=typeof window<"u"&&/^app\./i.test(window.location.hostname),Ja=Ye==="cloud"&&on,Mn=Ye==="cloud"&&rn,cn=l.pathname==="/login",hn=l.pathname==="/setup",ua=l.pathname==="/coming-soon",ea="/setup?step=workspace&source=cloud&postAuth=select-cloud-workspace",pr=!qn&&Me==="cloud",fr=pr&&Cn,Xt=r.useMemo(()=>{if(ke)return ke;if(ln!=="attach-cloud-import")return null;const q=String(dn||"").trim();if(!q||q.toLowerCase()==="default")return null;const Je=de.find(Ct=>Ct.id===q);return{workspaceId:q,name:Je?.name||q}},[de,dn,ke,ln]),ms=!!(Xt&&dn===Xt.workspaceId),zn=!!(Xt&&ms&&jn==="error"),Xa=!!(Xt&&ms&&Yt&&jn==="active"&&!Za),Vr=r.useMemo(()=>{if(!Xt)return[];const q=dt?"In progress":"Complete",Je=zn?"Needs attention":Za||jn==="attach-cloud"?"In progress":jn==="active"?"Complete":"Waiting",Ct=ae?"In progress":Xa?"Ready":"Waiting";return[`Connect workspace: ${q}`,`Import cloud data: ${Je}`,`Open local workspace: ${Ct}`]},[Xt,dt,zn,Za,jn,ae,Xa]),ma=Ya?(!kt||rn)&&!g&&!h&&!k:(Ja&&!kt||Mn)&&!g&&!h&&!k,qa=Ye==="cloud"&&kt&&!zt&&!g&&!h&&!k,Wr=Ye==="cloud"&&kt&&Ln&&_n?.canAccessApp===!1&&_n?.canAccessPlans!==!1&&!g&&!h&&!k,wa=Ye==="cloud"&&kt&&(!Ln||!et),Hn=yn,Ir=r.useMemo(()=>{switch(_){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"}},[_]),Pn=r.useMemo(()=>String(new URLSearchParams(l.search).get("step")||"").trim().toLowerCase(),[l.search]),ps=r.useMemo(()=>String(new URLSearchParams(l.search).get("intent")||"").trim().toLowerCase(),[l.search]),ta=hn&&Pn==="workspace"&&ps==="create-workspace",Tr=i!=="widget"&&Bn.authPending&&!cn&&!hn&&!g&&!h&&!k&&(Ye==="cloud"||Ya),hr=r.useMemo(()=>aF({setupState:Et?{globalSetupState:Et.globalSetupState,workspaceSetupState:Et.workspaceSetupState,runtimeMode:Et.runtimeMode,workspaceId:Et.workspaceId,mode:Et.mode,forceSetup:Et.forceSetup,forceGlobalSetup:Et.forceGlobalSetup,forceWorkspaceSetup:Et.forceWorkspaceSetup}:null,runtimeMode:Ye,isAuthenticated:kt}),[Et,Ye,kt]),Fr=hr.setupGateActive,pa=hr.needsGlobalSetup,gr=hr.needsWorkspaceSetup,xa=hr.hasSetupReadError,Ma=i!=="widget"&&Bn.auth.resolved&&!ma&&!qa&&!g&&!h&&!k&&Bn.appPending&&(hn||Ye==="cloud"||Ya),Qa=Ye==="cloud"&&ve&&!k,Kr=Bn.subtitle,Or=ta||hn&&!!Xt||hn&&Fr&&(xa||pa||gr),Ve=r.useMemo(()=>Tr?"auth-bootstrap":Qa||Ma?"app-bootstrap":cn?"login":ma&&!cn?"login-redirect":ua&&qa?"coming-soon":Or?"guided-setup":"app",[ua,cn,qa,ma,Qa,Tr,Ma,Or]),Bt=r.useCallback((q,Je,Ct)=>{const jt=String(q||"").trim().toLowerCase(),Nn=String(Je||"").trim().toLowerCase();return!!(!jt||jt==="system default workspace"||Nn&&jt===Nn)},[]);r.useEffect(()=>{const q=Et?.mode==="operations"?"operations":"core";at(q)},[Et?.mode]),r.useEffect(()=>{if(Ye!=="cloud"||!kt){pe(null),Ae(!1);return}if(!Ln){pe(null),Ae(!1);return}pe(null),Ae(!1);let q=!1;return(async()=>{try{const Je=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),Ct=await Je.json().catch(()=>({}));if(q)return;if(!Je.ok){pe(null),Ae(!0);return}const jt=String(Ct?.gate||"").trim().toLowerCase();if(jt!=="ok"&&jt!=="plan_selection_required"&&jt!=="checkout_pending"&&jt!=="misconfigured"&&jt!=="missing_entitlement"){pe(null),Ae(!0);return}pe({gate:jt,canAccessApp:Ct?.canAccessApp===!0,canAccessPlans:Ct?.canAccessPlans!==!1,message:typeof Ct?.message=="string"?Ct.message:null}),Ae(!0)}catch{q||(pe(null),Ae(!0))}})(),()=>{q=!0}},[Ln,kt,Ye,l.pathname,l.search]),r.useEffect(()=>{if(ta){Tt(""),d("");return}if(!Et)return;const q=String(Et.workspace?.name||"").trim(),Je=String(Et.suggestedWorkspaceName||"").trim(),Ct=Bt(q,Et.workspaceId,Et.workspace?.description)?Je:q;Tt(Ct||Je||q),d(String(Et.workspace?.description||""))},[Et?.workspace?.name,Et?.workspace?.description,Et?.suggestedWorkspaceName,Et?.workspaceId,ta,Bt]),r.useEffect(()=>{if(!hn||Pn!=="workspace")return;if(ot("details"),Xt&&Cn){We("cloud"),W(!1);return}if(String(new URLSearchParams(l.search).get("source")||"").trim().toLowerCase()==="cloud"&&Cn){We("cloud"),W(!1);return}We("local")},[Xt,Cn,hn,l.search,Pn]);const Dn=r.useCallback(async()=>{if(!Cn||!kt){Be([]),vt("");return}Ze(!0),Lt(null);try{const q=await fetch(`${Qt}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),Je=await q.json().catch(()=>({}));if(!q.ok||Je?.success===!1){Be([]),vt(""),Lt(Je?.error||`Failed to load cloud projects (${q.status})`);return}const Ct=Array.isArray(Je?.workspaces)?Je.workspaces.map(jt=>({id:String(jt?.id||"").trim(),name:String(jt?.name||jt?.id||"").trim(),description:typeof jt?.description=="string"?jt.description:null})).filter(jt=>jt.id.length>0):[];Be(Ct),vt(jt=>jt&&Ct.some(Nn=>Nn.id===jt)?jt:Ct[0]?.id||"")}catch{Be([]),vt(""),Lt("Failed to load cloud projects.")}finally{Ze(!1)}},[Cn,kt,Qt]);r.useEffect(()=>{Me==="cloud"&&Dn()},[Dn,Me]),r.useEffect(()=>{if(!hn||Pn!=="workspace"||Me==="cloud")return;let q=!1;return an(!0),Kn(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async Je=>{if(!Je.ok)throw new Error(`Failed to load setup libraries (${Je.status})`);const Ct=await Je.json().catch(()=>({})),jt=Array.isArray(Ct?.packs)?Ct.packs:[];q||jt.length===0||(Ut(jt),nn(Nn=>jt.some(nr=>nr.id===Nn)?Nn:jt.find(nr=>nr.isDefaultStarter)?.id||jt[0]?.id||""))}).catch(Je=>{q||(Ut(De),Kn(Je instanceof Error?Je.message:"Failed to load setup libraries."))}).finally(()=>{q||an(!1)}),()=>{q=!0}},[De,hn,Pn,Me]),r.useEffect(()=>{Wt(Bh(un))},[Gt,un]),r.useEffect(()=>{Me==="cloud"&&ot("details")},[Me]),r.useEffect(()=>{fr||(Ne(null),Pe(!1),Ge.current=!1)},[fr]),r.useEffect(()=>{!zn||!Xt||(yt(null),rt(fn||`Failed to import "${Xt.name}" from cloud. Retry import to continue.`))},[Xt,zn,fn]),r.useEffect(()=>{if(!Xa||!Xt||Ge.current)return;let q=!1;return Ge.current=!0,Pe(!0),rt(null),yt(`Workspace import complete. Opening ${Xt.name}...`),(async()=>{try{if(await kn(),await Promise.all([Xn(),ya(!0)]),q)return;await ba(Xt.workspaceId,{setupIntent:null}),In({enabled:Yt,phase:jn,setupIntent:null}),Ne(null),x("/",{replace:!0})}catch{if(q)return;yt(null),rt(`Imported "${Xt.name}" but failed to finish opening it.`),Pe(!1),Ge.current=!1}})(),()=>{q=!0}},[Xt,In,ya,Xn,Xa,x,ba,kn]);const sn=r.useMemo(()=>{const q=new URLSearchParams(l.search).get("next")||"/";return!q.startsWith("/")||q==="/login"?"/":q},[l.search]),_a=r.useMemo(()=>{try{const q=new URL(sn,"https://taskforce.local");return q.pathname==="/setup"&&q.searchParams.get("step")==="workspace"&&q.searchParams.get("source")==="cloud"&&q.searchParams.get("postAuth")==="select-cloud-workspace"}catch{return!1}},[sn]),Zn=r.useCallback(()=>_a?ea:"/setup?step=workspace",[_a]),Is=b==="year"?"year":"month",Zr=r.useCallback(q=>!!(q?.planSelectionRequired||q?.checkoutPending||q?.commercialState==="pending_plan_selection"||q?.commercialState==="checkout_pending"),[]),Yr=r.useCallback(q=>q?.planSelectionRequired||q?.commercialState==="pending_plan_selection"?I:q?.checkoutPending||q?.commercialState==="checkout_pending"?Wh({gate:"checkout_pending",checkout:v?"start":null,planId:y||null,planVersionId:v||null,interval:v?Is:null}):sn,[sn,I,Is,y,v]),Yn=r.useMemo(()=>{const q=String(new URLSearchParams(l.search).get("mode")||"").trim().toLowerCase();return q==="register"?Hn?"register":"login":q==="verify"||q==="forgot"||q==="reset"||q==="invite"?q:"login"},[Hn,l.search]),Mt=r.useMemo(()=>String(new URLSearchParams(l.search).get("token")||"").trim(),[l.search]),mn=r.useCallback(q=>{const Je=new URLSearchParams(l.search),Ct=q==="register"&&!Hn?"login":q;Ct==="login"?Je.delete("mode"):Je.set("mode",Ct);const jt=Je.toString();x(`/login${jt?`?${jt}`:""}`,{replace:!0})},[Hn,l.search,x]);r.useEffect(()=>{cn&&(J(Yn),Yn==="verify"&&Mt&&ie(Mt),Yn==="reset"&&Mt&&Le(Mt),Yn==="invite"&&Mt&&Oe(Mt))},[cn,Yn,Mt]),r.useEffect(()=>{_!=="verify"&&(cn&&Yn==="verify"||(P(!1),se(null),V(null)))},[_,cn,Yn]),r.useEffect(()=>{_!=="register"&&be("")},[_]),r.useEffect(()=>{if(!Ce||!kt||!Ce.commercialOnboardingGate&&(!Ln||wa))return;const q=!Ce.commercialOnboardingGate&&Ce.workspaceSetupRequired?Zn():Ce.path;`${l.pathname}${l.search}${l.hash||""}`!==q&&x(q,{replace:!0})},[Ln,wa,kt,l.hash,l.pathname,l.search,x,Ce,Zn]),r.useEffect(()=>{if(!ve||!Ln)return;if(!kt){ge(!1),Se(null);return}if(et&&_n?.canAccessApp===!0){M(""),ue(""),ce(""),be(""),Se(null),ge(!1);return}const q=Ce?.commercialOnboardingGate?Ce.path:I;`${l.pathname}${l.search}${l.hash||""}`!==q&&x(q,{replace:!0})},[_n?.canAccessApp,et,Ln,ve,kt,l.hash,l.pathname,l.search,x,Ce,I]),r.useEffect(()=>{if(!Ce||!kt)return;const q=!Ce.commercialOnboardingGate&&Ce.workspaceSetupRequired?Zn():Ce.path;`${l.pathname}${l.search}${l.hash||""}`===q&&(Ce.commercialOnboardingGate||(M(""),ue(""),ce(""),be(""),Se(null)))},[l.hash,l.pathname,l.search,kt,Ce,Zn,Ye]),r.useEffect(()=>{cn&&(document.title=Ir)},[Ir,cn]),r.useEffect(()=>{if(!cn||_!=="invite"||!Ie.trim())return;let q=!0;return(async()=>{const Je=await da(Ie);if(q)if(Je.success){T(Je.email||null),j(Je.workspaceId||null),C(Je.passwordRequired===!0);const Ct=(Je.availableMethods||[]).filter(nr=>nr==="google"||nr==="github"||nr==="apple");K(Je.inviteeState==="pending_setup"?Ct:[]);const jt=!!(kt&&Pa&&Je.email&&Pa.trim().toLowerCase()===Je.email.trim().toLowerCase()),Nn=Je.passwordRequired===!0?"new_user":jt?"existing_user_ready":"existing_user_signed_out";ee(Nn),L(Nn==="new_user"?"Create your account password to join this workspace.":Nn==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),fe(null),le(null)}else T(null),j(null),ee("invalid"),C(!1),K([]),fe(Nr(Je)),le(Je.code||Je.state||null)})(),()=>{q=!1}},[cn,_,Ie,da,kt,Pa]),r.useEffect(()=>{_==="invite"&&F==="existing_user_signed_out"&&z&&M(q=>q.trim()?q:z)},[_,F,z]),r.useEffect(()=>{if(!(Xe>Date.now()||lt>Date.now()))return;const Je=window.setInterval(()=>ft(Date.now()),1e3);return()=>window.clearInterval(Je)},[Xe,lt]);const Da=Math.max(0,Math.ceil((Xe-$e)/1e3)),yr=Math.max(0,Math.ceil((lt-$e)/1e3)),kr=Da>0,er=yr>0,fs=r.useMemo(()=>iy(),[]),Nr=q=>{const Je=q.error||"Request failed.",Ct=q.code||q.state;return Ct?`[${Ct}] ${Je}`:Je},Jr=q=>q?.deliveryAttempted===!1?q?.intro||"If that account exists and still needs verification, we sent an email.":q?.emailSent===!1?`Verification email failed to send. ${q?.emailError||"Try Resend Verification again."}`:"Verification email resent.",tr=q=>q?.deliveryAttempted===!1?"If that account exists, we sent password reset instructions.":q?.emailSent===!1?`Password reset email failed to send. ${q?.emailError||"Try again in a minute."}`:"Password reset instructions sent.";r.useEffect(()=>{if(i==="widget"||cn&&we)return;const q=Ye==="cloud"&&kt&&et&&_n?.canAccessApp===!1&&_n?.canAccessPlans!==!1;if(Bn.workspace.pending&&!q)return;if(qa){ua||x("/coming-soon",{replace:!0});return}if(ua&&!qa){x("/",{replace:!0});return}if(ma){if(!cn){const Ct=`${l.pathname}${l.search}${l.hash}`;x(`/login?next=${encodeURIComponent(Ct||"/")}`,{replace:!0});return}return}else{const Ct=cn&&_==="invite"&&Ie.trim().length>0;if(cn&&kt&&!Ct&&(!!Ce||Bn.workspace.pending||_==="register"||_==="verify"||!Bn.config.loaded||wa))return;cn&&kt&&!Ct&&x(sn,{replace:!0})}if(!(cn&&!kt||Ce&&kt||cn&&kt&&(_==="register"||_==="verify"||_==="invite"&&Ie.trim().length>0))&&!ve&&!k){if(Wr){if(!k){const Ct=encodeURIComponent(String(_n?.gate||"plan_selection_required"));x(`/?screen=plans&gate=${Ct}`,{replace:!0})}return}if(Xt){hn&&Pn==="workspace"&&new URLSearchParams(l.search).get("source")==="cloud"||x(ea,{replace:!0});return}if(!(k&&wa)&&!(k&&Ye==="cloud"&&et&&_n?.canAccessApp===!1&&_n?.canAccessPlans!==!1)){if(Fr){if(xa){(!hn||Pn!=="error")&&x("/setup?step=error",{replace:!0});return}if(pa){(!hn||Pn!=="global")&&x("/setup?step=global",{replace:!0});return}if(gr){(!hn||Pn!=="workspace")&&x(Zn(),{replace:!0});return}hn&&x("/",{replace:!0});return}hn&&Et&&!ta&&x("/",{replace:!0})}}},[i,ma,qa,Wr,cn,hn,ua,h,k,_n,_n?.gate,et,_,ve,wa,Fr,Et,xa,ta,Xt,pa,gr,Pn,Bn,Ye,we,kt,et,Ie,l.pathname,l.search,l.hash,x,sn,Ce,ea]),r.useEffect(()=>{if(i==="widget"||Ye!=="local"||!Bn.config.loaded||cn||hn)return;const q=String(dn||"").trim().toLowerCase();(!q||q==="default")&&x("/setup?step=workspace",{replace:!0})},[i,Ye,Bn.config.loaded,cn,hn,dn,x]);const ra=r.useCallback(async()=>{Jn(!0);try{await Jt()}finally{Jn(!1)}},[Jt]),Ts=r.useCallback(async()=>{await Un(),x("/login",{replace:!0})},[Un,x]);if(i==="widget")return t.jsx(rD,{...Nt,onHeaderMouseDown:s,isDragging:o,onClose:c});if(g){const q=new URLSearchParams(l.search);return q.set("screen","plans"),t.jsx(jf,{to:`/?${q.toString()}${l.hash||""}`,replace:!0})}if(h){const q=new URLSearchParams(l.search);return q.set("screen","plans"),t.jsx(jf,{to:`/?${q.toString()}${l.hash||""}`,replace:!0})}if(Ve==="auth-bootstrap")return t.jsx("div",{className:pn.standaloneWrapper,"data-theme":wn,children:t.jsx("div",{className:me.loginView,children:t.jsxs("div",{className:me.loginCard,children:[t.jsxs("div",{className:me.authBrandRow,children:[t.jsx("img",{src:Ea,alt:"Taskforce",className:me.loginLogo}),t.jsx("h1",{className:me.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:me.loginSubtitle,children:"Checking your session..."})]})})});if(Ve==="app-bootstrap")return t.jsx("div",{className:pn.standaloneWrapper,"data-theme":wn,children:t.jsx("div",{className:me.loginView,children:t.jsxs("div",{className:me.loginCard,children:[t.jsxs("div",{className:me.authBrandRow,children:[t.jsx("img",{src:Ea,alt:"Taskforce",className:me.loginLogo}),t.jsx("h1",{className:me.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:me.loginSubtitle,children:Kr}),Bn.stalled&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:me.loginError,children:Bn.error||"Startup checks timed out."}),t.jsx("button",{className:p.submitBtn,disabled:Fn,onClick:ra,children:Fn?"Retrying...":"Retry checks"}),qn&&t.jsx("button",{className:p.cancelBtn,disabled:Fn,onClick:Ts,children:"Go to sign-in"})]})]})})});if(Ve==="login")return t.jsx("div",{className:pn.standaloneWrapper,"data-theme":wn,children:t.jsx("div",{className:me.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Sp})`},children:t.jsxs("div",{className:me.loginCard,children:[!qn&&!ma&&t.jsx("button",{className:me.loginCloseBtn,"aria-label":"Close sign in","data-testid":"auth-close-button",onClick:()=>x(sn,{replace:!0}),children:"×"}),t.jsxs("div",{className:me.authBrandRow,children:[t.jsx("img",{src:Ea,alt:"Taskforce",className:me.loginLogo}),t.jsxs("h1",{className:me.loginTitle,children:["TASKFORCE ",t.jsx("span",{className:me.loginTitleAccent,children:"HQ"})]})]}),t.jsxs("p",{className:me.loginSubtitle,children:[_==="login"&&"Sign in with your account credentials.",_==="register"&&"Create your Taskforce account.",_==="verify"&&"Enter your verification token.",_==="forgot"&&"Request a password reset link.",_==="reset"&&"Set a new password using your reset token.",_==="invite"&&(F==="existing_user_ready"?`You've been invited to join ${w||"this workspace"}.`:F==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(_==="login"||_==="register"||_==="verify"||_==="forgot"||_==="invite"&&F==="existing_user_signed_out")&&t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:"Email"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"email",value:A,placeholder:"Email",autoComplete:"email","data-testid":"auth-email-input",onChange:q=>M(q.target.value)})]}),_==="register"&&t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:"Display name"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"text",value:B,placeholder:"Display name",autoComplete:"nickname","data-testid":"auth-display-name-input",onChange:q=>ue(q.target.value)})]}),(_==="login"||_==="register"||_==="reset"||_==="invite"&&(N||F==="existing_user_signed_out"))&&t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:_==="reset"?"New password":_==="invite"&&N?"Create password":"Password"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"password",value:X,placeholder:_==="reset"?"New password":_==="invite"&&N?"Create password":"Password",autoComplete:_==="register"||_==="reset"||_==="invite"&&N?"new-password":"current-password","data-testid":"auth-password-input",onChange:q=>ce(q.target.value)})]}),(_==="register"||_==="invite"&&N)&&t.jsx(t.Fragment,{children:t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:"Confirm password"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"password",value:oe,placeholder:"Confirm password",autoComplete:"new-password","data-testid":"auth-confirm-password-input",onChange:q=>be(q.target.value)})]})}),(_==="register"||_==="invite"&&N)&&t.jsx("p",{className:me.loginSubtitle,children:fs.join(" ")}),_==="verify"&&t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:"Verification token"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"text",value:Q,placeholder:"Verification token",autoComplete:"one-time-code","data-testid":"auth-verification-token-input",onChange:q=>ie(q.target.value)})]}),_==="reset"&&t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:"Reset token"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"text",value:Te,placeholder:"Reset token",autoComplete:"one-time-code","data-testid":"auth-reset-token-input",onChange:q=>Le(q.target.value)})]}),_==="invite"&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:me.loginField,children:[t.jsx("span",{className:me.loginFieldLabel,children:"Invite token"}),t.jsx("input",{className:`${p.input} ${me.loginInput}`,type:"text",value:Ie,placeholder:"Invite token","data-testid":"auth-invite-token-input",onChange:q=>Oe(q.target.value)})]}),z&&t.jsxs("p",{className:me.loginSubtitle,children:["Invite for: ",t.jsx("strong",{children:z}),w?` · Workspace: ${w}`:""]})]}),te&&t.jsx("p",{className:me.loginSubtitle,children:te}),re&&t.jsx("p",{className:me.loginError,children:re}),_==="login"&&xe==="EMAIL_NOT_VERIFIED"&&A.trim()&&t.jsx("button",{className:me.authModeLink,disabled:we||kr,onClick:async()=>{Re(!0),L(null);const q=await Tn(A);q.success?(ze(Date.now()+3e4),mn("verify"),q.verificationToken&&ie(q.verificationToken),L(Jr(q)),fe(null),le(null)):fe(Nr(q)),Re(!1)},children:kr?`Resend in ${Da}s`:"Resend Verification Email"}),t.jsx("div",{className:me.authPrimaryActions,role:"group","aria-label":"Primary authentication action",children:t.jsx("button",{className:`${p.submitBtn} ${me.loginPrimaryBtn}`,disabled:we||_==="forgot"&&er,"data-testid":"auth-submit-button",onClick:async()=>{if(Re(!0),L(null),fe(null),le(null),_==="register"&&!B.trim()){fe("Display name is required."),Re(!1);return}if(_==="register"){const Je=cy(X,{email:A,displayName:B});if(!Je.ok){fe(Je.message||"Password does not meet the password policy."),le(Je.code||null),Re(!1);return}if(X!==oe){fe("Passwords do not match."),le("PASSWORD_CONFIRMATION_MISMATCH"),Re(!1);return}}let q={success:!1};if(_==="login"?q=await Ar(A,X):_==="register"?q=await Qn(A,X,{displayName:B,planId:y||void 0,planVersionId:v||void 0,interval:b||void 0}):_==="verify"?q=await Br(Q):_==="forgot"?q=await _t(A):_==="reset"?q=await Sa(Te,X):_==="invite"&&(F==="existing_user_signed_out"?q=await Ar(A,X):q=N?await va(Ie,X):await $n(Ie)),q.success)if(_==="register"){const Je=Yr(q),Ct=Zr(q);q.verificationRequired?(P(!!q.workspaceSetupRequired),se(Ct?String(q.commercialState||"").trim()||(q.planSelectionRequired?"pending_plan_selection":"checkout_pending"):null),V(Je),q.verificationToken&&ie(q.verificationToken),ze(Date.now()+3e4),mn("verify"),L(q.emailSent===!1?`Account created, but verification email failed to send. ${q.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")):(ge(Ct),Se({path:Je,workspaceSetupRequired:!!q.workspaceSetupRequired,commercialOnboardingGate:Ct}))}else if(_==="verify"){await Jt();const Je=U==="pending_plan_selection"||U==="checkout_pending";ge(Je),Se({path:he||sn,workspaceSetupRequired:H,commercialOnboardingGate:Je})}else if(_==="forgot"){const Je=q.deliveryAttempted===!0&&q.emailSent===!1;q.resetToken&&Le(q.resetToken),L(tr(q)),Je||(wt(Date.now()+3e4),mn("reset"))}else if(_==="reset")mn("login"),L("Password updated. Sign in with your new password.");else if(_==="invite"){if(F==="existing_user_signed_out"){const Je=String(z||"").trim().toLowerCase(),Ct=A.trim().toLowerCase();if(Je&&Ct===Je){J("invite"),ee("existing_user_ready"),ce(""),be(""),L("Signed in. Review the invite details to continue."),fe(null),le(null),Re(!1);return}Je&&M(z||""),ee("existing_user_signed_out"),ce(""),be(""),L(Je?`Signed in, but this invite is for ${z}. Sign in with that account to continue.`:"Signed in, but this invite requires the invited account. Sign in with that account to continue."),fe("Sign in with the invited account to join this workspace."),le("INVITE_ACCOUNT_MISMATCH"),Re(!1);return}if(q.workspaceSetupRequired){x(Zn(),{replace:!0}),Re(!1);return}x(sn,{replace:!0})}else if(_==="login"){if(Ie.trim()){J("invite"),ce(""),be(""),L("Signed in. Review the invite details to continue."),Re(!1);return}if(q.workspaceSetupRequired){x(Zn(),{replace:!0}),Re(!1);return}M(""),ue(""),ce(""),be(""),x(sn,{replace:!0})}else M(""),ue(""),ce(""),be(""),x(sn,{replace:!0});else{if(_==="register"&&(q.code==="SIGNUP_PLAN_NOT_ENABLED"||q.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||q.code==="SIGNUP_PLAN_VERSION_REQUIRED")){x(I,{replace:!0}),Re(!1);return}if(fe(Nr(q)),le(q.code||null),_==="login"&&(q.code==="WORKSPACE_NOT_FOUND"||q.code==="WORKSPACE_ID_REQUIRED")){x("/setup?step=workspace",{replace:!0}),Re(!1);return}if(_==="login"&&q.code==="EMAIL_NOT_VERIFIED"&&A.trim()){const Je=await Tn(A);Je.success&&(ze(Date.now()+3e4),mn("verify"),Je.verificationToken&&ie(Je.verificationToken),L(Jr({...Je,intro:"If that account exists and still needs verification, we sent an email."})),fe(null),le(null))}_==="register"&&q.code==="EMAIL_ALREADY_EXISTS_UNVERIFIED"&&A.trim()&&(ze(Date.now()+3e4),mn("verify"),q.verificationToken&&ie(q.verificationToken),L(q.emailSent===!1?`This email already has an unverified account, but verification email delivery failed. ${q.emailError||"Try Resend Verification again."}`:"This email already has an unverified account. Check your email for verification instructions."),fe(null),le(null))}Re(!1)},children:we?"Working...":_==="login"?"Sign In":_==="register"?"Create Account":_==="verify"?"Verify Email":_==="forgot"?er?`Retry in ${yr}s`:"Send Reset Link":_==="reset"?"Reset Password":F==="existing_user_signed_out"?"Sign In to Continue":N?"Create Account and Join":"Join Workspace"})}),(_==="login"||_==="register")&&ja.length>0&&t.jsxs("div",{className:me.oauthProviders,children:[t.jsx("div",{className:me.oauthDivider,children:t.jsx("span",{children:"or continue with"})}),t.jsxs("div",{className:me.oauthButtons,children:[ja.includes("google")&&t.jsx("button",{type:"button",className:me.oauthButton,disabled:we,onClick:()=>ka("google",l.pathname!=="/login"?l.pathname:"/"),"aria-label":"Continue with Google",children:"Google"}),ja.includes("github")&&t.jsx("button",{type:"button",className:me.oauthButton,disabled:we,onClick:()=>ka("github",l.pathname!=="/login"?l.pathname:"/"),"aria-label":"Continue with GitHub",children:"GitHub"}),ja.includes("apple")&&t.jsx("button",{type:"button",className:me.oauthButton,disabled:we,onClick:()=>ka("apple",l.pathname!=="/login"?l.pathname:"/"),"aria-label":"Continue with Apple",children:"Apple"})]})]}),_==="invite"&&F==="new_user"&&$.length>0&&t.jsxs("div",{className:me.oauthProviders,children:[t.jsx("div",{className:me.oauthDivider,children:t.jsx("span",{children:"or join with"})}),t.jsxs("div",{className:me.oauthButtons,children:[$.includes("google")&&t.jsx("button",{type:"button",className:me.oauthButton,disabled:we,onClick:()=>ka("google","/",Ie),"aria-label":"Join with Google",children:"Google"}),$.includes("github")&&t.jsx("button",{type:"button",className:me.oauthButton,disabled:we,onClick:()=>ka("github","/",Ie),"aria-label":"Join with GitHub",children:"GitHub"}),$.includes("apple")&&t.jsx("button",{type:"button",className:me.oauthButton,disabled:we,onClick:()=>ka("apple","/",Ie),"aria-label":"Join with Apple",children:"Apple"})]})]}),_==="register"&&t.jsxs("p",{className:me.registerConsent,children:["By creating an account, you agree to the"," ",t.jsx("a",{className:me.registerConsentLink,href:"https://taskforcehq.com/legal/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," ","and acknowledge the"," ",t.jsx("a",{className:me.registerConsentLink,href:"https://taskforcehq.com/legal/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]}),t.jsxs("div",{className:me.authSecondaryActions,role:"group","aria-label":"Authentication navigation",children:[Hn&&(_==="login"||_==="register")&&t.jsxs("p",{className:me.authModeSwitch,children:[_==="login"?"Need an account?":"Already have an account?"," ",t.jsx("button",{className:me.authModeSwitchLink,disabled:we,"data-testid":"auth-switch-mode-button",onClick:()=>{fe(null),le(null),L(null),mn(_==="login"?"register":"login")},children:_==="login"?"Register":"Sign In"})]}),t.jsxs("div",{className:me.authModeLinks,children:[(_==="login"||_==="register")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:me.authModeLink,disabled:we||er,"data-testid":"auth-forgot-password-button",onClick:()=>{fe(null),le(null),L(null),mn("forgot")},children:er?`Forgot Password (${yr}s)`:"Forgot Password"}),t.jsx("button",{className:me.authModeLink,disabled:we||kr,"data-testid":"auth-resend-verification-button",onClick:()=>{fe(null),le(null),L(null),mn("verify")},children:kr?`Resend Verification (${Da}s)`:"Resend Verification"}),t.jsx("button",{className:me.authModeLink,disabled:we,"data-testid":"auth-accept-invite-button",onClick:()=>{fe(null),le(null),L(null),mn("invite")},children:"Accept Invite"})]}),_!=="login"&&_!=="register"&&t.jsxs(t.Fragment,{children:[_==="verify"&&t.jsx("button",{className:me.authModeLink,disabled:we||kr||!A.trim(),"data-testid":"auth-resend-verification-button",onClick:async()=>{Re(!0),L(null),fe(null),le(null);const q=await Tn(A);q.success?(ze(Date.now()+3e4),q.verificationToken&&ie(q.verificationToken),L(Jr(q))):fe(Nr(q)),Re(!1)},children:kr?`Resend Verification (${Da}s)`:"Resend Verification"}),t.jsx("button",{className:me.authModeLink,disabled:we,"data-testid":"auth-return-sign-in-button",onClick:()=>{fe(null),le(null),L(null),mn("login")},children:_==="verify"?"Back to Sign In":"Sign In"}),Hn&&_!=="verify"&&t.jsx("button",{className:me.authModeLink,disabled:we,"data-testid":"auth-return-register-button",onClick:()=>{fe(null),le(null),L(null),mn("register")},children:"Register"}),_==="reset"&&t.jsx("button",{className:me.authModeLink,disabled:we||er,"data-testid":"auth-return-forgot-password-button",onClick:()=>{fe(null),le(null),L(null),mn("forgot")},children:er?`Forgot Password (${yr}s)`:"Forgot Password"})]})]})]})]})})});if(Ve==="login-redirect")return t.jsx("div",{className:pn.standaloneWrapper,"data-theme":wn,children:t.jsx("div",{className:me.loginView,children:t.jsxs("div",{className:me.loginCard,children:[t.jsxs("div",{className:me.authBrandRow,children:[t.jsx("img",{src:Ea,alt:"Taskforce",className:me.loginLogo}),t.jsx("h1",{className:me.loginTitle,children:"Loading Taskforce"})]}),t.jsx("p",{className:me.loginSubtitle,children:"Redirecting to sign in..."})]})})});if(Ve==="coming-soon")return t.jsx("div",{className:pn.standaloneWrapper,"data-theme":wn,children:t.jsx("div",{className:me.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Sp})`},children:t.jsxs("div",{className:me.loginCard,children:[t.jsxs("div",{className:me.authBrandRow,children:[t.jsx("img",{src:Ea,alt:"Taskforce",className:me.loginLogo}),t.jsx("h1",{className:me.loginTitle,children:"Private Beta"})]}),t.jsx("p",{className:me.loginSubtitle,children:"You are signed in, but your account is not in the beta allowlist yet."}),t.jsx("p",{className:me.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),t.jsx("button",{className:p.cancelBtn,onClick:async()=>{await Nt.logout(),x("/login",{replace:!0})},children:"Sign Out"})]})})});if(Ve==="guided-setup"){const q=!ta&&(xa||Pn==="error"),Je=!ta&&!q&&(pa||Pn==="global"),Ct=He(q?"setup.headingCheckFailed":Je?"setup.headingGlobalRequired":"setup.headingWorkspaceRequired"),jt=q?He("setup.subtitleUnreadable"):Je?He("setup.subtitleGlobalRequired"):null,Nn="Workspace",nr=qn||Me!=="cloud",Ca=nr&&Qe==="details",ho=nr&&Qe==="library",Ns=!qn&&Cn&&Ca&&!Xt,qo=On?.runtimeMode==="cloud"?Vh:_k,Gn=un?vp(un.categories):"",La=un?vp(un.types):"",R=un?vp(un.priorities):"",E=dt?He("setup.saving"):pr?Xt?zn?"Retry Import":"Importing Workspace...":"Connect Workspace":Ca?"Continue":ho?"Create Workspace":"Connect Workspace";return t.jsx("div",{className:pn.standaloneWrapper,"data-theme":wn,children:t.jsx("div",{className:me.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Sp})`},children:t.jsxs("div",{className:me.loginCard,children:[t.jsxs("div",{className:me.setupHeaderRow,children:[t.jsxs("div",{className:me.authBrandRow,children:[t.jsx("img",{src:Ea,alt:"Taskforce",className:me.loginLogo}),t.jsxs("h1",{className:me.loginTitle,children:["TASKFORCE ",t.jsx("span",{className:me.loginTitleAccent,children:"HQ"})]})]}),On&&t.jsx("span",{className:me.runtimeIconBadge,title:On.runtimeMode==="cloud"?"Cloud runtime":"Local runtime","aria-label":On.runtimeMode==="cloud"?"Cloud runtime":"Local runtime",children:pt.createElement(qo,{size:16,"aria-hidden":!0})})]}),t.jsx("p",{className:me.loginSubtitle,children:t.jsx("strong",{children:Ct})}),jt?t.jsx("p",{className:me.loginSubtitle,children:jt}):null,Pt&&t.jsx("p",{className:me.loginSubtitle,children:Pt}),tt&&t.jsx("p",{className:me.loginError,children:tt}),Je&&t.jsxs("div",{className:me.optionGrid,children:[t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:gt==="core",onChange:()=>at("core"),disabled:dt}),t.jsx("span",{children:He("setup.coreModeOption",{workspaceLabel:Nn})})]}),t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:gt==="operations",onChange:()=>at("operations"),disabled:dt}),t.jsx("span",{children:He("setup.operationsModeOption")})]})]}),!q&&!Je&&t.jsxs("div",{className:me.optionGrid,children:[Ns&&t.jsxs("div",{className:me.optionGroup,children:[t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:Me==="local",onChange:()=>We("local"),disabled:dt}),t.jsxs("span",{children:["Create new local ",Nn.toLowerCase()]})]}),t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:Me==="cloud",onChange:()=>We("cloud"),disabled:dt}),t.jsxs("span",{children:["Sync existing cloud ",Nn.toLowerCase()]})]})]}),pr?t.jsxs("div",{className:me.optionGroup,children:[!Xt&&!Cn&&t.jsx("p",{className:me.loginError,children:"Cloud workspace sync is unavailable right now. Switch back to local setup or refresh runtime configuration."}),!Xt&&Cn&&!kt&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:me.inlineHint,children:"Sign in to choose one of your cloud projects."}),t.jsxs("div",{className:me.actionRowEnd,children:[t.jsx("button",{className:p.cancelBtn,disabled:dt,onClick:()=>{x(`/login?mode=login&next=${encodeURIComponent(ea)}`,{replace:!0})},children:"Sign In"}),Hn&&t.jsx("button",{className:p.submitBtn,disabled:dt,onClick:()=>{x(`/login?mode=register&next=${encodeURIComponent(ea)}`,{replace:!0})},children:"Register"})]})]}),!Xt&&Cn&&kt&&t.jsxs(t.Fragment,{children:[t.jsxs("select",{className:p.input,value:St,onChange:je=>vt(je.target.value),disabled:dt||$t||de.length===0,children:[de.length===0&&t.jsx("option",{value:"",children:$t?"Loading cloud projects...":"No cloud projects found"}),de.map(je=>t.jsxs("option",{value:je.id,children:[je.name," (",je.id,")"]},je.id))]}),t.jsx("div",{className:me.actionRowEnd,children:t.jsx("button",{className:p.cancelBtn,disabled:dt||$t,onClick:()=>{Dn()},children:"Refresh Cloud Projects"})}),en&&t.jsx("p",{className:me.loginError,children:en})]}),Xt&&t.jsxs(t.Fragment,{children:[t.jsxs("p",{className:me.inlineHint,children:['Importing "',Xt.name,'" from cloud into local.']}),t.jsx("div",{className:me.optionGroup,children:Vr.map(je=>t.jsx("p",{className:me.inlineHint,children:je},je))}),t.jsx("p",{className:me.inlineHint,children:ae?"Finishing setup and opening your workspace.":ga||"Pulling tasks, taxonomies, and settings into local."}),!ae&&la&&t.jsx("p",{className:me.inlineHint,children:la})]})]}):t.jsxs(t.Fragment,{children:[Ca&&t.jsxs(t.Fragment,{children:[t.jsx("p",{className:me.loginSubtitle,children:"Workspace name"}),t.jsx("input",{className:p.input,type:"text",value:Rt,placeholder:"Workspace name",onChange:je=>Tt(je.target.value),disabled:dt}),t.jsx("p",{className:me.loginSubtitle,children:"Workspace description"}),t.jsx("textarea",{className:p.textarea,value:Dt,placeholder:"Workspace description (optional)",onChange:je=>d(je.target.value),disabled:dt,rows:4})]}),ho&&t.jsxs("div",{className:me.optionGroup,children:[t.jsx("p",{className:me.loginSubtitle,children:"What are you working on?"}),t.jsxs("select",{className:p.input,value:Gt,onChange:je=>nn(je.target.value),disabled:dt||Vt||it.length===0,children:[it.length===0&&t.jsx("option",{value:"",children:Vt?"Loading setup options...":"No setup options available"}),it.map(je=>t.jsx("option",{value:je.id,children:je.label},je.id))]}),un?t.jsx(t.Fragment,{children:un.description?t.jsx("p",{className:me.inlineHint,children:un.description}):null}):null,t.jsxs("div",{className:me.optionGroup,children:[t.jsx("p",{className:me.loginSubtitle,children:"Apply Setup Sections"}),t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:Ft.categories,onChange:()=>Wt(je=>({...je,categories:!je.categories})),disabled:dt||!un?.categories.length}),t.jsx("span",{children:"Categories"})]}),Gn?t.jsx("p",{className:me.inlineHint,children:Gn}):null,t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:Ft.types,onChange:()=>Wt(je=>({...je,types:!je.types})),disabled:dt||!un?.types.length}),t.jsx("span",{children:"Task Types"})]}),La?t.jsx("p",{className:me.inlineHint,children:La}):null,t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:Ft.priorities,onChange:()=>Wt(je=>({...je,priorities:!je.priorities})),disabled:dt||!un?.priorities.length}),t.jsx("span",{children:"Priorities"})]}),R?t.jsx("p",{className:me.inlineHint,children:R}):null]}),Vt?t.jsx("p",{className:me.inlineHint,children:"Loading setup options…"}):null,Kt?t.jsx("p",{className:me.loginError,children:Kt}):null]}),!qn&&Cn&&kt&&Ca&&t.jsxs("div",{className:me.optionGroup,children:[t.jsxs("label",{className:`${me.authModeLink} ${me.optionRow}`,children:[t.jsx("input",{type:"checkbox",checked:bt,onChange:je=>W(je.target.checked),disabled:dt}),t.jsx("span",{children:"Sync to cloud after setup"})]}),t.jsx("p",{className:me.inlineHint,children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),t.jsxs("div",{className:me.authModeLinks,children:[ho?t.jsx("button",{className:p.cancelBtn,onClick:()=>{rt(null),yt(null),ot("details")},children:"Back"}):ta?t.jsx("button",{className:p.cancelBtn,onClick:()=>{rt(null),yt(null),x("/",{replace:!0})},children:"Cancel"}):Ye==="cloud"?t.jsx("button",{className:p.cancelBtn,onClick:async()=>{await Nt.logout(),x("/login",{replace:!0})},children:He("setup.signOut")}):null,Je?t.jsx("button",{className:p.submitBtn,disabled:dt||fr&&!!Xt&&!zn,onClick:async()=>{ne(!0),yt(null),rt(null);try{const je=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:gt}})}),ct=await je.json().catch(()=>({}));!je.ok||ct?.success===!1?rt(ct?.error||He("setup.saveFailedWithStatus",{status:je.status})):(yt(He("setup.globalSetupSaved")),await kn())}catch{rt(He("setup.saveFailed"))}finally{ne(!1)}},children:He(dt?"setup.saving":"setup.saveGlobalSetup")}):q?t.jsx("button",{className:p.submitBtn,disabled:dt,onClick:kn,children:He("setup.retrySetupCheck")}):t.jsx("button",{className:p.submitBtn,disabled:dt||fr&&!Xt&&!kt,onClick:async()=>{if(fr&&Xt){if(!zn)return;ne(!0),yt(`Retrying import for ${Xt.name}...`),rt(null);try{await Cr()}catch{yt(null),rt(`Failed to retry import for "${Xt.name}".`)}finally{ne(!1)}return}if(pr){if(!Cn){rt("Cloud workspace sync is unavailable right now."),ne(!1);return}if(!kt){rt("Sign in is required before syncing a cloud project."),ne(!1);return}const je=de.find(Y=>Y.id===St);if(!je){rt("Select a cloud project to sync."),ne(!1);return}const ct=await Rn({workspaceId:je.id,name:je.name||je.id,description:je.description||void 0});if(!ct.success){rt(ct.error||He("setup.saveWorkspaceFailed")),ne(!1);return}const nt=String(ct.workspaceId||je.id||"").trim();if(!nt){rt("Failed to resolve workspace id for sync setup."),ne(!1);return}try{await ba(nt,{version:2,enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null})}catch(Y){rt(Y instanceof Error?Y.message:"Failed to configure workspace sync."),ne(!1);return}In({enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null}),await kn(),Ne({workspaceId:nt,name:je.name||je.id}),Pe(!1),yt(`Importing ${je.name||je.id} from cloud...`),ne(!1);return}if(Ca){if(!Rt.trim()){rt("Workspace name is required before continuing.");return}rt(null),yt(null),ot("library");return}ne(!0),yt(null),rt(null);{const je=ta||Et?.workspaceSetupState==="missing",ct=ta||Ot&&je,nt=ct?await Dr(Rt,Dt||void 0):null,Y=ct?null:await Rn({workspaceId:je?void 0:Et?.workspaceId,name:Rt,description:Dt}),zs=nt||Y;if(!zs?.success)rt(zs?.error||He("setup.saveWorkspaceFailed"));else{const ar=String(nt?.workspace?.id||Y?.workspaceId||Et?.workspaceId||"").trim();if(!ar){rt("Failed to resolve workspace id for setup."),ne(!1);return}if(Me==="local"&&!!un&&(Ft.categories||Ft.types||Ft.priorities)&&un){const Xr=await Lr.onApplySystemTaxonomyPack({pack:un,sections:Ft,remapExistingValuesToDefault:!0,workspaceIdOverride:ar});if(!Xr?.success){rt(Xr?.error||"Failed to apply setup library."),ne(!1);return}}const Ba=!!(!qn&&bt&&Cn&&kt),rr=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:ar,stateKey:"workspace-sync",patch:{version:2,enabled:Ba,phase:Ba?"provision-local":"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),sr=await rr.json().catch(()=>({}));if(!rr.ok||sr?.success===!1){rt(sr?.error||`Failed to configure workspace sync (${rr.status})`),ne(!1);return}In({enabled:Ba,phase:Ba?"provision-local":"idle",setupIntent:null,pullCursor:null}),yt(Ba?`${Nn} setup saved. Cloud sync enabled.`:He("setup.workspaceSetupSaved",{workspaceLabel:Nn})),ta&&(await kn(),await ya(!0),x("/",{replace:!0}))}}ne(!1)},children:E})]})]})})})}return t.jsx(nF,{...Nt,onHeaderMouseDown:s,isDragging:o,onClose:c})}function rF(e){return Lk()?t.jsx(Fh,{...e}):t.jsx(Bk,{children:t.jsx(Fh,{...e})})}const xy={},Oh="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=Oh,console.info(`[Taskforce] Build marker: ${Oh}`));function sF(){if(typeof window<"u"){const n=window.location.hostname.toLowerCase();if(n==="localhost"||n==="127.0.0.1"||n==="::1")return}return Jp(xy).apiBaseUrl||void 0}function oF(e){const n=Jp(xy),a=n.cloudAuthBaseUrl;if(a)if(typeof window<"u"){const s=window.location.hostname.toLowerCase(),o=s==="localhost"||s==="127.0.0.1"||s==="::1",c="".trim().toLowerCase()==="true";if(!o&&!c)try{const i=new URL(a,window.location.origin);if(i.origin!==window.location.origin)console.warn(`[Taskforce] Ignoring cross-origin cloud auth base in hosted runtime: ${i.origin}`);else return a}catch{}else return a}else return a;if(n.baseUrl)return n.baseUrl;if(e)return e}function iF(){const e=sF(),n=oF(e);return t.jsx(Wk,{children:t.jsx(rF,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:n}})})}Zy.createRoot(document.getElementById("root")).render(t.jsx(pt.StrictMode,{children:t.jsx(iF,{})}));export{vF as A,s1 as B,q2 as C,Dc as D,d1 as E,ML as F,Yp as G,Fp as H,Uc as I,Ch as J,Ah as K,R2 as L,As as M,z2 as N,bF as P,Fg as R,Ql as T,dm as a,Mr as b,xS as c,Zk as d,Ht as e,fF as f,qu as g,CP as h,Mb as i,wF as j,AP as k,Lg as l,FM as m,qe as n,US as o,Cg as p,Hu as q,Ra as r,Gu as s,p as t,Ag as u,yF as v,hF as w,kF as x,gF as y,SF as z};