@taskforcehq/taskforce 0.3.170 → 0.3.301

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 (698) hide show
  1. package/README.md +71 -21
  2. package/dist/Taskforce.module.css +3394 -5981
  3. package/dist/TaskforceCore.CategoryFallback.test.js +5 -2
  4. package/dist/TaskforceCore.filter-persistence.test.js +402 -0
  5. package/dist/TaskforceCore.js +388 -71
  6. package/dist/TaskforceCore.routing.test.js +311 -0
  7. package/dist/TaskforceCore.test.js +3344 -615
  8. package/dist/TaskforceWidget.js +3 -2
  9. package/dist/__tests__/localizationCatalogs.test.js +48 -31
  10. package/dist/__tests__/workflowSimulation.test.js +2 -2
  11. package/dist/annotatedAttachments/AnnotatedAttachmentSessionStore.d.ts +60 -0
  12. package/dist/annotatedAttachments/AnnotatedAttachmentSessionStore.js +324 -0
  13. package/dist/annotatedAttachments/AnnotatedAttachmentSessionStore.test.js +278 -0
  14. package/dist/annotatedAttachments/payload.d.ts +2 -0
  15. package/dist/annotatedAttachments/payload.js +54 -0
  16. package/dist/annotatedAttachments/payload.test.js +67 -0
  17. package/dist/annotatedAttachments/service.d.ts +49 -0
  18. package/dist/annotatedAttachments/service.js +121 -0
  19. package/dist/annotatedAttachments/types.d.ts +86 -0
  20. package/dist/cli.js +74 -25
  21. package/dist/compat/deploymentCompat.d.ts +12 -0
  22. package/dist/compat/deploymentCompat.js +43 -0
  23. package/dist/compat/workspaceSyncCompat.d.ts +6 -0
  24. package/dist/compat/workspaceSyncCompat.js +79 -0
  25. package/dist/compat/workspaceSyncCompat.test.js +87 -0
  26. package/dist/components/features/AgentsModule.d.ts +5 -0
  27. package/dist/components/features/AgentsModule.js +131 -0
  28. package/dist/components/features/AgentsModule.test.js +102 -0
  29. package/dist/components/features/AnnotatedAttachmentWorkspace.d.ts +24 -0
  30. package/dist/components/features/AnnotatedAttachmentWorkspace.js +1942 -0
  31. package/dist/components/features/AnnotatedAttachmentWorkspace.test.js +2831 -0
  32. package/dist/components/features/DocumentGenerateModal.js +8 -16
  33. package/dist/components/features/DocumentIndex.d.ts +3 -4
  34. package/dist/components/features/DocumentIndex.js +22 -10
  35. package/dist/components/features/DocumentViewer.d.ts +6 -2
  36. package/dist/components/features/DocumentViewer.js +1000 -18
  37. package/dist/components/features/DocumentWorkspace.d.ts +40 -2
  38. package/dist/components/features/DocumentWorkspace.js +96 -16
  39. package/dist/components/features/DocumentWorkspace.test.js +1202 -0
  40. package/dist/components/features/InitiativesModule.d.ts +22 -0
  41. package/dist/components/features/InitiativesModule.js +33 -0
  42. package/dist/components/features/TaskSettings.d.ts +41 -32
  43. package/dist/components/features/TaskSettings.js +798 -313
  44. package/dist/components/features/TaskSettings.test.js +1221 -47
  45. package/dist/components/features/WorkflowsModule.d.ts +27 -0
  46. package/dist/components/features/WorkflowsModule.js +21 -0
  47. package/dist/components/features/documentWorkspaceFilters.d.ts +10 -0
  48. package/dist/components/features/documentWorkspaceFilters.js +11 -0
  49. package/dist/components/features/settings/CategoryManager.d.ts +2 -0
  50. package/dist/components/features/settings/CategoryManager.js +15 -8
  51. package/dist/components/features/settings/PriorityManager.d.ts +18 -0
  52. package/dist/components/features/settings/PriorityManager.js +51 -0
  53. package/dist/components/features/settings/TaxonomyEditor.d.ts +2 -1
  54. package/dist/components/features/settings/TaxonomyEditor.js +41 -18
  55. package/dist/components/features/settings/TaxonomyLibraryManager.d.ts +26 -0
  56. package/dist/components/features/settings/TaxonomyLibraryManager.js +301 -0
  57. package/dist/components/features/settings/TaxonomyLibraryManager.test.js +141 -0
  58. package/dist/components/features/settings/TaxonomyManager.d.ts +35 -12
  59. package/dist/components/features/settings/TaxonomyManager.js +59 -27
  60. package/dist/components/features/settings/TypeManager.d.ts +11 -0
  61. package/dist/components/features/settings/TypeManager.js +48 -11
  62. package/dist/components/features/settings/{WorkflowEditorPrototype.d.ts → WorkflowEditor.d.ts} +2 -2
  63. package/dist/components/features/settings/{WorkflowEditorPrototype.js → WorkflowEditor.js} +3 -3
  64. package/dist/components/task/TaskActionHeader.d.ts +12 -2
  65. package/dist/components/task/TaskActionHeader.js +64 -8
  66. package/dist/components/task/TaskActionHeader.test.js +73 -0
  67. package/dist/components/task/TaskCard.d.ts +14 -16
  68. package/dist/components/task/TaskCard.js +144 -174
  69. package/dist/components/task/TaskCard.test.js +416 -64
  70. package/dist/components/task/TaskContextUpload.d.ts +6 -5
  71. package/dist/components/task/TaskContextUpload.js +199 -64
  72. package/dist/components/task/TaskContextUpload.test.js +331 -14
  73. package/dist/components/task/TaskForm.d.ts +23 -29
  74. package/dist/components/task/TaskForm.js +348 -169
  75. package/dist/components/task/TaskForm.test.js +419 -23
  76. package/dist/components/task/TaskKanban.d.ts +20 -21
  77. package/dist/components/task/TaskKanban.js +176 -316
  78. package/dist/components/task/TaskKanban.planning-drop.test.js +93 -0
  79. package/dist/components/task/TaskList.d.ts +22 -11
  80. package/dist/components/task/TaskList.js +98 -12
  81. package/dist/components/task/TaskList.test.js +206 -7
  82. package/dist/components/task/TaskReferenceBadge.d.ts +12 -0
  83. package/dist/components/task/TaskReferenceBadge.js +5 -0
  84. package/dist/components/task/TaskStatusActions.d.ts +12 -0
  85. package/dist/components/task/TaskStatusActions.js +18 -0
  86. package/dist/components/task/TaskStatusActions.test.js +45 -0
  87. package/dist/components/ui/ImageReferenceBadge.d.ts +12 -0
  88. package/dist/components/ui/ImageReferenceBadge.js +5 -0
  89. package/dist/components/ui/LevelSelector.d.ts +2 -1
  90. package/dist/components/ui/LevelSelector.js +2 -2
  91. package/dist/components/ui/Markdown.d.ts +1 -2
  92. package/dist/components/ui/Markdown.js +2 -13
  93. package/dist/components/ui/Modal.d.ts +3 -2
  94. package/dist/components/ui/Modal.js +4 -3
  95. package/dist/components/ui/MultiSelectFilter.d.ts +3 -1
  96. package/dist/components/ui/MultiSelectFilter.js +2 -2
  97. package/dist/components/ui/ReferenceBadgeButton.d.ts +13 -0
  98. package/dist/components/ui/ReferenceBadgeButton.js +6 -0
  99. package/dist/components/ui/TaxonomyDropdown.d.ts +7 -1
  100. package/dist/components/ui/TaxonomyDropdown.js +58 -23
  101. package/dist/components/ui/TopNoticeLayer.d.ts +7 -0
  102. package/dist/components/ui/TopNoticeLayer.js +14 -0
  103. package/dist/components/ui/TopNoticeLayer.test.js +25 -0
  104. package/dist/components/views/AppShellHeader.d.ts +13 -0
  105. package/dist/components/views/AppShellHeader.js +19 -0
  106. package/dist/components/views/AppShellHeader.test.js +21 -0
  107. package/dist/components/views/PlanComparisonPage.d.ts +73 -0
  108. package/dist/components/views/PlanComparisonPage.js +196 -0
  109. package/dist/components/views/PlanComparisonPage.test.js +251 -0
  110. package/dist/components/views/PlansPage.d.ts +14 -0
  111. package/dist/components/views/PlansPage.js +355 -0
  112. package/dist/components/views/StandaloneLayout.d.ts +2 -2
  113. package/dist/components/views/StandaloneLayout.js +2227 -1188
  114. package/dist/components/views/WidgetView.d.ts +2 -2
  115. package/dist/components/views/WidgetView.js +149 -43
  116. package/dist/components/views/chrome/WorkspaceChromeSections.d.ts +57 -0
  117. package/dist/components/views/chrome/WorkspaceChromeSections.js +38 -0
  118. package/dist/components/views/chrome/WorkspaceChromeSections.test.js +54 -0
  119. package/dist/components/views/chrome/workspaceChrome.d.ts +31 -0
  120. package/dist/components/views/chrome/workspaceChrome.js +108 -0
  121. package/dist/components/views/chrome/workspaceChrome.test.js +52 -0
  122. package/dist/components/views/panels/DocumentFilterToolbar.d.ts +10 -0
  123. package/dist/components/views/panels/DocumentFilterToolbar.js +7 -0
  124. package/dist/components/views/panels/DocumentFilterToolbar.test.js +19 -0
  125. package/dist/components/views/panels/FilterToolbar.d.ts +68 -0
  126. package/dist/components/views/panels/FilterToolbar.js +21 -0
  127. package/dist/components/views/panels/FilterToolbar.test.d.ts +1 -0
  128. package/dist/components/views/panels/FilterToolbar.test.js +45 -0
  129. package/dist/components/views/panels/FilterToolbarControls.d.ts +47 -0
  130. package/dist/components/views/panels/FilterToolbarControls.js +61 -0
  131. package/dist/components/views/panels/PlanningDrawer.d.ts +115 -0
  132. package/dist/components/views/panels/PlanningDrawer.js +220 -0
  133. package/dist/components/views/panels/ScheduleSidebar.d.ts +52 -0
  134. package/dist/components/views/panels/ScheduleSidebar.js +127 -0
  135. package/dist/components/views/panels/scheduleUtils.d.ts +14 -0
  136. package/dist/components/views/panels/scheduleUtils.js +79 -0
  137. package/dist/components/views/teamManagementAccess.d.ts +6 -0
  138. package/dist/components/views/teamManagementAccess.js +18 -0
  139. package/dist/components/views/teamManagementAccess.test.d.ts +1 -0
  140. package/dist/components/views/teamManagementAccess.test.js +44 -0
  141. package/dist/config/clientDeployment.d.ts +2 -0
  142. package/dist/config/clientDeployment.js +13 -0
  143. package/dist/config/cloudEnvironment.d.ts +15 -0
  144. package/dist/config/cloudEnvironment.js +60 -0
  145. package/dist/config/deployment.d.ts +20 -0
  146. package/dist/config/deployment.js +67 -0
  147. package/dist/config/deployment.test.d.ts +1 -0
  148. package/dist/config/deployment.test.js +88 -0
  149. package/dist/config/envSchema.js +36 -8
  150. package/dist/config/envSchema.test.js +28 -0
  151. package/dist/core/AiProfileService.d.ts +66 -0
  152. package/dist/core/AiProfileService.js +320 -0
  153. package/dist/core/AiProfileService.test.d.ts +1 -0
  154. package/dist/core/AiProfileService.test.js +164 -0
  155. package/dist/core/AiProfiles.test.d.ts +1 -0
  156. package/dist/core/AiProfiles.test.js +449 -0
  157. package/dist/core/AttachmentLinkService.d.ts +15 -0
  158. package/dist/core/AttachmentLinkService.js +157 -0
  159. package/dist/core/AuthTokenService.d.ts +44 -0
  160. package/dist/core/AuthTokenService.js +207 -0
  161. package/dist/core/CreatedBy.test.js +134 -6
  162. package/dist/core/DeletedTaskLifecycleService.d.ts +33 -0
  163. package/dist/core/DeletedTaskLifecycleService.js +158 -0
  164. package/dist/core/DeletedTaskTrash.test.d.ts +1 -0
  165. package/dist/core/DeletedTaskTrash.test.js +104 -0
  166. package/dist/core/EntitlementsPolicy.test.js +78 -5
  167. package/dist/core/GlobalSettingsService.d.ts +16 -0
  168. package/dist/core/GlobalSettingsService.js +370 -0
  169. package/dist/core/JsonBackupRuntime.test.d.ts +1 -0
  170. package/dist/core/JsonBackupRuntime.test.js +155 -0
  171. package/dist/core/McpTokenService.d.ts +118 -0
  172. package/dist/core/McpTokenService.js +921 -0
  173. package/dist/core/PlanEntitlementService.d.ts +201 -0
  174. package/dist/core/PlanEntitlementService.js +1442 -0
  175. package/dist/core/PlanVersionPolicy.test.d.ts +1 -0
  176. package/dist/core/PlanVersionPolicy.test.js +178 -0
  177. package/dist/core/PlanningEntities.test.d.ts +1 -0
  178. package/dist/core/PlanningEntities.test.js +95 -0
  179. package/dist/core/ScheduleFields.test.js +15 -19
  180. package/dist/core/SignupMonetizationSettings.test.d.ts +1 -0
  181. package/dist/core/SignupMonetizationSettings.test.js +159 -0
  182. package/dist/core/Stats.test.d.ts +1 -0
  183. package/dist/core/Stats.test.js +36 -0
  184. package/dist/core/SyncReconciliationService.d.ts +93 -0
  185. package/dist/core/SyncReconciliationService.js +406 -0
  186. package/dist/core/SystemAdmin.test.js +578 -13
  187. package/dist/core/TaskActivityService.d.ts +21 -0
  188. package/dist/core/TaskActivityService.js +130 -0
  189. package/dist/core/TaskAttachmentsCanonical.test.d.ts +1 -0
  190. package/dist/core/TaskAttachmentsCanonical.test.js +306 -0
  191. package/dist/core/TaskAuditTimeline.test.d.ts +1 -0
  192. package/dist/core/TaskAuditTimeline.test.js +132 -0
  193. package/dist/core/TaskTaxonomyValidation.test.js +338 -15
  194. package/dist/core/Taskforce.d.ts +930 -183
  195. package/dist/core/Taskforce.ids.test.js +252 -0
  196. package/dist/core/Taskforce.js +3848 -2532
  197. package/dist/core/Taskforce.mcpAuth.test.d.ts +1 -0
  198. package/dist/core/Taskforce.mcpAuth.test.js +343 -0
  199. package/dist/core/Taskforce.realtimeMutation.test.js +57 -2
  200. package/dist/core/TaxonomySettingsService.d.ts +18 -0
  201. package/dist/core/TaxonomySettingsService.js +162 -0
  202. package/dist/core/WorkspaceDelete.test.js +32 -13
  203. package/dist/core/WorkspaceLifecycleService.d.ts +11 -0
  204. package/dist/core/WorkspaceLifecycleService.js +88 -0
  205. package/dist/core/WorkspacePermissions.test.js +95 -0
  206. package/dist/core/WorkspacePlanMode.test.js +114 -1
  207. package/dist/core/WorkspacePreferenceService.d.ts +41 -0
  208. package/dist/core/WorkspacePreferenceService.js +246 -0
  209. package/dist/core/WorkspaceSyncSettings.test.d.ts +1 -0
  210. package/dist/core/WorkspaceSyncSettings.test.js +65 -0
  211. package/dist/core/__tests__/TaskAttachmentsCanonical.test.d.ts +1 -0
  212. package/dist/core/__tests__/TaskAttachmentsCanonical.test.js +212 -0
  213. package/dist/core/shared.d.ts +36 -0
  214. package/dist/core/shared.js +128 -0
  215. package/dist/core/types.d.ts +614 -0
  216. package/dist/core/types.js +27 -0
  217. package/dist/documentReviews/DocumentReviewCommentStore.d.ts +56 -0
  218. package/dist/documentReviews/DocumentReviewCommentStore.js +230 -0
  219. package/dist/documentReviews/DocumentReviewSessionStore.d.ts +52 -0
  220. package/dist/documentReviews/DocumentReviewSessionStore.js +193 -0
  221. package/dist/documentReviews/DocumentReviewSessionStore.test.d.ts +1 -0
  222. package/dist/documentReviews/DocumentReviewSessionStore.test.js +127 -0
  223. package/dist/documentReviews/service.d.ts +68 -0
  224. package/dist/documentReviews/service.js +210 -0
  225. package/dist/documentReviews/types.d.ts +58 -0
  226. package/dist/documentReviews/types.js +1 -0
  227. package/dist/hooks/auth/useAuthGuardPolicy.d.ts +2 -0
  228. package/dist/hooks/auth/useAuthGuardPolicy.js +1 -0
  229. package/dist/hooks/tasks/useCurrentTaskRelations.d.ts +15 -0
  230. package/dist/hooks/tasks/useCurrentTaskRelations.js +37 -0
  231. package/dist/hooks/tasks/useTaskActions.d.ts +3 -0
  232. package/dist/hooks/tasks/useTaskActions.js +2 -0
  233. package/dist/hooks/tasks/useTaskEditorNavigation.d.ts +65 -0
  234. package/dist/hooks/tasks/useTaskEditorNavigation.js +235 -0
  235. package/dist/hooks/tasks/useTaskFilters.d.ts +2 -0
  236. package/dist/hooks/tasks/useTaskFilters.js +2 -0
  237. package/dist/hooks/tasks/useTaskFormActions.d.ts +58 -0
  238. package/dist/hooks/tasks/useTaskFormActions.js +365 -0
  239. package/dist/hooks/tasks/useTaskRelationships.d.ts +16 -0
  240. package/dist/hooks/tasks/useTaskRelationships.js +64 -0
  241. package/dist/hooks/ui/useResourceExport.d.ts +19 -0
  242. package/dist/hooks/ui/useResourceExport.js +84 -0
  243. package/dist/hooks/ui/useSettingsModel.d.ts +203 -0
  244. package/dist/hooks/ui/useSettingsModel.js +125 -0
  245. package/dist/hooks/ui/useSettingsPersistence.d.ts +36 -0
  246. package/dist/hooks/ui/useSettingsPersistence.js +254 -0
  247. package/dist/hooks/ui/useSettingsTaxonomyManagement.d.ts +119 -0
  248. package/dist/hooks/ui/useSettingsTaxonomyManagement.js +536 -0
  249. package/dist/hooks/ui/useUiNotice.d.ts +1 -0
  250. package/dist/hooks/ui/useUiNotice.js +1 -0
  251. package/dist/hooks/ui/useWorkflowTemplates.d.ts +37 -0
  252. package/dist/hooks/ui/useWorkflowTemplates.js +111 -0
  253. package/dist/hooks/ui/useZenMode.d.ts +5 -0
  254. package/dist/hooks/ui/useZenMode.js +32 -0
  255. package/dist/hooks/useFilterSort.d.ts +60 -0
  256. package/dist/hooks/useFilterSort.js +362 -0
  257. package/dist/hooks/useFilterSort.test.d.ts +1 -0
  258. package/dist/hooks/useFilterSort.test.js +333 -0
  259. package/dist/hooks/useRealtimeSync.d.ts +1 -0
  260. package/dist/hooks/useRealtimeSync.js +24 -9
  261. package/dist/hooks/useRealtimeSync.test.js +28 -1
  262. package/dist/hooks/useSyncOrchestrator.aiProfiles.test.d.ts +1 -0
  263. package/dist/hooks/useSyncOrchestrator.aiProfiles.test.js +34 -0
  264. package/dist/hooks/useSyncOrchestrator.d.ts +65 -103
  265. package/dist/hooks/useSyncOrchestrator.js +1538 -670
  266. package/dist/hooks/useSyncOrchestrator.retry-closure.test.js +700 -174
  267. package/dist/hooks/useTaskData.d.ts +35 -0
  268. package/dist/hooks/useTaskData.js +243 -0
  269. package/dist/hooks/useTaskData.test.d.ts +1 -0
  270. package/dist/hooks/useTaskData.test.js +180 -0
  271. package/dist/hooks/useTaskMutations.d.ts +46 -0
  272. package/dist/hooks/useTaskMutations.js +472 -0
  273. package/dist/hooks/useTaskMutations.test.d.ts +1 -0
  274. package/dist/hooks/useTaskMutations.test.js +80 -0
  275. package/dist/hooks/useTaskforce.contract.test.d.ts +1 -0
  276. package/dist/hooks/useTaskforce.contract.test.js +7 -0
  277. package/dist/hooks/useTaskforce.d.ts +260 -295
  278. package/dist/hooks/useTaskforce.js +1954 -2623
  279. package/dist/hooks/useTaskforce.priority-filters.test.js +6 -11
  280. package/dist/hooks/useTaskforce.sync-behavior.test.d.ts +1 -0
  281. package/dist/hooks/useTaskforce.sync-behavior.test.js +1120 -0
  282. package/dist/hooks/useUiNotice.d.ts +16 -0
  283. package/dist/hooks/useUiNotice.js +49 -0
  284. package/dist/hooks/useWorkspaceSyncController.d.ts +23 -46
  285. package/dist/hooks/useWorkspaceSyncController.js +280 -461
  286. package/dist/hooks/useWorkspaceSyncController.test.js +106 -199
  287. package/dist/hooks/workspace/useTaskforceApiRouting.d.ts +8 -0
  288. package/dist/hooks/workspace/useTaskforceApiRouting.js +91 -0
  289. package/dist/hooks/workspace/useTaskforceApiRouting.test.d.ts +1 -0
  290. package/dist/hooks/workspace/useTaskforceApiRouting.test.js +60 -0
  291. package/dist/hooks/workspace/useWorkspaceSyncController.d.ts +1 -0
  292. package/dist/hooks/workspace/useWorkspaceSyncController.js +1 -0
  293. package/dist/hooks/workspace/workspaceLocalState.d.ts +30 -0
  294. package/dist/hooks/workspace/workspaceLocalState.js +101 -0
  295. package/dist/localization/locales/en-US.d.ts +1 -8
  296. package/dist/localization/locales/en-US.js +4 -11
  297. package/dist/localization/locales/es-419.js +2 -9
  298. package/dist/localization/locales/pt-BR.js +2 -9
  299. package/dist/localization/localizationCatalogs.test.d.ts +1 -0
  300. package/dist/localization/localizationCatalogs.test.js +37 -0
  301. package/dist/main.d.ts +1 -0
  302. package/dist/main.js +9 -15
  303. package/dist/mcp/clientIntegrations.d.ts +33 -0
  304. package/dist/mcp/clientIntegrations.js +199 -0
  305. package/dist/mcp/clientIntegrations.test.d.ts +1 -0
  306. package/dist/mcp/clientIntegrations.test.js +110 -0
  307. package/dist/mcp/index.d.ts +2 -0
  308. package/dist/mcp/index.js +2 -0
  309. package/dist/mcp/optionResolution.test.js +6 -2
  310. package/dist/mcp/runtime.d.ts +120 -0
  311. package/dist/mcp/runtime.js +5668 -0
  312. package/dist/mcp/runtime.test.d.ts +1 -0
  313. package/dist/mcp/runtime.test.js +3299 -0
  314. package/dist/mcp/server.js +2 -1793
  315. package/dist/mcp/structuredCommentValidation.test.d.ts +1 -0
  316. package/dist/{__tests__ → mcp}/structuredCommentValidation.test.js +1 -1
  317. package/dist/mcp/structuredDocValidation.js +1 -2
  318. package/dist/mcp/structuredDocValidation.test.d.ts +1 -0
  319. package/dist/{__tests__ → mcp}/structuredDocValidation.test.js +9 -4
  320. package/dist/mcp/toolRegistry.d.ts +570 -0
  321. package/dist/mcp/toolRegistry.js +90 -0
  322. package/dist/mcp/toolRegistry.test.d.ts +1 -0
  323. package/dist/mcp/toolRegistry.test.js +30 -0
  324. package/dist/migrations/billingSchemaParity.test.js +111 -0
  325. package/dist/migrations/taskSchemaMigrations.d.ts +5 -0
  326. package/dist/migrations/taskSchemaMigrations.js +681 -39
  327. package/dist/migrations/taskSchemaMigrations.test.d.ts +1 -0
  328. package/dist/migrations/taskSchemaMigrations.test.js +210 -0
  329. package/dist/plugins/vite.js +13 -7
  330. package/dist/public/apple-touch-icon.png +0 -0
  331. package/dist/public/archive/phoenix/apple-touch-icon.png +0 -0
  332. package/dist/public/archive/phoenix/favicon.ico +0 -0
  333. package/dist/public/archive/phoenix/site.webmanifest +1 -0
  334. package/dist/public/favicon-96x96.png +0 -0
  335. package/dist/public/favicon.ico +0 -0
  336. package/dist/public/favicon.svg +17 -0
  337. package/dist/public/site.webmanifest +21 -1
  338. package/dist/public/web-app-manifest-192x192.png +0 -0
  339. package/dist/public/web-app-manifest-512x512.png +0 -0
  340. package/dist/releaseVersion.test.d.ts +1 -0
  341. package/dist/{__tests__/releaseVersion.test.js → releaseVersion.test.js} +1 -1
  342. package/dist/resources/templates/WORKFLOW_V2_POLICY.md +1 -1
  343. package/dist/resources/templates/workflow-sources/workflowDocs.mjs +62 -52
  344. package/dist/resources/templates/workflows/collaborate.yaml +11 -5
  345. package/dist/resources/templates/workflows/do.yaml +8 -2
  346. package/dist/resources/templates/workflows/evaluate.yaml +13 -7
  347. package/dist/resources/templates/workflows/execute.yaml +40 -23
  348. package/dist/resources/templates/workflows/plan.yaml +15 -8
  349. package/dist/resources/templates/workflows/review.yaml +14 -8
  350. package/dist/runtime/appGateDefinitions.d.ts +32 -0
  351. package/dist/runtime/appGateDefinitions.js +32 -0
  352. package/dist/runtime/appGates.d.ts +29 -0
  353. package/dist/runtime/appGates.js +53 -0
  354. package/dist/runtime/appGates.test.d.ts +1 -0
  355. package/dist/runtime/appGates.test.js +42 -0
  356. package/dist/runtime/migrationFlags.d.ts +1 -0
  357. package/dist/runtime/migrationFlags.js +1 -0
  358. package/dist/server/annotatedAttachmentsRoutes.test.d.ts +1 -0
  359. package/dist/server/annotatedAttachmentsRoutes.test.js +473 -0
  360. package/dist/server/auth.js +14 -2
  361. package/dist/server/auth.test.js +21 -1
  362. package/dist/server/cors.js +11 -5
  363. package/dist/server/cors.test.js +6 -0
  364. package/dist/server/documentReviewRoutes.test.d.ts +1 -0
  365. package/dist/server/documentReviewRoutes.test.js +157 -0
  366. package/dist/server/index.cookieProxy.test.js +46 -1
  367. package/dist/server/index.d.ts +20 -0
  368. package/dist/server/index.js +168 -41
  369. package/dist/server/index.rateLimit.test.js +6 -0
  370. package/dist/server/index.test.js +133 -2
  371. package/dist/server/mockStripe.d.ts +72 -0
  372. package/dist/server/mockStripe.js +357 -0
  373. package/dist/server/realtimeSyncWs.js +4 -0
  374. package/dist/server/routes/admin.d.ts +114 -0
  375. package/dist/server/routes/admin.js +2226 -0
  376. package/dist/server/routes/annotatedAttachments.d.ts +24 -0
  377. package/dist/server/routes/annotatedAttachments.js +235 -0
  378. package/dist/server/routes/auth.d.ts +61 -0
  379. package/dist/server/routes/auth.js +1296 -0
  380. package/dist/server/{routes.billing.d.ts → routes/billing.d.ts} +3 -2
  381. package/dist/server/routes/billing.js +2001 -0
  382. package/dist/server/routes/billing.test.d.ts +1 -0
  383. package/dist/server/routes/billing.test.js +1631 -0
  384. package/dist/server/routes/documentReviews.d.ts +11 -0
  385. package/dist/server/routes/documentReviews.js +191 -0
  386. package/dist/server/routes/documents.d.ts +118 -0
  387. package/dist/server/routes/documents.js +1113 -0
  388. package/dist/server/routes/resources.d.ts +25 -0
  389. package/dist/server/routes/resources.js +225 -0
  390. package/dist/server/routes/shared.d.ts +35 -0
  391. package/dist/server/routes/shared.js +305 -0
  392. package/dist/server/routes/shared.test.d.ts +1 -0
  393. package/dist/server/routes/shared.test.js +32 -0
  394. package/dist/server/{routes.sync.d.ts → routes/sync.d.ts} +5 -5
  395. package/dist/server/routes/sync.integration.test.d.ts +1 -0
  396. package/dist/server/routes/sync.integration.test.js +2003 -0
  397. package/dist/server/routes/sync.js +3143 -0
  398. package/dist/server/routes/tasks.d.ts +72 -0
  399. package/dist/server/routes/tasks.js +1252 -0
  400. package/dist/server/routes/workspaces.d.ts +32 -0
  401. package/dist/server/routes/workspaces.js +307 -0
  402. package/dist/server/routes.d.ts +8 -9
  403. package/dist/server/routes.js +968 -4092
  404. package/dist/server/routes.test.js +9043 -2415
  405. package/dist/server/runtimeMode.d.ts +1 -1
  406. package/dist/server/runtimeMode.js +3 -18
  407. package/dist/server/runtimeMode.test.js +3 -3
  408. package/dist/server/securityHeaders.d.ts +1 -1
  409. package/dist/server/securityHeaders.js +65 -6
  410. package/dist/server/securityHeaders.test.js +40 -2
  411. package/dist/services/templateEngine.test.d.ts +1 -0
  412. package/dist/{__tests__ → services}/templateEngine.test.js +1 -1
  413. package/dist/services/templates.test.d.ts +1 -0
  414. package/dist/{__tests__ → services}/templates.test.js +1 -1
  415. package/dist/services/workflowDocumentFixtures.test.d.ts +1 -0
  416. package/dist/{__tests__ → services}/workflowDocumentFixtures.test.js +4 -4
  417. package/dist/services/workflowExportMatrix.test.d.ts +1 -0
  418. package/dist/{__tests__ → services}/workflowExportMatrix.test.js +1 -1
  419. package/dist/services/workflowExportSnapshots.test.d.ts +1 -0
  420. package/dist/services/workflowGeneration.test.d.ts +1 -0
  421. package/dist/services/workflowSimulation.test.d.ts +1 -0
  422. package/dist/services/workflowSimulation.test.js +113 -0
  423. package/dist/services/workflowV2Policy.test.d.ts +1 -0
  424. package/dist/{__tests__ → services}/workflowV2Policy.test.js +2 -2
  425. package/dist/shared/aiProfileSurfaceType.d.ts +9 -0
  426. package/dist/shared/aiProfileSurfaceType.js +49 -0
  427. package/dist/shared/customTaxonomyLibrary.d.ts +11 -0
  428. package/dist/shared/customTaxonomyLibrary.js +276 -0
  429. package/dist/shared/customTaxonomyLibrary.test.d.ts +1 -0
  430. package/dist/shared/customTaxonomyLibrary.test.js +20 -0
  431. package/dist/shared/taxonomyCatalog.d.ts +19 -0
  432. package/dist/shared/taxonomyCatalog.js +36 -0
  433. package/dist/shared/taxonomyDefaults.d.ts +29 -0
  434. package/dist/shared/taxonomyDefaults.js +26 -0
  435. package/dist/shared/taxonomyLibrary.d.ts +15 -0
  436. package/dist/shared/taxonomyLibrary.js +98 -0
  437. package/dist/shared/taxonomyLibrary.test.d.ts +1 -0
  438. package/dist/shared/taxonomyLibrary.test.js +26 -0
  439. package/dist/shared/taxonomyState.d.ts +36 -0
  440. package/dist/shared/taxonomyState.js +73 -0
  441. package/dist/shared/taxonomyState.test.d.ts +1 -0
  442. package/dist/shared/taxonomyState.test.js +71 -0
  443. package/dist/shared/workflowDefaults.d.ts +9 -0
  444. package/dist/shared/workflowDefaults.js +11 -0
  445. package/dist/storage/documentIntegrity.d.ts +2 -0
  446. package/dist/storage/documentIntegrity.js +34 -17
  447. package/dist/storage/documentPurge.d.ts +2 -1
  448. package/dist/storage/documentPurge.js +35 -8
  449. package/dist/storage/index.d.ts +4 -0
  450. package/dist/storage/index.js +2 -0
  451. package/dist/storage/objectStorage.d.ts +1 -1
  452. package/dist/storage/objectStorageClient.d.ts +6 -4
  453. package/dist/storage/objectStorageClient.js +77 -29
  454. package/dist/storage/objectStorageClient.test.d.ts +1 -0
  455. package/dist/storage/objectStorageClient.test.js +57 -0
  456. package/dist/storage/objectStorageConfig.js +3 -1
  457. package/dist/storage/objectStorageConfig.test.d.ts +1 -0
  458. package/dist/storage/objectStorageConfig.test.js +38 -0
  459. package/dist/storage/postgresAdapter.d.ts +5 -0
  460. package/dist/storage/postgresAdapter.js +2 -2
  461. package/dist/storage/postgresAdapter.test.d.ts +1 -0
  462. package/dist/storage/postgresAdapter.test.js +29 -0
  463. package/dist/storage/taskAssetStore.d.ts +7 -4
  464. package/dist/storage/taskAssetStore.js +65 -60
  465. package/dist/storage/workspaceAssetStore.d.ts +122 -0
  466. package/dist/storage/workspaceAssetStore.js +496 -0
  467. package/dist/storage/workspaceAssetStore.test.d.ts +1 -0
  468. package/dist/storage/workspaceAssetStore.test.js +501 -0
  469. package/dist/sync/cloudSyncApi.d.ts +33 -2
  470. package/dist/sync/cloudSyncApi.js +37 -15
  471. package/dist/sync/cloudSyncApi.test.js +60 -3
  472. package/dist/sync/index.d.ts +2 -0
  473. package/dist/sync/index.js +3 -0
  474. package/dist/sync/syncService.d.ts +25 -0
  475. package/dist/sync/syncService.js +184 -16
  476. package/dist/sync/syncService.test.js +289 -25
  477. package/dist/sync/workspaceRepair.d.ts +114 -0
  478. package/dist/sync/workspaceRepair.js +566 -0
  479. package/dist/sync/workspaceSyncModel.d.ts +230 -2
  480. package/dist/sync/workspaceSyncModel.js +456 -17
  481. package/dist/sync/workspaceSyncModel.test.js +642 -0
  482. package/dist/sync/workspaceSyncState.d.ts +12 -0
  483. package/dist/sync/workspaceSyncState.js +12 -0
  484. package/dist/sync/workspaceSyncSurface.d.ts +33 -0
  485. package/dist/sync/workspaceSyncSurface.js +74 -0
  486. package/dist/types.d.ts +143 -18
  487. package/dist/types.js +9 -24
  488. package/dist/ui/assets/AgentsModule-Bdq3T1Ts.js +1 -0
  489. package/dist/ui/assets/AnnotatedAttachmentWorkspace-BaS2VwIr.css +1 -0
  490. package/dist/ui/assets/AnnotatedAttachmentWorkspace-jKUVo-PJ.js +3 -0
  491. package/dist/ui/assets/DocumentWorkspace-C_8T8oz-.css +1 -0
  492. package/dist/ui/assets/DocumentWorkspace-DuQa-uIC.js +250 -0
  493. package/dist/ui/assets/InitiativesModule-C8Pi2VTk.js +1 -0
  494. package/dist/ui/assets/PlansPage-B6BDECSi.js +1 -0
  495. package/dist/ui/assets/PlansPage-BlVC_lRq.css +1 -0
  496. package/dist/ui/assets/TaskSettings-BwB9NtmJ.css +1 -0
  497. package/dist/ui/assets/TaskSettings-DUJgRTPU.js +8 -0
  498. package/dist/ui/assets/WorkflowsModule-b6TLuHwJ.js +5 -0
  499. package/dist/ui/assets/index-BiiF1cLQ.css +1 -0
  500. package/dist/ui/assets/index-xBWLPOEb.js +6 -0
  501. package/dist/ui/assets/vendor-dnd-DRzYolkg.js +5 -0
  502. package/dist/ui/assets/{vendor-icons-ZFG3SGwo.js → vendor-icons-QZyhEwgT.js} +1 -1
  503. package/dist/ui/assets/{vendor-markdown-CKYkQHfj.js → vendor-markdown-BUxTU7dS.js} +1 -1
  504. package/dist/ui/assets/vendor-react-CKJs5o3c.js +61 -0
  505. package/dist/ui/assets/vendor-router-BbWMxlnO.js +3 -0
  506. package/dist/ui/branding/logos/logo.png +0 -0
  507. package/dist/ui/branding/logos/logo_dark.svg +27 -0
  508. package/dist/ui/branding/logos/logo_favicon.svg +35 -0
  509. package/dist/ui/branding/logos/logo_light.svg +27 -0
  510. package/dist/ui/favicon/apple-touch-icon.png +0 -0
  511. package/dist/ui/favicon/archive/phoenix/apple-touch-icon.png +0 -0
  512. package/dist/ui/favicon/archive/phoenix/favicon.ico +0 -0
  513. package/dist/ui/favicon/archive/phoenix/site.webmanifest +1 -0
  514. package/dist/ui/favicon/favicon-96x96.png +0 -0
  515. package/dist/ui/favicon/favicon.ico +0 -0
  516. package/dist/ui/favicon/favicon.svg +17 -0
  517. package/dist/ui/favicon/site.webmanifest +21 -1
  518. package/dist/ui/favicon/web-app-manifest-192x192.png +0 -0
  519. package/dist/ui/favicon/web-app-manifest-512x512.png +0 -0
  520. package/dist/ui/index.html +10 -7
  521. package/dist/ui/product/screen_01.png +0 -0
  522. package/dist/ui/product/screen_02.png +0 -0
  523. package/dist/ui/product/screen_03.png +0 -0
  524. package/dist/utils/annotatedAttachments.d.ts +20 -0
  525. package/dist/utils/annotatedAttachments.js +74 -0
  526. package/dist/utils/annotatedAttachments.test.d.ts +1 -0
  527. package/dist/utils/annotatedAttachments.test.js +108 -0
  528. package/dist/utils/assignees.d.ts +26 -0
  529. package/dist/utils/assignees.js +132 -0
  530. package/dist/utils/canonicalAssetKind.d.ts +16 -0
  531. package/dist/utils/canonicalAssetKind.js +39 -0
  532. package/dist/utils/canonicalAssetKind.test.d.ts +1 -0
  533. package/dist/utils/canonicalAssetKind.test.js +24 -0
  534. package/dist/utils/coalescedRefresh.d.ts +5 -0
  535. package/dist/utils/coalescedRefresh.js +16 -0
  536. package/dist/utils/coalescedRefresh.test.d.ts +1 -0
  537. package/dist/utils/coalescedRefresh.test.js +30 -0
  538. package/dist/utils/constants.d.ts +16 -3
  539. package/dist/utils/constants.icons.test.js +2 -1
  540. package/dist/utils/constants.js +70 -13
  541. package/dist/utils/contextAssetEvents.d.ts +7 -0
  542. package/dist/utils/contextAssetEvents.js +6 -0
  543. package/dist/utils/contextFiles.d.ts +14 -3
  544. package/dist/utils/contextFiles.js +40 -8
  545. package/dist/utils/documentManagerApi.d.ts +6 -0
  546. package/dist/utils/documentManagerApi.js +19 -0
  547. package/dist/utils/documentNames.d.ts +24 -0
  548. package/dist/utils/documentNames.js +91 -0
  549. package/dist/utils/documentReferences.d.ts +9 -0
  550. package/dist/utils/documentReferences.js +11 -0
  551. package/dist/utils/entityReferences.d.ts +9 -0
  552. package/dist/utils/entityReferences.js +32 -0
  553. package/dist/utils/imageReferences.d.ts +9 -0
  554. package/dist/utils/imageReferences.js +11 -0
  555. package/dist/utils/planParser.d.ts +2 -2
  556. package/dist/utils/planParser.js +11 -11
  557. package/dist/utils/planParser.test.d.ts +1 -0
  558. package/dist/{__tests__ → utils}/planParser.test.js +22 -22
  559. package/dist/utils/planningReferences.d.ts +17 -0
  560. package/dist/utils/planningReferences.js +30 -0
  561. package/dist/utils/planningReferences.test.d.ts +1 -0
  562. package/dist/utils/planningReferences.test.js +17 -0
  563. package/dist/utils/taskActivity.d.ts +9 -0
  564. package/dist/utils/taskActivity.js +147 -0
  565. package/dist/utils/taskActivity.test.d.ts +1 -0
  566. package/dist/utils/taskActivity.test.js +34 -0
  567. package/dist/utils/taskDraftDefaults.d.ts +21 -0
  568. package/dist/utils/taskDraftDefaults.js +40 -0
  569. package/dist/utils/taskDraftDefaults.test.d.ts +1 -0
  570. package/dist/utils/taskDraftDefaults.test.js +34 -0
  571. package/dist/utils/taskNormalization.d.ts +25 -0
  572. package/dist/utils/taskNormalization.js +161 -0
  573. package/dist/utils/taskNormalization.test.d.ts +1 -0
  574. package/dist/utils/taskNormalization.test.js +158 -0
  575. package/dist/utils/taskReferences.d.ts +5 -0
  576. package/dist/utils/taskReferences.js +11 -0
  577. package/dist/utils/taskforceApiClient.d.ts +2 -0
  578. package/dist/utils/taskforceApiClient.js +101 -3
  579. package/dist/utils/taskforceApiClient.test.d.ts +1 -0
  580. package/dist/utils/taskforceApiClient.test.js +44 -0
  581. package/dist/utils/taxonomyFilterOptions.d.ts +2 -0
  582. package/dist/utils/taxonomyFilterOptions.js +17 -0
  583. package/dist/utils/taxonomyFormDefaults.d.ts +3 -0
  584. package/dist/utils/taxonomyFormDefaults.js +28 -0
  585. package/dist/utils/taxonomyFormDefaults.test.d.ts +1 -0
  586. package/dist/utils/taxonomyFormDefaults.test.js +63 -0
  587. package/dist/utils/taxonomyLifecycle.d.ts +3 -0
  588. package/dist/utils/taxonomyLifecycle.js +17 -0
  589. package/dist/utils/taxonomySorting.d.ts +7 -0
  590. package/dist/utils/taxonomySorting.js +74 -0
  591. package/dist/utils/theme.d.ts +15 -0
  592. package/dist/utils/theme.js +23 -0
  593. package/dist/utils/uiNotice.d.ts +7 -0
  594. package/dist/utils/uiNotice.js +6 -0
  595. package/dist/utils/uiNotice.test.d.ts +1 -0
  596. package/dist/utils/uiNotice.test.js +18 -0
  597. package/dist/utils/workspaceIdentity.d.ts +14 -0
  598. package/dist/utils/workspaceIdentity.js +21 -0
  599. package/dist/utils/workspaceIdentity.test.js +30 -1
  600. package/dist/utils/workspaceSyncPresentation.d.ts +20 -0
  601. package/dist/utils/workspaceSyncPresentation.js +21 -0
  602. package/dist/utils/workspaceSyncPresentation.test.d.ts +1 -0
  603. package/dist/utils/workspaceSyncPresentation.test.js +36 -0
  604. package/package.json +30 -23
  605. package/scripts/bootstrap-playwright-auth.mjs +155 -0
  606. package/scripts/check-compat-boundaries.mjs +41 -0
  607. package/scripts/check-env.ts +9 -2
  608. package/scripts/debug-login.mjs +32 -0
  609. package/scripts/deploy-prod.sh +41 -0
  610. package/scripts/deploy-staging.sh +23 -0
  611. package/scripts/migrate-planning-model.ts +233 -0
  612. package/scripts/migrate-task-data-assets.mjs +408 -0
  613. package/scripts/playwright-auth.sh +11 -0
  614. package/scripts/run-dev-proxy.sh +2 -0
  615. package/scripts/update-homebrew-formula.sh +2 -2
  616. package/scripts/with-esbuild.sh +11 -0
  617. package/src/resources/templates/WORKFLOW_V2_POLICY.md +1 -1
  618. package/src/resources/templates/workflow-sources/workflowDocs.mjs +62 -52
  619. package/src/resources/templates/workflows/collaborate.yaml +11 -5
  620. package/src/resources/templates/workflows/do.yaml +8 -2
  621. package/src/resources/templates/workflows/evaluate.yaml +13 -7
  622. package/src/resources/templates/workflows/execute.yaml +40 -23
  623. package/src/resources/templates/workflows/plan.yaml +15 -8
  624. package/src/resources/templates/workflows/review.yaml +14 -8
  625. package/dist/TaskforceScreenshot.d.ts +0 -11
  626. package/dist/TaskforceScreenshot.js +0 -113
  627. package/dist/compat/priorityCompat.d.ts +0 -2
  628. package/dist/compat/priorityCompat.js +0 -24
  629. package/dist/components/features/settings/TaxonomyManager 2.d.ts +0 -52
  630. package/dist/components/features/settings/TaxonomyManager 2.js +0 -75
  631. package/dist/components/task/TaskKanban 2.d.ts +0 -76
  632. package/dist/components/task/TaskKanban 2.js +0 -1004
  633. package/dist/components/task/TaskScreenshotSection.d.ts +0 -15
  634. package/dist/components/task/TaskScreenshotSection.js +0 -22
  635. package/dist/components/views/StandaloneLayout 2.d.ts +0 -8
  636. package/dist/components/views/StandaloneLayout 2.js +0 -1660
  637. package/dist/core/InitiativeTemplates.test.js +0 -50
  638. package/dist/core/ParentLifecycle.test.js +0 -98
  639. package/dist/migrations/clientMigrations.d.ts +0 -9
  640. package/dist/migrations/clientMigrations.js +0 -74
  641. package/dist/migrations/flags.d.ts +0 -6
  642. package/dist/migrations/flags.js +0 -8
  643. package/dist/migrations/taskMigrations.d.ts +0 -71
  644. package/dist/migrations/taskMigrations.js +0 -236
  645. package/dist/migrations/taskMigrations.test.js +0 -34
  646. package/dist/server/routes.billing.js +0 -991
  647. package/dist/server/routes.billing.test.js +0 -387
  648. package/dist/server/routes.sync.integration.test.js +0 -470
  649. package/dist/server/routes.sync.js +0 -1141
  650. package/dist/soak/syncSoakHarness.d.ts +0 -6
  651. package/dist/soak/syncSoakHarness.js +0 -10
  652. package/dist/ui/assets/index-0W5vyCpn.css +0 -1
  653. package/dist/ui/assets/index-MCZuNNfn.js +0 -23
  654. package/dist/ui/assets/logo_white_01-0Vx-iIIv.png +0 -0
  655. package/dist/ui/assets/vendor-dnd-BI1K77C1.js +0 -5
  656. package/dist/ui/assets/vendor-react-DdIDsh7f.js +0 -9
  657. package/dist/ui/assets/vendor-router-BtiNU7Dl.js +0 -3
  658. package/dist/utils/taskHierarchy.d.ts +0 -4
  659. package/dist/utils/taskHierarchy.js +0 -69
  660. package/dist/utils/taskHierarchy.test.js +0 -38
  661. package/dist/utils/taskParenting.d.ts +0 -3
  662. package/dist/utils/taskParenting.js +0 -24
  663. package/dist/utils/taskParenting.test.js +0 -21
  664. package/dist/utils/taskRelations.d.ts +0 -6
  665. package/dist/utils/taskRelations.js +0 -24
  666. package/dist/utils/taskRelations.test.js +0 -34
  667. package/scripts/check-compat-boundaries.js +0 -48
  668. /package/dist/{__tests__/planParser.test.d.ts → TaskforceCore.filter-persistence.test.d.ts} +0 -0
  669. /package/dist/{__tests__/releaseVersion.test.d.ts → TaskforceCore.routing.test.d.ts} +0 -0
  670. /package/dist/{__tests__/structuredCommentValidation.test.d.ts → annotatedAttachments/AnnotatedAttachmentSessionStore.test.d.ts} +0 -0
  671. /package/dist/{__tests__/structuredDocValidation.test.d.ts → annotatedAttachments/payload.test.d.ts} +0 -0
  672. /package/dist/{__tests__/templateEngine.test.d.ts → annotatedAttachments/types.js} +0 -0
  673. /package/dist/{__tests__/templates.test.d.ts → compat/workspaceSyncCompat.test.d.ts} +0 -0
  674. /package/dist/{__tests__/workflowDocumentFixtures.test.d.ts → components/features/AgentsModule.test.d.ts} +0 -0
  675. /package/dist/{__tests__/workflowExportMatrix.test.d.ts → components/features/AnnotatedAttachmentWorkspace.test.d.ts} +0 -0
  676. /package/dist/{__tests__/workflowExportSnapshots.test.d.ts → components/features/DocumentWorkspace.test.d.ts} +0 -0
  677. /package/dist/{__tests__/workflowGeneration.test.d.ts → components/features/settings/TaxonomyLibraryManager.test.d.ts} +0 -0
  678. /package/dist/{__tests__/workflowV2Policy.test.d.ts → components/task/TaskActionHeader.test.d.ts} +0 -0
  679. /package/dist/{core/InitiativeTemplates.test.d.ts → components/task/TaskKanban.planning-drop.test.d.ts} +0 -0
  680. /package/dist/{core/ParentLifecycle.test.d.ts → components/task/TaskStatusActions.test.d.ts} +0 -0
  681. /package/dist/{migrations/taskMigrations.test.d.ts → components/ui/TopNoticeLayer.test.d.ts} +0 -0
  682. /package/dist/{server/routes.billing.test.d.ts → components/views/AppShellHeader.test.d.ts} +0 -0
  683. /package/dist/{server/routes.sync.integration.test.d.ts → components/views/PlanComparisonPage.test.d.ts} +0 -0
  684. /package/dist/{utils/taskHierarchy.test.d.ts → components/views/chrome/WorkspaceChromeSections.test.d.ts} +0 -0
  685. /package/dist/{utils/taskParenting.test.d.ts → components/views/chrome/workspaceChrome.test.d.ts} +0 -0
  686. /package/dist/{utils/taskRelations.test.d.ts → components/views/panels/DocumentFilterToolbar.test.d.ts} +0 -0
  687. /package/dist/public/{android-chrome-192x192.png → archive/phoenix/android-chrome-192x192.png} +0 -0
  688. /package/dist/public/{android-chrome-512x512.png → archive/phoenix/android-chrome-512x512.png} +0 -0
  689. /package/dist/public/{favicon-16x16.png → archive/phoenix/favicon-16x16.png} +0 -0
  690. /package/dist/public/{favicon-32x32.png → archive/phoenix/favicon-32x32.png} +0 -0
  691. /package/dist/public/{favicon.png → archive/phoenix/favicon.png} +0 -0
  692. /package/dist/{__tests__ → services}/workflowExportSnapshots.test.js +0 -0
  693. /package/dist/{__tests__ → services}/workflowGeneration.test.js +0 -0
  694. /package/dist/ui/favicon/{android-chrome-192x192.png → archive/phoenix/android-chrome-192x192.png} +0 -0
  695. /package/dist/ui/favicon/{android-chrome-512x512.png → archive/phoenix/android-chrome-512x512.png} +0 -0
  696. /package/dist/ui/favicon/{favicon-16x16.png → archive/phoenix/favicon-16x16.png} +0 -0
  697. /package/dist/ui/favicon/{favicon-32x32.png → archive/phoenix/favicon-32x32.png} +0 -0
  698. /package/dist/ui/favicon/{favicon.png → archive/phoenix/favicon.png} +0 -0
@@ -1,23 +0,0 @@
1
- import{r as s,j as e,R as zs,a as Ci,b as su}from"./vendor-react-DdIDsh7f.js";import{I as da,C as po,a as Bn,F as au,b as nu,R as zl,T as yo,c as ho,d as Ll,A as fd,e as gd,L as aa,f as la,g as ll,h as mo,i as Wr,B as _c,U as jc,X as ga,S as _i,j as Sa,M as ou,k as ru,l as Bc,P as iu,m as cu,n as vc,o as yd,p as lu,q as cn,r as Tc,s as du,t as Xo,u as Cl,v as xi,w as uu,x as kd,y as Ml,Z as Jo,z as bi,D as $l,E as Fl,K as pu,G as xd,H as hu,J as mu,W as fu,N as gu,O as vd,Q as bd,V as yu,Y as ku,_ as _l,$ as xu,a0 as Ol,a1 as wd,a2 as vu,a3 as bu,a4 as wu,a5 as Su,a6 as Cu,a7 as Wl,a8 as _u,a9 as ju,aa as Tu,ab as Nu,ac as Iu,ad as Au,ae as Du,af as Bu,ag as Pu,ah as zu,ai as Lu,aj as Ru,ak as Eu,al as Mu,am as Ul,an as Hl,ao as $u,ap as Fu}from"./vendor-icons-ZFG3SGwo.js";import{M as jl,r as Tl,a as Ou,s as Wu}from"./vendor-markdown-CKYkQHfj.js";import{u as Uu,a as Gl,D as Hu,b as Gu,p as qu,c as ql,s as Vu,K as Ku,P as Ju,d as Yu,S as Xu,v as Qu,e as Zu,f as ep,C as tp}from"./vendor-dnd-BI1K77C1.js";import{u as Sd,a as Cd,b as sp,M as ap,B as np}from"./vendor-router-BtiNU7Dl.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))u(d);new MutationObserver(d=>{for(const m of d)if(m.type==="childList")for(const h of m.addedNodes)h.tagName==="LINK"&&h.rel==="modulepreload"&&u(h)}).observe(document,{childList:!0,subtree:!0});function r(d){const m={};return d.integrity&&(m.integrity=d.integrity),d.referrerPolicy&&(m.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?m.credentials="include":d.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function u(d){if(d.ep)return;d.ep=!0;const m=r(d);fetch(d.href,m)}})();const op={categories:[{value:"default",label:"Default",icon:"Inbox"}],types:[{value:"feature",label:"Feature"},{value:"bug",label:"Bug"},{value:"chore",label:"Chore"},{value:"refactor",label:"Refactor"},{value:"documentation",label:"Docs"}],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"},{value:4,label:"Critical",color:"red-500",icon:"AlertTriangle"}],approaches:[{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"}],taxonomies:[],apiEndpoint:"/api/taskforce/task",apiBaseUrl:void 0,cloudAuthBaseUrl:void 0,wsBaseUrl:void 0,position:"bottom-right",offsetY:70,theme:"dark",shortcut:"Alt+T",manualComplexityEnabled:!1,checklistDropdownEnabled:!1,assigneeFilterEnabled:!1},ji=[{value:"task",label:"To Do"},{value:"on-hold",label:"Blocked"},{value:"in-progress",label:"In Progress"},{value:"review",label:"Ready for Review"},{value:"done",label:"Completed"},{value:"cancelled",label:"Cancelled"}],_d=["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","Inbox","HelpCircle","Gauge","FileCode","ArrowDown","Minus","ArrowUp","AlertTriangle","CircleQuestionMark","TriangleAlert"],fo=_d.reduce((a,n)=>(a[n]=da[n]||po,a),{}),jd=_d,ko={bug:{icon:"Bug",color:"red-500"},feature:{icon:"Star",color:"teal-500"},chore:{icon:"Zap",color:"amber-500"},refactor:{icon:"Code",color:"blue-500"},documentation:{icon:"Book",color:"sky-500"}},Vl={"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"},bc=["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 ys(a){if(a)return Vl[a]?Vl[a]:a}const Pc=a=>[...a].sort((n,r)=>{const u=+!!n.isArchived-+!!r.isArchived;if(u!==0)return u;const d=typeof n.childDisplayOrder=="number"?n.childDisplayOrder:Number.POSITIVE_INFINITY,m=typeof r.childDisplayOrder=="number"?r.childDisplayOrder:Number.POSITIVE_INFINITY;return d!==m?d-m:new Date(r.createdAt).getTime()-new Date(n.createdAt).getTime()}),Nl=(a,n)=>!!(a&&n&&a!==n),Il=(a,n,r)=>{if(!n)return!1;if(a===n)return!0;const u=new Map;for(const h of r)u.set(h.id,h.parentTaskId);let d=n;const m=new Set;for(;d;){if(d===a||m.has(d))return!0;m.add(d),d=u.get(d)||null}return!1};function Nc(a){const n=new Map;a.forEach(d=>n.set(d.id,d));const r=new Map,u=(d,m)=>{const h=r.get(d);if(typeof h=="number")return h;const v=n.get(d);if(!v)return 0;const x=v.parentTaskId||null;if(!x||!n.has(x)||m.has(d)||m.has(x))return r.set(d,0),0;m.add(d);const _=u(x,m)+1;return m.delete(d),r.set(d,_),_};return a.forEach(d=>{u(d.id,new Set)}),r}function wc(a,n){if(!n)return new Set;const r=new Map;a.forEach(h=>{if(!h.parentTaskId)return;const v=r.get(h.parentTaskId)||[];v.push(h.id),r.set(h.parentTaskId,v)});const u=new Set,d=new Set,m=[n];for(;m.length>0;){const h=m.pop();if(d.has(h))continue;d.add(h),u.add(h),(r.get(h)||[]).forEach(x=>{d.has(x)||m.push(x)})}return u}const Al={"on-hold":1,low:1,medium:2,high:3,critical:4},rp={0:"low",1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function dl(a,n){return rp[String(a)]||n}function ul(a,n){const r=n?.mapLegacyTodoStatus??!1;return{...a,assignee:(()=>{const u=String(a.assignee||"").trim().toLowerCase();return u==="agent"||u==="ai"?"agent":u==="user"?"user":"unassigned"})(),category:typeof a.category=="string"?a.category:a.category?.value||"default",type:(typeof a.type=="string"?a.type:a.type?.label||"feature").toLowerCase(),priority:typeof a.priority=="number"?a.priority:Al[a.priority]??2,complexity:typeof a.complexity=="number"?a.complexity:3,parentTaskId:typeof a.parentTaskId=="string"&&a.parentTaskId.trim().length>0?a.parentTaskId.trim():null,...(()=>{const u=a.status==="blocked"||a.status==="on hold"?"on-hold":a.status;return r?{status:u==="todo"?"task":u}:{status:u}})()}}function ip(a,n){return!a.length||!n.length?a:Array.from(new Set(a.map(r=>{const u=n.find(d=>d.label===r);return u?u.value:r})))}function cp(a,n){if(!n.length||!a.length)return[];const r=new Set(n.map(x=>Number(x.value))),u=r.has(5)&&!r.has(0),d=r.has(4)&&!r.has(5)&&!r.has(0),m=a.map(x=>Number(x)).filter(x=>Number.isFinite(x)),h=u&&m.includes(0),v=d&&m.includes(5);return Array.from(new Set(m.map(x=>h&&x>=0&&x<=4?x+1:v&&x>=2&&x<=5?x-1:x).filter(x=>r.has(x))))}function pl(a,n){return n.some(r=>String(r)===String(a))}const lp={taskForm:{commentsSectionTitle:"Activity & Comments",hideComments:"Hide Comments",showComments:"Show Comments",noComments:"No comments yet. Start the conversation!",you:"You",commentPlaceholder:"Type a comment...",scheduledLabel:"Scheduled:",dueLabel:"Due:",createdLabel:"Created:",updatedLabel:"Updated:",completedLabel:"Completed:",emptyValue:"—",parentCannotSchedule:"Parent tasks cannot be scheduled. Schedule leaf tasks instead.",dueBeforeScheduled:"Due date is before scheduled date.",overdue:"This task is overdue."},schedule:{completedOnlyPastSchedule:"Only completed work can be scheduled in the past.",noUnscheduledLeafTasks:'No unscheduled leaf tasks found under "{parentTitle}".'},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:"Include Archive",noMatchingTasks:"No matching tasks",noActiveTasks:"No active tasks",addTaskToCategoryTitle:"Add task to {category}"},actionHeader:{blockedByActiveChildren:"Complete or cancel all direct child tasks first",confirmCascadeComplete:"This parent task has {count} active child task(s). Also mark all child tasks as complete?",confirmCascadeCancel:"This parent task has {count} active child task(s). Also mark all child tasks as cancelled?",confirmCascadeArchive:"This parent task has {count} child task(s). Also archive all child tasks?",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:"Approach",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:"Include Archive",clearFilters:"Clear Filters",noTasksMatchFilters:"No tasks match current filters.",showingWithLinksHint:"Showing: {parentFilterLabel}. Switch Links to All or clear filters.",visibleActiveTasksTitle:"Visible active tasks / total active tasks",totalActiveTasksTitle:"Total active tasks"},setup:{headingCheckFailed:"Setup Check Failed",headingGlobalRequired:"Global Setup Required",headingWorkspaceRequired:"Workspace Setup Required",subtitleUnreadable:"Taskforce could not read setup state. Retry to continue.",subtitleGlobalRequired:"Choose your default operating mode to continue.",subtitleWorkspaceRequired:"Set up your workspace profile to continue.",runtimeLabel:"Runtime",workspaceTermProject:"Project",workspaceTermMission:"Mission",coreModeOption:"Core Mode: {workspaceLabel} planning defaults",operationsModeOption:"Operations Mode: Mission-first terminology and flows",workspaceNamePlaceholder:"{workspaceLabel} name",workspaceDescriptionPlaceholder:"{workspaceLabel} description (optional)",saving:"Saving...",saveGlobalSetup:"Save Global Setup",saveWorkspaceSetup:"Save {workspaceLabel} Setup",globalSetupSaved:"Global setup saved.",workspaceSetupSaved:"{workspaceLabel} setup saved.",saveFailedWithStatus:"Failed to save setup ({status})",saveFailed:"Failed to save setup.",saveWorkspaceFailed:"Failed to save workspace profile.",retrySetupCheck:"Retry Setup Check",signOut:"Sign Out"}},dp={taskForm:{commentsSectionTitle:"Actividad y comentarios",hideComments:"Ocultar comentarios",showComments:"Mostrar comentarios",noComments:"Aun no hay comentarios. Inicia la conversacion.",you:"Tu",commentPlaceholder:"Escribe un comentario...",scheduledLabel:"Programado:",dueLabel:"Vence:",createdLabel:"Creado:",updatedLabel:"Actualizado:",completedLabel:"Completado:",emptyValue:"—",parentCannotSchedule:"Las tareas padre no se pueden programar. Programa tareas hoja en su lugar.",dueBeforeScheduled:"La fecha de vencimiento es anterior a la fecha programada.",overdue:"Esta tarea esta vencida."},schedule:{completedOnlyPastSchedule:"Solo el trabajo completado se puede programar en el pasado.",noUnscheduledLeafTasks:'No se encontraron tareas hoja sin programar en "{parentTitle}".'},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:{blockedByActiveChildren:"Primero completa o cancela todas las tareas hijas directas",confirmCascadeComplete:"Esta tarea padre tiene {count} tarea(s) hija(s) activa(s). Tambien quieres marcar todas las tareas hijas como completadas?",confirmCascadeCancel:"Esta tarea padre tiene {count} tarea(s) hija(s) activa(s). Tambien quieres marcar todas las tareas hijas como canceladas?",confirmCascadeArchive:"Esta tarea padre tiene {count} tarea(s) hija(s). Tambien quieres archivar todas las tareas hijas?",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:"Enfoque",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"}},up={taskForm:{commentsSectionTitle:"Atividade e comentarios",hideComments:"Ocultar comentarios",showComments:"Mostrar comentarios",noComments:"Ainda nao ha comentarios. Inicie a conversa.",you:"Voce",commentPlaceholder:"Digite um comentario...",scheduledLabel:"Agendado:",dueLabel:"Vencimento:",createdLabel:"Criado:",updatedLabel:"Atualizado:",completedLabel:"Concluido:",emptyValue:"—",parentCannotSchedule:"Tarefas pai nao podem ser agendadas. Agende as tarefas folha.",dueBeforeScheduled:"A data de vencimento e anterior a data agendada.",overdue:"Esta tarefa esta atrasada."},schedule:{completedOnlyPastSchedule:"Somente trabalho concluido pode ser agendado no passado.",noUnscheduledLeafTasks:'Nenhuma tarefa folha nao agendada foi encontrada em "{parentTitle}".'},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:{blockedByActiveChildren:"Conclua ou cancele todas as tarefas filhas diretas primeiro",confirmCascadeComplete:"Esta tarefa pai tem {count} tarefa(s) filha(s) ativa(s). Tambem deseja marcar todas as tarefas filhas como concluidas?",confirmCascadeCancel:"Esta tarefa pai tem {count} tarefa(s) filha(s) ativa(s). Tambem deseja marcar todas as tarefas filhas como canceladas?",confirmCascadeArchive:"Esta tarefa pai tem {count} tarefa(s) filha(s). Tambem deseja arquivar todas as tarefas filhas?",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:"Abordagem",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"}},Td=["en-US","es-419","pt-BR"],Ic="en-US",hl={"en-US":lp,"es-419":dp,"pt-BR":up},Nd={en:"en-US",es:"es-419",pt:"pt-BR"};let Yo=Ic;function pp(a){return a.split(".").filter(Boolean)}function ml(a,n){let r=a;for(const u of n){if(!r||typeof r!="object")return;r=r[u]}return typeof r=="string"?r:void 0}function Id(a){if(!a)return Ic;const n=Td.find(u=>u.toLowerCase()===a.toLowerCase());if(n)return n;const r=a.split("-")[0]?.toLowerCase()||"";return Nd[r]||Ic}function fl(a,n){return n?a.replace(/\{([^}]+)\}/g,(r,u)=>{const d=n[u];return d==null?"":String(d)}):a}function Ad(){return Yo}function hp(){return[...Td]}function Dd(a){const n=Id(a);return Yo=n,n}function mp(a){const n=typeof navigator<"u"?navigator.language:null;return Yo=Id(n),Yo}function E(a,n){const r=pp(a),u=ml(hl[Yo],r);if(u)return fl(u,n);const d=Yo.split("-")[0]?.toLowerCase()||"",m=Nd[d];if(m&&m!==Yo){const v=ml(hl[m],r);if(v)return fl(v,n)}const h=ml(hl[Ic],r);return h?fl(h,n):a}const fp="default",Ti="bootstrap";function gp(a){let n=2166136261;for(let r=0;r<a.length;r+=1)n^=a.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function Bd(a){const n=String(a||"").trim().toLowerCase();return n?`${(n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${gp(n)}`:Ti}function yp(a){const n=String(a||"").trim().toLowerCase();if(!n)return Ti;const r=n.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return r?r.slice(0,96):Ti}function kp(a){const n=String(a||"").trim();return n?Bd(n):Ti}function xp(a){return String(a||"").trim().toLowerCase()===fp}const vp={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function bp(a){return String(a||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function wp(a){return vp[bp(a)]}function Sp(a){const n=Number(a?.status);return Number.isFinite(n)&&n>0?Math.floor(n):0}async function Zo(a){try{const n=await a,r=await n.text().catch(()=>"");let u={};if(r)try{u=JSON.parse(r)}catch{u={error:!n.ok&&n.statusText?`${n.status} ${n.statusText}`:r.slice(0,400)}}else!n.ok&&n.statusText&&(u={error:`${n.status} ${n.statusText}`});const d=n.headers.get("retry-after");let m;if(d){const h=Number.parseInt(d,10);if(Number.isFinite(h)&&h>0)m=h*1e3;else{const v=Date.parse(d);if(Number.isFinite(v)){const x=v-Date.now();x>0&&(m=x)}}}return{ok:n.ok,status:n.status,data:u,retryAfterMs:m}}catch(n){return{ok:!1,status:Sp(n),data:{}}}}async function Cp(a){return Zo(fetch(a("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function _p(a,n){return Zo(fetch(a("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function Kl(a,n){return Zo(fetch(a("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n})}))}async function jp(a,n){return Zo(fetch(a("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function Tp(a,n){const r=new URLSearchParams({limit:String(n.limit),workspaceId:n.workspaceId});n.cursor&&r.set("cursor",n.cursor);const u=a("/api/taskforce/sync/workspace/pull"),d=u.includes("?")?"&":"?";return Zo(fetch(`${u}${d}${r.toString()}`,{method:"GET",credentials:"include"}))}async function Np(a,n){return Zo(fetch(a("/api/taskforce/sync/workspace/push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function Ip(a,n){return Zo(fetch(a("/api/taskforce/sync/workspace/bootstrap-push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(n)}))}async function Ap(a,n){const r=JSON.stringify({workspaceId:a,changes:n}),d=(()=>{if(typeof window>"u")return"/api/taskforce/sync/workspace/apply-local";const h=String(window.location?.pathname||"/");return h==="/taskforce"||h.startsWith("/taskforce/")?"/taskforce/api/taskforce/sync/workspace/apply-local":"/api/taskforce/sync/workspace/apply-local"})(),m=[];try{const h=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":a},credentials:"include",body:r});if(h.ok)return{ok:!0,data:await h.json().catch(()=>({})),failures:m};m.push(`${d}:${h.status}`)}catch{m.push(`${d}:network`)}return{ok:!1,data:{},failures:m}}const Dl="V1:AESGCM:",Rl="AES-GCM",Dp=12;async function Pd(a){const n=Buffer.from(a,"base64");if(n.length!==32)throw new Error("Encryption key must be exactly 32 bytes (256-bit).");return crypto.subtle.importKey("raw",n,{name:Rl},!1,["encrypt","decrypt"])}async function Bp(a,n){if(!a)return a;const r=crypto.getRandomValues(new Uint8Array(Dp)),u=await Pd(n),m=new TextEncoder().encode(a),h=await crypto.subtle.encrypt({name:Rl,iv:r},u,m),v=Buffer.from(h).toString("base64"),x=Buffer.from(r).toString("base64");return`${Dl}${x}:${v}`}async function Pp(a,n){if(!a||!a.startsWith(Dl))return a;const r=a.slice(Dl.length),[u,d]=r.split(":");if(!u||!d)throw new Error("Malformed encrypted document payload.");const m=Buffer.from(u,"base64"),h=Buffer.from(d,"base64"),v=await Pd(n);try{const x=await crypto.subtle.decrypt({name:Rl,iv:m},v,h);return new TextDecoder("utf-8").decode(x)}catch(x){throw new Error(`Failed to decrypt document: ${x.message}`)}}var Ac={};function go(a){return a&&typeof a=="object"?a:{}}async function zp(a){if(!a.cloudAuthConfigured)return{success:!1,error:"Cloud auth endpoint is not configured."};if(a.runtimeMode!=="local")return{success:!1,error:"Workspace sync is only available in local runtime."};if(!a.isAuthenticated)return{success:!1,error:"Authentication required."};try{let n=await Kl(a.resolveCloudAuthUrl,a.workspaceId);if(n.ok)return{success:!0,provisioned:!1};const r=go(n.data);if(n.status===401)return{success:!1,statusCode:401,error:String(r.error||"Authentication required for workspace sync.")};if(n.status===429)return{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,error:String(r.error||"Workspace sync rate limited. Please retry later.")};if(n.status===409&&r.code==="WORKSPACE_ID_MISMATCH"){const u=await jp(a.resolveCloudAuthUrl,{workspaceId:a.workspaceId,name:a.workspaceName||a.workspaceId});if(!u.ok){const d=go(u.data);return{success:!1,statusCode:u.status,error:String(d.error||`Workspace provisioning failed (${u.status})`)}}if(n=await Kl(a.resolveCloudAuthUrl,a.workspaceId),!n.ok){const d=go(n.data);return n.status===401?{success:!1,statusCode:401,error:String(d.error||"Authentication required for workspace sync.")}:n.status===429?{success:!1,statusCode:429,retryAfterMs:n.retryAfterMs,error:String(d.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:n.status,error:String(d.error||`Workspace sync handshake failed (${n.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:n.status,error:String(r.error||`Workspace sync handshake failed (${n.status})`)}}catch{return{success:!1,error:"Failed to validate workspace sync access."}}}async function Lp(a,n){const r=JSON.stringify([a,n]);try{const u=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(u)).map(d=>d.toString(16).padStart(2,"0")).join("")}catch{let u=2166136261;for(let m=0;m<r.length;m+=1)u^=r.charCodeAt(m),u=Math.imul(u,16777619);const d=(u>>>0).toString(16).padStart(8,"0");return`${a}:fallback:${d}`}}async function Rp(a){const n=a.payload.changes.length,r=a.payload.deleteTaskIds.size,u=await Lp(a.workspaceId,a.payload.changes);let d=0,m=a.payload.changes;if(typeof process<"u"&&Ac?.TASKFORCE_SYNC_KEY){const R=Ac.TASKFORCE_SYNC_KEY,j=[];for(const D of m)D.op==="document-upsert"&&typeof D.content=="string"?j.push({...D,content:await Bp(D.content,R)}):j.push(D);m=j}const h=async()=>{const R=Date.now(),j=await Np(a.resolveCloudAuthUrl,{workspaceId:a.workspaceId,idempotencyKey:u,changes:m});return d+=Date.now()-R,j};let v=await h();if(!v.ok&&(v.status===403||v.status===409)&&(await a.ensureCloudWorkspaceReadyForSync()).success&&(v=await h()),!v.ok){const R=go(v.data);return{success:!1,status:v.status,error:typeof R.error=="string"?R.error:void 0,code:typeof R.code=="string"?R.code:void 0,retryAfterMs:v.retryAfterMs,requestMs:d,changeCount:n,deleteCount:r,currentTaskIds:a.payload.currentTaskIds,deleteTaskIds:a.payload.deleteTaskIds,currentDocumentPaths:a.payload.currentDocumentPaths,deleteDocumentPaths:a.payload.deleteDocumentPaths,currentDocumentWatermarks:a.payload.currentDocumentWatermarks,pushedWatermarks:new Map,emittedEventIds:[]}}const x=go(v.data),_=Array.isArray(x.emittedEventIds)?Array.from(new Set(x.emittedEventIds.map(R=>String(R||"").trim()).filter(Boolean))):[];return{success:!0,syncedAt:new Date().toISOString(),requestMs:d,changeCount:n,deleteCount:r,currentTaskIds:a.payload.currentTaskIds,deleteTaskIds:a.payload.deleteTaskIds,currentDocumentPaths:a.payload.currentDocumentPaths,deleteDocumentPaths:a.payload.deleteDocumentPaths,currentDocumentWatermarks:a.payload.currentDocumentWatermarks,pushedWatermarks:a.payload.pushedWatermarks,emittedEventIds:_}}async function Ep(a){let n=a.cursor,r=!0,u=0,d=0,m=0,h=0;const v=new Set;let x=!1,_=!1;const R=new Set,j=Number.isFinite(Number(a.maxPages))?Math.max(1,Math.floor(Number(a.maxPages))):20;try{for(;r&&u<j;){const D=async()=>{const $=Date.now(),z=await Tp(a.resolveCloudAuthUrl,{workspaceId:a.workspaceId,cursor:n,limit:a.bootstrap?500:200});return m+=Date.now()-$,z};let b=await D();if(!b.ok&&b.status===403&&a.ensureCloudWorkspaceReadyForSync&&(await a.ensureCloudWorkspaceReadyForSync()).success&&(b=await D()),!b.ok)return{success:!1,kind:"pull_http",status:b.status,retryAfterMs:b.retryAfterMs,cursor:n,pages:u,appliedChanges:d,pullRequestMs:m,applyMs:h,pulledDeleteTaskIds:v,pulledActiveUpserts:x,pulledArchivedUpserts:_,documentDecryptFailures:Array.from(R)};const f=b.data||{},I=Array.isArray(f?.changes)?f.changes:[];for(const $ of I){if($.op==="upsert"){$?.archived===!0||$?.task?.isArchived===!0?_=!0:x=!0;continue}if($.op==="document-upsert"){if(typeof $.content=="string"&&typeof process<"u"&&Ac?.TASKFORCE_SYNC_KEY)try{$.content=await Pp($.content,Ac.TASKFORCE_SYNC_KEY)}catch{const w=String($.path||"").trim();w&&R.add(w)}continue}if($.op!=="delete")continue;const z=String($.taskId||"").trim();z&&v.add(z)}if(a.onPagePulled&&a.onPagePulled(),I.length>0){const $=Date.now(),z=await Ap(a.workspaceId,I),w=z.failures;if(!z.ok){if(h+=Date.now()-$,w.some(J=>J.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,failures:w,cursor:n,pages:u,appliedChanges:d,pullRequestMs:m,applyMs:h,pulledDeleteTaskIds:v,pulledActiveUpserts:x,pulledArchivedUpserts:_,documentDecryptFailures:Array.from(R)};const Ne=w.some(J=>{if(J.endsWith(":network"))return!0;const he=J.split(":").pop()||"",ce=Number.parseInt(he,10);return Number.isFinite(ce)&&(ce===429||ce>=500)});return{success:!1,kind:"apply_all_candidates",failures:w,hasTransientApplyFailure:Ne,cursor:n,pages:u,appliedChanges:d,pullRequestMs:m,applyMs:h,pulledDeleteTaskIds:v,pulledActiveUpserts:x,pulledArchivedUpserts:_,documentDecryptFailures:Array.from(R)}}const T=go(z.data);if(T.success===!1)return h+=Date.now()-$,{success:!1,kind:"apply_payload",error:String(T.error||"Workspace sync apply failed."),cursor:n,pages:u,appliedChanges:d,pullRequestMs:m,applyMs:h,pulledDeleteTaskIds:v,pulledActiveUpserts:x,pulledArchivedUpserts:_,documentDecryptFailures:Array.from(R)};h+=Date.now()-$,d+=I.length,a.onChangesApplied&&a.onChangesApplied(I.length)}f&&"nextCursor"in f&&(f.nextCursor===null||typeof f.nextCursor=="string")&&(n=f.nextCursor),r=!!f?.hasMore,u+=1}return{success:!0,syncedAt:new Date().toISOString(),cursor:n||null,pages:u,appliedChanges:d,pullRequestMs:m,applyMs:h,pulledDeleteTaskIds:v,pulledActiveUpserts:x,pulledArchivedUpserts:_,documentDecryptFailures:Array.from(R)}}catch{return{success:!1,kind:"exception",cursor:n||null,pages:u,appliedChanges:d,pullRequestMs:m,applyMs:h,pulledDeleteTaskIds:v,pulledActiveUpserts:x,pulledArchivedUpserts:_,documentDecryptFailures:Array.from(R)}}}async function Mp(a){const n=b=>b===0||b===429||b>=500,r=await Cp(a.resolveCloudAuthUrl);if(!r.ok){const b=Number(r.status||0);return{success:!1,error:`Sync pull failed (${r.status})`,statusCode:r.status,retryAfterMs:r.retryAfterMs,transient:n(b)}}const u=go(r.data),d=u.settings&&typeof u.settings=="object"?u.settings:{},m=typeof u.updatedAt=="string"&&u.updatedAt.trim().length>0?u.updatedAt.trim():null,h=a.getLocalUpdatedAt(a.userId),v=h?Date.parse(h):NaN,x=m?Date.parse(m):NaN;if(!h&&a.preferCloudOnFirstSync&&Number.isFinite(x))return await a.applyRemoteSettings(d),{success:!0,mode:"pulled",updatedAt:m};if(Number.isFinite(x)&&(!Number.isFinite(v)||x>v))return await a.applyRemoteSettings(d),{success:!0,mode:"pulled",updatedAt:m};const _=h||new Date().toISOString(),R=await _p(a.resolveCloudAuthUrl,{settings:a.buildLocalSettings(),updatedAt:_});if(!R.ok){const b=Number(R.status||0);return{success:!1,error:`Sync push failed (${R.status})`,statusCode:R.status,retryAfterMs:R.retryAfterMs,transient:n(b)}}const j=go(R.data);return{success:!0,mode:"pushed",updatedAt:typeof j.updatedAt=="string"&&j.updatedAt.trim().length>0?j.updatedAt.trim():_}}function zd(a){const n=Math.max(1,Math.floor(Number(a)||1)),r=Math.min(12e4,1500*2**Math.max(0,n-1)),u=Math.floor(r*(.15*Math.random()));return r+u}function $p(a){const n=new Date().toISOString(),r=new Set(Array.from(a.pendingDeletedTaskIds).map(w=>String(w||"").trim()).filter(w=>w.length>0)),u=a.lastPushedWatermarks,d=w=>{if(!u||u.size===0)return!0;const T=String(w?.id||"").trim();if(!T)return!1;const Z=String(w?.updatedAt||w?.createdAt||"").trim();return u.get(T)!==Z},m=new Map,h=(a.tasks||[]).filter(w=>!r.has(String(w?.id||"").trim())&&d(w)).map(w=>{const T=String(w?.id||"").trim(),Z=String(w?.updatedAt||w?.createdAt||"").trim();return T&&m.set(T,Z),{op:"upsert",archived:!1,task:w}}),v=(a.archivedTasks||[]).filter(w=>!r.has(String(w?.id||"").trim())&&d(w)).map(w=>{const T=String(w?.id||"").trim(),Z=String(w?.updatedAt||w?.createdAt||"").trim();return T&&m.set(T,Z),{op:"upsert",archived:!0,task:w}}),x=new Set;for(const w of a.tasks||[]){const T=String(w?.id||"").trim();T&&x.add(T)}for(const w of a.archivedTasks||[]){const T=String(w?.id||"").trim();T&&x.add(T)}const _=Array.from(a.lastPushedTaskIds).filter(w=>!x.has(w)).map(w=>({op:"delete",taskId:w})),R=Array.from(r).map(w=>({op:"delete",taskId:w})),j=new Set([..._.map(w=>String(w.taskId)),...R.map(w=>String(w.taskId))]),D=new Set((Array.isArray(a.documents)?a.documents:[]).map(w=>String(w?.path||"").trim()).filter(w=>w.length>0)),b=new Set(Array.from(a.lastPushedDocumentPaths||new Set).map(w=>String(w||"").trim()).filter(w=>w.length>0&&!D.has(w))),f=new Map((Array.isArray(a.documents)?a.documents:[]).map(w=>[String(w?.path||"").trim(),String(w?.updatedAt||"").trim()]).filter(([w])=>w.length>0)),I=a.lastPushedDocumentWatermarks,$=!I||I.size===0,z=(Array.isArray(a.documents)?a.documents:[]).map(w=>({op:"document-upsert",path:String(w.path||"").trim(),updatedAt:String(w.updatedAt||"").trim(),content:typeof w.content=="string"?w.content:""})).filter(w=>w.path.length>0).filter(w=>$?!0:I.get(w.path)!==w.updatedAt);return{changes:[...Array.isArray(a.taxonomies)?[{op:"taxonomy-upsert",taxonomies:a.taxonomies,updatedAt:n}]:[],...z,...Array.from(b).map(w=>({op:"document-delete",path:w})),...h,...v,...Array.from(j).map(w=>({op:"delete",taskId:w}))],currentTaskIds:new Set(Array.from(x).filter(w=>!r.has(w))),deleteTaskIds:j,currentDocumentPaths:D,deleteDocumentPaths:b,currentDocumentWatermarks:f,pushedWatermarks:m}}function Fp(a){const n=(a.tasks||[]).map(d=>`${d.id}:${d.updatedAt||d.createdAt||""}:${d.status}:${d.parentTaskId||""}`).sort(),r=(a.archivedTasks||[]).map(d=>`${d.id}:${d.updatedAt||d.createdAt||""}:${d.status}:${d.parentTaskId||""}`).sort(),u=a.pendingDeletedTaskIds?Array.from(a.pendingDeletedTaskIds).sort():[];return JSON.stringify({workspaceId:a.workspaceId,taxonomies:Array.isArray(a.taxonomies)?a.taxonomies:[],documents:Array.isArray(a.documents)?a.documents.map(d=>({path:String(d.path||"").trim(),updatedAt:String(d.updatedAt||"").trim(),length:typeof d.content=="string"?d.content.length:0})).filter(d=>d.path.length>0).sort((d,m)=>d.path.localeCompare(m.path)):[],active:n,archived:r,pendingDeletes:u})}const Op="taskforce.sync.pullLease.v1",Wp="taskforce.sync.pullCooldown.v1",Up=3e4,Jl=1e4,Hp="taskforce.syncDebug.v1";function Gp(){if(typeof window>"u")return!1;try{const a=String(window.localStorage.getItem(Hp)||"").trim().toLowerCase();return a==="1"||a==="true"||a==="on"||a==="yes"}catch{return!1}}function $r(a,n){if(!Gp())return;console.info("[Taskforce Sync]",a,n&&typeof n=="object"?n:{})}function Yl(a){return`${Op}.${a}`}function fc(a){return`${Wp}.${a}`}function gl(a){const n=String(a||"").trim();return n.length>0&&n.toLowerCase()!=="default"}function qp(a){const{currentWorkspaceId:n,setWorkspaceSyncReady:r,setWorkspaceCloudHydrated:u,setWorkspaceCloudSyncEnabled:d,setWorkspaceSyncSourceOfTruth:m,setWorkspaceSyncOnboardingCompleted:h,setUserGlobalLastSyncedAt:v,setWorkspaceLastPullAt:x,setWorkspaceLastPushAt:_}=a,[R,j]=s.useState(null),[D,b]=s.useState(!1),[f,I]=s.useState(0),[$,z]=s.useState(0),[w,T]=s.useState(0),[Z,Ne]=s.useState(0),[J,he]=s.useState(0),[ce,W]=s.useState(null),[U,Ge]=s.useState(null),ye=s.useRef(!1),ke=s.useRef(!1),Ae=s.useRef(null),se=s.useRef(null),Ye=s.useRef(0),We=s.useRef(""),Fe=s.useRef(""),te=s.useRef(new Set),ne=s.useRef(new Set),le=s.useRef(null),dt=s.useRef(!1),ae=s.useRef(new Set),q=s.useRef(new Set),M=s.useRef(new Set),Q=s.useRef(0),de=s.useRef(""),xe=s.useRef(null),B=s.useRef(null),oe=s.useRef(a.onFailureRecorded);if(s.useEffect(()=>{oe.current=a.onFailureRecorded},[a.onFailureRecorded]),!de.current){const V=Date.now().toString(36),Pe=Math.random().toString(36).slice(2,10);de.current=`pull-${V}-${Pe}`}const et=s.useCallback(()=>{Ye.current=0,se.current=null,Ae.current!==null&&typeof window<"u"&&(window.clearTimeout(Ae.current),Ae.current=null),j(null)},[]),yt=s.useCallback((V,Pe)=>{if(typeof window>"u")return;Ne(we=>we+1);const _e=Ye.current+1;Ye.current=_e;const Le=zd(_e),ze=Number(Pe?.minDelayMs),N=Number.isFinite(ze)&&ze>0?Math.max(Le,Math.floor(ze)):Le,G=Date.now()+N,je=new Date(Date.now()+N).toISOString(),Ie=String(Pe?.workspaceId||"").trim();if(Ie)try{const we=fc(Ie),qe=window.localStorage.getItem(we),vt=qe?JSON.parse(qe):null,st=Number(vt?.nextAllowedAt||0),Re=Math.max(st,G);window.localStorage.setItem(we,JSON.stringify({nextAllowedAt:Re}))}catch{}se.current=G,j(je),Ae.current!==null&&window.clearTimeout(Ae.current),Ae.current=window.setTimeout(()=>{if(Ae.current=null,se.current=null,j(null),Ie)try{const we=fc(Ie),qe=window.localStorage.getItem(we),vt=qe?JSON.parse(qe):null,st=Number(vt?.nextAllowedAt||0);Number.isFinite(st)&&st<=G&&window.localStorage.setItem(we,JSON.stringify({nextAllowedAt:Date.now()-1}))}catch{}V()},N)},[]),ut=s.useCallback(()=>{const V=se.current;return typeof V=="number"&&Number.isFinite(V)&&V>Date.now()},[]),mt=s.useCallback(V=>{if(typeof window>"u")return!1;const Pe=String(V||"").trim();if(!Pe)return!1;try{const _e=window.localStorage.getItem(fc(Pe)),Le=_e?JSON.parse(_e):null,ze=Number(Le?.nextAllowedAt||0);return Number.isFinite(ze)&&ze>Date.now()}catch{return!1}},[]),kt=s.useCallback((V,Pe)=>{if(typeof window>"u")return;const _e=String(V||"").trim();if(_e)try{const Le=fc(_e),ze=window.localStorage.getItem(Le),N=ze?JSON.parse(ze):null,G=Number(N?.nextAllowedAt||0),je=Number(Pe),Ie=Number.isFinite(je)&&je>0?Math.max(Jl,Math.floor(je)):Jl,we=Math.max(G,Date.now()+Ie);window.localStorage.setItem(Le,JSON.stringify({nextAllowedAt:we}))}catch{}},[]),Dt=s.useCallback(async V=>{const Pe=String(V||"").trim();if(!Pe)return!0;const _e=()=>{if(typeof window>"u")return!0;try{const N=Yl(Pe),G=de.current,je=Date.now(),Ie=window.localStorage.getItem(N),we=Ie?JSON.parse(Ie):null,qe=typeof we?.owner=="string"?we.owner:"",vt=Number(we?.expiresAt||0);if(Number.isFinite(vt)&&vt>je&&qe&&qe!==G)return!1;const Re={owner:G,acquiredAt:je,expiresAt:je+Up};window.localStorage.setItem(N,JSON.stringify(Re));const bt=window.localStorage.getItem(N);return(bt?JSON.parse(bt):null)?.owner===G}catch{return!0}};if(typeof window>"u"||typeof navigator>"u"||!navigator.locks)return _e();if(B.current)return xe.current===Pe;const Le=`taskforce.sync.pullLock.${Pe}`,ze=new AbortController;try{return await new Promise(G=>{navigator.locks.request(Le,{mode:"exclusive",ifAvailable:!0,signal:ze.signal},async je=>{if(!je){G(!1);return}return B.current=ze,xe.current=Pe,G(!0),new Promise(()=>{})}).catch(()=>{G(!1)})})}catch{return _e()}},[]),Mt=s.useCallback(V=>{const Pe=String(V||"").trim();if(!(Pe&&xe.current&&xe.current!==Pe)&&(B.current&&(B.current.abort(),B.current=null),xe.current=null,!(!Pe||typeof window>"u")))try{const _e=Yl(Pe),Le=window.localStorage.getItem(_e);(Le?JSON.parse(Le):null)?.owner===de.current&&window.localStorage.removeItem(_e)}catch{}},[]),Zt=s.useCallback((V,Pe)=>{const _e=typeof Pe=="number"&&Number.isFinite(Pe)?Pe:null;T(ze=>ze+1),W(V),Ge(_e);const Le=oe.current;Le&&Le(V,_e)},[]),tt=s.useCallback(()=>{he(V=>V+1)},[]),pt=s.useCallback(async V=>{if(gl(n))try{await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:n,stateKey:"workspace-sync",patch:{...V,updatedAt:new Date().toISOString()}})})}catch{}},[n]),Rt=s.useCallback(async()=>{const V=String(n||"").trim();if(!gl(V)){d(!1),m(null),h(!1),le.current=null,dt.current=!1,$r("workspace_sync_state_read_skipped_invalid_workspace",{workspaceId:V});return}Q.current+=1;const Pe=Q.current;try{const _e=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(V)}`,{method:"GET",credentials:"include"});if(!_e.ok){$r("workspace_sync_state_read_failed",{workspaceId:V,readCount:Pe,status:_e.status}),_e.status===429&&$r("workspace_sync_state_rate_limited",{workspaceId:V,readCount:Pe});return}const Le=await _e.json().catch(()=>({})),ze=Le?.state&&typeof Le.state=="object"?Le.state:null;if(!ze){$r("workspace_sync_state_read_empty",{workspaceId:V,readCount:Pe});return}d(!!ze.cloudSyncEnabled);const N=String(ze.sourceOfTruth||"").trim().toLowerCase();m(N==="cloud"||N==="local"?N:null),h(!!ze.onboardingCompleted);const G=typeof ze.lastSyncedAt=="string"?ze.lastSyncedAt:"";G.trim().length>0&&v(G.trim());const je=typeof ze.lastPullAt=="string"?ze.lastPullAt:"";je.trim().length>0&&x(je.trim());const Ie=typeof ze.lastPushAt=="string"?ze.lastPushAt:"";Ie.trim().length>0&&_(Ie.trim());const qe=(typeof ze.pullCursor=="string"?ze.pullCursor:"").trim();le.current=qe.length>0?qe:null,dt.current=qe.length>0,$r("workspace_sync_state_read_ok",{workspaceId:V,readCount:Pe,sourceOfTruth:N==="cloud"||N==="local"?N:null,cloudSyncEnabled:!!ze.cloudSyncEnabled})}catch{$r("workspace_sync_state_read_exception",{workspaceId:V,readCount:Pe})}},[n,d,m,h,v,x,_]),wt=s.useCallback(V=>{const Pe=!!V.cloudSyncEnabled;d(Pe);const _e=V.sourceOfTruth==="cloud"||V.sourceOfTruth==="local"?V.sourceOfTruth:null;if(m(_e),h(!!V.onboardingCompleted),typeof V.pullCursor=="string"){const Le=V.pullCursor.trim();le.current=Le.length>0?Le:null}else V.pullCursor===null&&(le.current=null)},[d,m,h]),Ut=s.useCallback(async(V,Pe)=>{if(!gl(n))return{success:!1,error:"Workspace setup is required before enabling sync."};const _e=!!V.enabled,Le=V.sourceOfTruth==="cloud"||V.sourceOfTruth==="local"?V.sourceOfTruth:null;let ze=Le;const N=_e?!1:!!V.onboardingCompleted;try{if(_e){if(!Pe.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!Pe.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const G=await Pe.ensureCloudWorkspaceReadyForSync();if(!G.success)return{success:!1,error:G.error||"Workspace sync handshake failed."};const je=Le==="local"||Le===null&&G.provisioned===!0;if(ze===null&&(ze=je?"local":"cloud"),je){const Ie=await Pe.fetchLocalWorkspaceSnapshot();if(Ie.error)return{success:!1,error:Ie.error};const[we,qe]=await Promise.allSettled([fetch("/api/taskforce/taxonomies",{method:"GET",credentials:"include"}).then(bt=>bt.ok?bt.json().catch(()=>({})):Promise.resolve({})).catch(()=>({})),fetch("/api/taskforce/sync/workspace/documents",{method:"GET",credentials:"include"}).then(bt=>bt.ok?bt.json().catch(()=>({})):Promise.resolve({})).catch(()=>({}))]),vt=we.status==="fulfilled"&&Array.isArray(we.value?.taxonomies)?we.value.taxonomies:void 0,st=qe.status==="fulfilled"&&Array.isArray(qe.value?.documents)?qe.value.documents.filter(bt=>{if(!bt||typeof bt!="object")return!1;const De=bt;return typeof De.path=="string"&&typeof De.updatedAt=="string"&&typeof De.content=="string"}):void 0,Re=await Ip(Pe.resolveCloudAuthUrl,{workspaceId:n,tasks:Ie.tasks,archived:Ie.archived,taxonomies:vt,documents:st});if(!Re.ok){const bt=Re.data&&typeof Re.data=="object"?Re.data:{};return{success:!1,error:String(bt.error||`Workspace bootstrap push failed (${Re.status})`)}}}}return await pt({cloudSyncEnabled:_e,sourceOfTruth:ze,onboardingCompleted:N}),d(_e),m(ze),h(N),{success:!0}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[d,m,h,pt]);return s.useEffect(()=>{We.current="",Fe.current="",te.current=new Set,ne.current=new Set,le.current=null,dt.current=!1,Q.current=0,ae.current.delete(n),q.current.delete(n),M.current.delete(n),Ye.current=0,se.current=null,ye.current=!1,ke.current=!1,r(!1),u(!1),T(0),Ne(0),he(0),W(null),Ge(null),b(!1),I(0),z(0),Ae.current!==null&&typeof window<"u"&&(window.clearTimeout(Ae.current),Ae.current=null),B.current&&(B.current.abort(),B.current=null),xe.current=null,j(null)},[n,r,u]),s.useEffect(()=>()=>{Ae.current!==null&&typeof window<"u"&&(window.clearTimeout(Ae.current),Ae.current=null),B.current&&(B.current.abort(),B.current=null),xe.current=null},[]),{workspaceRetryAt:R,setWorkspaceRetryAt:j,isWorkspacePullRetryPending:ut,workspaceBootstrapSyncInProgress:D,setWorkspaceBootstrapSyncInProgress:b,workspaceBootstrapSyncPages:f,setWorkspaceBootstrapSyncPages:I,workspaceBootstrapSyncAppliedChanges:$,setWorkspaceBootstrapSyncAppliedChanges:z,workspaceSyncFailureCount:w,workspaceSyncRetryScheduledCount:Z,workspaceSyncAuthFailureCount:J,workspaceSyncLastFailureSource:ce,workspaceSyncLastFailureStatusCode:U,workspacePushInFlightRef:ye,workspacePullInFlightRef:ke,workspaceLastPushedSignatureRef:We,workspacePendingSignatureRef:Fe,workspaceLastPushedTaskIdsRef:te,workspaceDeletedTaskIdsRef:ne,workspacePullCursorRef:le,workspacePullBootstrapDoneRef:dt,workspaceBackfillForcedRef:ae,workspaceSyncReadyRef:q,workspaceCloudHydratedRef:M,clearWorkspaceRetry:et,scheduleWorkspacePullRetry:yt,isWorkspacePullCooldownActive:mt,markWorkspacePullCooldown:kt,tryAcquireWorkspacePullLease:Dt,releaseWorkspacePullLease:Mt,recordWorkspaceSyncFailure:Zt,incrementWorkspaceSyncAuthFailure:tt,persistWorkspaceSyncPatch:pt,loadWorkspaceSyncState:Rt,applyWorkspaceSyncStateSnapshot:wt,saveWorkspaceCloudSyncSettings:Ut}}class Vp{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 r=typeof n.eventId=="string"?n.eventId.trim():"";if(r&&this.seenEventIds.has(r))return this.telemetry.duplicateDiscarded+=1,{accepted:!1,reason:"duplicate",shouldRecover:!1};const u=typeof n.serverEpoch=="string"?n.serverEpoch.trim():"",d=Number(n.seq);if(!(u.length>0&&Number.isFinite(d)&&d>=0))return r?(this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}):(this.telemetry.invalidDiscarded+=1,{accepted:!1,reason:"invalid",shouldRecover:!1});const h=Math.floor(d);if(this.activeEpoch&&this.activeEpoch!==u)return this.activeEpoch=u,this.lastSeq=h,r&&this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=u,this.lastSeq=h,r&&this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const v=this.lastSeq;if(typeof v=="number"){if(h<=v){this.telemetry.outOfOrderDiscarded+=h===v?0:1,this.telemetry.duplicateDiscarded+=h===v?1:0;const x=h<v;return x&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:h===v?"duplicate":"out-of-order",shouldRecover:x}}if(h>v+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=h,r&&this.rememberEventId(r),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 r=this.seenEventIdQueue.shift();r&&this.seenEventIds.delete(r)}}}function Kp(a){const{enabled:n,workspaceId:r,websocketUrl:u,reconnectBaseMs:d=400,reconnectMaxMs:m=1e4,degradeAfterAttempts:h=5,replayLimit:v=200,onSignal:x,onTelemetry:_}=a,[R,j]=s.useState("degraded-fallback"),D=s.useRef(null),b=s.useRef(null),f=s.useRef(0),I=s.useRef(""),$=s.useRef(!1),z=s.useRef(null),w=s.useRef(null),T=s.useRef(new Vp),[Z,Ne]=s.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),J=s.useMemo(()=>String(r||"").trim(),[r]),he=s.useMemo(()=>String(u||"").trim(),[u]);return s.useEffect(()=>{let ce=!1;const W=()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)},U=()=>{const te=D.current;if(D.current=null,te)try{te.close()}catch{}},Ge=te=>te==="taskforce:replay-gap"||te==="taskforce:replay-reset"?4:te==="taskforce:mutation"||te==="taskforce:replay"?3:1,ye=te=>{const ne=w.current;if(ne){const le=Ge(ne.type),dt=Ge(te.type);if(dt<le||dt===le&&ne.eventId&&!te.eventId)return}w.current=te,z.current!==null&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{if(z.current=null,!w.current||typeof x!="function")return;const le=w.current;w.current=null,x(le)},80)},ke=te=>{try{const ne=JSON.parse(String(te.data||""));return!ne||typeof ne!="object"?null:ne}catch{return null}},Ae=te=>{const ne=typeof te.serverEpoch=="string"?te.serverEpoch.trim():"",le=Number(te.seq);!ne||!Number.isFinite(le)||le<0||(I.current=`${ne}:${Math.floor(le)}`,$.current=!1)},se=()=>{const te=T.current.getTelemetry();Ne(te),typeof _=="function"&&_(te)},Ye=te=>{const ne={type:"taskforce:replay",workspaceId:J,limit:v},le=I.current;le&&(ne.cursor=le),te.send(JSON.stringify(ne))},We=()=>{if(!n||ce)return;W(),f.current+=1;const te=f.current,ne=Math.max(50,Math.floor(d)),le=Math.max(ne,Math.floor(m)),dt=Math.min(le,ne*Math.pow(2,Math.max(0,te-1)));j(te>=h?"degraded-fallback":"reconnecting"),b.current=window.setTimeout(()=>{ce||(b.current=null,Fe())},dt)},Fe=()=>{if(!n||ce||!J||!he)return;U();let te;try{te=new WebSocket(he)}catch{We();return}D.current=te,te.addEventListener("open",()=>{f.current=0,j("connected"),te.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:J})),Ye(te)}),te.addEventListener("message",ne=>{const le=ke(ne);if(!le||typeof le.type!="string")return;const dt=typeof le.workspaceId=="string"?le.workspaceId.trim():J;if(!(!dt||dt!==J)){if(le.type==="taskforce:update"){ye({type:"taskforce:update",workspaceId:J});return}if(le.type==="taskforce:mutation"){const ae=T.current.process({eventId:le.eventId,serverEpoch:le.serverEpoch,seq:le.seq});if(!ae.accepted){se(),ae.shouldRecover&&(I.current="",$.current||($.current=!0,ye({type:"taskforce:replay-gap",workspaceId:J})));return}Ae(le),se(),ye({type:le.type,workspaceId:J,eventId:typeof le.eventId=="string"?le.eventId.trim():void 0});return}if(le.type==="taskforce:replay"){const ae=Array.isArray(le.events)?le.events:[];let q=0;for(const M of ae)T.current.process({eventId:M.eventId,serverEpoch:M.serverEpoch,seq:M.seq}).accepted&&(q+=1,Ae(M));$.current=!1,se(),(q>0||le.truncated===!0)&&ye({type:"taskforce:replay",workspaceId:J}),le.truncated===!0&&Ye(te);return}if(le.type==="taskforce:replay-gap"||le.type==="taskforce:replay-reset"){if(I.current="",$.current)return;$.current=!0,ye({type:le.type,workspaceId:J})}}}),te.addEventListener("close",()=>{D.current===te&&(D.current=null),We()}),te.addEventListener("error",()=>{try{te.close()}catch{}})};return!n||!J||!he?(j("degraded-fallback"),W(),U(),()=>{W(),U()}):(j("reconnecting"),Fe(),()=>{ce=!0,W(),z.current!==null&&(window.clearTimeout(z.current),z.current=null),w.current=null,U()})},[n,J,he,d,m,h,v,x,_]),{connectionState:R,telemetry:Z}}const Ld="taskforce.userGlobalSyncMeta.v1",Jp="taskforce.syncDebug.v1",Yp="Local changes queued — waiting for initial cloud pull before upload.",Xp=45e3,Qp=15e3;function Zp(){if(typeof window>"u")return!1;try{const a=String(window.localStorage.getItem(Jp)||"").trim().toLowerCase();return a==="1"||a==="true"||a==="on"||a==="yes"}catch{return!1}}function rs(a,n){if(!Zp())return;console.info("[Taskforce Sync]",a,n&&typeof n=="object"?n:{})}function Xl(){if(typeof window>"u")return{};try{const a=window.localStorage.getItem(Ld);if(!a)return{};const n=JSON.parse(a);return n&&typeof n=="object"?n:{}}catch{return{}}}function eh(a){if(!(typeof window>"u"))try{window.localStorage.setItem(Ld,JSON.stringify(a))}catch{}}function th(a){const{currentWorkspaceId:n,cloudAuthConfigured:r,runtimeMode:u,isAuthenticated:d,authUserId:m,projectName:h,resolveCloudAuthUrl:v,resolveWebSocketUrl:x,realtimeSyncEnabled:_,tasks:R,archivedTasks:j,taxonomies:D,setupState:b,globalTheme:f,locale:I,globalWeekStartsOn:$,themeUseGlobalDefault:z,setTasks:w,setArchivedTasks:T,setAuthBlocked:Z,setIsAuthenticated:Ne,checkAuthSession:J,setGlobalTheme:he,setCurrentTheme:ce,setSetupState:W,setLocale:U,setGlobalWeekStartsOn:Ge}=a,[ye,ke]=s.useState("disconnected"),[Ae,se]=s.useState(null),[Ye,We]=s.useState(0),[Fe,te]=s.useState(null),[ne,le]=s.useState(null),[dt,ae]=s.useState(null),[q,M]=s.useState(null),[Q,de]=s.useState(null),[xe,B]=s.useState(null),[oe,et]=s.useState(!1),[yt,ut]=s.useState(null),[mt,kt]=s.useState(!1),[Dt,Mt]=s.useState(!1),[Zt,tt]=s.useState(!1),[pt,Rt]=s.useState([]),[wt,Ut]=s.useState(""),[V,Pe]=s.useState("degraded-fallback"),[_e,Le]=s.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),ze=s.useRef(!1),N=s.useRef(null),G=s.useRef(0),je=s.useRef(!1),Ie=s.useRef(new Set),we=s.useRef(""),qe=s.useRef(""),vt=s.useRef(!1),st=s.useRef(new Map),Re=s.useRef(new Map),bt=s.useRef(null),De=s.useRef(new Set),Jt=s.useRef([]),St=s.useRef(0),ls=s.useRef({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),Ee=s.useRef(()=>Promise.resolve(!1)),zt=s.useRef(!1),ts=s.useRef(async()=>{}),Et=s.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null)},[]),qt=s.useCallback(S=>{if(typeof window>"u")return;Et();const Y=Math.max(1,Math.floor(G.current)+1);G.current=Y;const pe=zd(Y),Te=Number.isFinite(Number(S))?Math.max(0,Math.floor(Number(S))):0,Nt=Math.max(pe,Te);N.current=window.setTimeout(()=>{N.current=null,ts.current({preferCloudOnFirstSync:!1})},Nt)},[Et]);s.useEffect(()=>{qe.current="",Rt([]),Ut(""),B(null),st.current.delete(n),Re.current.delete(n),ft.current=new Map,ss.current=new Set,Xt.current=new Map,De.current=new Set,Jt.current=[]},[n]);const Ct=s.useCallback(()=>{M(new Date().toISOString())},[]),{workspaceRetryAt:As,isWorkspacePullRetryPending:ds,workspaceBootstrapSyncInProgress:Ss,setWorkspaceBootstrapSyncInProgress:Ds,workspaceBootstrapSyncPages:us,setWorkspaceBootstrapSyncPages:Cs,workspaceBootstrapSyncAppliedChanges:L,setWorkspaceBootstrapSyncAppliedChanges:F,workspaceSyncFailureCount:re,workspaceSyncRetryScheduledCount:K,workspaceSyncAuthFailureCount:H,workspaceSyncLastFailureSource:me,workspaceSyncLastFailureStatusCode:Oe,workspacePushInFlightRef:ie,workspacePullInFlightRef:ve,workspaceLastPushedSignatureRef:_t,workspacePendingSignatureRef:Se,workspaceLastPushedTaskIdsRef:Ue,workspaceDeletedTaskIdsRef:ht,workspacePullCursorRef:nt,workspacePullBootstrapDoneRef:It,workspaceBackfillForcedRef:jt,workspaceSyncReadyRef:Vt,workspaceCloudHydratedRef:rt,clearWorkspaceRetry:ot,scheduleWorkspacePullRetry:y,isWorkspacePullCooldownActive:ue,markWorkspacePullCooldown:Ke,tryAcquireWorkspacePullLease:At,releaseWorkspacePullLease:ps,recordWorkspaceSyncFailure:Kt,incrementWorkspaceSyncAuthFailure:Lt,persistWorkspaceSyncPatch:vs,loadWorkspaceSyncState:Ms,applyWorkspaceSyncStateSnapshot:Bs,saveWorkspaceCloudSyncSettings:Qe}=qp({currentWorkspaceId:n,setWorkspaceSyncReady:Mt,setWorkspaceCloudHydrated:tt,onFailureRecorded:Ct,setWorkspaceCloudSyncEnabled:et,setWorkspaceSyncSourceOfTruth:ut,setWorkspaceSyncOnboardingCompleted:kt,setUserGlobalLastSyncedAt:se,setWorkspaceLastPullAt:le,setWorkspaceLastPushAt:ae}),ft=s.useRef(new Map),ss=s.useRef(new Set),Xt=s.useRef(new Map),Xe=s.useCallback(S=>{const Y=String(S||"").trim();if(!Y)return null;const Te=Xl()[Y]?.updatedAt;return typeof Te=="string"&&Te.trim().length>0?Te.trim():null},[]),at=s.useCallback((S,Y)=>{const pe=String(S||"").trim(),Te=String(Y||"").trim();if(!pe||!Te)return;const Nt=Xl();Nt[pe]={updatedAt:Te},eh(Nt)},[]),Bt=s.useCallback(()=>{const S=b?.mode==="operations"?"operations":"core";return{theme:f,operatingMode:S,localization:{locale:I,weekStartsOn:$}}},[f,b?.mode,I,$]),bs=s.useCallback(async S=>{if(!(!S||typeof S!="object")){je.current=!0;try{const Y={};if((S.theme==="dark"||S.theme==="light"||S.theme==="midnight")&&(he(S.theme),z&&ce(S.theme),Y.theme=S.theme),(S.operatingMode==="core"||S.operatingMode==="operations")&&(W(pe=>pe&&{...pe,mode:S.operatingMode}),Y.setup={mode:S.operatingMode}),S.localization&&typeof S.localization=="object"){const pe={};if(typeof S.localization.locale=="string"&&S.localization.locale.trim().length>0){const Nt=Dd(S.localization.locale.trim());U(Nt)}const Te=String(S.localization.weekStartsOn||"").trim().toLowerCase();(Te==="sunday"||Te==="monday")&&(Ge(Te),pe.weekStartsOn=Te),Object.keys(pe).length>0&&(Y.schedulePreferences=pe)}Object.keys(Y).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(Y)})}finally{je.current=!1}}},[z,he,ce,W,U,Ge]),xt=s.useCallback(async S=>{const Y=S?.preferCloudOnFirstSync!==!1;if(!r)return;if(u!=="local"||!d){Et(),G.current=0,ke("disconnected");return}const pe=String(m||"").trim();if(!pe||pe==="anonymous"){Et(),G.current=0,ke("disconnected");return}if(!ze.current){ke("syncing"),te(null),ze.current=!0;try{const Te=await Mp({resolveCloudAuthUrl:v,userId:pe,preferCloudOnFirstSync:Y,getLocalUpdatedAt:Xe,buildLocalSettings:Bt,applyRemoteSettings:bs});if(!Te.success){ke("error"),Te.transient?(te(Te.error||"Sync failed temporarily. Retrying automatically."),qt(Te.retryAfterMs)):(Et(),G.current=0,te(Te.error||"Sync failed."));return}Et(),G.current=0;const Nt=String(Te.updatedAt||"").trim()||new Date().toISOString();at(pe,Nt),se(Nt),We(0),ke("idle"),te(null),Ie.current.add(pe),Te.mode==="pulled"&&(we.current="")}catch{ke("error"),te("Sync failed temporarily. Retrying automatically."),qt()}finally{ze.current=!1}}},[u,d,m,Xe,at,bs,Bt,v,r,Et,qt]);s.useEffect(()=>{ts.current=xt},[xt]),s.useEffect(()=>()=>{Et()},[Et]);const $t=s.useCallback(async()=>zp({cloudAuthConfigured:r,runtimeMode:u,isAuthenticated:d,resolveCloudAuthUrl:v,workspaceId:n,workspaceName:h||n}),[r,u,d,v,n,h]),O=s.useCallback(()=>$p({tasks:R||[],archivedTasks:j||[],lastPushedTaskIds:Ue.current,pendingDeletedTaskIds:ht.current,taxonomies:D||[],documents:pt||[],lastPushedDocumentPaths:ss.current,lastPushedDocumentWatermarks:Xt.current,lastPushedWatermarks:ft.current}),[R,j,D,pt]),Ve=s.useCallback((S,Y)=>{u==="local"&&fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({...Y,workspaceId:S})}).catch(pe=>{rs("sync_event_post_failed",{workspaceId:S,eventType:Y.eventType,status:Y.status,error:String(pe?.message||pe||"")})})},[u]),Ft=s.useCallback(()=>Fp({workspaceId:n,tasks:R||[],archivedTasks:j||[],pendingDeletedTaskIds:ht.current,taxonomies:D||[],documents:pt||[]}),[R,j,n,D,pt]),Tt=s.useCallback(async()=>{if(u!=="local")return;const S=String(n||"").trim();if(!(!S||S.toLowerCase()==="default"))try{const Y=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(S)}`,{method:"GET",credentials:"include"});if(!Y.ok)return;const pe=await Y.json().catch(()=>({})),Te=Array.isArray(pe?.documents)?pe.documents.map(Ze=>({path:String(Ze?.path||"").trim(),updatedAt:String(Ze?.updatedAt||"").trim(),content:typeof Ze?.content=="string"?Ze.content:""})).filter(Ze=>Ze.path.length>0):[],Nt=typeof pe?.fingerprint=="string"?pe.fingerprint:JSON.stringify(Te.map(Ze=>`${Ze.path}:${Ze.updatedAt}:${Ze.content.length}`).sort());if(Nt===qe.current)return;qe.current=Nt,Rt(Te),Ut(Nt)}catch(Y){const pe=String(Y?.message||Y||"");rs("documents_snapshot_refresh_failed",{workspaceId:S,error:pe}),Ve(S,{eventType:"push",status:"error",errorMessage:`Workspace documents snapshot refresh failed: ${pe}`})}},[u,n,Ve]),Ot=s.useCallback(async(S,Y)=>{ot(),rs("sync_auth_failure",{source:S,status:Y,workspaceId:n}),Lt(),Kt(S,Y),ke("error");const pe="Session expired. Sign in again to resume cloud sync.";te(pe),de(pe),Z(!0),Ne(!1),await J()},[ot,n,J,Kt,Lt,Z,Ne]),Je=s.useCallback(async()=>{const S=String(n||"").trim();if(!S||S.toLowerCase()==="default"){rs("sync_ready_blocked_unresolved_workspace",{workspaceKey:S,runtimeMode:u}),ke("error");const pe="Workspace sync blocked: local workspace ID is unresolved.";return te(pe),de(pe),M(new Date().toISOString()),Mt(!1),!1}if(Vt.current.has(S))return!0;const Y=await $t();if(!Y.success){if(rs("sync_ready_failed",{workspaceKey:S,statusCode:Y.statusCode||null,error:Y.error||null}),Y.statusCode===401)return await Ot("handshake",401),!1;if(Y.statusCode===429){Kt("handshake",429),ke("error");const Te=Y.error||"Sync paused — rate limit reached. Will retry automatically.";return te(Te),de(Te),M(new Date().toISOString()),Mt(!1),y(()=>Ee.current(),{minDelayMs:Y.retryAfterMs,workspaceId:S}),!1}Kt("handshake"),ke("error");const pe=Y.error||"Workspace sync handshake failed.";return te(pe),de(pe),Mt(!1),!1}return rs("sync_ready_ok",{workspaceKey:S}),Vt.current.add(S),Mt(!0),!0},[n,$t,u,Kt,Ot,y]),Yt=s.useCallback(async S=>{if(!r||u!=="local"||!oe||!d&&!await J())return!1;const Y=String(n||"").trim();if(!Y||Y.toLowerCase()==="default")return!1;if(yt==="cloud"&&!rt.current.has(Y)){Se.current=S;const Te=Date.now(),Nt=st.current.get(Y)||Te;if(st.current.set(Y,Nt),B(Yp),ds()){const Ze=Te-Nt,$e=Re.current.get(Y)||0;Ze>=Xp&&Te>=$e&&(Re.current.set(Y,Te+Qp),rs("push_blocked_waiting_hydration_force_pull",{workspaceId:Y,blockedMs:Ze}),ot(),window.setTimeout(()=>{Ee.current()},120))}return!1}if(ie.current)return Se.current=S,!1;ie.current=!0,ke("syncing"),te(null);const pe=Date.now();try{if(await Tt(),!await Je())return!1;const Nt=O();rs("push_start",{workspaceId:n,changeCount:Nt.changes.length,deleteCount:Nt.deleteTaskIds.size}),We(Nt.changes.length);const Ze=await Rp({resolveCloudAuthUrl:v,workspaceId:n,payload:Nt,ensureCloudWorkspaceReadyForSync:$t});if(!Ze.success){if(Ze.status===401)return await Ot("push",401),!1;rs("push_failed_http",{workspaceId:n,status:Ze.status||0,error:Ze.error||null,code:Ze.code||null,elapsedMs:Date.now()-pe,requestMs:Ze.requestMs}),Kt("push",Ze.status||void 0),ke("error");const hs=Ze.error?`Workspace sync push failed (${Ze.status||0}): ${Ze.error}`:`Workspace sync push failed (${Ze.status||0})`;return te(hs),de(hs),!1}_t.current=S,Ue.current=Ze.currentTaskIds,ss.current=new Set(Ze.currentDocumentPaths),Xt.current=new Map(Ze.currentDocumentWatermarks);for(const[hs,as]of Ze.pushedWatermarks)ft.current.set(hs,as);if(Ze.deleteTaskIds.size>0)for(const hs of Ze.deleteTaskIds)ht.current.delete(hs),ft.current.delete(hs);const $e=Ze.syncedAt||new Date().toISOString();if(rs("push_success",{workspaceId:n,syncedAt:$e,changeCount:Ze.changeCount,deleteCount:Ze.deleteCount,elapsedMs:Date.now()-pe,requestMs:Ze.requestMs}),se($e),ae($e),We(0),ke("idle"),te(null),de(null),M(null),Array.isArray(Ze.emittedEventIds)&&Ze.emittedEventIds.length>0){for(const hs of Ze.emittedEventIds){const as=String(hs||"").trim();as&&(De.current.has(as)||(De.current.add(as),Jt.current.push(as)))}for(;Jt.current.length>2048;){const hs=Jt.current.shift();hs&&De.current.delete(hs)}}return vs({lastPushAt:$e,lastSyncedAt:$e}),!0}catch{rs("push_failed_exception",{workspaceId:n,elapsedMs:Date.now()-pe}),Kt("push"),ke("error");const Te="Workspace sync push failed.";return te(Te),de(Te),!1}finally{ie.current=!1;const Te=Se.current;Te&&Te!==_t.current&&(Se.current="",window.setTimeout(()=>{Yt(Te)},120))}},[r,u,d,J,oe,yt,O,Je,Tt,$t,Ot,Kt,ot,ds,n,v]),Ht=s.useCallback(async()=>{if(!r||u!=="local"||!oe)return rs("pull_abort",{reason:"config_disabled",cloudAuthConfigured:r,runtimeMode:u,workspaceCloudSyncEnabled:oe}),!1;if(!d&&!await J())return rs("pull_abort",{reason:"not_authenticated"}),!1;const S=String(n||"").trim();if(!S||S.toLowerCase()==="default")return rs("pull_abort",{reason:"invalid_workspace",workspaceKey:S}),!1;if(ds())return rs("pull_abort",{reason:"retry_pending"}),!1;if(ve.current)return rs("pull_abort",{reason:"already_in_flight"}),!1;if(!await At(S))return Ke(S,12e3),rs("pull_abort",{reason:"non_leader_tab",workspaceId:S}),!1;ve.current=!0;const pe=!rt.current.has(S);pe&&(Ds(!0),Cs(0),F(0)),ke("syncing"),te(null);const Te=Date.now();try{if(!await Je())return rs("pull_abort",{reason:"ensure_ready_failed"}),!1;const Ze=It.current?nt.current:null;rs("pull_start",{workspaceId:n,cursor:Ze});const $e=await Ep({resolveCloudAuthUrl:v,workspaceId:n,cursor:Ze,bootstrap:pe,ensureCloudWorkspaceReadyForSync:$t,maxPages:20,onPagePulled:pe?()=>{Cs(ns=>ns+1)}:void 0,onChangesApplied:pe?ns=>{F(_s=>_s+ns)}:void 0});if(!$e.success){if($e.kind==="pull_http"){if($e.status===401)return await Ot("pull",401),!1;rs("pull_failed_http",{workspaceId:n,status:$e.status||0,cursor:$e.cursor,elapsedMs:Date.now()-Te,requestMs:$e.pullRequestMs,applyMs:$e.applyMs}),Ve(n,{eventType:"pull",status:"error",statusCode:$e.status||0,requestMs:$e.pullRequestMs}),Kt("pull",$e.status||void 0),ke("error");const _s=`Workspace sync pull failed (${$e.status||0})`;return te(_s),de(_s),($e.status||0)===429||($e.status||0)>=500?y(()=>Ee.current(),{minDelayMs:$e.retryAfterMs,workspaceId:S}):ot(),!1}if($e.kind==="apply_auth")return await Ot("apply",401),!1;if($e.kind==="apply_all_candidates"){const _s=$e.failures||[];rs("apply_failed_all_candidates",{workspaceId:n,failures:_s}),ke("error");const _a=_s.length>0?` [${_s.join(", ")}]`:"";Kt("apply");const Rs=`Workspace sync apply failed${_a}`;return te(Rs),de(Rs),$e.hasTransientApplyFailure?y(()=>Ee.current(),{workspaceId:S}):ot(),!1}if($e.kind==="apply_payload"){rs("apply_failed_payload",{workspaceId:n,error:String($e.error||"")}),ke("error"),Kt("apply");const _s=String($e.error||"Workspace sync apply failed.");return te(_s),de(_s),!1}rs("pull_failed_exception",{workspaceId:n,elapsedMs:Date.now()-Te}),Kt("pull"),ke("error");const ns="Workspace sync pull failed.";return te(ns),de(ns),y(()=>Ee.current(),{workspaceId:S}),!1}$e.pulledDeleteTaskIds.size>0&&(w(ns=>ns.filter(_s=>!$e.pulledDeleteTaskIds.has(String(_s.id||"")))),T(ns=>ns.filter(_s=>!$e.pulledDeleteTaskIds.has(String(_s.id||"")))));const hs=Array.isArray($e.documentDecryptFailures)?$e.documentDecryptFailures.filter(ns=>String(ns||"").trim().length>0):[];if(hs.length>0){const ns=`Some synced documents could not be decrypted (${hs.length}).`;B(ns),rs("pull_document_decrypt_partial_failure",{workspaceId:n,count:hs.length,paths:hs}),Ve(n,{eventType:"apply",status:"error",errorMessage:`${ns} paths=${hs.join(", ")}`,changeCount:$e.appliedChanges})}else B(null);nt.current=$e.cursor||null,It.current=!0,rt.current.add(S),st.current.delete(S),Re.current.delete(S),tt(!0);const as=Ft();if(as&&as!==_t.current&&(Se.current=as),$e.appliedChanges>0&&($e.pulledActiveUpserts||$e.pulledArchivedUpserts))try{const ns=[];$e.pulledActiveUpserts&&ns.push(fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"})),$e.pulledArchivedUpserts&&ns.push(fetch("/api/taskforce/archive",{method:"GET",credentials:"include"}));const _s=await Promise.all(ns);for(const _a of _s){if(!_a.ok)continue;const Rs=await _a.json().catch(()=>({}));Array.isArray(Rs?.tasks)?w(Rs.tasks):Array.isArray(Rs?.archived)&&T(Rs.archived)}}catch{rs("pull_local_refresh_failed",{workspaceId:n,appliedChanges:$e.appliedChanges}),Ve(n,{eventType:"apply",status:"error",errorMessage:"Local state refresh failed after apply-local.",changeCount:$e.appliedChanges})}const Ns=$e.syncedAt||new Date().toISOString();rs("pull_success",{workspaceId:n,syncedAt:Ns,appliedChanges:$e.appliedChanges,pulledDeleteCount:$e.pulledDeleteTaskIds.size,cursor:nt.current,elapsedMs:Date.now()-Te,requestMs:$e.pullRequestMs,applyMs:$e.applyMs,pages:$e.pages}),Ve(n,{eventType:"pull",status:"success",changeCount:$e.appliedChanges,requestMs:$e.pullRequestMs}),se(Ns),le(Ns),We(0),ke("idle"),te(null),de(null),M(null),ot(),vs({pullCursor:nt.current,lastPullAt:Ns,lastSyncedAt:Ns}),zt.current||(zt.current=!0,kt(!0),vs({onboardingCompleted:!0}));const Ca=Se.current;return Ca&&Ca!==_t.current&&(Se.current="",window.setTimeout(()=>{Yt(Ca)},120)),!0}catch{rs("pull_failed_exception",{workspaceId:n,elapsedMs:Date.now()-Te}),Kt("pull"),ke("error");const Nt="Workspace sync pull failed.";return te(Nt),de(Nt),y(()=>Ee.current(),{workspaceId:S}),!1}finally{pe&&Ds(!1),ve.current=!1,ps(S)}},[r,u,d,J,oe,v,n,ds,Je,Ot,Kt,ot,y,At,ps,Ke,Ve,vs,Ft]);s.useEffect(()=>{Ee.current=Ht},[Ht]),s.useEffect(()=>{zt.current=mt},[mt]);const Ls=s.useCallback(S=>{if(!r||u!=="local"||!oe)return;const Y=String(S?.eventId||"").trim();if(Y&&De.current.delete(Y)){rs("realtime_signal_suppressed_self_echo",{workspaceId:n,eventId:Y,signalType:S.type});return}ds()||ve.current||(bt.current!==null&&window.clearTimeout(bt.current),bt.current=window.setTimeout(()=>{bt.current=null,Ee.current()},180))},[r,u,oe,ds,ve,n]),Us=x("/taskforce-ws"),ya=Kp({enabled:!!(_&&r&&u==="local"&&oe&&d),workspaceId:n,websocketUrl:Us,onSignal:Ls,onTelemetry:Le});s.useEffect(()=>{Pe(ya.connectionState)},[ya.connectionState]),s.useEffect(()=>{const S=_e,Y=ls.current,pe=Math.max(0,S.duplicateDiscarded-Y.duplicateDiscarded),Te=Math.max(0,S.outOfOrderDiscarded-Y.outOfOrderDiscarded),Nt=Math.max(0,S.invalidDiscarded-Y.invalidDiscarded);if(pe===0&&Te===0&&Nt===0)return;const Ze=Date.now();Te===0&&Ze-St.current<5e3||(St.current=Ze,ls.current={...S},Ve(n,{eventType:"apply",status:Te>0?"error":"success",errorMessage:`Realtime telemetry duplicate=${pe} outOfOrder=${Te} invalid=${Nt}`}))},[_e,Ve,n]),s.useEffect(()=>()=>{bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]);const na=s.useCallback(async()=>{const[S,Y]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(!S.ok||!Y.ok)return{tasks:[],archived:[],error:"Failed to read local workspace snapshot before sync bootstrap."};const pe=await S.json().catch(()=>({})),Te=await Y.json().catch(()=>({}));return{tasks:Array.isArray(pe?.tasks)?pe.tasks:[],archived:Array.isArray(Te?.archived)?Te.archived:[]}},[]),Vs=s.useCallback(async S=>Qe(S,{cloudAuthConfigured:r,isAuthenticated:d,resolveCloudAuthUrl:v,ensureCloudWorkspaceReadyForSync:$t,fetchLocalWorkspaceSnapshot:na}),[r,d,v,$t,na,Qe]),ua=s.useCallback(async()=>{await xt({preferCloudOnFirstSync:!1})},[xt]),$s=s.useCallback(async()=>{if(ot(),!r||u!=="local"||!oe||!d&&!await J())return;const S=Ft();S&&S!==_t.current&&Yt(S),await Ht()},[ot,r,u,d,J,oe,Ft,Yt,Ht]),P=s.useCallback(async()=>{if(ot(),!r||u!=="local"||!oe||!d&&!await J())return;nt.current=null,It.current=!1;const S=String(n||"").trim();!S||S.toLowerCase()==="default"||(rt.current.delete(S),tt(!1),ft.current=new Map,rs("pull_cursor_reset",{workspaceId:n}),vs({pullCursor:null}),await Ht())},[ot,r,u,d,J,oe,n,Ht]);return s.useEffect(()=>{if(!r||u!=="local"||!oe)return;Tt();const S=window.setInterval(()=>{Tt()},12e3);return()=>window.clearInterval(S)},[r,u,oe,Tt]),s.useEffect(()=>{if(!r||u!=="local"||!oe)return;const S=Ft();if(!S||S===_t.current)return;if(ie.current){Se.current=S;return}const Y=window.setTimeout(()=>{Yt(S)},1500);return()=>window.clearTimeout(Y)},[r,u,oe,Ft,wt,Yt]),s.useEffect(()=>{r&&u==="local"&&oe||(ot(),Mt(!1),tt(!1))},[r,u,oe,ot]),s.useEffect(()=>{if(!r||u!=="local"||!oe||ds())return;Ht();const S=window.setInterval(()=>{Ht()},8e3);return()=>window.clearInterval(S)},[r,u,oe,ds,Ht]),s.useEffect(()=>{if(!r||u!=="local"||!oe||R.length>0||j.length>0)return;const S=String(n||"").trim();!S||S.toLowerCase()==="default"||jt.current.has(S)||(jt.current.add(S),nt.current=null,It.current=!1,Ht())},[r,u,oe,n,R.length,j.length,Ht]),s.useEffect(()=>{u!=="local"||!d||!m||m==="anonymous"||xt({preferCloudOnFirstSync:!0})},[u,d,m,xt]),s.useEffect(()=>{if(u!=="local"||!d||!m||m==="anonymous"||!Ie.current.has(m)||je.current)return;const S=Bt(),Y=JSON.stringify(S);if(!we.current){we.current=Y;return}if(Y===we.current)return;we.current=Y,We(1),at(m,new Date().toISOString());const pe=window.setTimeout(()=>{xt({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(pe)},[u,d,m,Bt,at,xt]),{userGlobalSyncStatus:ye,setUserGlobalSyncStatus:ke,userGlobalLastSyncedAt:Ae,setUserGlobalLastSyncedAt:se,userGlobalSyncPendingChanges:Ye,setUserGlobalSyncPendingChanges:We,userGlobalSyncError:Fe,setUserGlobalSyncError:te,workspaceLastPullAt:ne,setWorkspaceLastPullAt:le,workspaceLastPushAt:dt,setWorkspaceLastPushAt:ae,workspaceLastErrorAt:q,setWorkspaceLastErrorAt:M,workspaceLastErrorMessage:Q,setWorkspaceLastErrorMessage:de,workspaceLastWarningMessage:xe,setWorkspaceLastWarningMessage:B,workspaceCloudSyncEnabled:oe,realtimeConnectionState:V,realtimeTelemetry:_e,setWorkspaceCloudSyncEnabled:et,workspaceSyncSourceOfTruth:yt,setWorkspaceSyncSourceOfTruth:ut,workspaceSyncOnboardingCompleted:mt,setWorkspaceSyncOnboardingCompleted:kt,workspaceSyncReady:Dt,setWorkspaceSyncReady:Mt,workspaceCloudHydrated:Zt,setWorkspaceCloudHydrated:tt,workspaceSyncDocuments:pt,setWorkspaceSyncDocuments:Rt,workspaceSyncDocumentsFingerprint:wt,setWorkspaceSyncDocumentsFingerprint:Ut,syncInFlightRef:vt,workspaceRetryAt:As,isWorkspacePullRetryPending:ds,workspaceBootstrapSyncInProgress:Ss,setWorkspaceBootstrapSyncInProgress:Ds,workspaceBootstrapSyncPages:us,setWorkspaceBootstrapSyncPages:Cs,workspaceBootstrapSyncAppliedChanges:L,setWorkspaceBootstrapSyncAppliedChanges:F,workspaceSyncFailureCount:re,workspaceSyncRetryScheduledCount:K,workspaceSyncAuthFailureCount:H,workspaceSyncLastFailureSource:me,workspaceSyncLastFailureStatusCode:Oe,workspacePushInFlightRef:ie,workspacePullInFlightRef:ve,workspaceLastPushedSignatureRef:_t,workspacePendingSignatureRef:Se,workspaceLastPushedTaskIdsRef:Ue,workspaceDeletedTaskIdsRef:ht,workspacePullCursorRef:nt,workspacePullBootstrapDoneRef:It,workspaceBackfillForcedRef:jt,workspaceSyncReadyRef:Vt,workspaceCloudHydratedRef:rt,clearWorkspaceRetry:ot,scheduleWorkspacePullRetry:y,isWorkspacePullCooldownActive:ue,markWorkspacePullCooldown:Ke,tryAcquireWorkspacePullLease:At,releaseWorkspacePullLease:ps,recordWorkspaceSyncFailure:Kt,incrementWorkspaceSyncAuthFailure:Lt,persistWorkspaceSyncPatch:vs,loadWorkspaceSyncState:Ms,applyWorkspaceSyncStateSnapshot:Bs,syncUserGlobalSettings:xt,getLocalUserSyncUpdatedAt:Xe,setLocalUserSyncUpdatedAt:at,buildUserGlobalSyncPayload:Bt,applyRemoteUserGlobalSyncPayload:bs,ensureCloudWorkspaceReadyForSync:$t,buildWorkspaceSyncPayload:O,buildWorkspaceSyncSignature:Ft,refreshWorkspaceSyncDocumentsSnapshot:Tt,handleSyncAuthFailure:Ot,ensureWorkspaceSyncReady:Je,pushWorkspaceChangesToCloud:Yt,pullWorkspaceChangesFromCloud:Ht,fetchLocalWorkspaceSnapshot:na,saveWorkspaceCloudSyncSettings:Vs,retryUserGlobalSettingsSync:ua,retryWorkspaceCloudSync:$s,resetWorkspaceSyncCursorAndPull:P}}function sh(a){const n=a.runtimeMode==="cloud",r=!!(a.shouldGateProtectedApiCalls&&n&&!a.authSessionResolved),u=!!(a.shouldGateProtectedApiCalls&&n&&a.authSessionResolved&&a.authRequiredForApi&&!a.isAuthenticated);return{shouldDeferProtectedApiCalls:r,shouldBlockProtectedApiCalls:u,canCallProtectedApi:!(r||u)}}function ah(a){return!!(!a.isOpen||!a.canCallProtectedApi||a.authBlocked||a.authRequiredForApi&&!a.isAuthenticated)}function nh(a){return!!(a.shouldGateProtectedApiCalls&&!a.authSessionResolved||a.authRequiredForApi&&!a.isAuthenticated)}const yl=[{value:"agent",label:"AI"},{value:"user",label:"User"},{value:"unassigned",label:"Unassigned"}];function oh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,14)}`}const kl="https://app.taskforcehq.ai",Rd="taskforce.workspaceContext.v2",vi=12e3;function Ed(a){const n=Bd(a);return`${Rd}.${n}`}function rh(a){const n=yp(a);return`${Rd}.${n}`}function gc(a){if(typeof window>"u")return"";try{const n=Ed(a),r=String(window.localStorage.getItem(n)||"").trim();if(r&&r.length<=120&&!/\s/.test(r))return r;const u=rh(a),d=String(window.localStorage.getItem(u)||"").trim();return d&&d.length<=120&&!/\s/.test(d)?(window.localStorage.setItem(n,d),d):""}catch{return""}}function ih(a,n){if(typeof window>"u")return;const r=String(a||"").trim();try{if(!r||xp(r))return;const u=Ed(n),d=String(window.localStorage.getItem(u)||"").trim();if(!r&&d&&d.toLowerCase()!=="default")return;window.localStorage.setItem(u,r)}catch{}}function ch({config:a={},initialTaskId:n,onTaskCountChange:r,onClose:u}){const d={...op,...a},{categories:m,types:h,apiEndpoint:v,apiBaseUrl:x,cloudAuthBaseUrl:_,wsBaseUrl:R,shortcut:j}=d,D=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",b=D==="localhost"||D==="127.0.0.1"||D==="::1",f=typeof window<"u"&&!b,[I,$]=s.useState({baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[z,w]=s.useState(!1),T=s.useCallback(o=>typeof o=="string"?o.trim().replace(/\/+$/,""):"",[]);s.useEffect(()=>{if(typeof window>"u"){w(!0);return}let o=!1;return(async()=>{try{const i=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!i.ok)return;const l=await i.json().catch(()=>({})),p=l?.config&&typeof l.config=="object"?l.config:{};if(o)return;const C=String(p.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",X=String(p.workspaceMode||"").trim(),lt=X==="single-local"||X==="multi-cloud"?X:C==="cloud"?"multi-cloud":"single-local",Pt=String(p.authSource||"").trim().toLowerCase()==="local"?"local":"cloud";$({baseUrl:T(p.baseUrl),apiBaseUrl:T(p.apiBaseUrl),cloudAuthBaseUrl:T(p.cloudAuthBaseUrl),wsBaseUrl:T(p.wsBaseUrl),cloudAuthViaLocalProxy:!!p.cloudAuthViaLocalProxy,authSource:Pt,workspaceMode:lt,workspaceSwitchingEnabled:typeof p.workspaceSwitchingEnabled=="boolean"?!!p.workspaceSwitchingEnabled:lt==="multi-cloud"})}catch{}finally{o||w(!0)}})(),()=>{o=!0}},[T]);const Z=typeof window>"u"?"":b?kl:"",Ne=T(void 0),J=T(void 0),he=T(void 0),ce=T(x),W=T(_),U=ce||I.apiBaseUrl||I.baseUrl||J||Ne||"",Ge=(W||I.cloudAuthBaseUrl||I.baseUrl||he||Ne||U||Z).trim().replace(/\/+$/,""),ye=!!Ge&&!U,ke=z&&(!!(Ge||U)||f),Ae=ke&&!ye,se=!!(Ge||U||f),Ye=f?"cloud":"local",We=s.useCallback(o=>!o||/^https?:\/\//i.test(o)||!U||!o.startsWith("/")?o:`${U}${o}`,[U]),Fe=s.useCallback(o=>{if(!o||/^https?:\/\//i.test(o)||!o.startsWith("/"))return o;const i=o.startsWith("/api/taskforce/auth/")||o.startsWith("/api/taskforce/sync/");if(!f&&i&&(!z||I.cloudAuthViaLocalProxy))return o;const l=Ge||U;if(l){const p=`${l}${o}`;if(typeof window<"u"&&!f&&i)try{if(new URL(p,window.location.origin).origin===window.location.origin)return`${kl}${o}`}catch{return`${kl}${o}`}return p}return o},[z,I.cloudAuthViaLocalProxy,Ge,U,f]),te=s.useCallback(o=>{const i=String(o||"").trim()||"/taskforce-ws",l=i.startsWith("/")?i:`/${i}`,p=String(R||I.wsBaseUrl||U||"").trim().replace(/\/+$/,""),g=typeof window<"u"?window.location.origin:"",C=p||g;if(!C)return"";try{const X=new URL(l,C);return X.protocol==="https:"&&(X.protocol="wss:"),X.protocol==="http:"&&(X.protocol="ws:"),X.toString()}catch{return""}},[R,I.wsBaseUrl,U]),[ne,le]=s.useState("tasks"),[dt,ae]=s.useState(!1),[q,M]=s.useState(!1),[Q,de]=s.useState(d.theme||"dark"),[xe,B]=s.useState(d.theme||"dark"),[oe,et]=s.useState(!0),[yt]=s.useState(".taskforce"),ut=!1,[mt,kt]=s.useState(!1),[Dt,Mt]=s.useState([]),[Zt,tt]=s.useState([]),[pt,Rt]=s.useState(""),[wt,Ut]=s.useState(null),[V,Pe]=s.useState(""),[_e,Le]=s.useState(null),[ze,N]=s.useState(""),[G,je]=s.useState(""),Ie=s.useMemo(()=>kp(ze),[ze]),[we,qe]=s.useState(""),[vt,st]=s.useState(""),[Re,bt]=s.useState([]),[De,Jt]=s.useState(()=>Ye),St=wp(De),ls=I.workspaceMode==="single-local"||I.workspaceMode==="multi-cloud"?I.workspaceMode:St.workspaceMode,Ee=typeof I.workspaceSwitchingEnabled=="boolean"?I.workspaceSwitchingEnabled:St.workspaceSwitchingEnabled,[zt,ts]=s.useState(!1),[Et,qt]=s.useState(!1),[Ct,As]=s.useState(!1),[ds,Ss]=s.useState("anonymous"),[Ds,us]=s.useState(""),[Cs,L]=s.useState(!0),[F,re]=s.useState(()=>{if(Ye==="local")return"default";const o=gc(Ie);return o&&o.toLowerCase()!=="default"?o:"default"}),[K,H]=s.useState([]),[me,Oe]=s.useState(!1),[ie,ve]=s.useState(!1),[_t,Se]=s.useState("idle"),[Ue,ht]=s.useState(null),[nt,It]=s.useState(null),jt=s.useRef(null),Vt=s.useRef(0),rt=s.useRef(!1),ot=s.useMemo(()=>sh({shouldGateProtectedApiCalls:Ae,runtimeMode:De,authSessionResolved:ie,authRequiredForApi:zt,isAuthenticated:Ct}),[Ae,De,ie,zt,Ct]),y=ot.shouldDeferProtectedApiCalls,ue=ot.shouldBlockProtectedApiCalls,[Ke,At]=s.useState(null),[ps,Kt]=s.useState(null),[Lt,vs]=s.useState(!1),[Ms,Bs]=s.useState("unknown"),[Qe,ft]=s.useState(null),[ss,Xt]=s.useState(d.shortcut||"Alt+T"),[Xe,at]=s.useState(d.priorities||[]),[Bt,bs]=s.useState(d.approaches||[]),[xt,$t]=s.useState(""),[O,Ve]=s.useState(!1),[Ft,Tt]=s.useState(!1),[Ot,Je]=s.useState(!0),[Yt,Ht]=s.useState(()=>mp()),Ls=s.useMemo(()=>hp(),[]),[Us,qs]=s.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[ya,na]=s.useState(!1),[Vs,ua]=s.useState(!1),[$s,P]=s.useState(!1),[S,Y]=s.useState(""),[pe,Te]=s.useState(null);s.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const o=window.fetch.bind(window),i=g=>g==="/api/taskforce/sync/workspace/apply-local",l=g=>{if(typeof g=="string")return De!=="cloud"?g:g.startsWith("/api/taskforce")&&!i(g)?We(g):g;if(g instanceof URL)return De!=="cloud"?g:g.origin===window.location.origin&&g.pathname.startsWith("/api/taskforce")?i(g.pathname)?g:new URL(We(`${g.pathname}${g.search}${g.hash}`)):g;if(typeof Request<"u"&&g instanceof Request){if(De!=="cloud")return g;const C=new URL(g.url,window.location.origin);if(C.origin===window.location.origin&&C.pathname.startsWith("/api/taskforce"))return i(C.pathname)?g:We(`${C.pathname}${C.search}${C.hash}`)}return g},p=g=>{try{return typeof g=="string"?new URL(g,window.location.origin):g instanceof URL?g:typeof Request<"u"&&g instanceof Request?new URL(g.url,window.location.origin):null}catch{return null}};return window.fetch=((g,C)=>{const X=l(g),lt=p(X);if(!!!(lt&&lt.origin===window.location.origin&&lt.pathname.startsWith("/api/taskforce")))return o(X,C);const Pt=String(F||"").trim();if(typeof Request<"u"&&X instanceof Request){const ee=new Headers(X.headers);C?.headers&&new Headers(C.headers).forEach((fa,An)=>ee.set(An,fa)),De==="cloud"&&Pt&&Pt!=="default"&&!ee.has("x-taskforce-workspace-id")&&ee.set("x-taskforce-workspace-id",Pt);const Qt=new Request(X,{...C,headers:ee});return o(Qt)}const gs=new Headers(C?.headers);return De==="cloud"&&Pt&&Pt!=="default"&&!gs.has("x-taskforce-workspace-id")&&gs.set("x-taskforce-workspace-id",Pt),o(X,{...C,headers:gs})}),()=>{window.fetch=o}},[F,U,We,De]);const[Nt,Ze]=s.useState([]),[$e,hs]=s.useState([]),as=s.useCallback(async()=>{if(!(y||ue))try{const o=await fetch("/api/taskforce/workflow-templates");if(o.ok){const i=await o.json();Ze(i.templates||[])}}catch{}},[y,ue]),Ns=s.useCallback(async()=>{try{const o=await fetch("/api/taskforce/initiative-templates");if(!o.ok)return[];const i=await o.json(),l=Array.isArray(i?.templates)?i.templates:[];return hs(l),l}catch{return[]}},[]),Ca=s.useCallback(async o=>{if(!o)return null;const i=[`/api/taskforce/workflow-template/${encodeURIComponent(o)}`,`/api/taskforce/workflow-templates/${encodeURIComponent(o)}`];try{for(const l of i){const p=await fetch(l);if(!p.ok)continue;const g=await p.json();if(g?.template)return g.template}return null}catch{return null}},[]),ns=s.useCallback(async()=>{try{const o=await fetch("/api/taskforce/workflow-editor/overrides");if(!o.ok)return[];const i=await o.json();return Array.isArray(i?.names)?i.names:[]}catch{return[]}},[]),_s=s.useCallback(async(o,i)=>{try{const l=await fetch("/api/taskforce/workflow-editor/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:o,draft:i})}),p=await l.json().catch(()=>({}));return!l.ok||!p.success?{success:!1,error:p.error||`Save failed (${l.status})`}:(as(),{success:!0})}catch(l){return{success:!1,error:l.message}}},[as]),_a=s.useCallback(async o=>{try{const i=await fetch(`/api/taskforce/workflow-editor/reset/${encodeURIComponent(o)}`,{method:"POST"}),l=await i.json().catch(()=>({}));return!i.ok||!l.success?{success:!1,error:l.error||`Reset failed (${i.status})`}:(as(),{success:!0})}catch(i){return{success:!1,error:i.message}}},[as]),[Rs,xo]=s.useState("antigravity"),[ms,vo]=s.useState([]),[bo,er]=s.useState("category"),[tr,Ni]=s.useState("show"),[Za,sr]=s.useState(!1),[ar,nr]=s.useState(".agent/workflows"),[Pn,wo]=s.useState(".tasknexus/agents"),[or,ka]=s.useState(null),[So,oa]=s.useState(null);s.useEffect(()=>{const o=ms.find(i=>i.id===Rs);o&&(nr(o.directory),wo(".tasknexus/agents"))},[Rs,ms]);const[Ii,Hr]=s.useState(!1),[Gr,zc]=s.useState(null),[Lc,Ys]=s.useState(null),[Rc,rr]=s.useState(null),[ir,Co]=s.useState(null),cr=s.useRef(null),[Ai,qr]=s.useState(0),Vr=s.useCallback(o=>!o||!ze?o:o.startsWith(ze)?o.slice(ze.length).replace(/^[/\\]+/,""):o,[ze]),lr=s.useCallback(async()=>{if(document.fullscreenElement)document.exitFullscreen&&(await document.exitFullscreen(),sr(!1));else try{await document.documentElement.requestFullscreen(),sr(!0)}catch(o){console.error(`Error attempting to enable full-screen mode: ${o}`)}},[Za]);s.useEffect(()=>{const o=()=>{sr(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",o),()=>document.removeEventListener("fullscreenchange",o)},[]);const Di=s.useCallback(async()=>{try{const o=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:ss})});if(!o.ok)throw new Error(`Failed to save global settings (${o.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[ss]),Bi=s.useCallback(async o=>{de(o),et(!1);try{const i=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:o})});if(!i.ok)throw new Error(`Failed to save config (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project theme"),!1}},[]),Pi=s.useCallback(async o=>{B(o),oe&&de(o);try{const i=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:o})});if(!i.ok)throw new Error(`Failed to save global settings (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global theme"),!1}},[oe]),zi=s.useCallback(async o=>{Ve(o),Je(!1);try{const i=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:o})});if(!i.ok)throw new Error(`Failed to save config (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project backup setting"),!1}},[]),Li=s.useCallback(async o=>{Tt(o),Ot&&Ve(o);try{const i=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:o})});if(!i.ok)throw new Error(`Failed to save global settings (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global backup setting"),!1}},[Ot]),Ri=s.useCallback(async o=>{qs(o);try{const i=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:o}})});if(!i.ok)throw new Error(`Failed to save global settings (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save regional week start setting"),!1}},[]),Kr=s.useCallback(async o=>{const i=Dd(o);return Ht(i),!0},[]),it=s.useCallback(async o=>{na(o);try{const i=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:o})});if(!i.ok)throw new Error(`Failed to save config (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save manual complexity setting"),!1}},[]),ws=s.useCallback(async o=>{ua(o),o||Jn(!1);try{const i=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:o})});if(!i.ok)throw new Error(`Failed to save config (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save checklist dropdown setting"),!1}},[]),ja=s.useCallback(async o=>{P(o);try{const i=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assigneeFilterEnabled:o})});if(!i.ok)throw new Error(`Failed to save config (${i.status})`);return!0}catch{return console.error("[Taskforce] Failed to save assignee filter setting"),!1}},[]),ln=s.useCallback(async()=>{et(!0),Je(!0),de(xe),Ve(Ft),na(!1),ua(!1),P(!1),Jn(!1);try{const o=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:null,jsonBackupEnabled:null,manualComplexityEnabled:null,checklistDropdownEnabled:null,assigneeFilterEnabled:null})});if(!o.ok)throw new Error(`Failed to save config (${o.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[xe,Ft]),dr=s.useCallback(async(o,i)=>{ka(o),oa(null);try{const p=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:o,path:i,variables:{STORAGE_PATH:yt.replace(/\/$/,"")||".Taskforce",WORKFLOWS_PATH:ar.replace(/\/$/,""),SPECIALISTS_PATH:Pn.replace(/\/$/,"")},environment:Rs})})).json();p.success?oa({type:"success",message:`Successfully exported ${p.count} ${o} to ${i}`}):oa({type:"error",message:p.error||`Failed to export ${o}`})}catch{oa({type:"error",message:`Network error exporting ${o}`})}finally{ka(null),setTimeout(()=>oa(null),5e3)}},[yt,ar,Pn,Rs]),Jr=s.useCallback(async(o,i)=>{ka("workflows"),oa(null);try{const p=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:o,workflowNames:i,variables:{STORAGE_PATH:yt.replace(/\/$/,"")||".Taskforce"}})})).json();p.success?oa({type:"success",message:`Successfully exported ${p.count} workflows to ${o}`}):oa({type:"error",message:p.error||"Export failed"})}catch{oa({type:"error",message:"Network error exporting workflows"})}finally{ka(null),setTimeout(()=>oa(null),5e3)}},[yt]),[Gt,Fs]=s.useState([]),[Ps,Fa]=s.useState([]),[Ec,Ei]=s.useState(!1),[ct,Mi]=s.useState(null),[Mc,Yr]=s.useState(!1),[ur,$i]=s.useState(null),[_o,Xr]=s.useState(null),[Qr,jo]=s.useState([]),[zn,dn]=s.useState(null),[Xs,To]=s.useState([]),[es,Ln]=s.useState(!1),[pr,Fi]=s.useState({}),un=s.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});s.useEffect(()=>{un.current={authSessionResolved:ie,configLoaded:es,workspaceBootstrapPending:me}},[ie,es,me]);const Ta=s.useCallback(o=>{Se(o),o!=="ready"&&(ht(null),It(Date.now()))},[]),Na=s.useCallback(o=>{const i=un.current;i.authSessionResolved&&i.configLoaded&&!i.workspaceBootstrapPending||(Se("stalled"),ht(o),It(l=>l??Date.now()))},[]),Oa=s.useCallback(async(o,i,l=vi)=>{const p=new AbortController,g=Number(l)>0?Number(l):vi,C=typeof window<"u"?window.setTimeout(()=>p.abort("bootstrap-timeout"),g):null;try{return await fetch(o,{...i||{},signal:p.signal})}catch(X){if(X instanceof DOMException?X.name==="AbortError":String(X?.name||"").toLowerCase()==="aborterror"){const He=new Error(`Startup checks timed out after ${g}ms.`);throw He.name="BootstrapTimeoutError",He}throw X}finally{C!==null&&typeof window<"u"&&window.clearTimeout(C)}},[]),No=s.useCallback(o=>String(o?.name||"")==="BootstrapTimeoutError",[]),[Wa,hr]=s.useState([]),[Qs,Zr]=s.useState(d.taxonomies||[]),Be=s.useMemo(()=>(Xs.length>0?Xs:m||[]).map(i=>typeof i=="string"?{value:i.toLowerCase().replace(/\s+/g,"-"),label:i}:i).sort((i,l)=>i.label.localeCompare(l.label)),[Xs,m]);s.useMemo(()=>Be.filter(o=>!o.disabled),[Be]);const Ks=s.useCallback(o=>o.find(l=>l.value==="default"||l.value==="general"||l.label==="General"||l.value==="Taskforce"||l.label==="Taskforce")?.value||o[0]?.value||"default",[]),Zs=Wa.length>0?Wa:h,[mr,Ua]=s.useState(!1),[fr,Ce]=s.useState(""),pn=s.useCallback(()=>{qt(De==="cloud"),As(!1),us(""),Ce("Authentication required. Sign in to continue.")},[De]),is=s.useCallback(async()=>{if(Ta("auth"),!z)return rt.current;if(!ke)return Jt("local"),ts(!1),As(!1),Ss("anonymous"),us(""),Rn("disconnected"),En(0),Mn(null),L(!0),H([]),qt(!1),ve(!0),rt.current=!1,Vt.current=Date.now(),!1;const o=Fe("/api/taskforce/auth/session"),i=Date.now();if(jt.current)return jt.current;if(ie&&i-Vt.current<1500)return rt.current;const l=(async()=>{const p=new AbortController,g=typeof window<"u"?window.setTimeout(()=>p.abort(),8e3):null;try{const C=await fetch(o,{method:"GET",credentials:"include",mode:"cors",signal:p.signal});if(C.status===429)return ve(!0),rt.current;if(!C.ok)return ve(!0),rt.current=!1,!1;const X=await C.json(),lt=!!X.authRequiredForApi,He=!!X.authenticated,Pt=He?X.betaAccess!==!1:!0,gs=typeof X.workspaceId=="string"&&X.workspaceId.trim().length>0?X.workspaceId.trim():"",ee=typeof X.userId=="string"&&X.userId.trim().length>0?X.userId.trim():"anonymous",Qt=typeof X.email=="string"&&X.email.trim().length>0?X.email.trim().toLowerCase():"",xs=De==="local",fa=De==="local"||ye;return ts(ye||xs?!1:lt),As(He),Ss(He?ee:"anonymous"),us(He?Qt:""),Rn(He?"idle":"disconnected"),Mn(null),He||En(0),L(Pt),fa||re(gs||gc(Ie)||"default"),qt(ye||xs?!1:lt&&!He),ve(!0),rt.current=He,He&&Ta("ready"),He}catch{return ve(!0),rt.current=!1,Na("Unable to verify your session."),rt.current}finally{g!==null&&typeof window<"u"&&window.clearTimeout(g),Vt.current=Date.now(),jt.current=null}})();return jt.current=l,l},[z,ke,ie,Fe,ye,De,Ie,Ta,Na]),{userGlobalSyncStatus:Oi,setUserGlobalSyncStatus:Rn,userGlobalLastSyncedAt:Wi,userGlobalSyncPendingChanges:Io,setUserGlobalSyncPendingChanges:En,userGlobalSyncError:hn,setUserGlobalSyncError:Mn,workspaceLastPullAt:gr,workspaceLastPushAt:$n,workspaceLastErrorAt:ei,workspaceLastErrorMessage:Ui,workspaceLastWarningMessage:Ao,workspaceCloudSyncEnabled:Do,realtimeConnectionState:$c,realtimeTelemetry:Hi,workspaceSyncSourceOfTruth:Gi,workspaceSyncOnboardingCompleted:qi,workspaceSyncReady:Vi,workspaceCloudHydrated:Ki,syncInFlightRef:Fn,workspaceRetryAt:ti,workspaceBootstrapSyncInProgress:Bo,workspaceBootstrapSyncPages:Fc,workspaceBootstrapSyncAppliedChanges:Oc,workspaceSyncFailureCount:yr,workspaceSyncRetryScheduledCount:On,workspaceSyncAuthFailureCount:kr,workspaceSyncLastFailureSource:Wc,workspaceSyncLastFailureStatusCode:Uc,workspacePendingSignatureRef:Os,workspaceDeletedTaskIdsRef:pa,loadWorkspaceSyncState:Ji,applyWorkspaceSyncStateSnapshot:Yi,syncUserGlobalSettings:mn,buildWorkspaceSyncSignature:Ia,pushWorkspaceChangesToCloud:Es,saveWorkspaceCloudSyncSettings:fs,retryUserGlobalSettingsSync:Xi,retryWorkspaceCloudSync:en,resetWorkspaceSyncCursorAndPull:xr}=th({currentWorkspaceId:F,cloudAuthConfigured:se,runtimeMode:De,isAuthenticated:Ct,authUserId:ds,projectName:G,resolveCloudAuthUrl:Fe,resolveWebSocketUrl:te,realtimeSyncEnabled:Lt,tasks:Gt,archivedTasks:Ps,taxonomies:Qs,setupState:Ke,globalTheme:xe,locale:Yt,globalWeekStartsOn:Us,themeUseGlobalDefault:oe,setTasks:Fs,setArchivedTasks:Fa,setAuthBlocked:qt,setIsAuthenticated:As,checkAuthSession:is,setGlobalTheme:B,setCurrentTheme:de,setSetupState:At,setLocale:Ht,setGlobalWeekStartsOn:qs}),[Js,Aa]=s.useState(()=>Ks(Be)),[xa,Da]=s.useState("feature"),[fn,Ha]=s.useState(2),[Po,ea]=s.useState(3),[Wn,Ba]=s.useState("default"),[Pa,zo]=s.useState("agent"),[Un,vr]=s.useState(""),[gn,Lo]=s.useState(""),[Hn,Ro]=s.useState(""),[si,br]=s.useState(""),[Gn,yn]=s.useState(""),[za,ta]=s.useState(""),[tn,Ga]=s.useState([]),[ai,qn]=s.useState(""),[wr,Vn]=s.useState({}),Qi=s.useRef(null),[Kn,Sr]=s.useState([]),[Cr,ni]=s.useState(!1),[_r,Jn]=s.useState(!1),[jr,va]=s.useState(!1),[Yn,oi]=s.useState(!1),[ba,Tr]=s.useState(""),[ra,sn]=s.useState(""),[js,qa]=s.useState([]),[Hs,Xn]=s.useState([]),[Is,Qn]=s.useState([]),[cs,Eo]=s.useState(!1),[kn,xn]=s.useState(ji.map(o=>o.value)),[La,vn]=s.useState(yl.map(o=>o.value)),[ia,an]=s.useState("all"),[Va,Zn]=s.useState({}),[Ra,Nr]=s.useState("created"),[bn,Mo]=s.useState("desc"),[ri,nn]=s.useState(!1),[Hc,$o]=s.useState(!1),[Zi,ec]=s.useState(!1),[Fo,ii]=s.useState([]),[Gc,ci]=s.useState([]),[qc,Ka]=s.useState(null),Oo=s.useRef(new Map),Ir=s.useRef(!1),eo=s.useRef(new Map),Wo=s.useRef(null),Uo=s.useRef(ie),wn=s.useRef(zt),Sn=s.useRef(Ct),Ho=s.useRef(!1),[ca,Ar]=s.useState(!1);s.useEffect(()=>{De==="cloud"&&ih(F,Ie)},[De,F,Ie]),s.useEffect(()=>{Uo.current=ie,wn.current=zt,Sn.current=Ct},[ie,zt,Ct]);const Ja=s.useCallback(o=>`${o.updatedAt||o.createdAt||""}|${o.status}|${o.priority}|${o.title}`,[]),to=s.useCallback(o=>{!o.length||typeof window>"u"||(ci(i=>Array.from(new Set([...i,...o]))),o.forEach(i=>{const l=eo.current.get(i);l&&window.clearTimeout(l);const p=window.setTimeout(()=>{eo.current.delete(i),ci(g=>g.filter(C=>C!==i))},4e3);eo.current.set(i,p)}))},[]),li=s.useCallback(async()=>{try{const o=await fetch("/api/taskforce/ui-state?key=app",{method:"GET",credentials:"include"});if(!o.ok){Ar(!0);return}const i=await o.json().catch(()=>({})),l=i?.state&&typeof i.state=="object"?i.state:null;if(!l){Ar(!0);return}typeof l.groupBy=="string"&&er(l.groupBy),(l.emptyColumnMode==="show"||l.emptyColumnMode==="collapse"||l.emptyColumnMode==="hide")&&Ni(l.emptyColumnMode),typeof l.zenMode=="boolean"&&sr(l.zenMode),typeof l.searchQuery=="string"&&sn(l.searchQuery),Array.isArray(l.filterCategories)&&qa(l.filterCategories),Array.isArray(l.filterPriorities)&&Xn(l.filterPriorities),Array.isArray(l.filterTypes)&&Qn(l.filterTypes),Array.isArray(l.filterStatus)&&xn(l.filterStatus),Array.isArray(l.filterAssignees)&&vn(l.filterAssignees),l.filterTaxonomies&&typeof l.filterTaxonomies=="object"&&Zn(l.filterTaxonomies),(l.parentTaskFilterMode==="all"||l.parentTaskFilterMode==="parents"||l.parentTaskFilterMode==="linked"||l.parentTaskFilterMode==="unlinked")&&an(l.parentTaskFilterMode),(l.sortBy==="created"||l.sortBy==="priority"||l.sortBy==="updated"||l.sortBy==="complexity")&&Nr(l.sortBy),(l.sortOrder==="asc"||l.sortOrder==="desc")&&Mo(l.sortOrder),typeof l.hasInitedFilters=="boolean"&&Eo(l.hasInitedFilters),typeof l.showChecklist=="boolean"&&Jn(l.showChecklist),typeof l.showTaskRelationships=="boolean"&&va(l.showTaskRelationships),typeof l.showChildTasks=="boolean"&&oi(l.showChildTasks),typeof l.lastCategory=="string"&&Tr(l.lastCategory),typeof l.exportEnvironment=="string"&&l.exportEnvironment.trim().length>0&&xo(l.exportEnvironment.trim())}catch{}finally{Ar(!0)}},[]);s.useEffect(()=>{if(!ca)return;const o=window.setTimeout(async()=>{try{await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({stateKey:"app",patch:{groupBy:bo,emptyColumnMode:tr,zenMode:Za,searchQuery:ra,filterCategories:js,filterPriorities:Hs,filterTypes:Is,filterStatus:kn,filterAssignees:La,filterTaxonomies:Va,parentTaskFilterMode:ia,sortBy:Ra,sortOrder:bn,hasInitedFilters:cs,showChecklist:_r,showTaskRelationships:jr,showChildTasks:Yn,lastCategory:ba||"",exportEnvironment:Rs}})})}catch{}},250);return()=>window.clearTimeout(o)},[ca,bo,tr,Za,ra,js,Hs,Is,kn,La,Va,ia,Ra,bn,cs,_r,jr,Yn,ba,Rs]);const Ts=s.useCallback(async o=>{if(!(!(o?.ignoreAuthGuard===!0)&&(y||ue))){Ta("config");try{const l=await Oa("/api/taskforce/config",void 0,vi);if(l.status===401){pn(),Ln(!0);return}if(l.ok){const ee=await l.json();if(Jt(ee.runtimeMode==="cloud"?"cloud":"local"),ts(!!ee.authRequiredForApi),typeof ee.workspaceId=="string"&&ee.workspaceId.trim().length>0){const lo=ee.workspaceId.trim(),ki=ee.runtimeMode==="cloud"?"cloud":"local";re(ki==="local"?lo:tu=>{const cl=String(tu||"").trim();return lo==="default"&&cl&&cl.toLowerCase()!=="default"?cl:lo})}ee.runtimeMode==="cloud"&&ee.authRequiredForApi?qt(!Ct):qt(!1),ee.setupState&&typeof ee.setupState=="object"?At(ee.setupState):At(null),ee.runtimeCapabilities&&typeof ee.runtimeCapabilities=="object"?Kt(ee.runtimeCapabilities):Kt(null),vs(!!ee.realtimeSyncEnabled);const Qt=String(ee.realtimeSyncFlagSource||"").trim().toLowerCase();Bs(Qt==="env"||Qt==="settings"||Qt==="default"?Qt:"unknown"),typeof ee.shortcut=="string"&&ee.shortcut.trim().length>0&&Xt(ee.shortcut),(ee.theme==="dark"||ee.theme==="light"||ee.theme==="midnight")&&de(ee.theme),(ee.globalTheme==="dark"||ee.globalTheme==="light"||ee.globalTheme==="midnight")&&B(ee.globalTheme),typeof ee.themeUseGlobalDefault=="boolean"&&et(ee.themeUseGlobalDefault),ee.projectRoot&&N(ee.projectRoot),typeof ee.tenantId=="string"&&ee.tenantId.trim().length>0&&st(ee.tenantId.trim());const xs=ee.runtimeMode==="cloud"?"cloud":"local",fa=xs==="cloud"?String(ee.projectName||"").trim():ee.projectName||ee.paths?.projectName||"";(String(fa||"").trim().length>0||xs==="cloud")&&je(fa),ee.mcpScript&&qe(ee.mcpScript),ee.hostRoot&&Y(ee.hostRoot),typeof ee.jsonBackupEnabled=="boolean"&&Ve(ee.jsonBackupEnabled),typeof ee.globalJsonBackupEnabled=="boolean"&&Tt(ee.globalJsonBackupEnabled),typeof ee.jsonBackupUseGlobalDefault=="boolean"&&Je(ee.jsonBackupUseGlobalDefault);const An=ee?.schedulePreferences?.weekStartsOn;(An==="sunday"||An==="monday")&&qs(An),typeof ee.manualComplexityEnabled=="boolean"&&na(ee.manualComplexityEnabled),typeof ee.checklistDropdownEnabled=="boolean"?ua(ee.checklistDropdownEnabled):ua(!1),typeof ee.assigneeFilterEnabled=="boolean"?P(ee.assigneeFilterEnabled):P(!1)}try{const ee=await Oa("/api/taskforce/version",void 0,vi);if(ee.ok){const Qt=await ee.json().catch(()=>({}));Qt?.build&&typeof Qt.build=="object"&&ft({version:String(Qt.build.version||""),gitSha:Qt.build.gitSha?String(Qt.build.gitSha):null,buildTime:Qt.build.buildTime?String(Qt.build.buildTime):null,deployId:Qt.build.deployId?String(Qt.build.deployId):null})}}catch(ee){No(ee)&&Na("Startup checks timed out.")}const p=await fetch("/api/taskforce/categories");if(p.ok){const ee=await p.json();if(ee.categories&&ee.categories.length>0){const Qt=ee.categories.map(xs=>typeof xs=="string"?{value:xs.toLowerCase().replace(/\s+/g,"-"),label:xs}:xs);To(Qt)}}const g=await fetch("/api/taskforce/types");if(g.ok){const ee=await g.json();ee.types&&ee.types.length>0&&hr(ee.types)}const C=await fetch("/api/taskforce/priorities");if(C.ok){const ee=await C.json();ee.priorities&&at(ee.priorities)}const X=await fetch("/api/taskforce/workflow-templates");if(X.ok){const ee=await X.json();ee.templates&&Ze(ee.templates)}await Ns();const lt=await fetch("/api/taskforce/environments");if(lt.ok){const ee=await lt.json();ee.environments&&vo(ee.environments)}const He=await fetch("/api/taskforce/approaches");if(He.ok){const ee=await He.json();ee.approaches&&bs(ee.approaches)}const Pt=await fetch("/api/taskforce/taxonomies");if(Pt.ok){const ee=await Pt.json();ee.taxonomies&&Zr(ee.taxonomies)}const gs=await fetch("/api/taskforce/specialists");if(gs.ok){const ee=await gs.json();ee.specialists&&bt(ee.specialists)}Ho.current||(Ho.current=!0,await li()),Ln(!0),Ta("ready")}catch(l){Ho.current||(Ho.current=!0,await li()),No(l)?Na("Startup checks timed out."):Na("Unable to finish startup checks."),Ln(!0)}}},[F,Oa,Ns,pn,Ct,No,li,Ta,Na,y,ue]),so=s.useCallback(async()=>{await is(),await Ts()},[is,Ts]),os=s.useCallback(async()=>{if(!Ee)return H([]),{success:!0,workspaces:[]};try{const o=await Oa("/api/taskforce/workspaces",{method:"GET",credentials:"include"},vi);if(o.status===401)return H([]),{success:!1,error:"Authentication required."};const i=await o.json().catch(()=>({}));if(!o.ok||i?.success===!1)return H([]),{success:!1,error:i?.error||`Failed to load workspaces (${o.status})`};const l=Array.isArray(i?.workspaces)?i.workspaces:[];if(H(l),De!=="local"&&typeof i?.currentWorkspaceId=="string"&&i.currentWorkspaceId.trim().length>0){const p=i.currentWorkspaceId.trim();re(g=>{const C=String(g||"").trim();return p==="default"&&C&&C.toLowerCase()!=="default"?C:p})}return{success:!0,workspaces:l}}catch(o){return No(o)&&Na("Startup checks timed out."),H([]),{success:!1,error:"Failed to load workspaces."}}},[Oa,No,Na,De,Ie,Ee]),Ea=s.useCallback(async(o,i)=>{if(!Ee)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const l=String(o||"").trim();if(!l)return{success:!1,error:"workspaceId is required."};try{const p=await fetch("/api/taskforce/session/workspace",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:l})}),g=await p.json().catch(()=>({}));return!p.ok||g?.success===!1?{success:!1,error:g?.error||`Failed to switch workspace (${p.status})`,code:g?.code}:(await is(),i?.hydrate===!1?await os():await Promise.all([Ts(),os()]),{success:!0})}catch{return{success:!1,error:"Failed to switch workspace."}}},[is,Ts,os,Ee]),Ma=s.useCallback(async o=>{Ta("workspace"),Oe(!0);try{if(!Ee){const He=String(F||"").trim()||"default";return re(He),{success:!0,workspaceSetupRequired:!1,workspaceId:He}}const i=String(o?.preferredWorkspaceId||"").trim(),l=gc(Ie),p=await os();if(!p.success)return{success:!1,workspaceSetupRequired:!1,error:p.error||"Failed to load workspaces after authentication."};const g=Array.isArray(p.workspaces)?p.workspaces:[];if(g.length===0)return re("default"),{success:!0,workspaceSetupRequired:!0};const C=new Set(g.map(He=>String(He.id||"").trim()).filter(Boolean)),X=(i&&C.has(i)?i:"")||(l&&C.has(l)?l:"")||String(g[0]?.id||"").trim();if(!X)return re("default"),{success:!0,workspaceSetupRequired:!0};if(String(F||"").trim()!==X){const He=await Ea(X,{hydrate:!1});if(!He.success)return{success:!1,workspaceSetupRequired:!1,error:He.error||"Failed to set workspace after authentication.",code:He.code}}else re(X);return{success:!0,workspaceSetupRequired:!1,workspaceId:X}}catch{return Na("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{Oe(!1)}},[F,os,Ta,Na,Ea,Ie,Ee]),Go=s.useCallback(async()=>{ht(null),Ta("auth");const o=await is();if(Ee&&o){const i=await Ma();if(!i.success||i.workspaceSetupRequired){await Ts({ignoreAuthGuard:!0});return}}await Ts({ignoreAuthGuard:!0})},[is,Ts,Ta,Ma,Ee]),ao=s.useCallback(async(o,i)=>{if(!Ee)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const l=String(o||"").trim();if(!l)return{success:!1,error:"Workspace name is required."};try{const p=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:l,description:typeof i=="string"?i:void 0})}),g=await p.json().catch(()=>({}));if(!p.ok||g?.success===!1)return{success:!1,error:g?.error||`Failed to create workspace (${p.status})`,code:g?.code};const C=g?.workspace;if(await os(),C?.id){const X=await Ea(C.id);if(!X.success)return{success:!1,error:X.error||"Workspace created but failed to activate.",code:X.code}}return{success:!0,workspace:C}}catch{return{success:!1,error:"Failed to create workspace."}}},[os,Ea,Ee]),Dr=s.useCallback(async o=>{if(!Ee)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const i=String(o||"").trim();if(!i)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const l=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(i)}`,{method:"DELETE",credentials:"include"}),p=await l.json().catch(()=>({}));if(!l.ok||p?.success===!1)return{success:!1,error:p?.error||`Failed to delete workspace (${l.status})`,code:p?.code};await is(),await Promise.all([Ts(),os()]);const g=typeof p?.nextWorkspaceId=="string"?p.nextWorkspaceId.trim():"";return g&&re(g),{success:!0,nextWorkspaceId:g||void 0,workspaceSetupRequired:p?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(p?.cleanupWarnings)?p.cleanupWarnings.map(C=>String(C||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[is,Ts,os,Ee]),tc=s.useCallback(async o=>{const i=o==="operations"?"operations":"core";try{const l=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:i}})}),p=await l.json().catch(()=>({}));return!l.ok||p?.success===!1?!1:(await so(),!0)}catch{return!1}},[so]),di=s.useCallback(async o=>{const i=String(o?.name||"").trim();if(!i)return{success:!1,error:"Workspace name is required.",code:"WORKSPACE_NAME_REQUIRED"};try{const l=await fetch("/api/taskforce/workspace-profile",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-runtime-mode":De},credentials:"include",body:JSON.stringify({workspaceId:o.workspaceId,name:i,description:typeof o.description=="string"?o.description:void 0,allowCreate:!0})}),p=await l.json().catch(()=>({}));if(!l.ok||p?.success===!1)return{success:!1,error:p?.error||`Failed to save workspace (${l.status})`,code:p?.code};const g=String(p?.workspace?.id||"").trim();if(g&&(re(g),await new Promise(C=>window.setTimeout(C,0)),De==="cloud"&&Ct&&g!==F)){const C=await Ea(g);if(!C.success)return{success:!1,error:C.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await so(),{success:!0,workspaceId:g||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[so,De,Ct,F,Ea]),Me=s.useCallback(async(o=!1,i)=>{if(!(!(i?.ignoreAuthGuard===!0)&&(y||ue))){o||Ei(!0);try{const p=await fetch("/api/taskforce/tasks");if(p.status===401){pn(),Fs([]),o||Ei(!1);return}if(p.ok){const C=((await p.json()).tasks||[]).map(He=>ul(He,{mapLegacyTodoStatus:!0})),X=new Map,lt=[];for(const He of C){const Pt=Ja(He);if(X.set(He.id,Pt),!Ir.current)continue;const gs=Oo.current.get(He.id);(!gs||gs!==Pt)&&lt.push(He.id)}Oo.current=X,Ir.current?to(lt):Ir.current=!0,Fs(C)}}catch(p){console.error("[Taskforce] Failed to fetch tasks:",p)}o||Ei(!1)}},[Ja,to,pn,zt,y,ue]),on=s.useCallback(async(o,i)=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const l=o.trim().toLowerCase(),p=i;if(!l||!p)return{success:!1,error:"Email and password are required."};try{const g=await fetch(Fe("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:l,password:p})}),C=await g.json().catch(()=>({}));if(!g.ok||!C?.success)return{success:!1,error:C?.error||"Sign in failed.",code:C?.code};Ce(""),await is();const X=await Ma();return X.success?X.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([Ts({ignoreAuthGuard:!0}),Me(!0,{ignoreAuthGuard:!0})]),mn({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:X.error||"Unable to resolve workspace after sign in.",code:X.code}}catch{return{success:!1,error:"Sign in failed."}}},[is,Ts,Me,Ma,mn,Fe,se]),Vc=s.useCallback(async(o,i)=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const l=o.trim().toLowerCase(),p=i;if(!l||!p)return{success:!1,error:"Email and password are required."};try{const g=await fetch(Fe("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:l,password:p})}),C=await g.json().catch(()=>({}));return!g.ok||!C?.success?{success:!1,error:C?.error||"Create account failed.",code:C?.code}:{success:!0,workspaceSetupRequired:!!C?.workspaceSetupRequired,verificationRequired:!!C?.verificationRequired,verificationToken:typeof C?.verificationToken=="string"?C.verificationToken:void 0,emailSent:C?.emailSent!==!1,emailError:typeof C?.emailError=="string"?C.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[Fe,se]),Kc=s.useCallback(async o=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const i=o.trim().toLowerCase();if(!i)return{success:!1,error:"Email is required."};try{const l=await fetch(Fe("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:i})}),p=await l.json().catch(()=>({}));return!l.ok||!p?.success?{success:!1,error:p?.error||"Failed to request verification email.",code:p?.code}:{success:!0,verificationToken:p?.verificationToken??null,emailSent:p?.emailSent!==!1,emailError:typeof p?.emailError=="string"?p.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[Fe,se]),Jc=s.useCallback(async o=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const i=o.trim();if(!i)return{success:!1,error:"Token is required."};try{const l=await fetch(Fe("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:i})}),p=await l.json().catch(()=>({}));return!l.ok||!p?.success?{success:!1,error:p?.error||"Verification failed.",code:p?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[Fe,se]),Br=s.useCallback(async o=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const i=o.trim().toLowerCase();if(!i)return{success:!1,error:"Email is required."};try{const l=await fetch(Fe("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:i})}),p=await l.json().catch(()=>({}));return!l.ok||!p?.success?{success:!1,error:p?.error||"Failed to request password reset.",code:p?.code}:{success:!0,resetToken:p?.resetToken??null,emailSent:p?.emailSent!==!1,emailError:typeof p?.emailError=="string"?p.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[Fe,se]),qo=s.useCallback(async(o,i)=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const l=o.trim(),p=i;if(!l||!p)return{success:!1,error:"Token and password are required."};try{const g=await fetch(Fe("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:l,password:p})}),C=await g.json().catch(()=>({}));return!g.ok||!C?.success?{success:!1,error:C?.error||"Failed to reset password.",code:C?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[Fe,se]),Cn=s.useCallback(async o=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const i=o.trim();if(!i)return{success:!1,error:"Token is required."};try{const l=await fetch(Fe("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:i})}),p=await l.json().catch(()=>({}));return!l.ok||!p?.success?{success:!1,error:p?.error||"Invite inspection failed.",code:p?.code,state:p?.state}:{success:!0,state:p?.state,email:typeof p?.email=="string"?p.email:void 0,workspaceId:typeof p?.workspaceId=="string"?p.workspaceId:void 0}}catch{return{success:!1,error:"Invite inspection failed."}}},[Fe,se]),Pr=s.useCallback(async(o,i)=>{if(!se)return{success:!1,error:"Cloud auth endpoint is not configured."};const l=o.trim(),p=i;if(!l||!p)return{success:!1,error:"Token and password are required."};try{const g=await fetch(Fe("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:l,password:p})}),C=await g.json().catch(()=>({}));if(!g.ok||!C?.success)return{success:!1,error:C?.error||"Invite acceptance failed.",code:C?.code};Ce(""),await is();const X=typeof C?.workspaceId=="string"?C.workspaceId:null,lt=await Ma({preferredWorkspaceId:X});return lt.success?lt.workspaceSetupRequired?{success:!0,workspaceSetupRequired:!0}:(await Promise.all([Ts({ignoreAuthGuard:!0}),Me(!0,{ignoreAuthGuard:!0})]),mn({preferCloudOnFirstSync:!0}),{success:!0}):{success:!1,error:lt.error||"Unable to resolve workspace after invite acceptance.",code:lt.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[is,Ts,Me,Ma,mn,Fe,se]),sc=s.useCallback(async()=>{try{se&&await fetch(Fe("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{As(!1),Ss("anonymous"),us(""),Rn("disconnected"),En(0),Mn(null),qt(De==="cloud"&&zt),re(o=>{const i=String(o||"").trim();return i&&i.toLowerCase()!=="default"?i:De==="local"?"default":gc(Ie)||"default"}),H([]),Fs([])}},[zt,Fe,se,Ie,De]),zr=s.useCallback(async o=>{try{const i=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),l=await i.json().catch(()=>({}));return!i.ok||!l?.success?{success:!1,error:l?.error||`Create failed (${i.status})`}:(await Me(!0),{success:!0,result:l?.results})}catch(i){return{success:!1,error:i.message}}},[Me]),Yc=s.useCallback(async o=>{try{const i=await fetch("/api/taskforce/initiative-templates/clone-checklists",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),l=await i.json().catch(()=>({}));return!i.ok||!l?.success?{success:!1,error:l?.error||`Clone failed (${i.status})`}:(await Me(!0),{success:!0,updated:Number(l?.results?.updated||0)})}catch(i){return{success:!1,error:i.message}}},[Me]),ac=s.useRef(!1),Lr=s.useRef(!1);s.useEffect(()=>{ae(!0),!ac.current&&(ac.current=!0,is())},[is]),s.useEffect(()=>{z&&is()},[z,is]),s.useEffect(()=>{if(De!=="local"||!ke||typeof window>"u")return;const o=()=>{is()},i=()=>{document.visibilityState==="visible"&&o()};window.addEventListener("focus",o),window.addEventListener("online",o),document.addEventListener("visibilitychange",i);const l=window.setInterval(o,3e4);return()=>{window.removeEventListener("focus",o),window.removeEventListener("online",o),document.removeEventListener("visibilitychange",i),window.clearInterval(l)}},[De,ke,is]),s.useEffect(()=>{y||ue||Lr.current||(Lr.current=!0,(async()=>{if(as(),De==="cloud"&&ie&&Ct){const o=await Ma();if(!o.success||o.workspaceSetupRequired){await Ts();return}}await Ts(),await Me()})())},[y,ue,De,ie,Ct,Ma,Ts,as,Me]),s.useEffect(()=>{y||ue||Ie!==Ti&&Lr.current&&Ts()},[y,ue,Ie,Ts]),s.useEffect(()=>{y||ue||Ji()},[y,ue,F,Ji]),s.useEffect(()=>{if(De!=="cloud"||!ie||!Ct){De!=="cloud"&&H([]);return}os()},[De,ie,Ct,os]),s.useEffect(()=>{r&&r(Gt.length)},[Gt.length,r]),s.useEffect(()=>{if(n&&Gt.length>0){const o=Gt.find(i=>i.id.endsWith(n)||i.id===n);o&&(sa(o),ro("add"))}},[n,Gt]);const no=s.useRef(!1);s.useEffect(()=>{if(!es)return;if(!no.current&&Be.length>0){no.current=!0;const i=ba,l=Be.some(p=>p.label===i||p.value===i);if(i&&l){const p=Be.find(g=>g.label===i||g.value===i);Aa(p?.value||i)}else Aa(Ks(Be));return}const o=Be.some(i=>i.value===Js);Be.length>0&&!o&&Aa(Ks(Be))},[es,Be,Js,Ks,ba]),s.useEffect(()=>{if(!es||Be.length===0)return;const o=p=>!Be.some(g=>g.value===p.category),i=Gt.some(o),l=Ps.some(o);if(i||l){const p=Ks(Be);i&&Fs(g=>g.map(C=>o(C)?{...C,category:p}:C)),l&&Fa(g=>g.map(C=>o(C)?{...C,category:p}:C))}},[es,Be,Gt,Ps,Ks]);const $a=s.useCallback(async(o=!1)=>{if(!(y||ue))try{const i=await fetch("/api/taskforce/archive");if(i.ok){const p=((await i.json()).archived||[]).map(g=>({...ul(g),isArchived:!0}));Fa(p)}}catch(i){console.error("[Taskforce] Failed to fetch archive:",i)}},[y,ue]);s.useEffect(()=>{},[Me,$a]),s.useEffect(()=>()=>{typeof window>"u"||(eo.current.forEach(o=>window.clearTimeout(o)),eo.current.clear())},[]),s.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||ah({isOpen:dt,authBlocked:Et,authRequiredForApi:zt,isAuthenticated:Ct,canCallProtectedApi:ot.canCallProtectedApi}))return;let o=!1;const i=async()=>{if(!(o||document.visibilityState!=="visible"||Fn.current)&&!nh({shouldGateProtectedApiCalls:Ae,authSessionResolved:Uo.current,authRequiredForApi:wn.current,isAuthenticated:Sn.current})){Fn.current=!0;try{const g=await fetch("/api/taskforce/data-version");if(!g.ok)return;const C=await g.json(),X=Number(C?.dataVersion);if(!Number.isFinite(X))return;if(Wo.current===null){Wo.current=X;return}X!==Wo.current&&(Wo.current=X,await Promise.all([Me(!0),$a(!0)]))}catch{}finally{Fn.current=!1}}},l=()=>{document.visibilityState==="visible"&&i()},p=window.setInterval(i,3e3);return document.addEventListener("visibilitychange",l),i(),()=>{o=!0,window.clearInterval(p),document.removeEventListener("visibilitychange",l)}},[dt,Me,$a,Et,zt,Ct,ot,y,ue,Ae]);const nc=s.useCallback(()=>{Mo(o=>o==="asc"?"desc":"asc")},[]);s.useEffect(()=>{if(es&&!cs&&Be.length>0&&Zs.length>0&&Xe.length>0){qa(Be.map(i=>i.value)),Xn(Xe.map(i=>i.value)),Qn(Zs.map(i=>i.value)),vn(yl.map(i=>i.value));const o={};Qs.forEach(i=>{o[i.id]=i.options.map(l=>l.value)}),Zn(o),Eo(!0)}},[es,Be,Zs,Xe,Qs,cs]),s.useEffect(()=>{if(!es||!cs||Be.length===0)return;js.some(i=>Be.some(l=>l.label===i&&l.value!==i))&&qa(i=>ip(i,Be))},[es,Be,cs,js]),s.useEffect(()=>{if(!es||!cs||Xe.length===0||Hs.length===0)return;const o=cp(Hs,Xe),i=Array.from(new Set(Hs.map(p=>Number(p)).filter(p=>Number.isFinite(p))));(o.length!==i.length||o.some((p,g)=>p!==i[g]))&&Xn(o)},[es,cs,Xe,Hs]);const oc=()=>{sn(""),qa(Be.map(i=>i.value)),Xn(Xe.map(i=>i.value)),Qn(Zs.map(i=>i.value)),xn(ji.map(i=>i.value)),vn(yl.map(i=>i.value)),an("all");const o={};Qs.forEach(i=>{o[i.id]=i.options.map(l=>l.value)}),Zn(o),Nr("created"),Mo("desc")},Rr=s.useMemo(()=>{const o=new Set;for(const i of Gt)i.parentTaskId&&o.add(i.parentTaskId);for(const i of Ps)i.parentTaskId&&o.add(i.parentTaskId);return Gt.filter(i=>{const l=i.title.toLowerCase().includes(ra.toLowerCase())||(i.description?.toLowerCase()||"").includes(ra.toLowerCase())||i.id.toLowerCase().includes(ra.toLowerCase()),p=!cs||js.includes(i.category),g=!cs||pl(i.priority,Hs),C=!cs||Is.includes(i.type||"feature"),X=!cs||kn.includes(i.status),lt=!$s||!cs||La.includes(i.assignee||"unassigned"),He=!!i.parentTaskId,Pt=o.has(i.id),gs=ia==="all"?!0:ia==="parents"?Pt:ia==="linked"?He||Pt:!He&&!Pt,ee=Object.entries(Va).every(([Qt,xs])=>{const fa=i.taxonomies?.[Qt];return fa?Array.isArray(fa)?fa.some(An=>xs.includes(An)):xs.includes(fa):(Qs.find(ki=>ki.id===Qt)?.options.every(ki=>xs.includes(ki.value))??!0)||xs.includes("")});return l&&p&&g&&C&&X&&lt&&ee&&gs}).sort((i,l)=>{let p=0;if(Ra==="created")p=new Date(l.createdAt).getTime()-new Date(i.createdAt).getTime();else if(Ra==="updated"){const g=i.updatedAt||i.createdAt,C=l.updatedAt||l.createdAt;p=new Date(C).getTime()-new Date(g).getTime()}else if(Ra==="priority"){const g=typeof i.priority=="number"?i.priority:Al[i.priority]??2,C=typeof l.priority=="number"?l.priority:Al[l.priority]??2;g!==C?p=C-g:p=new Date(l.createdAt).getTime()-new Date(i.createdAt).getTime()}else if(Ra==="complexity"){const g=typeof i.complexity=="number"?i.complexity:3,C=typeof l.complexity=="number"?l.complexity:3;g!==C?p=C-g:p=new Date(l.createdAt).getTime()-new Date(i.createdAt).getTime()}else p=new Date(l.createdAt).getTime()-new Date(i.createdAt).getTime();return bn==="desc"?p:-p})},[Gt,Ps,ra,js,Hs,Is,kn,La,$s,Va,Ra,bn,cs,ia]),rc=s.useMemo(()=>{const o=new Set;for(const i of Gt)i.parentTaskId&&o.add(i.parentTaskId);for(const i of Ps)i.parentTaskId&&o.add(i.parentTaskId);return Gt.filter(i=>{const l=!cs||js.includes(i.category),p=!cs||pl(i.priority,Hs),g=!cs||Is.includes(i.type||"feature"),C=!cs||kn.includes(i.status),X=!$s||!cs||La.includes(i.assignee||"unassigned"),lt=!!i.parentTaskId,He=o.has(i.id),Pt=ia==="all"?!0:ia==="parents"?He:ia==="linked"?lt||He:!lt&&!He,gs=Object.entries(Va).every(([ee,Qt])=>{const xs=i.taxonomies?.[ee];return xs?Array.isArray(xs)?xs.some(fa=>Qt.includes(fa)):Qt.includes(xs):(Qs.find(lo=>lo.id===ee)?.options.every(lo=>Qt.includes(lo.value))??!0)||Qt.includes("")});return l&&p&&g&&C&&X&&gs&&Pt})},[Gt,Ps,js,Hs,Is,kn,La,$s,Va,cs,Qs,ia]),ic=s.useMemo(()=>{const o=Be.every(i=>js.includes(i.value));return Ps.filter(i=>{const l=i.title.toLowerCase().includes(ra.toLowerCase())||(i.description?.toLowerCase()||"").includes(ra.toLowerCase())||i.id.toLowerCase().includes(ra.toLowerCase()),p=!cs||o||js.includes(i.category),g=!cs||pl(i.priority,Hs),C=!cs||Is.includes(i.type||"feature"),X=!$s||!cs||La.includes(i.assignee||"unassigned"),lt=Object.entries(Va).every(([He,Pt])=>{const gs=i.taxonomies?.[He];return gs?Array.isArray(gs)?gs.some(ee=>Pt.includes(ee)):Pt.includes(gs):(Qs.find(xs=>xs.id===He)?.options.every(xs=>Pt.includes(xs.value))??!0)||Pt.includes("")});return l&&p&&g&&C&&X&&lt}).sort((i,l)=>{const p=new Date(l.createdAt).getTime()-new Date(i.createdAt).getTime();return Ra==="created"?bn==="desc"?p:-p:0})},[Ps,ra,js,Hs,Is,La,$s,Va,Ra,cs,Be]),Ws=s.useMemo(()=>{const o=new Map;for(const i of Ps)o.set(i.id,i);for(const i of Gt)o.set(i.id,i);return Array.from(o.values())},[Gt,Ps]),[Xc,Qc]=s.useState({}),Zc=s.useMemo(()=>{const o={};return Rr.forEach(i=>{const l=Be.find(g=>g.value===i.category),p=l?l.label:i.category||"General";o[p]||(o[p]=[]),o[p].push(i)}),o},[Rr,Be]);s.useEffect(()=>{y||ue||dt&&(ne==="tasks"?(Me(),$a(!0)):ne==="settings"&&(Ts(),(_e==="commands"||_e==="resources")&&as()))},[dt,ne,_e,q,Me,$a,Ts,as,y,ue]);const cc=s.useCallback(async(o="")=>{try{const i=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(o)}`);if(i.ok){const l=await i.json();Mt(l.folders||[]),tt(l.files||[]),Rt(o)}}catch(i){console.error("[Taskforce] Failed to fetch folders:",i)}},[]),Gs=s.useCallback(o=>{const i=[];if(o.path&&i.push(o.path),o.paths&&o.paths.length>0)for(const l of o.paths)i.includes(l)||i.push(l);return i},[]),oo=s.useCallback(async o=>{if(o.length!==0)try{const i=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:o})});if(i.ok){const l=await i.json();Fi(p=>({...p,...l.results}))}}catch(i){console.error("[Taskforce] Failed to validate paths:",i)}},[]);s.useEffect(()=>{if(ne==="settings"&&es){const o=[];Be.forEach(l=>{Gs(l).forEach(g=>{o.includes(g)||o.push(g)})});const i=o.filter(l=>!pr[l]);i.length>0&&oo(i)}},[ne,es,Be,Gs,oo,pr]);const wa=s.useCallback(async(o,i)=>{if(es){To(l=>(l.length>0?l:Be).map(g=>g.value===o.value?o:g)),i&&i!==o.label&&(Js===i&&Aa(o.label),js.includes(i)&&qa(l=>l.map(p=>p===i?o.label:p)));try{const g={categories:(Xs.length>0?Xs:Be).map(C=>C.value===o.value?o:C)};i&&i!==o.label&&(g.reassignFrom=i,g.reassignTo=o.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)}),i&&Me()}catch(l){console.error("[Taskforce] Failed to update category",l)}}},[es,Be,Xs,Js,js,Me]),lc=s.useCallback(async o=>{if(!es)return;const i=o.trim().toLowerCase().replace(/\s+/g,"-");if(Be.some(p=>p.value===i))return;const l={value:i,label:o.trim(),color:"blue-200",icon:"Folder"};To(p=>[...p.length>0?p:Be,l]);try{const g=[...Xs.length>0?Xs:Be,l];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:g})})}catch(p){console.error("[Taskforce] Failed to create category",p)}},[es,Be,Xs]),ro=s.useCallback(o=>{ne==="tasks"&&cr.current&&qr(cr.current.scrollTop),le(o)},[ne]),ha=s.useCallback(o=>{let i=!1;if(ct){const l=Gt.find(p=>p.id===ct);if(l){const p=(l.description||"")===(za||""),g=Number(l.priority)===Number(fn),C=Number(l.complexity??3)===Number(Po??3),X=(l.approach||"")===(Wn||""),lt=(l.assignee||"unassigned")===(Pa||"unassigned"),He=(l.parentTaskId||"")===(Hn||"").trim(),Pt=JSON.stringify(l.taxonomies||{})===JSON.stringify(wr),gs=JSON.stringify(l.specialists||[])===JSON.stringify(Kn),ee=JSON.stringify(l.attachments||l.screenshots||[])===JSON.stringify(Fo);(l.title!==Gn||!p||l.category!==Js||l.type!==xa||!g||!C||!X||!lt||!He||!Pt||!gs||!ee||ai.trim()!=="")&&(i=!0)}}else i=Gn.trim()!==""||za.trim()!==""||ai.trim()!==""||tn.length>0||Fo.length>0;if(!i){o();return}zc(()=>o),Hr(!0)},[Gn,za,Js,xa,fn,Po,Wn,Pa,Un,gn,Hn,ct,Gt,wr,Kn,Fo,Be]),el=s.useCallback(()=>{ae(!1)},[]),_n=s.useCallback(()=>{Mi(null),yn(""),ta("");const o=ba,i=Be.some(l=>l.label===o||l.value===o);if(o&&i){const l=Be.find(p=>p.label===o||p.value===o);Aa(l?.value||o)}else Aa(Ks(Be));Da("feature"),Ha(2),ea(3),Ba("default"),zo("agent"),vr(""),Lo(""),Ro(""),br(""),Vn({}),Ga([]),qn(""),Sr([]),ii([]),Ce("")},[Be,Ks,ba]),ma=s.useCallback(o=>{const i=o.trim();if(!i)return null;const l=Ws.find(g=>g.id===i);if(l)return l;const p=Ws.filter(g=>g.id.endsWith(i));return p.length===1?p[0]:null},[Ws]),sa=s.useCallback(o=>{ir&&o.id!==ir&&(rr(null),Co(null)),Mi(o.id),yn(o.title),ta(o.description||""),Aa(o.category||Ks(Be)),Da(o.type||"feature"),Ha(typeof o.priority=="number"?o.priority:2),ea(typeof o.complexity=="number"?o.complexity:3),Ba(o.approach||"default"),zo(o.assignee||"unassigned"),vr(o.scheduledDate||""),Lo(o.dueDate||""),Ro(o.parentTaskId||""),br(""),Ga(o.comments||[]),Vn(o.taxonomies||{}),o.taxonomies?.approach&&Ba(o.taxonomies.approach),Sr(o.specialists||[]),ii(o.attachments||o.screenshots||[]),ro("add")},[Be,ir,Ks]),Er=s.useCallback(o=>{const i=Gt.find(l=>l.id===o);i&&(ne==="add"&&ct&&ct!==i.id&&(rr(ct),Co(i.id)),sa(i))},[Gt,sa,ne,ct]),io=async()=>{if(!Gn.trim())return Ce("Title is required"),!1;if(ct&&Ws.find(i=>i.id===ct)?.isArchived)return Ce("Archived tasks are read-only. Unarchive first to make changes."),!1;Ua(!0),Ce("");try{const o=ct?`/api/taskforce/task/${ct}`:v.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),i=ct?"PATCH":"POST",l=typeof Js=="string"?Js:Js.label||Ks(Be),p=typeof xa=="string"?xa:xa.label||"feature",g=await fetch(o,{method:i,headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Gn,description:za||null,category:l||Ks(Be),type:p,priority:fn,complexity:Number(Po)||3,approach:Wn||"default",assignee:Pa||"agent",scheduledDate:Un||null,dueDate:gn||null,parentTaskId:Hn.trim()||null,comments:tn,attachments:Fo,taxonomies:wr,specialists:Kn,createdAt:new Date().toISOString(),createdBy:"user"})});if(g.ok)return Tr(l),Ua(!1),!0;{const C=await g.json();return Ce(C.message||`Failed to ${ct?"update":"save"} task`),Ua(!1),!1}}catch{return Ce("Failed to connect to server"),Ua(!1),!1}},ui=s.useCallback(async()=>{await io()&&(Ys({message:`Task ${ct?"updated":"added"} successfully`,type:ct?"updated":"added"}),setTimeout(()=>Ys(null),3e3),ne==="add"&&(_n(),ro("tasks"),Me()))},[io,ct,ne,_n,Me]),rn=async o=>{if(o.preventDefault(),gn&&Un&&gn<Un){Ka({dueDate:gn,scheduledDate:Un});return}await ui()},jn=s.useCallback(async()=>{Ka(null),await ui()},[ui]),dc=s.useCallback(()=>{Ka(null)},[]),pi=async(o,i=!1,l={})=>{if(!l.skipConfirm&&!confirm("Are you sure you want to delete this task permanently?"))return!1;const p=i||Ps.some(g=>g.id===o);try{const g=await fetch(`/api/taskforce/task/${o}`,{method:"DELETE"});if(!g.ok){const C=await g.json().catch(()=>({}));return Ce(C.error||"Failed to delete task."),!1}if(window.location.search.includes(o)){const C=new URL(window.location.href);C.searchParams.delete("task"),window.history.pushState({},"",C.toString())}if(p?Fa(C=>C.filter(X=>X.id!==o)):Fs(C=>C.filter(X=>X.id!==o)),pa.current.add(o),se&&De==="local"&&Ct&&Do){const C=Ia();Os.current=C,Es(C)}return ct===o&&(_n(),ro("tasks")),Ce(""),!0}catch(g){return console.error("Failed to delete task:",g),Ce("Failed to delete task."),!1}},hi=s.useCallback(async(o,i)=>{const l=Gt,p=Ps;Fs(g=>g.map(C=>C.id===o?{...C,...i}:C)),Fa(g=>g.map(C=>C.id===o?{...C,...i}:C));try{const g=await fetch(`/api/taskforce/task/${o}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!g.ok){const C=await g.json().catch(()=>({}));Ce(C.error||`Failed to update task ${o}.`),Fs(l),Fa(p);return}Ce("")}catch(g){console.error("Failed to update task",g),Ce(`Failed to update task ${o}.`),Fs(l),Fa(p)}},[Gt,Ps]),mi=async o=>{const i=o.status==="done"?"task":"done",l=i==="done",p=[...Gt,...Ps],g=Array.from(wc(p,o.id)).some(C=>C!==o.id);if(l&&g){Ce("Parent tasks complete automatically when all descendant tasks are done or cancelled.");return}try{const C=l?new Date().toISOString():void 0,X=await fetch(`/api/taskforce/task/${o.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:i,completedAt:C})});if(!X.ok){const lt=await X.json().catch(()=>({}));Ce(lt.error||"Failed to update task status."),await Me(!0);return}await Me(!0),Ce("")}catch(C){console.error("Failed to toggle complete",C),Ce("Failed to update task status."),Me()}},Tn=async o=>{const i=o.status==="cancelled"?"task":"cancelled";if(i==="cancelled"){const p=new Map;Gt.forEach(X=>p.set(X.id,X));const g=Nc(Gt),C=Array.from(wc(Gt,o.id)).filter(X=>X!==o.id).filter(X=>{const lt=p.get(X);return!!lt&&!lt?.isArchived&&lt?.status!=="done"&&lt?.status!=="cancelled"}).sort((X,lt)=>(g.get(lt)||0)-(g.get(X)||0));jo(C),dn(null),Xr(o);return}try{const p=await fetch(`/api/taskforce/task/${o.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:i})});if(!p.ok){const g=await p.json().catch(()=>({}));Ce(g.error||"Failed to update task status."),await Me(!0);return}await Me(!0),Ce("")}catch(p){console.error("Failed to toggle cancel",p),Ce("Failed to update task status."),Me()}},Nn=s.useCallback(async(o,i)=>{if(!_o)return!1;const l=_o,p=i||zn;if(Qr.length>0&&!p)return Ce("Choose how to handle open descendant tasks before confirming cancellation."),!1;try{const g=await fetch(`/api/taskforce/task/${l.id}/cancel-parent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:o,mode:p||"cascade"})});if(!g.ok){const C=await g.json().catch(()=>({}));return Ce(C.error||"Failed to update task status."),await Me(!0),!1}return Ce(""),Xr(null),jo([]),dn(null),await Me(!0),!0}catch(g){return console.error("Failed to confirm cancellation",g),Ce("Failed to update task status."),Me(),!1}},[_o,Qr,zn,Me]),Ya=s.useCallback(()=>{Xr(null),jo([]),dn(null)},[]),Mr=async o=>{const i=o.status==="in-progress"?"task":"in-progress";Fs(l=>l.map(p=>p.id===o.id?{...p,status:i}:p));try{await fetch(`/api/taskforce/task/${o.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:i})})}catch{Me()}},fi=async o=>{const i=o.status==="review"?"task":"review";Fs(l=>l.map(p=>p.id===o.id?{...p,status:i}:p));try{await fetch(`/api/taskforce/task/${o.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:i})})}catch{Me()}},gi=async o=>{try{const i=new Map;Gt.forEach(He=>i.set(He.id,He));const l=Nc(Gt),p=Array.from(wc(Gt,o.id)).filter(He=>He!==o.id).filter(He=>{const Pt=i.get(He);return!!Pt&&!Pt?.isArchived}).sort((He,Pt)=>(l.get(Pt)||0)-(l.get(He)||0)),g=p.length>0?window.confirm(E("actionHeader.confirmCascadeArchive",{count:p.length})):!1;if(p.length>0&&g)for(const He of p){const Pt=i.get(He);if(!Pt)continue;const gs=Pt.status==="cancelled"?"cancel":"complete",ee=await fetch(`/api/taskforce/task/${He}/${gs}`,{method:"POST"});if(!ee.ok){const Qt=await ee.json().catch(()=>({}));Ce(Qt.error||"Failed to archive task."),await Me(!0);return}}const X=o.status==="cancelled"?"cancel":"complete",lt=await fetch(`/api/taskforce/task/${o.id}/${X}`,{method:"POST"});if(lt.ok){const He=new Set([o.id,...g?p:[]]);Fs(Pt=>Pt.filter(gs=>!He.has(gs.id))),$a(),ct&&He.has(ct)&&(_n(),ro("tasks"))}else{const He=await lt.json().catch(()=>({}));Ce(He.error||"Failed to archive task.")}}catch(i){console.error("Failed to archive",i),Ce("Failed to archive task.")}},tl=async()=>{const o=Gt.filter(i=>i.status==="done"||i.status==="cancelled");if(o.length!==0&&confirm(`Archive ${o.length} completed/cancelled tasks?`))try{const i=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:o.map(l=>l.id)})});if(i.ok){const l=await i.json();Fs(p=>p.filter(g=>!["done","cancelled"].includes(g.status))),$a(),Ys({message:`${l.archived||o.length} tasks archived`,type:"info"}),setTimeout(()=>Ys(null),3e3),Ce("")}else{const l=await i.json().catch(()=>({}));Ce(l.error||"Failed to bulk archive tasks.")}}catch(i){console.error("Failed to bulk archive",i),Ce("Failed to bulk archive tasks.")}},sl=async o=>{try{const i=await fetch(`/api/taskforce/task/${o}/unarchive`,{method:"POST"});if(i.ok){const l=await i.json();Fa(p=>p.filter(g=>g.id!==o)),Me()}}catch(i){console.error("Failed to unarchive",i)}},uc=async o=>{if(!ct||!o.trim())return;const i={id:`comment-${oh()}`,author:"user",text:o,timestamp:new Date().toISOString()},l=[...tn,i];Ga(l),qn("");try{await fetch(`/api/taskforce/task/${ct}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({comments:l})}),Fs(p=>p.map(g=>g.id===ct?{...g,comments:l}:g))}catch(p){console.error("Failed to add comment",p)}},Xa=s.useCallback(async o=>{if(!ct)return;const i=Ws.find(C=>C.id===ct);if(!i)return;const l=typeof o=="string"?o.trim():o===null?"":Hn.trim(),p=l?ma(l):null,g=l.length>0?p?.id||l:null;if(g===ct){Ce("A task cannot be its own parent.");return}if(Il(ct,g,Ws)){Ce(`Cannot set parent ${g} for ${ct}: link would create a cycle.`);return}if(!(Nl(i.parentTaskId,g)&&!window.confirm(`This task already has parent ${i.parentTaskId}. Re-parent to ${g}?`)))try{const C=await fetch(`/api/taskforce/task/${ct}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentTaskId:g})});if(!C.ok){const X=await C.json().catch(()=>({}));Ce(X.error||"Failed to set parent task.");return}Ce(""),Ys({message:g?"Parent set":"Parent removed",type:"info"}),setTimeout(()=>Ys(null),2500),await Me(!0)}catch{Ce("Failed to set parent task.")}},[ct,Hn,Ws,Me,ma]),al=s.useCallback(async()=>{if(!ct)return;const o=si.trim();if(!o)return;const i=ma(o);if(!i){Ce("Child task not found by that ID.");return}if(i.id===ct){Ce("A task cannot be a child of itself.");return}if(Il(i.id,ct,Ws)){Ce(`Cannot link child ${i.id} to parent ${ct}: link would create a cycle.`);return}if(!(Nl(i.parentTaskId,ct)&&!window.confirm(`Task ${i.id} is already parented to ${i.parentTaskId}. Re-parent it to ${ct}?`)))try{const l=await fetch(`/api/taskforce/task/${i.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentTaskId:ct})});if(!l.ok){const p=await l.json().catch(()=>({}));Ce(p.error||"Failed to add child task.");return}Ce(""),br(""),Ys({message:`Child linked: ${i.id}`,type:"info"}),setTimeout(()=>Ys(null),2500),await Me(!0)}catch{Ce("Failed to add child task.")}},[ct,si,ma,Ws,Me]),nl=s.useCallback(async()=>{if(!ct)return;const o=Ws.find(p=>p.id===ct);if(!o){Ce("Parent task not found.");return}const l={title:`Child of ${o.title}`,description:null,category:o.category||Js||Ks(Be),type:o.type||xa||"feature",priority:typeof o.priority=="number"?o.priority:2,complexity:typeof o.complexity=="number"?o.complexity:3,approach:o.approach||null,assignee:o.assignee||"agent",parentTaskId:ct,comments:[],attachments:[],taxonomies:{},specialists:[],createdAt:new Date().toISOString(),createdBy:"user"};try{const p=await fetch("/api/taskforce/task",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!p.ok){const X=await p.json().catch(()=>({}));Ce(X.error||"Failed to create child task.");return}const g=await p.json(),C=ul(g,{mapLegacyTodoStatus:!0});Fs(X=>[C,...X]),Ce(""),Ys({message:`Child task created: ${C.id}`,type:"added"}),setTimeout(()=>Ys(null),3e3),rr(ct),Co(C.id),sa(C),await Me(!0)}catch{Ce("Failed to create child task.")}},[ct,Ws,Js,xa,ya,sa,Me,Ks,Be]),ol=s.useCallback(()=>{rr(null),Co(null)},[]),rl=s.useCallback(async o=>{if(window.confirm(`Remove child link for ${o}?`))try{const l=await fetch(`/api/taskforce/task/${o}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentTaskId:null})});if(!l.ok){const p=await l.json().catch(()=>({}));Ce(p.error||"Failed to unlink child task.");return}Ce(""),Ys({message:`Child unlinked: ${o}`,type:"info"}),setTimeout(()=>Ys(null),2500),await Me(!0)}catch{Ce("Failed to unlink child task.")}},[Me]),il=s.useCallback(async(o,i)=>{if(!o||i.length===0)return;const l=i.map((g,C)=>({id:g,childDisplayOrder:C})),p=new Map(l.map(g=>[g.id,g.childDisplayOrder]));Fs(g=>g.map(C=>{const X=p.get(C.id);return X===void 0?C:{...C,childDisplayOrder:X}})),Fa(g=>g.map(C=>{const X=p.get(C.id);return X===void 0?C:{...C,childDisplayOrder:X}}));try{const g=await fetch("/api/taskforce/bulk-update-fields",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:l})});if(!g.ok){const C=await g.json().catch(()=>({}));Ce(C.error||"Failed to save child task order."),await Me(!0);return}Ce("")}catch{Ce("Failed to save child task order."),await Me(!0)}},[Me]),pc=s.useCallback(async o=>{if(window.confirm(`Remove parent link for ${o}?`))try{const l=await fetch(`/api/taskforce/task/${o}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentTaskId:null})});if(!l.ok){const p=await l.json().catch(()=>({}));Ce(p.error||"Failed to remove parent task.");return}Ce(""),Ys({message:`Parent removed: ${o}`,type:"info"}),setTimeout(()=>Ys(null),2500),await Me(!0)}catch{Ce("Failed to remove parent task.")}},[Me]),hc=(o,i)=>{o.stopPropagation(),navigator.clipboard.writeText(i),$i(i),setTimeout(()=>$i(null),2e3)},c=s.useCallback((o,i)=>{if(!i.trim())return;const l=Be.find(p=>p.value===o);if(l){const p=Gs(l),g=i.trim();if(!p.includes(g)){const C=[...p,g];wa({...l,path:void 0,paths:C}),oo(C)}}},[Be,Gs,oo,wa]),k=s.useCallback((o,i)=>{const l=Be.find(p=>p.value===o);l&&wa({...l,icon:i})},[Be,wa]),A=s.useCallback((o,i)=>{const l=Be.find(p=>p.value===o);l&&wa({...l,color:i})},[Be,wa]),fe=s.useCallback((o,i)=>{const l=Be.find(p=>p.value===o);if(l){const g=Gs(l).filter(C=>C!==i);wa({...l,path:void 0,paths:g})}},[Be,Gs]),ge=s.useCallback(o=>{const i=Vr(o);if(wt&&typeof wt=="object"&&wt.type==="category"){const l=Be.find(p=>p.value===wt.value);if(l){const p=Gs(l);if(!p.includes(i)){const g=[...p,i];wa({...l,path:void 0,paths:g})}kt(!1)}}wt&&typeof wt=="object"&&wt.type==="context-link"&&(Pe(i),kt(!1)),kt(!1),Ut(null)},[wt,Q,ss,xt,Be,Gs,Vr]),gt=s.useCallback(async o=>{if(!es)return;const i="default",l="Default",p=Be.find(g=>g.value===o);To(g=>{let X=(g.length>0?g:Be).filter(lt=>lt.value!==o);return X.some(lt=>lt.value===i)||X.unshift({value:i,label:l}),X}),p&&((Js===p.label||Js===p.value)&&Aa(i),(js.includes(p.label)||js.includes(p.value))&&qa(g=>{const C=g.filter(lt=>lt!==p.label&&lt!==p.value),X=C.includes(i)?[]:[i];return[...C,...X]}));try{let C=(Xs.length>0?Xs:Be).filter(X=>X.value!==o);C.some(X=>X.value===i)||C.unshift({value:i,label:l}),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:C,reassignFrom:p?.label||o,reassignTo:l})}),Me()}catch(g){console.error("[Taskforce] Failed to remove category",g)}},[es,Be,Xs,Js,js,Me]),ks=async o=>{if(!o.trim())return;const i=o.trim().toLowerCase().replace(/\s+/g,"-");if(Zs.some(p=>p.value===i))return;const l=[...Zs,{value:i,label:o.trim()}];hr(l);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:l})})}catch(p){console.error("Failed to save type",p)}},Wt=async o=>{const i="feature",l=Zs.filter(p=>p.value!==o);!l.some(p=>p.value===i)&&o!==i&&l.unshift({value:"feature",label:"Feature"}),hr(l);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:l,reassignFrom:o,reassignTo:i})}),Me()}catch(p){console.error("Failed to save type",p)}},co=s.useCallback(async o=>{if(es){Zr(o);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:o})})}catch(i){console.error("[Taskforce] Failed to save taxonomies",i)}}},[es]),In=s.useCallback(async o=>{if(es){at(o);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:o})})}catch(i){console.error("[Taskforce] Failed to save priorities",i)}}},[es]),yi=s.useCallback(async o=>{if(es){bs(o);try{await fetch("/api/taskforce/approaches",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({approaches:o})})}catch(i){console.error("[Taskforce] Failed to save approaches",i)}}},[es]),mc=s.useMemo(()=>{if(ct)return Ws.find(o=>o.id===ct)},[Ws,ct]),Yd=s.useMemo(()=>{if(mc?.parentTaskId)return Ws.find(o=>o.id===mc.parentTaskId)},[Ws,mc]),Xd=s.useMemo(()=>ct?Pc(Ws.filter(o=>o.parentTaskId===ct)):[],[Ws,ct]),Qd={currentTheme:Q,configLoaded:es,globalTheme:xe,themeUseGlobalDefault:oe,keyShortcut:ss,jsonBackupEnabled:O,globalJsonBackupEnabled:Ft,globalWeekStartsOn:Us,locale:Yt,supportedLocales:Ls,jsonBackupUseGlobalDefault:Ot,manualComplexityEnabled:ya,checklistDropdownEnabled:Vs,assigneeFilterEnabled:$s,exportWorkflowsPath:ar,exportSpecialistsPath:Pn,exportingResource:or,exportResult:So,pathSaved:ut,initialSection:_e,exportEnvironment:Rs,setupState:Ke,buildInfo:Qe,onSaveSetupMode:tc,onSaveWorkspaceProfile:di,onThemeChange:de,onSaveTheme:Bi,onSaveGlobalTheme:Pi,onKeyShortcutChange:Xt,onJsonBackupEnabledChange:zi,onSaveGlobalJsonBackupEnabled:Li,onSaveGlobalWeekStartsOn:Ri,onSaveLocale:Kr,onManualComplexityEnabledChange:it,onChecklistDropdownEnabledChange:ws,onAssigneeFilterEnabledChange:ja,onResetProjectToGlobal:ln,onSaveSettings:Di,onExportWorkflowsPathChange:nr,onExportSpecialistsPathChange:wo,onExportEnvironmentChange:xo,onExportResources:dr,availableWorkflows:Nt,initiativeTemplates:$e,availableEnvironments:ms,onRefreshWorkflows:as,onRefreshInitiativeTemplates:Ns,onCreateInitiativeFromTemplate:zr,onCloneChecklistBlocksToChildren:Yc,onFetchWorkflowTemplate:Ca,onFetchWorkflowOverrideNames:ns,onSaveWorkflowTemplateDraft:_s,onResetWorkflowTemplateDraft:_a,onExportWorkflows:Jr,onShowFolderBrowserChange:kt,onBrowserTargetChange:Ut,onFetchFolders:cc,categories:Be,pathValidation:pr,onUpdateCategory:wa,onRemoveCategory:gt,onSaveCategory:lc,onAddPath:c,onRemovePath:fe,onUpdateCategoryIcon:k,onUpdateCategoryColor:A,types:Zs,onSaveType:ks,onRemoveType:Wt,taxonomies:Qs,onUpdateTaxonomies:co,priorities:Xe,onUpdatePriorities:In,approaches:Bt,onUpdateApproaches:yi,projectRoot:ze,projectName:G,mcpHostRoot:xt,serverHostRoot:S,mcpScriptPath:we,tenantId:vt,workspaceId:F,runtimeMode:De,workspaceSwitchingEnabled:Ee,currentWorkspaceRole:K.find(o=>o.id===F)?.role||"member",currentWorkspaceName:String(K.find(o=>o.id===F)?.name||""),onDeleteWorkspace:Dr,onMcpHostRootChange:$t,isAuthenticated:Ct},Zd=ia==="parents",eu=s.useCallback(o=>{an(o?"parents":"all")},[]);return s.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:Gt,archivedTasks:Ps,runtimeMode:De,currentWorkspaceId:F,isAuthenticated:Ct,workspaceCloudSyncEnabled:Do,realtimeSyncEnabled:Lt,fetchTasks:Me,fetchArchive:$a,retryWorkspaceCloudSync:en,resetWorkspaceSyncCursorAndPull:xr,__dispatch:{handleUpdateTask:hi,handleToggleComplete:mi,handleArchiveTask:gi,handleToggleCancel:Tn,handleToggleInProgress:Mr,handleToggleReview:fi,handleSubmit:rn,handleDelete:pi}})},[Gt,Ps,De,F,Ct,Do,Lt,Me,$a,en,xr,hi,mi,gi,Tn,Mr,fi,rn,pi]),{config:d,isOpen:dt,setIsOpen:ae,activeTab:ne,setActiveTab:ro,currentTheme:Q,setCurrentTheme:de,configLoaded:es,storagePath:yt,saveSettings:Di,pathSaved:ut,keyShortcut:ss,setKeyShortcut:Xt,globalWeekStartsOn:Us,locale:Yt,supportedLocales:Ls,saveLocale:Kr,jsonBackupEnabled:O,setJsonBackupEnabled:Ve,manualComplexityEnabled:ya,checklistDropdownEnabled:Vs,assigneeFilterEnabled:$s,setManualComplexityEnabled:na,mcpHostRoot:xt,setMcpHostRoot:$t,settingsSection:_e,setSettingsSection:Le,runtimeMode:De,workspaceMode:ls,workspaceSwitchingEnabled:Ee,cloudAuthConfigured:se,authRequiredForApi:zt,authBlocked:Et,isAuthenticated:Ct,authUserEmail:Ds,userGlobalSyncStatus:Oi,userGlobalLastSyncedAt:Wi,workspaceLastPullAt:gr,workspaceLastPushAt:$n,workspaceLastErrorAt:ei,workspaceRetryAt:ti,userGlobalSyncPendingChanges:Io,userGlobalSyncError:hn,workspaceLastErrorMessage:Ui,workspaceLastWarningMessage:Ao,workspaceSyncFailureCount:yr,workspaceSyncRetryScheduledCount:On,workspaceSyncAuthFailureCount:kr,workspaceSyncLastFailureSource:Wc,workspaceSyncLastFailureStatusCode:Uc,workspaceBootstrapSyncInProgress:Bo,workspaceBootstrapSyncPages:Fc,workspaceBootstrapSyncAppliedChanges:Oc,retryUserGlobalSettingsSync:Xi,retryWorkspaceCloudSync:en,resetWorkspaceSyncCursorAndPull:xr,hasBetaAccess:Cs,realtimeSyncEnabled:Lt,realtimeSyncFlagSource:Ms,currentWorkspaceId:F,availableWorkspaces:K,workspaceCloudSyncEnabled:Do,realtimeConnectionState:$c,realtimeTelemetry:Hi,workspaceSyncSourceOfTruth:Gi,workspaceSyncOnboardingCompleted:qi,workspaceSyncReady:Vi,workspaceCloudHydrated:Ki,saveWorkspaceCloudSyncSettings:fs,applyWorkspaceSyncStateSnapshot:Yi,authSessionResolved:ie,workspaceBootstrapPending:me,bootstrapPhase:_t,bootstrapError:Ue,bootstrapStartedAt:nt,setupState:Ke,runtimeCapabilities:ps,refreshSetupContext:so,retryBootstrapChecks:Go,saveWorkspaceProfile:di,fetchWorkspaces:os,createWorkspace:ao,deleteWorkspace:Dr,switchWorkspace:Ea,loginWithCredentials:on,registerWithCredentials:Vc,requestEmailVerification:Kc,confirmEmailVerification:Jc,requestPasswordReset:Br,confirmPasswordReset:qo,inspectInviteAcceptance:Cn,acceptInviteWithToken:Pr,logout:sc,showFolderBrowser:mt,setShowFolderBrowser:kt,folders:Dt,files:Zt,currentBrowsePath:pt,fetchFolders:cc,browserTarget:wt,setBrowserTarget:Ut,contextLinkBrowsePath:V,groupBy:bo,setGroupBy:er,emptyColumnMode:tr,setEmptyColumnMode:Ni,zenMode:Za,setZenMode:lr,handleSelectPath:ge,handleAddPath:c,handleRemovePath:fe,tasks:Gt,loadingTasks:Ec,archivedTasks:Ps,activeCategories:Be,activeTypes:Zs,priorities:Xe,approaches:Bt,availableSpecialists:Re,taxonomies:Qs,searchQuery:ra,setSearchQuery:sn,filterCategories:js,setFilterCategories:qa,filterTypes:Is,setFilterTypes:Qn,filterPriorities:Hs,setFilterPriorities:Xn,filterStatus:kn,setFilterStatus:xn,filterAssignees:La,setFilterAssignees:vn,parentTaskFilterMode:ia,setParentTaskFilterMode:an,showParentsOnly:Zd,setShowParentsOnly:eu,filterTaxonomies:Va,setFilterTaxonomies:Zn,sortBy:Ra,setSortBy:Nr,sortOrder:bn,setSortOrder:Mo,toggleSortOrder:nc,showArchive:q,setShowArchive:M,clearFilters:oc,filteredTasks:Rr,searchAgnosticTasks:rc,filteredArchive:ic,groupedTasks:Zc,collapsedCategories:Xc,setCollapsedCategories:Qc,fetchTasks:Me,fetchArchive:$a,handleEdit:sa,handleDelete:pi,handleCopyId:hc,handleToggleComplete:mi,handleToggleCancel:Tn,handleToggleInProgress:Mr,handleToggleReview:fi,handleArchiveTask:gi,handleBulkArchive:tl,handleUnarchive:sl,handleUpdateTask:hi,editingTaskId:ct,loading:mr,error:fr,title:Gn,setTitle:yn,description:za,setDescription:ta,category:Js,setCategory:Aa,type:xa,setType:Da,priority:fn,setPriority:Ha,complexity:Po,setComplexity:ea,approach:Wn,setApproach:Ba,assignee:Pa,setAssignee:zo,scheduledDate:Un,setScheduledDate:vr,dueDate:gn,setDueDate:Lo,parentTaskIdInput:Hn,setParentTaskIdInput:Ro,addChildTaskIdInput:si,setAddChildTaskIdInput:br,formTaxonomies:wr,setFormTaxonomies:Vn,selectedSpecialists:Kn,setSelectedSpecialists:Sr,comments:tn,newCommentText:ai,setNewCommentText:qn,screenshots:Fo,setScreenshots:ii,descriptionFocused:Hc,setDescriptionFocused:$o,showMarkdownHelp:Mc,setShowMarkdownHelp:Yr,showSpecialists:Cr,setShowSpecialists:ni,showChecklist:_r,setShowChecklist:Jn,showTaskRelationships:jr,setShowTaskRelationships:va,showChildTasks:Yn,setShowChildTasks:oi,showComments:ri,setShowComments:nn,isCapturingScreenshot:Zi,setIsCapturingScreenshot:ec,handleSubmit:rn,resetForm:_n,handleAddComment:uc,handleSetParentForCurrentTask:Xa,handleAddChildToCurrentTask:al,handleCreateChildForCurrentTask:nl,handleUnlinkChildTask:rl,handleReorderChildTasks:il,handleClearParentTask:pc,handleOpenTaskById:Er,unsavedModalOpen:Ii,setUnsavedModalOpen:Hr,pendingNavigation:Gr,handleNavigation:ha,handleClose:el,successBanner:Lc,returnToParentTaskId:Rc,returnFromChildTaskId:ir,clearReturnToParentTask:ol,copiedId:ur,recentlyChangedTaskIds:Gc,cancellationPromptTask:_o,cancellationOpenDescendantIds:Qr,cancellationMode:zn,setCancellationMode:dn,confirmCancellation:Nn,cancelCancellationPrompt:Ya,scheduleWarningPrompt:qc,confirmScheduleWarning:jn,cancelScheduleWarning:dc,tasksScrollRef:cr,setTasksScrollPos:qr,exportEnvironment:Rs,setExportEnvironment:xo,exportWorkflowsPath:ar,setExportWorkflowsPath:nr,exportSpecialistsPath:Pn,setExportSpecialistsPath:wo,exportResult:So,handleExportResources:dr,exportingResource:or,handleUpdateCategory:wa,handleRemoveCategory:gt,handleSaveCategory:lc,handleUpdateCategoryIcon:k,handleUpdateCategoryColor:A,handleSaveType:ks,handleRemoveType:Wt,handleUpdateTaxonomies:co,handleUpdatePriorities:In,handleUpdateApproaches:yi,pathValidation:pr,validatePaths:oo,getCategoryPaths:Gs,customCategories:Xs,setCustomCategories:To,projectRoot:ze,projectName:G,mcpScriptPath:we,serverHostRoot:S,commentsEndRef:Qi,currentTask:mc,currentTaskParent:Yd,currentTaskChildren:Xd,availableWorkflows:Nt,initiativeTemplates:$e,availableEnvironments:ms,fetchWorkflows:as,fetchInitiativeTemplates:Ns,fetchWorkflowTemplate:Ca,fetchWorkflowOverrideNames:ns,saveWorkflowTemplateDraft:_s,resetWorkflowTemplateDraft:_a,onExportWorkflows:Jr,settingsModel:Qd}}const lh="_filterGlow_1s7z6_13",dh="_standaloneWrapper_1s7z6_21",uh="_standalonePage_1s7z6_31",ph="_floatingButton_1s7z6_45",hh="_badge_1s7z6_76",mh="_configBadge_1s7z6_93",fh="_header_1s7z6_110",gh="_headerTitle_1s7z6_124",yh="_brandIcon_1s7z6_140",kh="_projectSlash_1s7z6_146",xh="_projectName_1s7z6_153",vh="_taskCountBadge_1s7z6_167",bh="_authBlockedBanner_1s7z6_183",wh="_loginView_1s7z6_192",Sh="_loginCard_1s7z6_202",Ch="_loginCloseBtn_1s7z6_215",_h="_loginLogo_1s7z6_236",jh="_authBrandRow_1s7z6_242",Th="_loginBrandRow_1s7z6_248",Nh="_loginTitle_1s7z6_254",Ih="_loginTitleAccent_1s7z6_264",Ah="_loginSubtitle_1s7z6_268",Dh="_loginError_1s7z6_274",Bh="_authModeSwitch_1s7z6_280",Ph="_authModeSwitchLink_1s7z6_287",zh="_authModeLinks_1s7z6_302",Lh="_authModeLink_1s7z6_302",Rh="_authModeLinkActive_1s7z6_326",Eh="_headerSuccess_1s7z6_330",Mh="_fadeInSlideDown_1s7z6_1",$h="_headerActions_1s7z6_357",Fh="_accountMenuWrap_1s7z6_364",Oh="_headerActionBtn_1s7z6_368",Wh="_headerActionBtnActive_1s7z6_386",Uh="_avatarBtn_1s7z6_392",Hh="_avatarBadge_1s7z6_396",Gh="_accountMenu_1s7z6_364",qh="_accountMenuItem_1s7z6_424",Vh="_accountMenuItemActive_1s7z6_444",Kh="_accountMenuSection_1s7z6_449",Jh="_accountMenuSectionLabel_1s7z6_455",Yh="_accountMenuMeta_1s7z6_464",Xh="_accountMenuHint_1s7z6_469",Qh="_accountIdentityEmail_1s7z6_475",Zh="_accountMenuWorkspaceForm_1s7z6_480",em="_input_1s7z6_487",tm="_primaryUpdateBtn_1s7z6_491",sm="_accountMenuError_1s7z6_496",am="_accountHubCard_1s7z6_502",nm="_syncStatusModal_1s7z6_509",om="_syncStatusTop_1s7z6_514",rm="_syncStatusHeading_1s7z6_521",im="_syncStatusSubtext_1s7z6_527",cm="_syncStatusPausedHint_1s7z6_542",lm="_syncStatusBadge_1s7z6_549",dm="_syncStatusGrid_1s7z6_563",um="_syncStatusItem_1s7z6_569",pm="_syncStatusLabel_1s7z6_580",hm="_syncStatusValue_1s7z6_587",mm="_syncStatusDiagnostics_1s7z6_594",fm="_syncStatusDetailsToggle_1s7z6_600",gm="_syncStatusTableWrap_1s7z6_619",ym="_syncStatusDetailsGrid_1s7z6_626",km="_syncStatusTable_1s7z6_619",xm="_syncStatusTableNarrowLabel_1s7z6_660",vm="_syncStatusTableError_1s7z6_669",bm="_syncStatusActions_1s7z6_673",wm="_sortDirectionBtn_1s7z6_697",Sm="_sortDirectionBtnWidget_1s7z6_704",Cm="_form_1s7z6_712",_m="_topRow_1s7z6_723",jm="_field_1s7z6_729",Tm="_labelRow_1s7z6_735",Nm="_label_1s7z6_735",Im="_manageLink_1s7z6_749",Am="_select_1s7z6_769",Dm="_textarea_1s7z6_770",Bm="_markdownPreview_1s7z6_798",Pm="_taskIdInlineLink_1s7z6_848",zm="_readOnly_1s7z6_867",Lm="_selectWithConfig_1s7z6_875",Rm="_configBtn_1s7z6_885",Em="_configBtnActive_1s7z6_915",Mm="_hasPath_1s7z6_923",$m="_pathIndicator_1s7z6_928",Fm="_formActions_1s7z6_934",Om="_hasCancel_1s7z6_941",Wm="_submitBtn_1s7z6_945",Um="_cancelBtn_1s7z6_961",Hm="_successMessage_1s7z6_992",Gm="_successIcon_1s7z6_998",qm="_error_1s7z6_1018",Vm="_keyboardHint_1s7z6_1028",Km="_spinner_1s7z6_1045",Jm="_spin_1s7z6_1045",Ym="_destructiveBtn_1s7z6_1061",Xm="_warningBtn_1s7z6_1083",Qm="_cancelTaskConfirmBtn_1s7z6_1105",Zm="_cancelTaskDeleteBtn_1s7z6_1109",ef="_viewTab_1s7z6_1122",tf="_deleteBtn_1s7z6_1133",sf="_loading_1s7z6_1143",af="_emptyState_1s7z6_1149",nf="_taskList_1s7z6_1159",of="_taskItem_1s7z6_1165",rf="_compressed_1s7z6_1178",cf="_taskHeader_1s7z6_1183",lf="_taskMeta_1s7z6_1188",df="_taskTitle_1s7z6_1194",uf="_taskItemRecentlyChanged_1s7z6_1205",pf="_taskGlowFade_1s7z6_1",hf="_taskItemGlowPersistent_1s7z6_1220",mf="_taskItemLinkedFeedback_1s7z6_1227",ff="_taskLinkGlowPulse_1s7z6_1",gf="_taskLinkFeedbackPill_1s7z6_1245",yf="_taskLinkPillOut_1s7z6_1",kf="_inProgress_1s7z6_1325",xf="_taskContent_1s7z6_1336",vf="_taskIdBadge_1s7z6_1352",bf="_kanbanCardWrapper_1s7z6_1372",wf="_taskIdText_1s7z6_1372",Sf="_kanbanCardOverlay_1s7z6_1373",Cf="_taskIdBadgeStatic_1s7z6_1385",_f="_copiedId_1s7z6_1411",jf="_highlight_1s7z6_1418",Tf="_modal_1s7z6_1430",Nf="_priorityEmoji_1s7z6_1437",If="_metaItem_1s7z6_1453",Af="_taskFormLifecycle_1s7z6_1467",Df="_taskFormDateStack_1s7z6_1472",Bf="_taskFormDateRow_1s7z6_1478",Pf="_taskFormDateLabel_1s7z6_1487",zf="_taskFormDateValue_1s7z6_1493",Lf="_taskFormDateInput_1s7z6_1499",Rf="_metaBadge_1s7z6_1509",Ef="_complexityPill_1s7z6_1524",Mf="_complexityDots_1s7z6_1528",$f="_dot_1s7z6_1534",Ff="_dotFilled_1s7z6_1542",Of="_typePill_1s7z6_1548",Wf="_type_bug_1s7z6_1552",Uf="_type_feature_1s7z6_1556",Hf="_type_chore_1s7z6_1560",Gf="_type_refactor_1s7z6_1564",qf="_type_documentation_1s7z6_1568",Vf="_type_research_1s7z6_1572",Kf="_type_security_1s7z6_1580",Jf="_approachPill_1s7z6_1585",Yf="_approach_evaluate_1s7z6_1590",Xf="_approach_collaborate_1s7z6_1596",Qf="_approach_plan_1s7z6_1602",Zf="_approachActive_1s7z6_1608",eg="_taskActions_1s7z6_1623",tg="_actionBtn_1s7z6_1631",sg="_startWorkBtn_1s7z6_1655",ag="_workingBtn_1s7z6_1664",ng="_pulse_1s7z6_1",og="_reviewBtn_1s7z6_1670",rg="_reviewActiveBtn_1s7z6_1680",ig="_reviewPill_1s7z6_1686",cg="_readyForReview_1s7z6_1692",lg="_completed_1s7z6_1703",dg="_cancelled_1s7z6_1714",ug="_archiveTaskBtn_1s7z6_1725",pg="_bulkArchiveBtn_1s7z6_1734",hg="_completeBtn_1s7z6_1782",mg="_completeActiveBtn_1s7z6_1792",fg="_deleteActiveBtn_1s7z6_1798",gg="_disabledBtn_1s7z6_1804",yg="_archiveList_1s7z6_1811",kg="_archiveHeader_1s7z6_1819",xg="_archived_1s7z6_1827",vg="_settingsTab_1s7z6_1849",bg="_settingsTabs_1s7z6_1861",wg="_appScrollbar_1s7z6_1890",Sg="_settingsTabBtn_1s7z6_1916",Cg="_settingsTabBtnActive_1s7z6_1942",_g="_settingsContent_1s7z6_1948",jg="_settingsToast_1s7z6_1959",Tg="_settingsToastSuccess_1s7z6_1976",Ng="_settingsToastError_1s7z6_1982",Ig="_inputWithPrefix_1s7z6_1988",Ag="_pathHint_1s7z6_1995",Dg="_settingGroup_1s7z6_2008",Bg="_settingTitle_1s7z6_2014",Pg="_settingTitleRow_1s7z6_2023",zg="_settingTitleActionBtn_1s7z6_2030",Lg="_themeOptions_1s7z6_2050",Rg="_buttonGrid_1s7z6_2055",Eg="_themeBtn_1s7z6_2067",Mg="_activeTheme_1s7z6_2090",$g="_pathInputGroup_1s7z6_2098",Fg="_saveSettingsBtn_1s7z6_2107",Og="_shortcutInputWrapper_1s7z6_2128",Wg="_inputIcon_1s7z6_2133",Ug="_settingHelper_1s7z6_2142",Hg="_browseBtn_1s7z6_2149",Gg="_folderBrowserOverlay_1s7z6_2168",qg="_folderBrowser_1s7z6_2168",Vg="_fadeIn_1s7z6_1",Kg="_browserHeader_1s7z6_2194",Jg="_browserPathInfo_1s7z6_2203",Yg="_browserActions_1s7z6_2219",Xg="_browserList_1s7z6_2224",Qg="_browserItem_1s7z6_2230",Zg="_folderItem_1s7z6_2247",ey="_noFolders_1s7z6_2251",ty="_selectFolderBtn_1s7z6_2258",sy="_inlineCategoryManager_1s7z6_2275",ay="_categoryManager_1s7z6_2286",ny="_categoryList_1s7z6_2292",oy="_categoryChip_1s7z6_2304",ry="_categoryChipLabel_1s7z6_2317",iy="_chipActionBtn_1s7z6_2325",cy="_removeCategoryBtn_1s7z6_2345",ly="_addCategoryForm_1s7z6_2365",dy="_addCategoryBtn_1s7z6_2370",uy="_filesList_1s7z6_2395",py="_tabs_1s7z6_2425",hy="_tab_1s7z6_2425",my="_archiveBtn_1s7z6_2481",fy="_closeBtn_1s7z6_2490",gy="_settingsLabel_1s7z6_2499",yy="_settingsHint_1s7z6_2503",ky="_settingsNote_1s7z6_2504",xy="_active_1s7z6_2090",vy="_helpLink_1s7z6_2633",by="_markdownHelp_1s7z6_2652",wy="_helpHeader_1s7z6_2673",Sy="_helpClose_1s7z6_2684",Cy="_helpGrid_1s7z6_2698",_y="_taskDescription_1s7z6_2717",jy="_inlineCode_1s7z6_2755",Ty="_codeBlock_1s7z6_2774",Ny="_taskLatestComment_1s7z6_2813",Iy="_taskCancellationReason_1s7z6_2825",Ay="_taskChildrenList_1s7z6_2854",Dy="_taskChildrenItems_1s7z6_2862",By="_taskChildrenItemsScrollable_1s7z6_2868",Py="_taskChildrenToggleBtn_1s7z6_2874",zy="_taskChildrenCountBadge_1s7z6_2895",Ly="_taskChildrenSummaryBadges_1s7z6_2910",Ry="_taskChildrenMetaRow_1s7z6_2918",Ey="_taskChildrenProgressBar_1s7z6_2925",My="_taskChildrenProgressBarFill_1s7z6_2935",$y="_taskChildrenProgressText_1s7z6_2942",Fy="_taskParentIdBtn_1s7z6_2950",Oy="_taskParentTitle_1s7z6_2954",Wy="_taskParentCompact_1s7z6_2964",Uy="_taskChildMiniTask_1s7z6_2979",Hy="_taskParentMiniTask_1s7z6_2987",Gy="_taskChildMiniTaskArchived_1s7z6_2992",qy="_childTaskIdButton_1s7z6_2999",Vy="_taskChildMiniRow_1s7z6_3003",Ky="_taskChildMiniTitle_1s7z6_3013",Jy="_taskChildUnlinkBtn_1s7z6_3023",Yy="_aboutText_1s7z6_3041",Xy="_versionInfo_1s7z6_3048",Qy="_filterBar_1s7z6_3056",Zy="_kanbanHintText_1s7z6_3069",ek="_searchContainer_1s7z6_3075",tk="_searchIcon_1s7z6_3082",sk="_searchInput_1s7z6_3090",ak="_searchActive_1s7z6_3108",nk="_searchCount_1s7z6_3113",ok="_clearSearchBtn_1s7z6_3129",rk="_filterRow_1s7z6_3151",ik="_sortLabel_1s7z6_3157",ck="_archiveToggle_1s7z6_3165",lk="_filterContainer_1s7z6_3202",dk="_filterButton_1s7z6_3207",uk="_filterActive_1s7z6_3232",pk="_filterDropdown_1s7z6_3238",hk="_filterOption_1s7z6_3253",mk="_filterDivider_1s7z6_3279",fk="_filterSelect_1s7z6_3285",gk="_filterToggleBtn_1s7z6_3320",yk="_inProgressToggle_1s7z6_3340",kk="_activeInProgress_1s7z6_3358",xk="_activeFilter_1s7z6_3367",vk="_resetFiltersBtn_1s7z6_3377",bk="_categoryChip_disabled_1s7z6_3411",wk="_categoryVisibilityToggle_1s7z6_3421",Sk="_editCategoryInput_1s7z6_3434",Ck="_categoryChipActionBtn_1s7z6_3445",_k="_categoryChipActionBtn_active_1s7z6_3463",jk="_categoryGroup_1s7z6_3468",Tk="_categoryHeader_1s7z6_3476",Nk="_categoryTitle_1s7z6_3490",Ik="_categoryCount_1s7z6_3500",Ak="_categoryItems_1s7z6_3506",Dk="_priorityItem_low_1s7z6_3515",Bk="_priorityItem_medium_1s7z6_3519",Pk="_priorityItem_high_1s7z6_3523",zk="_priorityItem_critical_1s7z6_3527",Lk="_priorityPill_low_1s7z6_3534",Rk="_priorityPill_medium_1s7z6_3540",Ek="_priorityPill_high_1s7z6_3546",Mk="_priorityPill_critical_1s7z6_3552",$k="_selectPriority_low_1s7z6_3606",Fk="_selectPriority_medium_1s7z6_3611",Ok="_selectPriority_high_1s7z6_3616",Wk="_selectPriority_critical_1s7z6_3621",Uk="_levelSelect_1s7z6_3630",Hk="_levelOption_1s7z6_3640",Gk="_levelOptionFilled_1s7z6_3657",qk="_levelOption_priority_low_1s7z6_3664",Vk="_levelOption_priority_medium_1s7z6_3669",Kk="_levelOption_priority_high_1s7z6_3674",Jk="_levelOption_priority_critical_1s7z6_3679",Yk="_levelOption_complexity_tiny_1s7z6_3686",Xk="_levelOption_complexity_low_1s7z6_3691",Qk="_levelOption_complexity_medium_1s7z6_3696",Zk="_levelOption_complexity_high_1s7z6_3701",ex="_levelOption_complexity_epic_1s7z6_3706",tx="_levelOptionActive_1s7z6_3713",sx="_levelOptionSelected_1s7z6_3718",ax="_levelLabel_1s7z6_3726",nx="_closeConfigBtn_1s7z6_3751",ox="_configItem_1s7z6_3773",rx="_pathList_1s7z6_3795",ix="_pathChip_1s7z6_3802",cx="_pathValid_1s7z6_3815",lx="_pathInvalid_1s7z6_3820",dx="_pathValidIcon_1s7z6_3825",ux="_pathInvalidIcon_1s7z6_3830",px="_pathText_1s7z6_3835",hx="_removePathBtn_1s7z6_3842",mx="_pathCount_1s7z6_3864",fx="_specialistSection_1s7z6_3887",gx="_toggleHeading_1s7z6_3895",yx="_dropdownList_1s7z6_3932",kx="_childCardRow_1s7z6_3940",xx="_childCardRowDragging_1s7z6_3947",vx="_childCardRowDropTarget_1s7z6_3951",bx="_childCardRemoveBtn_1s7z6_3956",wx="_specialistChip_1s7z6_3978",Sx="_specialistChipActive_1s7z6_4001",Cx="_taskSpecialists_1s7z6_4011",_x="_specialistBadge_1s7z6_4019",jx="_iconGrid_1s7z6_4049",Tx="_iconPickerBtn_1s7z6_4060",Nx="_iconPickerBtnActive_1s7z6_4079",Ix="_categorySubConfig_1s7z6_4086",Ax="_colorPickerRow_1s7z6_4094",Dx="_colorPickerGrid_1s7z6_4100",Bx="_colorSwatch_1s7z6_4107",Px="_colorSwatchActive_1s7z6_4126",zx="_categoryChipIcon_1s7z6_4132",Lx="_fieldIconWrapper_1s7z6_4137",Rx="_fieldIcon_1s7z6_4137",Ex="_field_dynamic_1s7z6_4159",Mx="_fieldIcon_dynamic_1s7z6_4165",$x="_categoryTitleIcon_1s7z6_4169",Fx="_editActionsHeader_1s7z6_4175",Ox="_editActionsGroup_1s7z6_4184",Wx="_archiveBadge_1s7z6_4189",Ux="_urlInputGroup_1s7z6_4195",Hx="_iconBtn_1s7z6_4208",Gx="_stickyActionHeader_1s7z6_4229",qx="_headerSuccessFeedback_1s7z6_4246",Vx="_slideInUp_1s7z6_1",Kx="_successCheck_1s7z6_4258",Jx="_scaleIn_1s7z6_1",Yx="_secondaryHeaderBtn_1s7z6_4324",Xx="_commentSection_1s7z6_4346",Qx="_commentPanel_1s7z6_4369",Zx="_commentThread_1s7z6_4383",ev="_emptyComments_1s7z6_4392",tv="_comment_1s7z6_4346",sv="_commentAi_1s7z6_4410",av="_commentUser_1s7z6_4414",nv="_commentHeader_1s7z6_4418",ov="_commentAuthor_1s7z6_4435",rv="_commentTime_1s7z6_4443",iv="_commentText_1s7z6_4447",cv="_commentInputArea_1s7z6_4483",lv="_commentInput_1s7z6_4483",dv="_sendCommentBtn_1s7z6_4515",uv="_screenshotThumbnails_1s7z6_4554",pv="_screenshotThumbnail_1s7z6_4554",hv="_contextDocThumb_1s7z6_4584",mv="_contextDocType_1s7z6_4612",fv="_screenshotContainer_1s7z6_4620",gv="_capturePrompt_1s7z6_4628",yv="_previewContainer_1s7z6_4642",kv="_previewHeader_1s7z6_4648",xv="_screenshotPreview_1s7z6_4658",vv="_actions_1s7z6_4665",bv="_primaryButton_1s7z6_4671",wv="_secondaryButton_1s7z6_4686",Sv="_iconButton_1s7z6_4701",Cv="_screenshotGrid_1s7z6_4723",_v="_screenshotCard_1s7z6_4730",jv="_screenshotImageContainer_1s7z6_4744",Tv="_contextFileLink_1s7z6_4765",Nv="_screenshotActions_1s7z6_4791",Iv="_screenshotActionBtn_1s7z6_4805",Av="_screenshotCaptionInput_1s7z6_4827",Dv="_hiddenInput_1s7z6_4845",Bv="_contextUploadActions_1s7z6_4849",Pv="_contextDropzone_1s7z6_4857",zv="_contextDropzoneActive_1s7z6_4873",Lv="_contextDropzonePulse_1s7z6_1",Rv="_contextLinkRow_1s7z6_4881",Ev="_contextNotice_1s7z6_4887",Mv="_brokenImage_1s7z6_4903",$v="_brokenImagePlaceholder_1s7z6_4911",Fv="_regionOverlay_1s7z6_4925",Ov="_selectionBox_1s7z6_4936",Wv="_exportRow_1s7z6_4944",Uv="_exportItem_1s7z6_4949",Hv="_taxonomyDrillDown_1s7z6_4958",Gv="_drillDownList_1s7z6_4968",qv="_drillDownSection_1s7z6_4976",Vv="_drillDownSectionHeader_1s7z6_4982",Kv="_drillDownSectionTitle_1s7z6_4989",Jv="_drillDownItem_1s7z6_4998",Yv="_drillDownItemDimmed_1s7z6_5020",Xv="_drillDownItemActive_1s7z6_5028",Qv="_drillDownItemInfo_1s7z6_5033",Zv="_drillDownItemText_1s7z6_5039",eb="_drillDownItemLabel_1s7z6_5044",tb="_drillDownItemSubtext_1s7z6_5049",sb="_addTaxonomyBtnSmall_1s7z6_5054",ab="_taxonomyDetailView_1s7z6_5076",nb="_slideIn_1s7z6_1",ob="_detailHeader_1s7z6_5096",rb="_detailTitle_1s7z6_5105",ib="_detailContent_1s7z6_5112",cb="_createOverlay_1s7z6_5119",lb="_createDialog_1s7z6_5131",db="_zoomIn_1s7z6_1",ub="_dialogActions_1s7z6_5159",pb="_settingsGroup_1s7z6_5177",hb="_settingsItem_1s7z6_5183",mb="_settingLabelGroup_1s7z6_5189",fb="_settingLabel_1s7z6_5189",gb="_settingDescription_1s7z6_5201",yb="_settingInput_1s7z6_5208",kb="_codeBlockWrapper_1s7z6_5231",xb="_codeHeader_1s7z6_5240",vb="_codeHeaderActions_1s7z6_5251",bb="_codeLabel_1s7z6_5258",wb="_copyBtn_1s7z6_5281",Sb="_copyBtnActive_1s7z6_5302",Cb="_copyBtnNeutralActive_1s7z6_5308",_b="_standaloneHeader_1s7z6_5327",jb="_standaloneTitle_1s7z6_5332",Tb="_headerDivider_1s7z6_5336",Nb="_groupByContainer_1s7z6_5342",Ib="_groupByLabel_1s7z6_5350",Ab="_groupBySelect_1s7z6_5355",Db="_viewSwitcher_1s7z6_5360",Bb="_standaloneContent_1s7z6_5368",Pb="_taxonomyFieldsGrid_1s7z6_5374",zb="_markdownPreviewContainer_1s7z6_5380",Lb="_selectWithIcon_1s7z6_5385",Rb="_marginBottom16_1s7z6_5389",Eb="_headerDraggable_1s7z6_5394",Mb="_headerDragging_1s7z6_5398",$b="_browserItemCurrent_1s7z6_5405",Fb="_browserItemFile_1s7z6_5411",Ob="_browserEmpty_1s7z6_5415",Wb="_filterSelectSort_1s7z6_5421",Ub="_archiveRow_1s7z6_5425",Hb="_taxonomiesList_1s7z6_5431",Gb="_widgetOverlay_1s7z6_5436",qb="_widgetModal_1s7z6_5440",Vb="_headerTitleWidget_1s7z6_5444",Kb="_overlayHighZ_1s7z6_5453",Jb="_savedText_1s7z6_5463",Yb="_shortcutInput_1s7z6_2128",Xb="_saveSettingsBtnWrapper_1s7z6_5471",Qb="_marginBottom12_1s7z6_5475",Zb="_exportRowGrid_1s7z6_5479",ew="_settingSubtitleCustom_1s7z6_5484",tw="_capitalize_1s7z6_5490",sw="_marginTop12_1s7z6_5494",aw="_marginTop16_1s7z6_5498",nw="_labelGroupFlex_1s7z6_5502",ow="_codeBlockWrapperCustom_1s7z6_5508",rw="_kanbanWrapper_1s7z6_5514",iw="_kanbanContainer_1s7z6_5522",cw="_kanbanTopScroll_1s7z6_5544",lw="_kanbanTopScrollSpacer_1s7z6_5575",dw="_kanbanColumn_1s7z6_5579",uw="_kanbanColumnSticky_1s7z6_5594",pw="_kanbanColumnCollapsed_1s7z6_5600",hw="_kanbanColumnPast_1s7z6_5605",mw="_kanbanColumnSelectedDay_1s7z6_5610",fw="_kanbanHeader_1s7z6_5617",gw="_kanbanCount_1s7z6_5627",yw="_kanbanHeaderDraggable_1s7z6_5647",kw="_kanbanHeaderPanning_1s7z6_5651",xw="_kanbanQuickAdd_1s7z6_5655",vw="_kanbanColorDot_1s7z6_5676",bw="_kanbanDroppable_1s7z6_5688",ww="_kanbanDroppableScroll_1s7z6_5697",Sw="_kanbanEmpty_1s7z6_5709",Cw="_kanbanCard_1s7z6_1372",_w="_kanbanCardWrapperRaised_1s7z6_5744",jw="_kanbanCardTitle_1s7z6_5748",Tw="_kanbanBadges_1s7z6_5752",Nw="_kanbanBadge_1s7z6_5752",Iw="_headerFlex_1s7z6_5768",Aw="_marginBottom8_1s7z6_5775",Dw="_marginBottom20_1s7z6_5779",Bw="_configPanel_1s7z6_5783",Pw="_configPanelLarge_1s7z6_5792",zw="_categoryManagerContainer_1s7z6_5796",Lw="_subLabelBlock_1s7z6_5804",Rw="_subLabelBlock12_1s7z6_5811",Ew="_flexBetween_1s7z6_5815",Mw="_flexBetweenCenter_1s7z6_5822",$w="_deleteBtnSmall_1s7z6_5827",Fw="_deleteBtnMedium_1s7z6_5833",Ow="_trashIcon_1s7z6_5840",Ww="_gridConfig_1s7z6_5844",Uw="_flexColGap4_1s7z6_5851",Hw="_flexColGap4Center_1s7z6_5857",Gw="_flex1_1s7z6_5864",qw="_flexCol_1s7z6_5851",Vw="_flexGrow1_1s7z6_5874",Kw="_inputLabel_1s7z6_5878",Jw="_inputLabelBlock_1s7z6_5882",Yw="_checkboxInput_1s7z6_5888",Xw="_configDividerMargin_1s7z6_5894",Qw="_configDividerMargin24_1s7z6_5899",Zw="_pathListMargin_1s7z6_5904",eS="_pathInputGroupStretch_1s7z6_5908",tS="_cancelBtnRed_1s7z6_5912",sS="_emptyStateItalic_1s7z6_5917",aS="_emptyStateBox_1s7z6_5933",nS="_emptyStateIcon_1s7z6_5949",oS="_createDialogOverlay_1s7z6_5955",rS="_taxonomyGrid_1s7z6_5963",iS="_checkboxRow_1s7z6_5969",cS="_checkboxLabel_1s7z6_5975",lS="_checkboxSmall_1s7z6_5983",dS="_flexGap8_1s7z6_5988",uS="_systemIcon_1s7z6_6099",pS="_chevron_1s7z6_6103",hS="_inputGroup_1s7z6_6141",mS="_taxonomyBreadcrumbs_1s7z6_6196",fS="_breadcrumbPrev_1s7z6_6202",gS="_breadcrumbDivider_1s7z6_6223",yS="_breadcrumbActive_1s7z6_6228",kS="_taxonomyDropdown_1s7z6_6250",xS="_taxonomyDropdownButton_1s7z6_6255",vS="_taxonomyDropdownOpen_1s7z6_6290",bS="_taxonomyDropdownButtonContent_1s7z6_6296",wS="_taxonomyDropdownIcon_1s7z6_6304",SS="_taxonomyDropdownLabel_1s7z6_6312",CS="_taxonomyDropdownChevron_1s7z6_6321",_S="_taxonomyDropdownChevronOpen_1s7z6_6327",jS="_taxonomyDropdownPanel_1s7z6_6331",TS="_dropdownSlideIn_1s7z6_1",NS="_taxonomyDropdownOption_1s7z6_6361",IS="_taxonomyDropdownOptionHighlighted_1s7z6_6389",AS="_taxonomyDropdownOptionSelected_1s7z6_6395",DS="_zenModeEnabled_1s7z6_6407",BS="_code_1s7z6_2774",PS="_workflowList_1s7z6_6442",zS="_workflowActions_1s7z6_6450",LS="_textBtn_1s7z6_6459",RS="_workflowGrid_1s7z6_6473",ES="_docWorkspace_1s7z6_6503",MS="_docIndexPanel_1s7z6_6512",$S="_docIndex_1s7z6_6512",FS="_docIndexHeader_1s7z6_6531",OS="_docIndexTitle_1s7z6_6540",WS="_docIndexRefreshBtn_1s7z6_6549",US="_docSpinning_1s7z6_6571",HS="_docSpin_1s7z6_6571",GS="_docIndexSearch_1s7z6_6581",qS="_docIndexSearchIcon_1s7z6_6587",VS="_docIndexSearchInput_1s7z6_6596",KS="_docIndexFilters_1s7z6_6613",JS="_docIndexFilterBtn_1s7z6_6621",YS="_docIndexFilterBtnActive_1s7z6_6638",XS="_docIndexList_1s7z6_6644",QS="_docIndexState_1s7z6_6653",ZS="_docIndexStateError_1s7z6_6661",eC="_docIndexItem_1s7z6_6668",tC="_docIndexItemActive_1s7z6_6687",sC="_docIndexItemIcon_1s7z6_6695",aC="_docIndexItemBody_1s7z6_6705",nC="_docIndexItemTitle_1s7z6_6712",oC="_docIndexItemTask_1s7z6_6722",rC="_docIndexItemMeta_1s7z6_6730",iC="_docViewerPanel_1s7z6_6736",cC="_docViewerEmpty_1s7z6_6744",lC="_docViewer_1s7z6_6736",dC="_docMeta_1s7z6_6762",uC="_docMetaLeft_1s7z6_6774",pC="_docTypeBadge_1s7z6_6781",hC="_docTypeBadge_implementation_plan_1s7z6_6796",mC="_docTypeBadge_review_1s7z6_6802",fC="_docTypeBadge_walkthrough_1s7z6_6808",gC="_docMetaTaskName_1s7z6_6814",yC="_docMetaDate_1s7z6_6823",kC="_docMetaSize_1s7z6_6831",xC="_docActions_1s7z6_6839",vC="_docActionBtn_1s7z6_6846",bC="_docViewerTitleRow_1s7z6_6868",wC="_docViewerTitle_1s7z6_6868",SC="_docViewerContent_1s7z6_6882",CC="_docViewerState_1s7z6_6891",_C="_docViewerStateError_1s7z6_6898",jC="_docMarkdown_1s7z6_6906",TC="_docViewerMonochrome_1s7z6_7049",NC="_docPreviewPane_1s7z6_7054",IC="_docViewerEditMode_1s7z6_7122",AC="_docEditBtn_1s7z6_7126",DC="_docSaveBtn_1s7z6_7137",BC="_docLayoutToggle_1s7z6_7153",PC="_docLayoutBtn_1s7z6_7161",zC="_docLayoutBtnActive_1s7z6_7177",LC="_docSaveStatus_1s7z6_7182",RC="_docUnsaved_1s7z6_7198",EC="_docEditorArea_1s7z6_7204",MC="_docEditorPane_1s7z6_7211",$C="_docEditorLayout_split_1s7z6_7219",FC="_docEditorLayout_editor_1s7z6_7224",OC="_docEditorLayout_preview_1s7z6_7225",WC="_docEditorPaneLabel_1s7z6_7229",UC="_docEditorTextarea_1s7z6_7241",HC="_docGenerateBtn_1s7z6_7286",GC="_genModalOverlay_1s7z6_7297",qC="_genModal_1s7z6_7297",VC="_genModalHeader_1s7z6_7320",KC="_genModalTitle_1s7z6_7329",JC="_genModalDocName_1s7z6_7339",YC="_genModalClose_1s7z6_7350",XC="_genModalBody_1s7z6_7368",QC="_genModalState_1s7z6_7376",ZC="_genModalStateError_1s7z6_7390",e_="_genModalStateDone_1s7z6_7403",t_="_genToolbar_1s7z6_7428",s_="_genToolbarCount_1s7z6_7438",a_="_genToolbarBtn_1s7z6_7444",n_="_genTaskTree_1s7z6_7462",o_="_genTaskRow_1s7z6_7470",r_="_genTaskRowDimmed_1s7z6_7483",i_="_genTaskCheck_1s7z6_7487",c_="_genTaskExpandBtn_1s7z6_7496",l_="_genTaskExpandSpacer_1s7z6_7510",d_="_genTaskTitle_1s7z6_7515",u_="_genTaskBadge_1s7z6_7524",p_="_genModalFooter_1s7z6_7535",h_="_genCancelBtn_1s7z6_7545",m_="_genCommitBtn_1s7z6_7563",t={filterGlow:lh,standaloneWrapper:dh,standalonePage:uh,floatingButton:ph,badge:hh,configBadge:mh,header:fh,headerTitle:gh,brandIcon:yh,projectSlash:kh,projectName:xh,taskCountBadge:vh,authBlockedBanner:bh,loginView:wh,loginCard:Sh,loginCloseBtn:Ch,loginLogo:_h,authBrandRow:jh,loginBrandRow:Th,loginTitle:Nh,loginTitleAccent:Ih,loginSubtitle:Ah,loginError:Dh,authModeSwitch:Bh,authModeSwitchLink:Ph,authModeLinks:zh,authModeLink:Lh,authModeLinkActive:Rh,headerSuccess:Eh,fadeInSlideDown:Mh,headerActions:$h,accountMenuWrap:Fh,headerActionBtn:Oh,headerActionBtnActive:Wh,avatarBtn:Uh,avatarBadge:Hh,accountMenu:Gh,accountMenuItem:qh,accountMenuItemActive:Vh,accountMenuSection:Kh,accountMenuSectionLabel:Jh,accountMenuMeta:Yh,accountMenuHint:Xh,accountIdentityEmail:Qh,accountMenuWorkspaceForm:Zh,input:em,primaryUpdateBtn:tm,accountMenuError:sm,accountHubCard:am,syncStatusModal:nm,syncStatusTop:om,syncStatusHeading:rm,syncStatusSubtext:im,syncStatusPausedHint:cm,syncStatusBadge:lm,syncStatusGrid:dm,syncStatusItem:um,syncStatusLabel:pm,syncStatusValue:hm,syncStatusDiagnostics:mm,syncStatusDetailsToggle:fm,syncStatusTableWrap:gm,syncStatusDetailsGrid:ym,syncStatusTable:km,syncStatusTableNarrowLabel:xm,syncStatusTableError:vm,syncStatusActions:bm,sortDirectionBtn:wm,sortDirectionBtnWidget:Sm,form:Cm,topRow:_m,field:jm,labelRow:Tm,label:Nm,manageLink:Im,select:Am,textarea:Dm,markdownPreview:Bm,taskIdInlineLink:Pm,readOnly:zm,selectWithConfig:Lm,configBtn:Rm,configBtnActive:Em,hasPath:Mm,pathIndicator:$m,formActions:Fm,hasCancel:Om,submitBtn:Wm,cancelBtn:Um,successMessage:Hm,successIcon:Gm,error:qm,keyboardHint:Vm,spinner:Km,spin:Jm,destructiveBtn:Ym,warningBtn:Xm,cancelTaskConfirmBtn:Qm,cancelTaskDeleteBtn:Zm,viewTab:ef,deleteBtn:tf,loading:sf,emptyState:af,taskList:nf,taskItem:of,compressed:rf,taskHeader:cf,taskMeta:lf,taskTitle:df,taskItemRecentlyChanged:uf,taskGlowFade:pf,taskItemGlowPersistent:hf,taskItemLinkedFeedback:mf,taskLinkGlowPulse:ff,taskLinkFeedbackPill:gf,taskLinkPillOut:yf,inProgress:kf,taskContent:xf,taskIdBadge:vf,kanbanCardWrapper:bf,taskIdText:wf,kanbanCardOverlay:Sf,taskIdBadgeStatic:Cf,copiedId:_f,highlight:jf,modal:Tf,priorityEmoji:Nf,metaItem:If,taskFormLifecycle:Af,taskFormDateStack:Df,taskFormDateRow:Bf,taskFormDateLabel:Pf,taskFormDateValue:zf,taskFormDateInput:Lf,metaBadge:Rf,complexityPill:Ef,complexityDots:Mf,dot:$f,dotFilled:Ff,typePill:Of,type_bug:Wf,type_feature:Uf,type_chore:Hf,type_refactor:Gf,type_documentation:qf,type_research:Vf,"type_ui-ux":"_type_ui-ux_1s7z6_1576",type_security:Kf,approachPill:Jf,approach_evaluate:Yf,approach_collaborate:Xf,approach_plan:Qf,approachActive:Zf,taskActions:eg,actionBtn:tg,startWorkBtn:sg,workingBtn:ag,pulse:ng,reviewBtn:og,reviewActiveBtn:rg,reviewPill:ig,readyForReview:cg,completed:lg,cancelled:dg,archiveTaskBtn:ug,bulkArchiveBtn:pg,completeBtn:hg,completeActiveBtn:mg,deleteActiveBtn:fg,disabledBtn:gg,archiveList:yg,archiveHeader:kg,archived:xg,settingsTab:vg,settingsTabs:bg,appScrollbar:wg,settingsTabBtn:Sg,settingsTabBtnActive:Cg,settingsContent:_g,settingsToast:jg,settingsToastSuccess:Tg,settingsToastError:Ng,inputWithPrefix:Ig,pathHint:Ag,settingGroup:Dg,settingTitle:Bg,settingTitleRow:Pg,settingTitleActionBtn:zg,themeOptions:Lg,buttonGrid:Rg,themeBtn:Eg,activeTheme:Mg,pathInputGroup:$g,saveSettingsBtn:Fg,shortcutInputWrapper:Og,inputIcon:Wg,settingHelper:Ug,browseBtn:Hg,folderBrowserOverlay:Gg,folderBrowser:qg,fadeIn:Vg,browserHeader:Kg,browserPathInfo:Jg,browserActions:Yg,browserList:Xg,browserItem:Qg,folderItem:Zg,noFolders:ey,selectFolderBtn:ty,inlineCategoryManager:sy,categoryManager:ay,categoryList:ny,categoryChip:oy,categoryChipLabel:ry,chipActionBtn:iy,removeCategoryBtn:cy,addCategoryForm:ly,addCategoryBtn:dy,filesList:uy,tabs:py,tab:hy,archiveBtn:my,closeBtn:fy,settingsLabel:gy,settingsHint:yy,settingsNote:ky,active:xy,helpLink:vy,markdownHelp:by,helpHeader:wy,helpClose:Sy,helpGrid:Cy,taskDescription:_y,inlineCode:jy,codeBlock:Ty,taskLatestComment:Ny,taskCancellationReason:Iy,taskChildrenList:Ay,taskChildrenItems:Dy,taskChildrenItemsScrollable:By,taskChildrenToggleBtn:Py,taskChildrenCountBadge:zy,taskChildrenSummaryBadges:Ly,taskChildrenMetaRow:Ry,taskChildrenProgressBar:Ey,taskChildrenProgressBarFill:My,taskChildrenProgressText:$y,taskParentIdBtn:Fy,taskParentTitle:Oy,taskParentCompact:Wy,taskChildMiniTask:Uy,taskParentMiniTask:Hy,taskChildMiniTaskArchived:Gy,childTaskIdButton:qy,taskChildMiniRow:Vy,taskChildMiniTitle:Ky,taskChildUnlinkBtn:Jy,aboutText:Yy,versionInfo:Xy,filterBar:Qy,kanbanHintText:Zy,searchContainer:ek,searchIcon:tk,searchInput:sk,searchActive:ak,searchCount:nk,clearSearchBtn:ok,filterRow:rk,sortLabel:ik,archiveToggle:ck,filterContainer:lk,filterButton:dk,filterActive:uk,filterDropdown:pk,filterOption:hk,filterDivider:mk,filterSelect:fk,filterToggleBtn:gk,inProgressToggle:yk,activeInProgress:kk,activeFilter:xk,resetFiltersBtn:vk,categoryChip_disabled:bk,categoryVisibilityToggle:wk,editCategoryInput:Sk,categoryChipActionBtn:Ck,categoryChipActionBtn_active:_k,categoryGroup:jk,categoryHeader:Tk,categoryTitle:Nk,categoryCount:Ik,categoryItems:Ak,priorityItem_low:Dk,priorityItem_medium:Bk,priorityItem_high:Pk,priorityItem_critical:zk,"critical-border-pulse":"_critical-border-pulse_1s7z6_1",priorityPill_low:Lk,priorityPill_medium:Rk,priorityPill_high:Ek,priorityPill_critical:Mk,"critical-glow":"_critical-glow_1s7z6_1",selectPriority_low:$k,selectPriority_medium:Fk,selectPriority_high:Ok,selectPriority_critical:Wk,levelSelect:Uk,levelOption:Hk,levelOptionFilled:Gk,levelOption_priority_low:qk,levelOption_priority_medium:Vk,levelOption_priority_high:Kk,levelOption_priority_critical:Jk,levelOption_complexity_tiny:Yk,levelOption_complexity_low:Xk,levelOption_complexity_medium:Qk,levelOption_complexity_high:Zk,levelOption_complexity_epic:ex,levelOptionActive:tx,levelOptionSelected:sx,levelLabel:ax,closeConfigBtn:nx,configItem:ox,pathList:rx,pathChip:ix,pathValid:cx,pathInvalid:lx,pathValidIcon:dx,pathInvalidIcon:ux,pathText:px,removePathBtn:hx,pathCount:mx,specialistSection:fx,toggleHeading:gx,dropdownList:yx,childCardRow:kx,childCardRowDragging:xx,childCardRowDropTarget:vx,childCardRemoveBtn:bx,specialistChip:wx,specialistChipActive:Sx,taskSpecialists:Cx,specialistBadge:_x,iconGrid:jx,iconPickerBtn:Tx,iconPickerBtnActive:Nx,categorySubConfig:Ix,colorPickerRow:Ax,colorPickerGrid:Dx,colorSwatch:Bx,colorSwatchActive:Px,categoryChipIcon:zx,fieldIconWrapper:Lx,fieldIcon:Rx,field_dynamic:Ex,fieldIcon_dynamic:Mx,categoryTitleIcon:$x,editActionsHeader:Fx,editActionsGroup:Ox,archiveBadge:Wx,urlInputGroup:Ux,iconBtn:Hx,stickyActionHeader:Gx,headerSuccessFeedback:qx,slideInUp:Vx,successCheck:Kx,scaleIn:Jx,secondaryHeaderBtn:Yx,commentSection:Xx,commentPanel:Qx,commentThread:Zx,emptyComments:ev,comment:tv,commentAi:sv,commentUser:av,commentHeader:nv,commentAuthor:ov,commentTime:rv,commentText:iv,commentInputArea:cv,commentInput:lv,sendCommentBtn:dv,screenshotThumbnails:uv,screenshotThumbnail:pv,contextDocThumb:hv,contextDocType:mv,screenshotContainer:fv,capturePrompt:gv,previewContainer:yv,previewHeader:kv,screenshotPreview:xv,actions:vv,primaryButton:bv,secondaryButton:wv,iconButton:Sv,screenshotGrid:Cv,screenshotCard:_v,screenshotImageContainer:jv,contextFileLink:Tv,screenshotActions:Nv,screenshotActionBtn:Iv,screenshotCaptionInput:Av,hiddenInput:Dv,contextUploadActions:Bv,contextDropzone:Pv,contextDropzoneActive:zv,contextDropzonePulse:Lv,contextLinkRow:Rv,contextNotice:Ev,brokenImage:Mv,brokenImagePlaceholder:$v,regionOverlay:Fv,selectionBox:Ov,exportRow:Wv,exportItem:Uv,taxonomyDrillDown:Hv,drillDownList:Gv,drillDownSection:qv,drillDownSectionHeader:Vv,drillDownSectionTitle:Kv,drillDownItem:Jv,drillDownItemDimmed:Yv,drillDownItemActive:Xv,drillDownItemInfo:Qv,drillDownItemText:Zv,drillDownItemLabel:eb,drillDownItemSubtext:tb,addTaxonomyBtnSmall:sb,taxonomyDetailView:ab,slideIn:nb,detailHeader:ob,detailTitle:rb,detailContent:ib,createOverlay:cb,createDialog:lb,zoomIn:db,dialogActions:ub,settingsGroup:pb,settingsItem:hb,settingLabelGroup:mb,settingLabel:fb,settingDescription:gb,settingInput:yb,codeBlockWrapper:kb,codeHeader:xb,codeHeaderActions:vb,codeLabel:bb,copyBtn:wb,copyBtnActive:Sb,copyBtnNeutralActive:Cb,standaloneHeader:_b,standaloneTitle:jb,headerDivider:Tb,groupByContainer:Nb,groupByLabel:Ib,groupBySelect:Ab,viewSwitcher:Db,standaloneContent:Bb,taxonomyFieldsGrid:Pb,markdownPreviewContainer:zb,selectWithIcon:Lb,marginBottom16:Rb,headerDraggable:Eb,headerDragging:Mb,browserItemCurrent:$b,browserItemFile:Fb,browserEmpty:Ob,filterSelectSort:Wb,archiveRow:Ub,taxonomiesList:Hb,widgetOverlay:Gb,widgetModal:qb,headerTitleWidget:Vb,overlayHighZ:Kb,savedText:Jb,shortcutInput:Yb,saveSettingsBtnWrapper:Xb,marginBottom12:Qb,exportRowGrid:Zb,settingSubtitleCustom:ew,capitalize:tw,marginTop12:sw,marginTop16:aw,labelGroupFlex:nw,codeBlockWrapperCustom:ow,kanbanWrapper:rw,kanbanContainer:iw,kanbanTopScroll:cw,kanbanTopScrollSpacer:lw,kanbanColumn:dw,kanbanColumnSticky:uw,kanbanColumnCollapsed:pw,kanbanColumnPast:hw,kanbanColumnSelectedDay:mw,kanbanHeader:fw,kanbanCount:gw,kanbanHeaderDraggable:yw,kanbanHeaderPanning:kw,kanbanQuickAdd:xw,kanbanColorDot:vw,kanbanDroppable:bw,kanbanDroppableScroll:ww,kanbanEmpty:Sw,kanbanCard:Cw,kanbanCardWrapperRaised:_w,kanbanCardTitle:jw,kanbanBadges:Tw,kanbanBadge:Nw,headerFlex:Iw,marginBottom8:Aw,marginBottom20:Dw,configPanel:Bw,configPanelLarge:Pw,categoryManagerContainer:zw,subLabelBlock:Lw,subLabelBlock12:Rw,flexBetween:Ew,flexBetweenCenter:Mw,deleteBtnSmall:$w,deleteBtnMedium:Fw,trashIcon:Ow,gridConfig:Ww,flexColGap4:Uw,flexColGap4Center:Hw,flex1:Gw,flexCol:qw,flexGrow1:Vw,inputLabel:Kw,inputLabelBlock:Jw,checkboxInput:Yw,configDividerMargin:Xw,configDividerMargin24:Qw,pathListMargin:Zw,pathInputGroupStretch:eS,cancelBtnRed:tS,emptyStateItalic:sS,emptyStateBox:aS,emptyStateIcon:nS,createDialogOverlay:oS,taxonomyGrid:rS,checkboxRow:iS,checkboxLabel:cS,checkboxSmall:lS,flexGap8:dS,systemIcon:uS,chevron:pS,inputGroup:hS,taxonomyBreadcrumbs:mS,breadcrumbPrev:fS,breadcrumbDivider:gS,breadcrumbActive:yS,taxonomyDropdown:kS,taxonomyDropdownButton:xS,taxonomyDropdownOpen:vS,taxonomyDropdownButtonContent:bS,taxonomyDropdownIcon:wS,taxonomyDropdownLabel:SS,taxonomyDropdownChevron:CS,taxonomyDropdownChevronOpen:_S,taxonomyDropdownPanel:jS,dropdownSlideIn:TS,taxonomyDropdownOption:NS,taxonomyDropdownOptionHighlighted:IS,taxonomyDropdownOptionSelected:AS,zenModeEnabled:DS,code:BS,workflowList:PS,workflowActions:zS,textBtn:LS,workflowGrid:RS,docWorkspace:ES,docIndexPanel:MS,docIndex:$S,docIndexHeader:FS,docIndexTitle:OS,docIndexRefreshBtn:WS,docSpinning:US,docSpin:HS,docIndexSearch:GS,docIndexSearchIcon:qS,docIndexSearchInput:VS,docIndexFilters:KS,docIndexFilterBtn:JS,docIndexFilterBtnActive:YS,docIndexList:XS,docIndexState:QS,docIndexStateError:ZS,docIndexItem:eC,docIndexItemActive:tC,docIndexItemIcon:sC,docIndexItemBody:aC,docIndexItemTitle:nC,docIndexItemTask:oC,docIndexItemMeta:rC,docViewerPanel:iC,docViewerEmpty:cC,docViewer:lC,docMeta:dC,docMetaLeft:uC,docTypeBadge:pC,docTypeBadge_implementation_plan:hC,docTypeBadge_review:mC,docTypeBadge_walkthrough:fC,docMetaTaskName:gC,docMetaDate:yC,docMetaSize:kC,docActions:xC,docActionBtn:vC,docViewerTitleRow:bC,docViewerTitle:wC,docViewerContent:SC,docViewerState:CC,docViewerStateError:_C,docMarkdown:jC,"task-list-item":"_task-list-item_1s7z6_7017","contains-task-list":"_contains-task-list_1s7z6_7027",docViewerMonochrome:TC,docPreviewPane:NC,docViewerEditMode:IC,docEditBtn:AC,docSaveBtn:DC,docLayoutToggle:BC,docLayoutBtn:PC,docLayoutBtnActive:zC,docSaveStatus:LC,docUnsaved:RC,docEditorArea:EC,docEditorPane:MC,docEditorLayout_split:$C,docEditorLayout_editor:FC,docEditorLayout_preview:OC,docEditorPaneLabel:WC,docEditorTextarea:UC,docGenerateBtn:HC,genModalOverlay:GC,genModal:qC,genModalHeader:VC,genModalTitle:KC,genModalDocName:JC,genModalClose:YC,genModalBody:XC,genModalState:QC,genModalStateError:ZC,genModalStateDone:e_,genToolbar:t_,genToolbarCount:s_,genToolbarBtn:a_,genTaskTree:n_,genTaskRow:o_,genTaskRowDimmed:r_,genTaskCheck:i_,genTaskExpandBtn:c_,genTaskExpandSpacer:l_,genTaskTitle:d_,genTaskBadge:u_,genModalFooter:p_,genCancelBtn:h_,genCommitBtn:m_},f_="_overlay_1jsq2_3",g_="_overlayHighZ_1jsq2_16",y_="_modal_1jsq2_21",k_="_draggableModal_1jsq2_65",x_="_header_1jsq2_73",v_="_draggableHeader_1jsq2_87",b_="_headerTitle_1jsq2_95",w_="_headerActions_1jsq2_110",S_="_headerActionBtn_1jsq2_117",C_="_headerActionBtnActive_1jsq2_135",__="_modalContent_1jsq2_142",j_="_form_1jsq2_147",T_="_formActions_1jsq2_158",N_="_modalFooter_1jsq2_165",I_="_modalSizeSm_1jsq2_171",A_="_modalSizeMd_1jsq2_175",D_="_modalSizeLg_1jsq2_179",B_="_modalSizeXl_1jsq2_183",P_="_modalSizeFull_1jsq2_187",z_="_settingsViewModal_1jsq2_192",L_="_unsavedOverlay_1jsq2_200",R_="_unsavedModal_1jsq2_205",E_="_unsavedHeader_1jsq2_211",M_="_unsavedTitle_1jsq2_216",$_="_unsavedContent_1jsq2_220",F_="_unsavedText_1jsq2_224",O_="_unsavedActions_1jsq2_229",be={overlay:f_,overlayHighZ:g_,modal:y_,draggableModal:k_,header:x_,draggableHeader:v_,headerTitle:b_,headerActions:w_,headerActionBtn:S_,headerActionBtnActive:C_,modalContent:__,form:j_,formActions:T_,modalFooter:N_,modalSizeSm:I_,modalSizeMd:A_,modalSizeLg:D_,modalSizeXl:B_,modalSizeFull:P_,settingsViewModal:z_,unsavedOverlay:L_,unsavedModal:R_,unsavedHeader:E_,unsavedTitle:M_,unsavedContent:$_,unsavedText:F_,unsavedActions:O_};function W_(a){const n=a.charAt(0).toUpperCase()+a.slice(1).toLowerCase(),r={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return r[n]?r[n]:`${a}s`}function Qa({label:a,options:n,selected:r,onChange:u,variant:d="label"}){const[m,h]=s.useState(!1),v=s.useRef(null);s.useEffect(()=>{const I=$=>{v.current&&!v.current.contains($.target)&&h(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[]);const x=I=>{r.includes(I)?u(r.filter($=>$!==I)):u([...r,I])},_=n.length>0&&n.every(I=>{const $=d==="label"?I.label:I.value;return r.includes($)}),R=!n.some(I=>{const $=d==="label"?I.label:I.value;return r.includes($)}),j=()=>{u(_?[]:n.map(I=>d==="label"?I.label:I.value))},D=n.filter(I=>{const $=d==="label"?I.label:I.value;return r.includes($)}).length,b=W_(a),f=_?`All ${b}`:R?`No ${b}`:D===1?`1 ${a}`:`${D} ${b}`;return e.jsxs("div",{className:t.filterContainer,ref:v,children:[e.jsxs("button",{className:`${t.filterButton} ${_?"":t.filterActive}`,onClick:()=>h(!m),title:`Filter by ${a}`,children:[e.jsx("span",{children:f}),e.jsx(Bn,{size:14,style:{transform:m?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),m&&e.jsxs("div",{className:`${t.filterDropdown} ${t.appScrollbar}`,children:[e.jsxs("div",{className:t.filterOption,onClick:j,children:[e.jsx("input",{type:"checkbox",checked:_,onChange:()=>{}}),e.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),e.jsx("div",{className:t.filterDivider}),n.map(I=>{const $=d==="label"?I.label:I.value,z=r.includes($);return e.jsxs("div",{className:t.filterOption,onClick:()=>x($),children:[e.jsx("input",{type:"checkbox",checked:z,onChange:()=>{}}),e.jsx("span",{children:I.label})]},I.value)})]})]})}const Md=/^(\s*[-*]\s+\[)( |x|X)(\]\s+)(.*)$/;function El(a){if(!a)return[];const n=a.split(/\r?\n/),r=[];return n.forEach((u,d)=>{const m=u.match(Md);if(!m)return;const h=String(m[4]||"").trim();h&&r.push({lineIndex:d,text:h,completed:String(m[2]).toLowerCase()==="x"})}),r}function U_(a,n){const r=n.trim();if(!r)return a||"";const u=a?a.replace(/\s+$/,""):"";return u?`${u}
2
- - [ ] ${r}`:`- [ ] ${r}`}function H_(a,n){const r=(a||"").split(/\r?\n/);return n<0||n>=r.length?a||"":(r.splice(n,1),r.join(`
3
- `).replace(/\s+$/,""))}function Ql(a,n,r){const u=(a||"").split(/\r?\n/);if(n<0||n>=u.length)return a||"";const m=u[n].match(Md);return m?(u[n]=`${m[1]}${r?"x":" "}${m[3]}${m[4]}`,u.join(`
4
- `)):a||""}const Bl=({children:a,className:n,onChecklistToggle:r,onTaskIdClick:u})=>{if(!a)return null;const d=El(a||"");let m=0;const h=_=>zs.Children.toArray(_).some(j=>zs.isValidElement(j)?String(j.props?.className||"").includes("task-list-item"):!1),v=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,x=_=>{if(!u)return _;if(typeof _=="string"){const D=Array.from(_.matchAll(v));if(!D.length)return _;const b=[];let f=0;for(let I=0;I<D.length;I+=1){const $=D[I],z=$[1],w=$.index??-1;w<f||(w>f&&b.push(_.slice(f,w)),b.push(e.jsx("button",{type:"button",className:t.taskIdInlineLink,onClick:T=>{T.preventDefault(),T.stopPropagation(),u(z)},children:z},`${z}-${w}-${I}`)),f=w+z.length)}return f<_.length&&b.push(_.slice(f)),b}if(Array.isArray(_))return _.map(x);if(!zs.isValidElement(_))return _;const R=typeof _.type=="string"?_.type:"";if(R==="code"||R==="pre"||R==="a")return _;const j=_.props?.children;return j===void 0?_:zs.cloneElement(_,{},zs.Children.map(j,x))};return e.jsx("div",{className:n,children:e.jsx(jl,{remarkPlugins:[Tl,Ou],components:{p:({children:_})=>e.jsx("p",{children:x(_)}),ul:({children:_})=>e.jsx("ul",{style:h(_)?{paddingLeft:0}:void 0,children:_}),li:({children:_,className:R})=>{const j=String(R||"").includes("task-list-item");return e.jsx("li",{className:R,style:j?{listStyle:"none"}:void 0,children:x(_)})},input:({type:_,checked:R})=>{if(_!=="checkbox")return e.jsx("input",{type:_,checked:R,readOnly:!0});const j=d[m];m+=1;const D=!!(r&&j);return e.jsx("input",{type:"checkbox",checked:!!R,readOnly:!D,onClick:b=>{!D||!j||(b.stopPropagation(),r?.(j.lineIndex,!R))},style:{cursor:D?"pointer":"default",marginRight:8}})},code:({children:_,className:R,...j})=>{const D=String(_||"").replace(/\n$/,"");return/language-(\w+)/.test(R||"")||D.includes(`
5
- `)?e.jsx("pre",{className:t.codeBlock,children:e.jsx("code",{className:R,...j,children:D})}):e.jsx("code",{className:t.inlineCode,...j,children:D})}},children:a})})},G_=(a,n=10)=>{const r=ko[a?.toLowerCase()]||{icon:"FileCode"},u=da[r.icon]||au;return e.jsx(u,{size:n})},yc=(a,n)=>{if(!a)return null;if(!n.trim())return a;const r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=a.split(new RegExp(`(${r})`,"gi"));return e.jsx(e.Fragment,{children:u.map((d,m)=>d.toLowerCase()===n.toLowerCase()?e.jsx("mark",{className:t.highlight,children:d},m):d)})};function Dc(a){return a.trim().replace(/\\/g,"/")}function q_(a){return a.split("?")[0].split("#")[0]}function $d(a){if(!a.includes("/api/taskforce/context-link?path="))return null;try{const r=new URL(a,window.location.origin).searchParams.get("path");return r?Dc(r):null}catch{return null}}function V_(a,n){const r=(n||"").trim();if(r)return Dc(r);const u=$d(a);return u?Dc(u):null}function K_(a,n){return[(n||"").trim(),$d(a)||"",a].some(u=>{if(!u)return!1;const d=q_(Dc(u)).toLowerCase();return d.endsWith(".md")||d.endsWith(".markdown")})}function Fd(a,n){const r=V_(a,n);if(!r||!K_(a,r))return!1;const u=new CustomEvent("taskforce:open-markdown-document",{detail:{path:a,fsPath:r},cancelable:!0});return!window.dispatchEvent(u)}const{Copy:xl,Check:kc,Play:J_,Pause:Y_,Sparkles:X_,Ban:Q_,Archive:Z_,MessageSquare:ej,User:Zl,Layers:ed,Bot:tj,Gauge:sj,X:td,ChevronDown:aj,ChevronRight:nj,ClipboardList:oj,HelpCircle:rj}=da,Qo=({task:a,searchQuery:n="",copiedId:r=null,availableSpecialists:u=[],taxonomies:d=[],priorities:m=[],approaches:h=[],categories:v=[],isOverlay:x=!1,isArchived:_=!1,isRecentlyChanged:R=!1,linkedParentIdSet:j,parentDropTargetId:D=null,onClick:b,onCopyId:f,onToggleInProgress:I,onToggleReview:$,onToggleComplete:z,onToggleCancel:w,onArchiveTask:T,onUnarchive:Z,onDelete:Ne,onUnlinkChildTask:J,onClearParentTask:he,onOpenTaskById:ce,showParentRelationship:W=!0,compressed:U=!1,allTasks:Ge=[]})=>{const ye=m.find(N=>String(N.value)===String(a.priority)),ke=ye?ye.label.toLowerCase().replace(/\s+/g,"-"):String(a.priority),Ae=v.find(N=>N.value===a.category||N.label===a.category),se=typeof a.complexity=="number"?a.complexity:Number(a.complexity??3),Ye=Number.isFinite(se)?Math.max(1,Math.min(5,Math.round(se))):3,We={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},Fe={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},te=We[Ye],ne=`var(--complexity-${Fe[Ye]})`,le=dl(a.priority,ke),dt=!!t[`priorityItem_${le}`],ae=!!j?.has(a.id),q=D===a.id,M=[t.taskItem,a.status==="in-progress"?t.inProgress:"",a.status==="review"?t.readyForReview:"",a.status==="done"?t.completed:"",a.status==="cancelled"?t.cancelled:"",R||q?t.taskItemRecentlyChanged:"",q?t.taskItemGlowPersistent:"",t[`priorityItem_${le}`]||"",x?t.kanbanCardOverlay:"",_?t.archived:"",U?t.compressed:""].filter(Boolean).join(" "),Q=ys(ye?.color),de=ko[a.type?.toLowerCase()],xe=ys(de?.color)||"#8b5cf6",B=N=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(N),oe=N=>{const G=typeof N=="string"?N:N.path,je=typeof N=="string"?"":(N.caption||"").trim();return je||G.split("?")[0].split("#")[0].split("/").pop()||"Context file"},et=N=>{const G=typeof N=="string"?N:N.path,je=typeof N=="string"?"":(N.fsPath||"").trim(),Ie=typeof N=="string"?"":(N.caption||"").trim(),we=[];if(je&&we.push(je),Ie&&we.push(Ie),G.includes("/api/taskforce/context-link?path="))try{const vt=new URL(G,"http://localhost").searchParams.get("path");vt&&we.push(vt)}catch{}we.push(G);for(const qe of we){const st=qe.split("?")[0].split("#")[0].split("/").pop()||"",Re=st.lastIndexOf(".");if(Re<=0||Re===st.length-1)continue;const bt=st.slice(Re+1);if(bt)return bt.slice(0,5).toUpperCase()}return"FILE"},yt=N=>{const G=N.toUpperCase();return G==="PDF"?"#ef4444":G==="DOC"||G==="DOCX"?"#3b82f6":G==="CSV"?"#14b8a6":G==="JSON"?"#f59e0b":G==="TXT"||G==="MD"?"#a78bfa":"#64748b"},ut={"--task-change-glow-color":Q||`var(--priority-${le})`,...Q?{borderLeftColor:Q,[`--priority-${le}`]:Q}:{},...!dt&&Q?{borderLeft:`4px solid ${Q}`}:{}},mt=N=>N.replace(/\b\w/g,G=>G.toUpperCase()),kt=zs.useMemo(()=>{const N=new Map;return Ge.forEach(G=>N.set(G.id,G)),N},[Ge]),Dt=zs.useMemo(()=>{const N=[],G=new Set;let je=a.parentTaskId||null;for(;je&&!G.has(je);){G.add(je);const Ie=kt.get(je)||null;N.push({id:je,task:Ie}),je=Ie?.parentTaskId||null}return N},[a.parentTaskId,kt]),Mt=zs.useMemo(()=>[...Dt].reverse(),[Dt]),Zt=Pc(Ge.filter(N=>N.parentTaskId===a.id)),tt=Zt.length,pt=Zt.filter(N=>N.isArchived||N.status==="done"||N.status==="cancelled").length,Rt=tt>0?Math.round(pt/tt*100):0,wt=zs.useMemo(()=>El(a.description||""),[a.description]),Ut=wt.length,V=Ut>0?wt.filter(N=>N.completed).length:0,Pe=tt>0,[_e,Le]=zs.useState(!1),ze=N=>{N.stopPropagation(),Le(G=>!G)};return e.jsxs("div",{className:`${M} ${ae?t.taskItemLinkedFeedback:""}`,onClick:()=>b?.(a),style:ut,children:[ae&&e.jsx("div",{className:t.taskLinkFeedbackPill,children:"Linked as child"}),W&&Dt.length>0&&(U?e.jsxs("div",{className:t.taskParentCompact,title:`Ancestors: ${Mt.map(N=>N.task?.title||N.id).join(" > ")}`,children:[e.jsx(nu,{size:11}),e.jsx("span",{children:`Ancestors: ${Mt.map(N=>N.id.split("-").slice(-1)[0]).join(" > ")}`})]}):Mt.map(N=>{const G=N.task,je=G?m.find(Re=>String(Re.value)===String(G.priority)):null,Ie=je?je.label.toLowerCase().replace(/\s+/g,"-"):String(G?.priority??""),we=G?dl(G.priority,Ie):"",qe=ys(je?.color),vt=!!(we&&t[`priorityItem_${we}`]),st={...qe?{borderLeftColor:qe,[`--priority-${we}`]:qe}:{},...!vt&&qe?{borderLeft:`4px solid ${qe}`}:{}};return e.jsx("div",{className:`${t.taskItem} ${t.compressed} ${t.taskChildMiniTask} ${t.taskParentMiniTask} ${G?.isArchived?t.taskChildMiniTaskArchived:""} ${t[`priorityItem_${we}`]||""}`,style:st,title:G?G.title:`Ancestor: ${N.id}`,onClick:Re=>{Re.stopPropagation(),G?b?.(G):ce?.(N.id)},children:e.jsxs("div",{className:t.taskChildMiniRow,children:[e.jsxs("button",{type:"button",className:`${t.taskIdBadge} ${t.taskParentIdBtn} ${r===N.id?t.copiedId:""}`,onClick:Re=>f?.(Re,N.id),title:"Copy ancestor task ID",children:[r===N.id?e.jsx(kc,{size:13}):e.jsx(xl,{size:13}),e.jsxs("span",{children:["ID",e.jsxs("span",{className:t.taskIdText,children:[": ",N.id.split("-").slice(-1)[0]]})]})]}),e.jsx("div",{className:t.taskParentTitle,children:G?.title||`Ancestor: ${N.id}`}),N.id===(a.parentTaskId||"")&&he&&e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.taskChildUnlinkBtn}`,onClick:Re=>{Re.stopPropagation(),he(a.id)},title:"Unlink parent","aria-label":`Unlink parent for ${a.id}`,children:e.jsx(td,{size:12})})]})},N.id)})),e.jsxs("div",{className:t.taskHeader,children:[e.jsxs("button",{type:"button",className:`${t.taskIdBadge} ${r===a.id?t.copiedId:""} ${_?t.archiveBadge:""}`,onClick:N=>f?.(N,a.id),title:"Click to copy Task ID",children:[r===a.id?e.jsx(kc,{size:13}):e.jsx(xl,{size:13}),e.jsxs("span",{children:["ID",e.jsxs("span",{className:t.taskIdText,children:[": ",yc(a.id.split("-").slice(-1)[0],n)]})]})]}),e.jsx("div",{className:t.taskActions,onClick:N=>N.stopPropagation(),children:_?Z||Ne?e.jsxs(e.Fragment,{children:[Z&&e.jsx("button",{type:"button",className:t.actionBtn,onClick:()=>Z(a.id),title:"Restore",children:e.jsx(zl,{size:16})}),Ne&&e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.deleteBtn}`,onClick:()=>Ne(a.id),title:"Delete Permanently",children:e.jsx(yo,{size:16})})]}):null:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:`${t.actionBtn} ${a.status==="in-progress"?t.workingBtn:t.startWorkBtn}`,style:U?{width:"24px",height:"24px",padding:0}:{},onClick:()=>I?.(a),title:a.status==="in-progress"?"Stop Working":"Start Working",children:a.status==="in-progress"?e.jsx(Y_,{size:U?12:16}):e.jsx(J_,{size:U?12:16})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${a.status==="review"?t.reviewActiveBtn:t.reviewBtn}`,style:U?{width:"24px",height:"24px",padding:0}:{},onClick:()=>$?.(a),title:a.status==="review"?"Unlock & Continue Work":"Ready for Review",children:e.jsx(X_,{size:U?12:16})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${a.status==="done"?t.completeActiveBtn:t.completeBtn}`,style:U?{width:"24px",height:"24px",padding:0}:{},onClick:()=>z?.(a),title:a.status==="done"?"Unmark Complete":"Mark Complete",children:e.jsx(kc,{size:U?12:16})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${a.status==="cancelled"?t.deleteActiveBtn:t.deleteBtn}`,style:U?{width:"24px",height:"24px",padding:0}:{},onClick:()=>w?.(a),title:a.status==="cancelled"?"Unmark Cancelled":"Cancel Task",children:e.jsx(Q_,{size:U?12:16})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.archiveTaskBtn} ${a.status==="done"||a.status==="cancelled"?"":t.disabledBtn}`,style:U?{width:"24px",height:"24px",padding:0}:{},onClick:()=>(a.status==="done"||a.status==="cancelled")&&T?.(a),disabled:!(a.status==="done"||a.status==="cancelled"),title:a.status==="done"||a.status==="cancelled"?"Archive Now":"Complete task to archive",children:e.jsx(Z_,{size:U?12:16})})]})})]}),e.jsxs("div",{className:t.taskContent,children:[_&&e.jsx("div",{className:t.taskMeta,style:{marginBottom:"8px",marginTop:0}}),e.jsxs("div",{children:[e.jsxs("div",{className:t.taskTitle,style:U?{fontSize:"13px",lineHeight:"1.4"}:{},children:[_&&"✓ ",yc(a.title,n)]}),a.description&&!_&&!U&&e.jsx("div",{className:t.taskDescription,children:e.jsx(Bl,{onTaskIdClick:ce,children:a.description})})]}),(a.attachments||a.screenshots)&&(a.attachments||a.screenshots).length>0&&!_&&!U&&e.jsx("div",{className:t.screenshotThumbnails,children:(a.attachments||a.screenshots||[]).map((N,G)=>{const je=typeof N=="string"?N:N.path,Ie=typeof N=="string"?void 0:N.fsPath,we=oe(N);if(!B(je)){const qe=et(N);return e.jsx("button",{type:"button",className:t.contextDocThumb,onClick:vt=>{vt.stopPropagation(),!Fd(je,Ie)&&window.open(je,"_blank")},title:we,style:{"--context-doc-accent":yt(qe)},children:e.jsx("span",{className:t.contextDocType,children:qe})},G)}return e.jsx("div",{className:t.screenshotThumbnail,onClick:qe=>{qe.stopPropagation(),window.open(je,"_blank")},children:e.jsx("img",{src:je,alt:`Screenshot ${G}`})},G)})}),a.status==="cancelled"&&a.canceledReason&&!U&&e.jsxs("div",{className:t.taskCancellationReason,children:[e.jsx("strong",{children:"Cancellation Reason:"})," ",yc(a.canceledReason,n)]}),a.comments&&a.comments.length>0&&!_&&!U&&e.jsxs("div",{className:t.taskLatestComment,children:[e.jsx("strong",{children:"Latest Activity:"})," ",yc(a.comments[a.comments.length-1].text.length>120?a.comments[a.comments.length-1].text.substring(0,120)+"...":a.comments[a.comments.length-1].text,n)]}),a.specialists&&a.specialists.length>0&&!_&&!U&&e.jsx("div",{className:t.taskSpecialists,children:a.specialists.map(N=>{const G=u.find(je=>je.value===N);return e.jsxs("span",{className:t.specialistBadge,title:G?.label||N,children:[e.jsx(Zl,{size:10}),G?.label||N]},N)})}),!_&&d.length>0&&!U&&e.jsx("div",{className:`${t.taskSpecialists} ${t.taxonomiesList}`,children:d.map(N=>{const G=a.taxonomies?.[N.id];return G?(Array.isArray(G)?G:[G]).map(Ie=>{const we=N.options.find(st=>st.value===Ie);if(!we)return null;const qe=da[we.icon||"Layer"]||ed,vt=ys(we.color)||"var(--text-primary)";return e.jsx("span",{className:t.specialistBadge,style:{borderColor:`${vt}50`,backgroundColor:`${vt}15`,color:vt},title:mt(we.label),children:e.jsx(qe,{size:10})},`${N.id}-${Ie}`)}):null})}),Pe&&(U?e.jsxs("div",{className:t.taskChildrenSummaryBadges,children:[e.jsxs("div",{className:t.taskChildrenCountBadge,title:`${tt} child tasks`,children:[e.jsx(ed,{size:12}),e.jsx("span",{children:`Child Tasks: ${tt}`})]}),e.jsx("div",{className:t.taskChildrenProgressBar,title:`${pt} of ${tt} child tasks are done/cancelled (${Rt}%)`,children:e.jsx("div",{className:t.taskChildrenProgressBarFill,style:{width:`${Rt}%`}})}),e.jsx("div",{className:t.taskChildrenProgressText,children:`${pt}/${tt} • ${Rt}%`})]}):e.jsxs("div",{className:t.taskChildrenList,children:[e.jsxs("div",{className:t.taskChildrenSummaryBadges,children:[e.jsx("div",{className:t.taskChildrenProgressBar,title:`${pt} of ${tt} child tasks are done/cancelled (${Rt}%)`,children:e.jsx("div",{className:t.taskChildrenProgressBarFill,style:{width:`${Rt}%`}})}),e.jsxs("div",{className:t.taskChildrenMetaRow,children:[e.jsxs("button",{type:"button",className:t.taskChildrenToggleBtn,onClick:ze,title:_e?"Hide child tasks":"Show child tasks",children:[_e?e.jsx(aj,{size:12}):e.jsx(nj,{size:12}),e.jsx("span",{children:`Child Tasks: ${tt}`})]}),e.jsx("div",{className:t.taskChildrenProgressText,children:`${pt}/${tt} • ${Rt}%`})]})]}),_e&&e.jsx("div",{className:`${t.taskChildrenItems} ${tt>5?t.taskChildrenItemsScrollable:""}`,children:Zt.map(N=>{const G=m.find(st=>String(st.value)===String(N.priority)),je=G?G.label.toLowerCase().replace(/\s+/g,"-"):String(N.priority),Ie=dl(N.priority,je),we=ys(G?.color),qe=!!t[`priorityItem_${Ie}`],vt={...we?{borderLeftColor:we,[`--priority-${Ie}`]:we}:{},...!qe&&we?{borderLeft:`4px solid ${we}`}:{}};return e.jsx("div",{className:`${t.taskItem} ${t.compressed} ${t.taskChildMiniTask} ${N.isArchived?t.taskChildMiniTaskArchived:""} ${t[`priorityItem_${Ie}`]||""}`,style:vt,onClick:st=>{st.stopPropagation(),b?.(N)},children:e.jsxs("div",{className:t.taskChildMiniRow,children:[e.jsxs("button",{type:"button",className:`${t.taskIdBadge} ${t.childTaskIdButton} ${r===N.id?t.copiedId:""}`,onClick:st=>{st.stopPropagation(),f?.(st,N.id)},title:"Click to copy Child Task ID",children:[r===N.id?e.jsx(kc,{size:13}):e.jsx(xl,{size:13}),e.jsxs("span",{children:["ID",e.jsxs("span",{className:t.taskIdText,children:[": ",N.id.split("-").slice(-1)[0]]})]})]}),e.jsx("div",{className:t.taskChildMiniTitle,title:N.title,children:N.title}),J&&e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.taskChildUnlinkBtn}`,onClick:st=>{st.stopPropagation(),J(N.id)},title:"Unlink child","aria-label":`Remove child ${N.id}`,children:e.jsx(td,{size:12})})]})},N.id)})})]})),e.jsx("div",{className:t.taskMeta,children:_?e.jsx("span",{children:a.category}):e.jsx(e.Fragment,{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",marginBottom:U?"0px":"4px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[(()=>{const N=ys(Ae?.color),G=Ae?.icon||"Folder",je=da[G]||ho;return e.jsx("span",{className:t.metaBadge,title:mt(a.category),style:{color:N||"var(--text-secondary)",backgroundColor:N?`${N}15`:"var(--bg-tertiary)",borderColor:N?`${N}40`:"transparent"},children:e.jsx(je,{size:14})})})(),e.jsx("span",{className:`${t.metaBadge} ${t[`type_${a.type}`]||""}`,title:mt(a.type||"feature"),style:{color:`var(--type-color, ${xe})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${xe}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${xe}), transparent 75%)`},children:G_(a.type,14)}),(()=>{const N=h.find(we=>we.value===a.approach),G=ys(N?.color),je=N?.icon||"HelpCircle",Ie=da[je]||po;return e.jsx("span",{className:`${t.metaBadge} ${t[`approach_${a.approach||"default"}`]||""}`,title:mt(a.approach||"Default"),style:{color:G||"var(--text-muted)",backgroundColor:G?`${G}15`:"var(--bg-tertiary)",borderColor:G?`${G}40`:"var(--border-primary)"},children:e.jsx(Ie,{size:14})})})(),ye&&e.jsx("span",{className:t.metaBadge,style:{color:Q||"var(--text-secondary)",backgroundColor:Q?`${Q}15`:"var(--bg-tertiary)",borderColor:Q?`${Q}40`:"var(--border-color)"},title:`${ye.label}`,children:(()=>{const N=ye.icon||"AlertCircle",G=da[N]||Ll;return e.jsx(G,{size:14})})()}),a.comments&&a.comments.length>0&&e.jsxs("span",{className:t.metaBadge,title:`${a.comments.length} comments`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[e.jsx(ej,{size:14}),e.jsx("span",{children:a.comments.length})]}),Ut>0&&e.jsxs("span",{className:t.metaBadge,title:`${V}/${Ut} checklist items complete`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[e.jsx(oj,{size:14}),e.jsx("span",{children:`${V}/${Ut}`})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[e.jsxs("span",{className:t.metaBadge,title:`AI-estimated complexity: ${te} (${Ye}/5)`,style:{color:ne,backgroundColor:`color-mix(in srgb, ${ne}, transparent 88%)`,borderColor:`color-mix(in srgb, ${ne}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[e.jsx(sj,{size:14}),!U&&e.jsx("span",{children:te})]}),e.jsx("span",{className:t.metaBadge,title:a.assignee==="agent"?"Assigned to: AI":a.assignee==="user"?"Assigned to: User":"Assigned to: Unassigned","aria-label":a.assignee==="agent"?"Assigned to AI":a.assignee==="user"?"Assigned to User":"Unassigned",style:{backgroundColor:a.assignee==="agent"?"color-mix(in srgb, var(--color-violet-500, #8b5cf6), transparent 88%)":a.assignee==="user"?"color-mix(in srgb, var(--color-green-500, #22c55e), transparent 88%)":"color-mix(in srgb, var(--text-secondary, #888), transparent 88%)",padding:"0 8px",color:a.assignee==="agent"?"var(--color-violet-500, #8b5cf6)":a.assignee==="user"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",borderColor:a.assignee==="agent"?"color-mix(in srgb, var(--color-violet-500, #8b5cf6), transparent 72%)":a.assignee==="user"?"color-mix(in srgb, var(--color-green-500, #22c55e), transparent 72%)":"color-mix(in srgb, var(--text-secondary, #888), transparent 70%)",display:"flex",alignItems:"center"},children:a.assignee==="agent"?e.jsx(tj,{size:U?14:16}):a.assignee==="user"?e.jsx(Zl,{size:U?14:16}):e.jsx(rj,{size:U?14:16})})]})]})})})]})]})},{Search:sd,ClipboardList:ij,ChevronRight:cj,ChevronDown:lj,Folder:dj,Archive:uj,RotateCcw:pj,X:hj,Plus:mj,ArrowUpDown:fj}=da,Od=s.forwardRef((a,n)=>{const{tasks:r,archivedTasks:u,categories:d,types:m,priorities:h,approaches:v,availableSpecialists:x,searchQuery:_,filterCategories:R,filterTypes:j,filterPriorities:D,filterStatus:b,filterAssignees:f=["agent","user","unassigned"],filterTaxonomies:I,sortBy:$,sortOrder:z,showArchive:w,parentTaskFilterMode:T="all",assigneeFilterEnabled:Z=!1,collapsedCategories:Ne,loadingTasks:J,filteredTasks:he,filteredArchive:ce,groupedTasks:W,copiedId:U,recentlyChangedTaskIds:Ge=[],onSearchChange:ye,onFilterCategoriesChange:ke,onFilterTypesChange:Ae,onFilterPrioritiesChange:se,onFilterStatusChange:Ye,onFilterAssigneesChange:We,onTaxonomyFilterChange:Fe,onSortByChange:te,onSortOrderChange:ne,onShowArchiveChange:le,onParentTaskFilterModeChange:dt,onClearFilters:ae,onToggleCategory:q,onEditTask:M,onOpenTaskById:Q,onCopyId:de,onToggleInProgress:xe,onToggleReview:B,onToggleComplete:oe,onToggleCancel:et,onArchiveTask:yt,onBulkArchive:ut,onUnarchive:mt,onDelete:kt,onUnlinkChildTask:Dt,onClearParentTask:Mt,onFetchArchive:Zt,onAddTaskToCategory:tt,taxonomies:pt}=a,Rt=new Set(Ge),wt=[...r,...u],Ut=d.filter(V=>!V.disabled);return e.jsxs("div",{className:t.viewTab,ref:n,children:[e.jsxs("div",{className:t.filterBar,children:[e.jsxs("div",{className:t.searchContainer,children:[e.jsx(sd,{size:16,className:t.searchIcon}),e.jsx("input",{type:"text",className:t.searchInput,placeholder:E("taskList.searchPlaceholder"),value:_,onChange:V=>ye(V.target.value)}),_&&e.jsx("button",{className:t.clearSearchBtn,onClick:()=>ye(""),title:E("taskList.clearSearchTitle"),children:e.jsx(hj,{size:14})})]}),e.jsxs("div",{className:t.filterRow,children:[e.jsx(Qa,{label:E("taskList.categoryLabel"),options:Ut.map(V=>({value:V.value,label:V.label})),selected:R,onChange:ke}),e.jsx(Qa,{label:E("taskList.typeLabel"),options:m,selected:j,onChange:Ae,variant:"value"})]}),e.jsxs("div",{className:t.filterRow,children:[e.jsx(Qa,{label:E("taskList.priorityLabel"),options:h,selected:D,onChange:se,variant:"value"}),e.jsx(Qa,{label:E("taskList.statusLabel"),options:ji,selected:b,onChange:Ye,variant:"value"}),Z&&e.jsx(Qa,{label:E("taskList.assigneeLabel"),options:[{value:"agent",label:"AI"},{value:"user",label:"User"},{value:"unassigned",label:"Unassigned"}],selected:f,onChange:V=>We?.(V),variant:"value"})]}),pt.map(V=>e.jsx(Qa,{label:V.label,options:V.options,selected:I[V.id]||[],onChange:Pe=>Fe(V.id,Pe),variant:"value"},V.id)),e.jsxs("div",{className:t.filterRow,children:[e.jsxs("div",{className:t.sortLabel,children:[e.jsx(fj,{size:14,style:{marginRight:"4px"}})," ",E("taskList.sortByLabel")]}),e.jsxs("select",{value:$,onChange:V=>te(V.target.value),className:`${t.filterSelect} ${t.filterSelectSort} `,children:[e.jsx("option",{value:"created",children:E("taskList.sortCreated")}),e.jsx("option",{value:"updated",children:E("taskList.sortUpdated")}),e.jsx("option",{value:"priority",children:E("taskList.sortPriority")})]}),e.jsx("button",{className:`${t.resetFiltersBtn} ${t.sortDirectionBtnWidget}`,onClick:ne,title:E(z==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:z==="desc"?e.jsx(fd,{size:14}):e.jsx(gd,{size:14})}),e.jsx("button",{className:t.resetFiltersBtn,onClick:ae,title:E("taskList.resetFiltersTitle"),children:e.jsx(pj,{size:14})})]}),e.jsxs("div",{className:`${t.filterRow} ${t.archiveRow} `,children:[e.jsxs("button",{className:`${t.bulkArchiveBtn} ${r.some(V=>V.status==="done"||V.status==="cancelled")?"":t.disabledBtn} `,onClick:()=>r.some(V=>V.status==="done"||V.status==="cancelled")&&ut(),disabled:!r.some(V=>V.status==="done"||V.status==="cancelled"),title:r.some(V=>V.status==="done"||V.status==="cancelled")?E("taskList.archiveAllTitle"):E("taskList.noTasksToArchiveTitle"),children:[e.jsx(uj,{size:12}),e.jsx("span",{children:E("taskList.archiveFinished")})]}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("span",{children:E("taskList.linksLabel")}),e.jsxs("select",{className:`${t.filterSelect} ${t.filterSelectSort}`,value:T,onChange:V=>dt?.(V.target.value),children:[e.jsx("option",{value:"all",children:E("taskList.linksAll")}),e.jsx("option",{value:"parents",children:E("taskList.linksParents")}),e.jsx("option",{value:"linked",children:E("taskList.linksLinked")}),e.jsx("option",{value:"unlinked",children:E("taskList.linksUnlinked")})]})]}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("input",{type:"checkbox",checked:w,onChange:V=>{le(V.target.checked),V.target.checked&&Zt()}}),e.jsx("span",{children:E("taskList.includeArchive")})]})]})]}),J&&r.length===0?e.jsx("div",{className:t.loading,children:e.jsx(aa,{size:24,className:t.spinner})}):he.length===0&&!J?e.jsxs("div",{className:t.emptyState,children:[_?e.jsx(sd,{size:48}):e.jsx(ij,{size:48}),e.jsx("p",{children:E(_?"taskList.noMatchingTasks":"taskList.noActiveTasks")})]}):e.jsx("div",{className:t.taskList,style:{opacity:J?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(W).map(([V,Pe])=>{if(Pe.length===0)return null;const _e=Ne[V];return e.jsxs("div",{className:t.categoryGroup,children:[e.jsx("div",{className:t.categoryHeader,onClick:()=>q(V),children:e.jsxs("div",{className:t.categoryTitle,children:[_e?e.jsx(cj,{size:16}):e.jsx(lj,{size:16}),(()=>{const Le=d.find(G=>G.label===V),ze=Le?.icon&&fo[Le.icon]?fo[Le.icon]:dj,N=ys(Le?.color)||"var(--color-purple, #8b5cf6)";return e.jsx(ze,{size:16,className:t.categoryTitleIcon,style:{color:N}})})(),V,e.jsxs("span",{className:t.categoryCount,children:["(",Pe.length,")"]}),tt&&e.jsx("button",{className:t.kanbanQuickAdd,onClick:Le=>{Le.stopPropagation(),tt(V)},title:E("taskList.addTaskToCategoryTitle",{category:V}),style:{marginLeft:"auto"},children:e.jsx(mj,{size:14})})]})}),!_e&&e.jsx("div",{className:t.categoryItems,children:Pe.map(Le=>e.jsx(Qo,{task:Le,allTasks:wt,searchQuery:_,copiedId:U,availableSpecialists:x,taxonomies:pt,priorities:h,approaches:v,onClick:M,onOpenTaskById:Q,onCopyId:de,onToggleInProgress:xe,onToggleReview:B,onToggleComplete:oe,onToggleCancel:et,onArchiveTask:yt,onUnlinkChildTask:Dt,onClearParentTask:Mt,categories:d,isRecentlyChanged:Rt.has(Le.id)},Le.id))})]},V)})}),w&&ce.length>0&&e.jsxs("div",{className:t.archiveList,children:[e.jsx("div",{className:t.archiveHeader,children:"Archived"}),ce.map(V=>e.jsx(Qo,{task:V,searchQuery:_,copiedId:U,isArchived:!0,approaches:v,onClick:M,onCopyId:de,onUnarchive:mt,onDelete:kt,categories:d},V.id))]})]})});Od.displayName="TaskList";function vl({label:a,value:n,options:r,onChange:u,type:d="priority",hideLabel:m=!1}){const h=r.find(v=>String(v.value)===String(n));return e.jsxs("div",{className:t.field,children:[!m&&e.jsxs("div",{className:t.labelRow,children:[e.jsx("label",{className:t.label,children:a}),h&&e.jsx("span",{className:t.levelLabel,style:{color:ys(h.color)||(d==="priority"?`var(--priority-${n})`:d==="complexity"?`var(--complexity-${n})`:"var(--text-secondary)"),backgroundColor:(ys(h.color)?`${ys(h.color)}25`:void 0)||(d==="priority"?`color-mix(in srgb, var(--priority-${n}), transparent 85%)`:d==="complexity"?`color-mix(in srgb, var(--complexity-${n}), transparent 85%)`:"rgba(255,255,255,0.05)")},children:h.label})]}),e.jsx("div",{className:t.levelSelect,children:r.map((v,x)=>{const _=r.findIndex(D=>String(D.value)===String(n)),R=x<=_,j=String(v.value)===String(n);return e.jsx("button",{type:"button",className:`${t.levelOption} ${R?t.levelOptionFilled:""} ${R?t[`levelOption_${d}_${v.value}`]:""} ${j?t.levelOptionSelected:""}`,onClick:()=>u(v.value),title:v.label,style:{opacity:R?1:.15,backgroundColor:R?ys(v.color)||(d==="priority"?`var(--priority-${v.value})`:d==="complexity"?`var(--complexity-${v.value})`:"var(--text-primary)"):void 0,color:R?d==="priority"&&String(v.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:R&&(d==="priority"&&(String(v.value).toLowerCase()==="critical"||v.value===4)||d==="complexity"&&(String(v.value).toLowerCase()==="epic"||v.value===5))?`0 0 12px ${d==="priority"?"rgba(239, 68, 68, 0.6)":"rgba(217, 70, 239, 0.6)"}`:void 0}},String(v.value))})})]})}function Ko({value:a,options:n,onChange:r,placeholder:u="Select...",required:d=!1,disabled:m=!1,className:h="",ariaLabelledBy:v}){const[x,_]=s.useState(!1),[R,j]=s.useState(-1),D=s.useRef(null),b=s.useRef(null),f=n.find(T=>String(T.value)===String(a));s.useEffect(()=>{if(!x)return;const T=Z=>{D.current&&!D.current.contains(Z.target)&&(_(!1),j(-1))};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[x]),s.useEffect(()=>{if(!x)j(-1);else{const T=n.findIndex(Z=>String(Z.value)===String(a));j(T>=0?T:0)}},[x,n,a]);const I=()=>{m||_(!x)},$=T=>{r(T.value),_(!1),b.current?.focus()},z=T=>{if(!m)switch(T.key){case"Enter":case" ":T.preventDefault(),x?R>=0&&$(n[R]):_(!0);break;case"Escape":T.preventDefault(),_(!1),b.current?.focus();break;case"ArrowDown":T.preventDefault(),x?j(Z=>Z<n.length-1?Z+1:0):_(!0);break;case"ArrowUp":T.preventDefault(),x?j(Z=>Z>0?Z-1:n.length-1):_(!0);break;case"Home":T.preventDefault(),x&&j(0);break;case"End":T.preventDefault(),x&&j(n.length-1);break;case"Tab":_(!1);break}},w=T=>{const Z=T.icon&&da[T.icon]?da[T.icon]:po,Ne=T.color?ys(T.color):"var(--text-secondary)";return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.taxonomyDropdownIcon,style:{color:Ne},children:e.jsx(Z,{size:16})}),e.jsx("span",{className:t.taxonomyDropdownLabel,children:T.label})]})};return e.jsxs("div",{ref:D,className:`${t.taxonomyDropdown} ${h}`,children:[e.jsxs("button",{ref:b,type:"button",className:`${t.taxonomyDropdownButton} ${x?t.taxonomyDropdownOpen:""}`,onClick:I,onKeyDown:z,disabled:m,role:"combobox","aria-haspopup":"listbox","aria-expanded":x,"aria-controls":`taxonomy-listbox-${u.replace(/\s+/g,"-")}`,"aria-labelledby":v,style:(()=>{if(!f)return{};const T=f.color,Z=ys(T),Ne=!Z||Z.startsWith("var("),J=Ne?"#8b5cf6":Z,he=Ne?"30":"50",ce=Ne?"05":"10";return{"--field-color":Z||"var(--text-primary)","--field-border":`${J}${he}`,"--field-bg":`${J}${ce}`}})(),children:[e.jsx("span",{className:t.taxonomyDropdownButtonContent,children:f?w(f):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.taxonomyDropdownIcon,children:e.jsx(po,{size:16})}),e.jsx("span",{className:t.taxonomyDropdownLabel,children:u})]})}),e.jsx(Bn,{size:16,className:`${t.taxonomyDropdownChevron} ${x?t.taxonomyDropdownChevronOpen:""}`})]}),x&&e.jsx("div",{id:`taxonomy-listbox-${u.replace(/\s+/g,"-")}`,className:t.taxonomyDropdownPanel,role:"listbox","aria-labelledby":v,children:n.map((T,Z)=>{const Ne=String(T.value)===String(a),J=Z===R;return e.jsx("div",{className:`${t.taxonomyDropdownOption} ${Ne?t.taxonomyDropdownOptionSelected:""} ${J?t.taxonomyDropdownOptionHighlighted:""}`,role:"option","aria-selected":Ne,onClick:()=>$(T),onMouseEnter:()=>j(Z),style:(()=>{const he=T.color,ce=ys(he),W=!ce||ce.startsWith("var("),U=W?"#8b5cf6":ce,Ge=W?"20":"30",ye=W?"05":"10";return{"--option-color":ce||"var(--text-primary)","--option-border":`${U}${Ge}`,"--option-bg":`${U}${ye}`}})(),children:w(T)},String(T.value))})})]})}const ad=new Map;function gj(a){const n=a instanceof Date?a:new Date(a);return Number.isNaN(n.getTime())?null:n}function yj(a,n){const r=Object.entries(n).sort(([u],[d])=>u.localeCompare(d));return JSON.stringify([a,r])}function wi(a,n,r){const u=gj(a);if(!u)return"";const d=r??Ad(),m=yj(d,n);let h=ad.get(m);return h||(h=new Intl.DateTimeFormat(d,n),ad.set(m,h)),h.format(u)}const Wd=[".png",".jpg",".jpeg",".webp",".gif",".pdf",".txt",".md",".csv",".json",".doc",".docx",".html",".js",".ts",".tsx",".css",".py",".java",".go",".rs",".sh"].join(","),kj=new Set(Wd.split(",").map(a=>a.trim().toLowerCase())),xj=10*1024*1024,vj=3500;function bj(a){const n=a.trim().toLowerCase(),r=n.lastIndexOf(".");return r===-1?"":n.slice(r)}function bl(a){if(a.length===0)return"";const n=a.slice(0,3).join(", "),r=a.length-3;return r>0?`${n}, +${r} more`:n}function wj(a){return`${a.name.trim().toLowerCase()}::${a.size}::${a.lastModified}`}function Sj(a){return new Promise((n,r)=>{const u=new FileReader;u.onload=()=>n(String(u.result||"")),u.onerror=()=>r(u.error||new Error("Failed to read file")),u.readAsDataURL(a)})}function Cj(a){return/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(a)}function _j(a){const{taskId:n,contextFiles:r,browsedPath:u,onBrowseLinkPath:d,onAddContextFile:m,onRemoveContextFile:h,onUpdateContextCaption:v}=a,x=s.useRef(null),[_,R]=s.useState(!1),[j,D]=s.useState(null),[b,f]=s.useState(""),[I,$]=s.useState(null),[z,w]=s.useState(null),[T,Z]=s.useState(!1),[Ne,J]=s.useState(!1),[he,ce]=s.useState(0),W=s.useRef(new Set),U=s.useRef(new Set),Ge=ae=>(ae||"").trim(),ye=(ae,q)=>{const M=[],Q=Ge(ae),de=Ge(q);return Q&&M.push(`path:${Q}`),de&&M.push(`fs:${de}`),M},ke=s.useMemo(()=>{const ae=new Set;return r.forEach(q=>{if(typeof q=="string"){ye(q).forEach(M=>ae.add(M));return}ye(q.path,q.fsPath).forEach(M=>ae.add(M))}),ae},[r]);s.useEffect(()=>{W.current=new Set(ke)},[ke]);const Ae=(ae,q)=>q.some(M=>ae.has(M)),se=(ae,q)=>q.forEach(M=>ae.add(M)),Ye=(ae,q=!0,M=W.current)=>{const Q=ae.trim();if(!Q)return"invalid";const de=/^https?:\/\//i.test(Q),xe=de?Q:`/api/taskforce/context-link?path=${encodeURIComponent(Q)}`,B=de?void 0:Q,oe=ye(xe,B);if(Ae(M,oe))return"duplicate";const et=Q.split(/[\\/]/).pop()||Q;return m({path:xe,fsPath:B,caption:et,timestamp:new Date().toISOString()}),se(M,oe),q&&f(""),$(null),"added"};s.useEffect(()=>{if(!u)return;const ae=Ye(u,!0);ae==="duplicate"?w("Link already exists in task context."):ae==="added"&&w(null)},[u]),s.useEffect(()=>{if(!z)return;const ae=window.setTimeout(()=>{w(null)},vj);return()=>window.clearTimeout(ae)},[z]);const We=async ae=>{if(!ae||ae.length===0)return;D(null),w(null);const q=Array.from(ae),M=[],Q=[],de=[],xe=[],B=new Set(U.current);q.forEach(ut=>{const mt=bj(ut.name);if(!kj.has(mt)){M.push(ut.name);return}if(ut.size>xj){Q.push(ut.name);return}const kt=wj(ut);if(B.has(kt)){de.push(ut.name);return}B.add(kt),xe.push({file:ut,fingerprint:kt})});const oe=[];if(M.length>0&&oe.push(`${M.length} unsupported file${M.length===1?"":"s"} skipped: ${bl(M)}.`),Q.length>0&&oe.push(`${Q.length} file${Q.length===1?"":"s"} over 10 MB skipped: ${bl(Q)}.`),de.length>0&&oe.push(`${de.length} local duplicate file${de.length===1?"":"s"} skipped before upload: ${bl(de)}.`),xe.length===0){oe.length>0&&w(oe.join(" ")),x.current&&(x.current.value="");return}R(!0);const et=new Set(W.current);let yt=0;try{for(const{file:mt,fingerprint:kt}of xe){let Dt=null;const Mt=await fetch("/api/taskforce/context-upload/init",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({originalName:mt.name,mimeType:mt.type||"application/octet-stream",size:mt.size,taskId:n||null})});if(Mt.ok){const tt=await Mt.json();if(tt?.success&&typeof tt?.uploadUrl=="string"&&typeof tt?.path=="string"){if(!(await fetch(tt.uploadUrl,{method:String(tt.method||"PUT"),headers:tt.headers||{"Content-Type":mt.type||"application/octet-stream"},body:mt})).ok)throw new Error(`Upload failed for ${mt.name}`);const Rt=await fetch("/api/taskforce/context-upload/finalize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({relativePath:tt.relativePath,mimeType:mt.type||"application/octet-stream",originalName:mt.name,size:mt.size})});if(!Rt.ok){const wt=await Rt.json().catch(()=>({}));throw new Error(wt?.error||`Upload failed for ${mt.name}`)}Dt={success:!0,path:tt.path,fsPath:tt.fsPath}}else tt?.success&&typeof tt?.path=="string"&&(Dt=tt)}if(!Dt){const tt=await Sj(mt),pt=await fetch("/api/taskforce/context-upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:tt,originalName:mt.name,taskId:n||null})});if(!pt.ok)throw new Error(`Upload failed for ${mt.name}`);Dt=await pt.json()}if(!Dt?.success||!Dt?.path)throw new Error(`Upload failed for ${mt.name}`);const Zt=ye(Dt.path,Dt.fsPath);if(Ae(et,Zt)){yt+=1;continue}m({path:Dt.path,fsPath:Dt.fsPath,caption:mt.name,timestamp:new Date().toISOString()}),se(et,Zt),U.current.add(kt)}const ut=[...oe];yt>0&&ut.push(`${yt} duplicate file${yt===1?"":"s"} skipped.`),w(ut.length>0?ut.join(" "):null),W.current=et}catch(ut){D(ut instanceof Error?ut.message:"Failed to upload context file")}finally{R(!1),x.current&&(x.current.value="")}},Fe=ae=>{const q=new Set,M=ae.dataTransfer.getData("text/uri-list")||"",Q=ae.dataTransfer.getData("text/plain")||"",de=`${M}
6
- ${Q}`.split(`
7
- `).map(xe=>xe.trim()).filter(xe=>!!xe&&!xe.startsWith("#"));for(const xe of de){if(/^file:\/\//i.test(xe)){try{const B=new URL(xe),oe=decodeURIComponent(B.pathname||"").trim();oe&&q.add(oe)}catch{}continue}q.add(xe)}return Array.from(q)},te=ae=>{if(ae.preventDefault(),ae.stopPropagation(),J(!1),ce(0),D(null),$(null),w(null),ae.dataTransfer.files&&ae.dataTransfer.files.length>0){We(ae.dataTransfer.files);return}const q=Fe(ae);if(q.length===0){$("Drop a file, URL, or file path.");return}const M=new Set(W.current);let Q=0,de=0;q.forEach(xe=>{const B=Ye(xe,!1,M);B==="duplicate"&&(Q+=1),B==="added"&&(de+=1)}),Q>0?w(`${Q} duplicate link${Q===1?"":"s"} skipped.`):de>0&&w(null),W.current=M},ne=ae=>{ae.preventDefault(),ae.stopPropagation(),ce(q=>q+1),J(!0)},le=ae=>{ae.preventDefault(),ae.stopPropagation(),ce(q=>{const M=Math.max(0,q-1);return M===0&&J(!1),M})},dt=ae=>{ae.preventDefault(),ae.stopPropagation(),ae.dataTransfer.dropEffect="copy"};return e.jsxs("div",{className:t.specialistSection,children:[e.jsxs("div",{className:t.toggleHeading,onClick:()=>Z(!T),title:T?"Hide context documents":"Show context documents",children:[e.jsxs("label",{className:t.label,children:["Context Documents ",r.length>0&&`(${r.length})`]}),T?e.jsx(Bn,{size:14}):e.jsx(la,{size:14})]}),T&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:t.settingsHint,children:"Upload copies into context storage, or link to existing files/URLs without copying."}),e.jsxs("div",{className:t.contextUploadActions,children:[e.jsxs("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>x.current?.click(),disabled:_,children:[_?e.jsx(aa,{size:12,className:t.spinner}):e.jsx(ll,{size:12}),_?"Uploading...":"Upload File"]}),e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>d?.(),children:"Browse Link"})]}),e.jsx("input",{ref:x,type:"file",accept:Wd,multiple:!0,className:t.hiddenInput,onChange:ae=>{We(ae.target.files)}}),j&&e.jsx("div",{className:t.error,children:j}),e.jsxs("div",{className:t.contextLinkRow,children:[e.jsx("input",{type:"text",className:t.input,placeholder:"Link file path (e.g. docs/spec.pdf) or URL (https://...)",value:b,onChange:ae=>{f(ae.target.value),I&&$(null),z&&w(null)}}),e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>{if(!b.trim()){$("Enter a file path or URL to link.");return}const ae=Ye(b,!0);ae==="duplicate"?w("Link already exists in task context."):ae==="added"&&w(null)},children:"Save Link"})]}),e.jsxs("div",{className:`${t.contextDropzone} ${Ne?t.contextDropzoneActive:""}`,onDragEnter:ne,onDragLeave:le,onDragOver:dt,onDrop:te,children:[e.jsx(ll,{size:14}),e.jsx("span",{children:"Drop files, URLs, or file paths here"})]}),z&&e.jsx("div",{className:t.contextNotice,children:z}),I&&e.jsx("div",{className:t.error,children:I}),r.length>0&&e.jsx("div",{className:t.screenshotGrid,children:r.map((ae,q)=>{const M=typeof ae=="string"?ae:ae.path,Q=typeof ae=="string"?void 0:ae.fsPath,de=typeof ae=="string"?"":ae.caption||"",xe=Cj(M);return e.jsxs("div",{className:t.screenshotCard,children:[e.jsxs("div",{className:t.screenshotImageContainer,children:[xe?e.jsx("img",{src:M,alt:de||`Context file ${q}`,onClick:()=>window.open(M,"_blank"),onError:B=>{B.target.style.display="none",B.target.parentElement.classList.add(t.brokenImage)}}):e.jsxs("button",{type:"button",className:t.contextFileLink,onClick:()=>{Fd(M,Q)||window.open(M,"_blank")},title:"Open file",children:[e.jsx(ll,{size:16}),e.jsx("span",{children:de||Q||M.split("/").pop()||"Context file"})]}),e.jsxs("div",{className:t.brokenImagePlaceholder,children:[e.jsx(mo,{size:16}),e.jsx("span",{children:"Preview unavailable"})]}),e.jsxs("div",{className:t.screenshotActions,children:[Q&&e.jsx("button",{type:"button",className:t.screenshotActionBtn,onClick:B=>{B.stopPropagation(),navigator.clipboard.writeText(Q)},title:`Copy path: ${Q}`,children:e.jsx(Wr,{size:12})}),e.jsx("button",{type:"button",className:t.screenshotActionBtn,onClick:B=>{B.stopPropagation(),h(q)},title:"Delete",children:e.jsx(yo,{size:12})})]})]}),e.jsx("input",{type:"text",className:t.screenshotCaptionInput,placeholder:"Add a label...",value:de,onChange:B=>v(q,B.target.value)})]},q)})})]})]})}function Ud(a){const{editingTaskId:n,error:r,title:u,description:d,category:m,type:h,priority:v,complexity:x,manualComplexityEnabled:_=!1,approach:R,assignee:j,scheduledDate:D,dueDate:b,selectedSpecialists:f,comments:I,newCommentText:$,contextFiles:z,contextLinkBrowsePath:w,descriptionFocused:T,showMarkdownHelp:Z,showSpecialists:Ne,showChecklist:J=!1,checklistEnabled:he=!0,showTaskRelationships:ce=!1,showComments:W,showChildTasks:U=!1,formTaxonomies:Ge,onTaxonomyChange:ye,onParentTaskIdInputChange:ke,onAddChildTaskIdInputChange:Ae,onOpenSettings:se,categories:Ye,types:We,priorities:Fe,approaches:te,availableSpecialists:ne,taxonomies:le,copiedId:dt,onTitleChange:ae,onDescriptionChange:q,onCategoryChange:M,onTypeChange:Q,onPriorityChange:de,onComplexityChange:xe,onApproachChange:B,onAssigneeChange:oe,onScheduledDateChange:et,onDueDateChange:yt,onSelectedSpecialistsChange:ut,onNewCommentTextChange:mt,onDescriptionFocusedChange:kt,onShowMarkdownHelpChange:Dt,onShowSpecialistsChange:Mt,onShowChecklistChange:Zt=()=>{},onShowTaskRelationshipsChange:tt,onShowCommentsChange:pt,onShowChildTasksChange:Rt,onSubmit:wt,onAddComment:Ut,onAddContextFile:V,onBrowseContextLinkPath:Pe,onRemoveContextFile:_e,onUpdateContextCaption:Le,onCopyId:ze,onToggleInProgress:N,onToggleReview:G,onToggleComplete:je,onToggleCancel:Ie,onArchiveTask:we,onUnarchive:qe,onSetParentForCurrentTask:vt,onAddChildToCurrentTask:st,onCreateChildForCurrentTask:Re,onUnlinkChildTask:bt,onReorderChildTasks:De,onOpenTaskById:Jt,currentTask:St,currentTaskParent:ls,currentTaskChildren:Ee=[],parentTaskIdInput:zt="",addChildTaskIdInput:ts="",commentsEndRef:Et}=a,qt=Ye.filter(y=>!y.disabled),Ct=zs.useMemo(()=>{const y={value:"default",label:"Default",icon:"HelpCircle",color:"var(--text-secondary)"},ue=qt.filter(Ke=>Ke.value!=="default").map(Ke=>({value:Ke.value,label:Ke.label,icon:Ke.icon,color:Ke.color}));return[y,...ue]},[qt]),As=zs.useMemo(()=>{const y={value:"default",label:"Default",icon:"HelpCircle",color:"var(--text-secondary)"},ue=te.filter(Ke=>Ke.value!=="default").map(Ke=>({value:Ke.value,label:Ke.label,icon:Ke.icon,color:Ke.color}));return[y,...ue]},[te]),ds=y=>y&&wi(y,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,Ss=ds(St?.createdAt),Ds=ds(St?.updatedAt||St?.createdAt),us=ds(St?.completedAt),Cs=zs.useMemo(()=>{const y=new Date,ue=y.getFullYear(),Ke=String(y.getMonth()+1).padStart(2,"0"),At=String(y.getDate()).padStart(2,"0");return`${ue}-${Ke}-${At}`},[]),L=!!(b&&D&&b<D),F=!!(b&&b<Cs&&(!St||St.status!=="done"&&St.status!=="cancelled")),re=!!(St&&Ee.length>0),K=Pc(Ee),[H,me]=zs.useState(null),[Oe,ie]=zs.useState(null),ve=zs.useRef(null),_t=K.filter(y=>!!y.isArchived||y.status==="done"||y.status==="cancelled").length,Se=zs.useMemo(()=>El(d||""),[d]),Ue=Se.filter(y=>y.completed).length,ht=K.length>0?Math.round(_t/K.length*100):0,[nt,It]=zs.useState(""),jt=!!St?.isArchived,Vt=()=>{const y=nt.trim();y&&(q(U_(d||"",y)),It(""))},rt=(y,ue)=>{if(!n||y===ue)return;const Ke=K.map(vs=>vs.id),At=Ke.indexOf(y),ps=Ke.indexOf(ue);if(At<0||ps<0||At===ps)return;const Kt=[...Ke],[Lt]=Kt.splice(At,1);Kt.splice(ps,0,Lt),De?.(n,Kt)},ot=y=>{const ue=y.trim().replace(/[-_]+/g," ").replace(/\s+/g," ");return!ue||ue==="ai"?"AI Agent":`AI Agent - ${ue.split(" ").map(At=>At.charAt(0).toUpperCase()+At.slice(1)).join(" ")}`};return e.jsxs("form",{onSubmit:wt,className:t.form,children:[r&&e.jsx("div",{className:t.error,children:r}),jt&&e.jsx("div",{className:t.settingsHint,style:{marginBottom:"10px"},children:"Archived tasks are read-only. Unarchive the task to make changes."}),e.jsxs("fieldset",{disabled:jt,style:{border:"none",margin:0,padding:0,minInlineSize:0},children:[e.jsxs("div",{className:t.field,children:[e.jsxs("div",{className:t.labelRow,children:[e.jsx("label",{className:t.label,children:"Title"}),j&&e.jsx("span",{title:j==="agent"?"Assigned to: AI":j==="user"?"Assigned to: User":"Assigned to: Unassigned",style:{color:j==="agent"?"var(--color-violet-500, #8b5cf6)":j==="user"?"var(--color-green-500, #22c55e)":"#b45309",display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",fontWeight:600},children:j==="agent"?e.jsx(_c,{size:20}):j==="user"?e.jsx(jc,{size:20}):e.jsx(po,{size:20})})]}),e.jsx("input",{type:"text",value:u,onChange:y=>ae(y.target.value),placeholder:"What needs to be done?",className:t.input,required:!0,maxLength:255,autoFocus:!0})]}),e.jsxs("div",{className:t.field,children:[e.jsxs("div",{className:t.labelRow,children:[e.jsx("label",{className:t.label,children:"Description"}),e.jsx("button",{type:"button",className:t.helpLink,onClick:()=>Dt(!Z),title:"Markdown Help",tabIndex:-1,children:e.jsx(po,{size:14})})]}),Z&&e.jsxs("div",{className:t.markdownHelp,children:[e.jsxs("div",{className:t.helpHeader,children:[e.jsx("span",{children:"Markdown Guide"}),e.jsx("button",{onClick:()=>Dt(!1),className:t.helpClose,children:e.jsx(ga,{size:12})})]}),e.jsxs("div",{className:t.helpGrid,children:[e.jsx("div",{children:e.jsx("code",{children:"**bold**"})}),e.jsx("div",{children:e.jsx("code",{children:"_italic_"})}),e.jsx("div",{children:e.jsx("code",{children:"- list"})}),e.jsx("div",{children:e.jsx("code",{children:"1. list"})}),e.jsx("div",{children:e.jsx("code",{children:"- [ ] checklist item"})}),e.jsx("div",{children:e.jsx("code",{children:"- [x] completed item"})}),e.jsx("div",{className:t.helpGridItem,children:e.jsx("code",{children:"`inline code`"})}),e.jsxs("div",{className:t.helpGridItem,children:[e.jsx("code",{children:"```"}),e.jsx("br",{}),e.jsx("code",{children:"code block"}),e.jsx("br",{}),e.jsx("code",{children:"```"})]}),e.jsx("div",{children:e.jsx("code",{children:"[link](url)"})})]}),e.jsx("div",{className:t.settingsHint,style:{marginTop:"8px"},children:"Checklist checkboxes are clickable in preview mode."})]}),T||!d?e.jsx("textarea",{className:t.textarea,placeholder:"What needs to be done? (Markdown supported)",value:d,onChange:y=>q(y.target.value),onFocus:()=>kt(!0),onBlur:()=>kt(!1),rows:9,autoFocus:T}):e.jsx("div",{className:`${t.textarea} ${t.markdownPreview} ${t.markdownPreviewContainer}`,onClick:()=>kt(!0),children:e.jsx(Bl,{onChecklistToggle:(y,ue)=>{q(Ql(d||"",y,ue))},onTaskIdClick:Jt,children:d})})]}),e.jsxs("div",{className:t.topRow,children:[e.jsxs("div",{className:t.field,children:[e.jsxs("div",{className:t.labelRow,children:[e.jsx("label",{id:"category-label",className:t.label,children:"Category"}),e.jsx("button",{type:"button",className:t.manageLink,onClick:()=>se?.("categories"),title:"Manage Categories",tabIndex:-1,children:e.jsx(_i,{size:14})})]}),e.jsx(Ko,{value:m,options:Ct,onChange:y=>M(String(y)),required:!0,ariaLabelledBy:"category-label"})]}),e.jsxs("div",{className:t.field,children:[e.jsxs("div",{className:t.labelRow,children:[e.jsx("label",{id:"type-label",className:t.label,children:"Type"}),e.jsx("button",{type:"button",className:t.manageLink,onClick:()=>se?.("types"),title:"Manage Types",tabIndex:-1,children:e.jsx(_i,{size:14})})]}),e.jsx(Ko,{value:h,options:We.map(y=>({value:y.value,label:y.label,icon:ko[y.value]?.icon||"Box",color:ko[y.value]?.color||"violet-500"})),onChange:y=>Q(String(y)),ariaLabelledBy:"type-label"})]}),e.jsxs("div",{className:t.field,children:[e.jsx("label",{id:"approach-label",className:t.label,children:"Approach"}),e.jsx(Ko,{value:R||"default",options:As,onChange:y=>B(String(y)),ariaLabelledBy:"approach-label"})]}),e.jsxs("div",{className:t.field,children:[e.jsx("label",{id:"assignee-label",className:t.label,children:"Assigned To"}),e.jsx(Ko,{value:j||"agent",options:[{value:"unassigned",label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)"},{value:"agent",label:"AI",icon:"Bot",color:"#8b5cf6"},{value:"user",label:"User",icon:"User",color:"#22c55e"}],onChange:y=>oe(String(y)),ariaLabelledBy:"assignee-label"})]}),e.jsx(vl,{label:"Priority",options:Fe,value:v,onChange:de,type:"priority"}),_&&e.jsx(vl,{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:x,onChange:xe,type:"general"})]}),e.jsx("div",{className:t.taxonomyFieldsGrid,children:le.map(y=>y.id==="approach"&&y.isSystem?null:e.jsxs("div",{className:t.field,children:[e.jsx("label",{className:t.label,children:y.label}),y.widgetType==="level"?e.jsx(vl,{label:y.label,options:y.options,value:Ge[y.id]||"",onChange:ue=>ye(y.id,ue),type:"general",hideLabel:!0}):e.jsxs("div",{className:t.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 ue=y.options.find(ps=>ps.value===Ge[y.id]),Ke=ue?.icon&&da[ue.icon]?da[ue.icon]:po,At=ue?.color||"var(--text-secondary)";return e.jsx("div",{className:t.fieldIcon,style:{color:ys(At)},children:e.jsx(Ke,{size:16})})})(),e.jsxs("select",{value:Ge[y.id]||"",onChange:ue=>ye(y.id,ue.target.value),className:`${t.select} ${t.field_dynamic}`,required:y.isRequired,children:[e.jsxs("option",{value:"",children:["Select ",y.label,"..."]}),y.options.map(ue=>e.jsx("option",{value:ue.value,children:ue.label},ue.value))]})]})]},y.id))}),he&&e.jsxs("div",{className:t.specialistSection,children:[e.jsxs("div",{className:t.toggleHeading,onClick:()=>Zt(!J),title:J?"Hide checklist":"Show checklist",children:[e.jsxs("label",{className:t.label,children:["Checklist ",Se.length>0&&`(${Ue}/${Se.length})`]}),J?e.jsx(Bn,{size:14}):e.jsx(la,{size:14})]}),J&&e.jsxs("div",{className:t.dropdownList,style:{marginTop:"8px",flexDirection:"column",gap:6},children:[e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("input",{type:"text",className:t.input,placeholder:"Add checklist item",value:nt,onChange:y=>It(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),Vt())}}),e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:Vt,disabled:!nt.trim(),children:"Add"})]}),Se.length>0?Se.map(y=>e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>{q(Ql(d||"",y.lineIndex,!y.completed))},title:y.completed?"Mark incomplete":"Mark complete",style:{minWidth:28,padding:"4px 8px"},children:y.completed?e.jsx(Sa,{size:12}):e.jsx(ou,{size:12})}),e.jsx("span",{style:{flex:1,minWidth:0,color:y.completed?"var(--text-muted)":"var(--text-primary)",textDecoration:y.completed?"line-through":"none"},children:y.text}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.deleteBtn}`,onClick:()=>q(H_(d||"",y.lineIndex)),title:"Remove checklist item",children:e.jsx(ga,{size:12})})]},`checklist-${y.lineIndex}`)):e.jsx("div",{className:t.settingsHint,children:"No checklist items yet."})]})]}),ne.length>0&&e.jsxs("div",{className:t.specialistSection,children:[e.jsxs("div",{className:t.toggleHeading,onClick:()=>Mt(!Ne),title:Ne?"Hide unassigned specialists":"Show all specialists",children:[e.jsxs("label",{className:t.label,children:["Specialists ",f.length>0&&`(${f.length})`]}),Ne?e.jsx(Bn,{size:14}):e.jsx(la,{size:14})]}),Ne&&e.jsxs("div",{className:t.dropdownList,style:{padding:"8px 4px",background:"rgba(0,0,0,0.1)",borderRadius:"8px",marginTop:"4px"},children:[f.map(y=>{const ue=ne.find(Ke=>Ke.value===y);return ue?e.jsxs("button",{type:"button",className:`${t.specialistChip} ${t.specialistChipActive}`,onClick:()=>{ut(f.filter(Ke=>Ke!==ue.value))},title:"Click to unassign",children:[e.jsx(Sa,{size:12}),ue.label]},ue.value):null}),ne.filter(y=>!f.includes(y.value)).map(y=>e.jsx("button",{type:"button",className:t.specialistChip,onClick:()=>{ut([...f,y.value])},title:"Click to assign",children:y.label},y.value)),ne.filter(y=>!f.includes(y.value)).length===0&&e.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",fontStyle:"italic",padding:"4px 8px"},children:"All available specialists have been assigned."})]})]}),e.jsxs("div",{className:t.specialistSection,children:[e.jsxs("div",{className:t.toggleHeading,onClick:()=>tt?.(!ce),title:ce?"Hide Parent Task":"Show Parent Task",children:[e.jsx("label",{className:t.label,children:"Parent Task"}),ce?e.jsx(Bn,{size:14}):e.jsx(la,{size:14})]}),ce&&e.jsx(e.Fragment,{children:ls?e.jsx("div",{className:t.dropdownList,style:{marginTop:"8px",flexDirection:"column",gap:6},children:e.jsxs("div",{className:t.childCardRow,children:[e.jsx("div",{style:{flex:1,minWidth:0},children:e.jsx(Qo,{task:ls,compressed:!0,showParentRelationship:!1,isArchived:!!ls.isArchived,copiedId:dt,taxonomies:le,priorities:Fe,approaches:te,categories:Ye,onClick:()=>Jt?.(ls.id),onCopyId:ze,onToggleInProgress:N,onToggleReview:G,onToggleComplete:je,onToggleCancel:Ie,onArchiveTask:we,onUnarchive:qe})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.deleteBtn} ${t.childCardRemoveBtn}`,onClick:()=>{ke?.(""),vt?.(null)},title:"Remove parent","aria-label":`Remove parent ${ls.id}`,children:e.jsx(ga,{size:12})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.pathInputGroup,style:{marginTop:"8px"},children:[e.jsx("input",{type:"text",className:t.input,placeholder:"Paste parent task ID",value:zt,onChange:y=>ke?.(y.target.value)}),n&&e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>vt?.(),children:"Set Parent"})]}),!n&&e.jsx("div",{className:t.settingsHint,style:{marginTop:"8px"},children:"Parent link is applied when the task is created."})]})})]}),e.jsxs("div",{className:t.specialistSection,children:[e.jsxs("div",{className:t.toggleHeading,onClick:()=>Rt?.(!U),title:U?"Hide Child Tasks":"Show Child Tasks",children:[e.jsxs("label",{className:t.label,children:["Child Tasks ",Ee.length>0&&`(${Ee.length})`]}),U?e.jsx(Bn,{size:14}):e.jsx(la,{size:14})]}),U&&e.jsx(e.Fragment,{children:n?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.pathInputGroup,style:{marginTop:"8px"},children:[e.jsx("input",{type:"text",className:t.input,placeholder:"Paste child task ID",value:ts,onChange:y=>Ae?.(y.target.value)}),e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>st?.(),disabled:!ts.trim(),children:"Add Child"}),e.jsx("button",{type:"button",className:t.secondaryHeaderBtn,onClick:()=>Re?.(),children:"New Child"})]}),K.length>0&&e.jsxs("div",{className:t.taskChildrenSummaryBadges,style:{marginTop:"8px"},children:[e.jsx("div",{className:t.taskChildrenProgressBar,title:`${_t} of ${K.length} child tasks are done/cancelled (${ht}%)`,children:e.jsx("div",{className:t.taskChildrenProgressBarFill,style:{width:`${ht}%`}})}),e.jsx("div",{className:t.taskChildrenProgressText,children:`${_t}/${K.length} • ${ht}%`})]}),K.length>0&&e.jsx("div",{className:t.dropdownList,style:{marginTop:"8px",flexDirection:"column",gap:6},children:K.map(y=>e.jsxs("div",{className:`${t.childCardRow} ${H===y.id?t.childCardRowDragging:""} ${Oe===y.id&&H&&H!==y.id?t.childCardRowDropTarget:""}`,draggable:!0,onDragStart:ue=>{ve.current=y.id,me(y.id),ue.dataTransfer.effectAllowed="move",ue.dataTransfer.setData("text/plain",y.id)},onDragOver:ue=>{const Ke=ve.current||H;!Ke||Ke===y.id||(ue.preventDefault(),ue.dataTransfer.dropEffect="move",Oe!==y.id&&ie(y.id))},onDragLeave:()=>{Oe===y.id&&ie(null)},onDrop:ue=>{ue.preventDefault();const Ke=ue.dataTransfer.getData("text/plain")||ve.current||H;Ke&&rt(Ke,y.id),ie(null),me(null),ve.current=null},onDragEnd:()=>{ie(null),me(null),ve.current=null},children:[e.jsx("div",{style:{flex:1,minWidth:0},children:e.jsx(Qo,{task:y,compressed:!0,showParentRelationship:!1,isArchived:!!y.isArchived,copiedId:dt,taxonomies:le,priorities:Fe,approaches:te,categories:Ye,onClick:()=>Jt?.(y.id),onCopyId:ze,onToggleInProgress:N,onToggleReview:G,onToggleComplete:je,onToggleCancel:Ie,onArchiveTask:we,onUnarchive:qe})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.deleteBtn} ${t.childCardRemoveBtn}`,onClick:()=>bt?.(y.id),title:"Remove child","aria-label":`Remove child ${y.id}`,children:e.jsx(ga,{size:12})})]},y.id))})]}):e.jsx("div",{className:t.settingsHint,style:{marginTop:"8px"},children:"Save this task first, then you can add child tasks."})})]}),e.jsx(_j,{taskId:n,contextFiles:z,browsedPath:w,onBrowseLinkPath:Pe,onAddContextFile:V,onRemoveContextFile:_e,onUpdateContextCaption:Le}),n&&e.jsxs("div",{className:t.specialistSection,children:[e.jsxs("div",{className:t.toggleHeading,onClick:()=>pt(!W),title:E(W?"taskForm.hideComments":"taskForm.showComments"),children:[e.jsxs("label",{className:t.label,children:[E("taskForm.commentsSectionTitle")," ",I.length>0&&`(${I.length})`]}),W?e.jsx(Bn,{size:14}):e.jsx(la,{size:14})]}),W&&e.jsxs("div",{className:t.commentPanel,children:[e.jsxs("div",{className:t.commentThread,children:[I.length===0&&e.jsx("div",{className:t.emptyComments,children:E("taskForm.noComments")}),I.map(y=>{const ue=String(y.author||"").trim().toLowerCase(),Ke=ue!==""&&ue!=="user"&&ue!=="human",At=Ke?ot(ue):E("taskForm.you");return e.jsxs("div",{className:`${t.comment} ${Ke?t.commentAi:t.commentUser}`,children:[e.jsxs("div",{className:t.commentHeader,children:[e.jsx("span",{className:t.commentAuthor,children:Ke?e.jsxs(e.Fragment,{children:[e.jsx(_c,{size:12,strokeWidth:1.5})," ",At]}):e.jsxs(e.Fragment,{children:[e.jsx(jc,{size:12,strokeWidth:1.5})," ",E("taskForm.you")]})}),e.jsx("span",{className:t.commentTime,children:wi(y.timestamp,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]}),e.jsx("div",{className:t.commentText,children:e.jsx(Bl,{onTaskIdClick:Jt,children:y.text})})]},y.id)}),e.jsx("div",{ref:Et})]}),e.jsxs("div",{className:t.commentInputArea,children:[e.jsx("textarea",{className:t.commentInput,placeholder:E("taskForm.commentPlaceholder"),value:$,onChange:y=>mt(y.target.value),onKeyDown:y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),Ut())},rows:1}),e.jsx("button",{type:"button",className:t.sendCommentBtn,onClick:Ut,disabled:!$.trim(),children:e.jsx(ru,{size:16})})]})]})]}),e.jsx("div",{className:t.taskFormLifecycle,children:e.jsxs("div",{className:t.taskFormDateStack,children:[e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel,children:E("taskForm.scheduledLabel")}),e.jsx("input",{type:"date",value:D,onChange:y=>et(y.target.value),className:`${t.input} ${t.taskFormDateInput}`,disabled:re})]}),re&&e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel}),e.jsx("span",{style:{color:"var(--text-muted)",fontSize:"11px",fontWeight:500},children:E("taskForm.parentCannotSchedule")})]}),e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel,children:E("taskForm.dueLabel")}),e.jsx("input",{type:"date",value:b,onChange:y=>yt(y.target.value),className:`${t.input} ${t.taskFormDateInput}`})]}),L&&e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel}),e.jsx("span",{style:{color:"var(--color-warning-500, #f59e0b)",fontSize:"11px",fontWeight:600},children:E("taskForm.dueBeforeScheduled")})]}),F&&e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel}),e.jsx("span",{style:{color:"var(--color-error, #ef4444)",fontSize:"11px",fontWeight:600},children:E("taskForm.overdue")})]}),St&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel,children:E("taskForm.createdLabel")}),e.jsx("span",{className:t.taskFormDateValue,children:Ss||E("taskForm.emptyValue")})]}),e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel,children:E("taskForm.updatedLabel")}),e.jsx("span",{className:t.taskFormDateValue,children:Ds||E("taskForm.emptyValue")})]}),e.jsxs("div",{className:t.taskFormDateRow,children:[e.jsx("span",{className:t.taskFormDateLabel,children:E("taskForm.completedLabel")}),e.jsx("span",{className:t.taskFormDateValue,children:us||E("taskForm.emptyValue")})]})]})]})}),e.jsxs("div",{className:t.keyboardHint,children:["Press ",e.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function Hd({editingTaskId:a,loading:n,title:r,handleSubmit:u,resetForm:d,handleCopyId:m,copiedId:h,tasks:v,currentTask:x,handleToggleInProgress:_,handleToggleReview:R,handleToggleComplete:j,handleToggleCancel:D,handleArchiveTask:b}){const f=x??(a&&v.find($=>$.id===a)||null),I=!!f?.isArchived;return e.jsx("div",{className:t.stickyActionHeader,children:a?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:$=>u($),disabled:n||!r.trim()||I,className:t.primaryUpdateBtn,title:I?"Archived tasks are read-only. Unarchive first.":E("actionHeader.saveChangesTitle"),children:[n?e.jsx(aa,{size:16,className:t.spinner}):e.jsx(Bc,{size:16}),E("actionHeader.update")]}),e.jsxs("button",{className:`${t.taskIdBadgeStatic} ${h===a?t.copiedId:""}`,onClick:$=>m($,a),disabled:n,title:E("actionHeader.copyTaskIdTitle"),children:[h===a?e.jsx(Sa,{size:13}):e.jsx(Wr,{size:13}),e.jsxs("span",{children:["ID: ",a.split("-").slice(-1)[0]]})]}),e.jsxs("div",{className:t.editActionsGroup,children:[e.jsx("button",{type:"button",className:`${t.actionBtn} ${f?.status==="in-progress"?t.workingBtn:t.startWorkBtn}`,disabled:n||!f||I,onClick:()=>f&&_(f),title:f?.status==="in-progress"?E("actionHeader.stopWorking"):E("actionHeader.startWorking"),children:f?.status==="in-progress"?e.jsx(iu,{size:18}):e.jsx(cu,{size:18})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${f?.status==="review"?t.reviewActiveBtn:t.reviewBtn}`,disabled:n||!f||I,onClick:()=>f&&R(f),title:f?.status==="review"?E("actionHeader.unlockAndContinue"):E("actionHeader.readyForReview"),children:e.jsx(vc,{size:18})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${f?.status==="done"?t.completeActiveBtn:t.completeBtn}`,disabled:n||!f||I,onClick:()=>f&&j(f),title:f?.status==="done"?E("actionHeader.unmarkComplete"):E("actionHeader.markComplete"),children:e.jsx(Sa,{size:18})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${f?.status==="cancelled"?t.deleteActiveBtn:t.deleteBtn}`,disabled:n||!f||I,onClick:()=>f&&D(f),title:f?.status==="cancelled"?E("actionHeader.unmarkCancelled"):E("actionHeader.cancelTask"),children:e.jsx(yd,{size:18})}),e.jsx("button",{type:"button",className:`${t.actionBtn} ${t.archiveTaskBtn} ${f?.status==="done"||f?.status==="cancelled"?"":t.disabledBtn}`,onClick:()=>{f&&(f.status==="done"||f.status==="cancelled")&&b(f)},disabled:n||I||!(f?.status==="done"||f?.status==="cancelled"),title:f?.status==="done"||f?.status==="cancelled"?E("actionHeader.archiveNow"):E("actionHeader.completeTaskToArchive"),children:e.jsx(lu,{size:18})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:d,disabled:n,className:t.secondaryHeaderBtn,title:E("actionHeader.clearFormTitle"),children:[e.jsx(zl,{size:16}),E("actionHeader.clear")]}),e.jsxs("button",{type:"button",onClick:$=>u($),disabled:n||!r.trim(),className:t.primaryUpdateBtn,title:E("actionHeader.addTaskTitle"),children:[n?e.jsx(aa,{size:16,className:t.spinner}):e.jsx(cn,{size:16}),E("actionHeader.addTask")]})]})})}function wl({taxonomy:a,onUpdateTaxonomy:n,onRemoveTaxonomy:r}){const[u,d]=s.useState(""),[m,h]=s.useState(!1),[v,x]=s.useState(""),[_,R]=s.useState(a.label),[j,D]=s.useState(null);s.useEffect(()=>{R(a.label);const z=a.options.find(w=>String(w.value)===String(u));D(z||null)},[a,u]);const b=z=>{n({...a,...z})},f=()=>{if(!v.trim())return;const z=v.toLowerCase().trim().replace(/\s+/g,"-");if(a.options.some(T=>T.value===z)){alert("Option value already exists");return}const w={value:z,label:v.trim(),color:bc[a.options.length%bc.length]};b({options:[...a.options,w]}),x(""),h(!1),d(z)},I=(z,w)=>{b({options:a.options.map(T=>String(T.value)===String(z)?{...T,...w}:T)})},$=z=>{confirm("Are you sure you want to remove this option?")&&(b({options:a.options.filter(w=>String(w.value)!==String(z))}),d(""))};return e.jsxs("div",{className:t.categoryManagerContainer,children:[e.jsxs("div",{className:`${t.categoryConfigPanel} ${t.configPanel} ${t.marginBottom24}`,children:[e.jsxs("div",{className:`${t.flexBetween} ${t.marginBottom16}`,children:[e.jsx("div",{className:t.flex1,children:e.jsx("label",{className:`${t.subLabel} ${t.subLabelBlock} ${t.marginBottom8}`,children:"Taxonomy Settings"})}),!a.isSystem&&r&&e.jsxs("button",{type:"button",className:`${t.destructiveBtn} ${t.deleteBtnSmall}`,onClick:()=>{confirm(`Delete taxonomy "${a.label}"? All associated data will be hidden.`)&&r(a.id)},children:[e.jsx(yo,{size:14,className:t.trashIcon})," Delete Taxonomy"]})]}),e.jsxs("div",{className:t.taxonomyGrid,children:[e.jsxs("div",{className:t.settingGroup,style:{margin:0},children:[e.jsx("label",{className:`${t.label} ${t.inputLabel}`,children:"Display Label"}),e.jsx("input",{className:t.input,value:_,onChange:z=>R(z.target.value),onBlur:()=>b({label:_}),disabled:a.isSystem,placeholder:"e.g. Sprint, Phase..."})]}),e.jsxs("div",{className:t.settingGroup,style:{margin:0},children:[e.jsx("label",{className:`${t.label} ${t.inputLabel}`,children:"Widget Type"}),e.jsxs("select",{className:t.select,value:a.widgetType,onChange:z=>{const w=z.target.value;b({widgetType:w,multiSelect:w==="level"?!1:a.multiSelect})},children:[e.jsx("option",{value:"select",children:"Dropdown (Select Box)"}),e.jsx("option",{value:"level",children:"Level Selector (Segmented)"})]})]})]}),e.jsxs("div",{className:t.checkboxRow,children:[e.jsxs("label",{className:t.checkboxLabel,children:[e.jsx("input",{type:"checkbox",checked:a.isRequired,onChange:z=>b({isRequired:z.target.checked}),className:t.checkboxSmall}),"Mark as Required"]}),e.jsxs("label",{className:`${t.checkboxLabel} ${a.widgetType==="level"?t.opacity50:""}`,children:[e.jsx("input",{type:"checkbox",checked:a.multiSelect,onChange:z=>b({multiSelect:z.target.checked}),disabled:a.widgetType==="level",className:t.checkboxSmall}),"Allow Multi-select"]})]})]}),e.jsx("div",{className:`${t.configDivider} ${t.configDividerMargin24}`}),e.jsxs("div",{className:`${t.configPanel} ${t.flex1} ${t.flexCol}`,children:[e.jsxs("div",{className:`${t.headerFlex}`,style:{marginBottom:j&&!m||m?"16px":"0"},children:[e.jsx("div",{style:{flex:1},children:e.jsx(Ko,{value:u,options:[{value:"",label:"Select an option to configure...",icon:"HelpCircle",color:"var(--text-secondary)"},...a.options.map(z=>({value:z.value,label:z.label,icon:z.icon,color:z.color}))],onChange:z=>{d(z),h(!1)},disabled:m})}),m?e.jsx("button",{type:"button",onClick:()=>h(!1),title:"Cancel",className:`${t.browseBtn} ${t.cancelBtnRed}`,children:e.jsx(ga,{size:18})}):e.jsx("button",{type:"button",className:t.browseBtn,onClick:()=>h(!0),title:"Add Option",children:e.jsx(cn,{size:18})})]}),m&&e.jsx("div",{className:`${t.configItem} ${t.marginBottom16}`,children:e.jsxs("div",{className:t.flexGap8,children:[e.jsx("input",{type:"text",className:t.input,placeholder:"New option label...",value:v,onChange:z=>x(z.target.value),onKeyDown:z=>{z.key==="Enter"&&f()},autoFocus:!0}),e.jsx("button",{type:"button",className:t.saveSettingsBtn,onClick:f,disabled:!v.trim(),children:"Add Option"})]})}),j&&!m&&e.jsxs("div",{className:t.flex1,children:[e.jsx("div",{className:`${t.configDivider} ${t.marginBottom20}`}),e.jsx("div",{className:`${t.flexBetweenCenter} ${t.marginBottom20}`,children:e.jsxs("div",{className:`${t.flexColGap4} ${t.flex1}`,children:[e.jsx("label",{className:`${t.label} ${t.inputLabel}`,children:"Option Label"}),e.jsxs("div",{className:t.gridConfig,children:[e.jsx("input",{className:t.input,value:j.label,onChange:z=>I(j.value,{label:z.target.value}),placeholder:"Option Label"}),e.jsxs("button",{type:"button",className:`${t.destructiveBtn} ${t.deleteBtnMedium}`,onClick:()=>$(j.value),title:"Delete Option",children:[e.jsx(yo,{size:14,className:t.trashIcon})," Delete"]})]})]})}),e.jsx("div",{className:`${t.configDivider} ${t.configDividerMargin}`}),e.jsxs("div",{className:t.configSection,children:[e.jsx("label",{className:`${t.label} ${t.inputLabelBlock}`,children:"Visual Style"}),e.jsxs("div",{className:t.categorySubConfig,children:[e.jsx("div",{className:t.colorPickerGrid,children:bc.map(z=>{const w=ys(z)||"#000000",T=j.color===z,Z=j.icon&&da[j.icon]?da[j.icon]:Tc;return e.jsx("button",{type:"button",className:`${t.colorSwatch} ${T?t.colorSwatchActive:""}`,style:{borderColor:T?w:void 0,"--swatch-color":w,"--swatch-border-color":`${w}80`},onClick:()=>I(j.value,{color:z}),title:z,children:e.jsx(Z,{size:14,style:{color:w}})},z)})}),e.jsx("div",{className:t.iconGrid,children:jd.map(z=>{const w=da[z]||fo[z]||Tc;return e.jsx("button",{type:"button",className:`${t.iconPickerBtn} ${j.icon===z?t.iconPickerBtnActive:""}`,style:j.icon===z?{borderColor:ys(j.color),color:ys(j.color),background:`${ys(j.color)}15`}:{},onClick:()=>I(j.value,{icon:z}),title:z,children:e.jsx(w,{size:16})},z)})})]})]})]}),!j&&!m&&e.jsxs("div",{className:t.emptyStateBox,style:{border:"none",background:"transparent"},children:[e.jsx(du,{size:24,className:t.emptyStateIcon}),"Select an option above to configure its appearance"]})]})]})}function jj(a){const{categories:n,pathValidation:r,onUpdateCategory:u,onRemoveCategory:d,onSaveCategory:m,onAddPath:h,onRemovePath:v,onUpdateCategoryIcon:x,onUpdateCategoryColor:_,onBrowseFolders:R}=a,[j,D]=s.useState(""),[b,f]=s.useState(!1),[I,$]=s.useState(""),[z,w]=s.useState(""),[T,Z]=s.useState("");s.useEffect(()=>{const W=n.find(U=>U.value===j);W&&w(W.label)},[j,n]);const Ne=()=>{if(!I.trim())return;m(I);const W=I.trim().toLowerCase().replace(/\s+/g,"-");$(""),f(!1),setTimeout(()=>D(W),100)},J=W=>{z&&z!==W.label&&u({...W,label:z},W.label)},he=W=>{const U=[];if(W.path&&U.push(W.path),W.paths&&W.paths.length>0)for(const Ge of W.paths)U.includes(Ge)||U.push(Ge);return U},ce=n.find(W=>W.value===j);return e.jsxs("div",{className:`${t.configPanel} ${t.flex1}`,children:[e.jsxs("div",{className:`${t.headerFlex}`,style:{marginBottom:ce&&!b||b?"20px":"0"},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{id:"category-config-label",className:t.label,style:{display:"none"},children:"Select Category"}),e.jsx(Ko,{value:j,options:[{value:"",label:"Select a category to configure...",icon:"HelpCircle",color:"var(--text-secondary)"},...n.map(W=>({value:W.value,label:`${W.label}${W.disabled?" (Disabled)":""}`,icon:W.icon,color:W.color}))],onChange:W=>{D(String(W)),f(!1)},disabled:b,ariaLabelledBy:"category-config-label"})]}),b?e.jsx("button",{type:"button",className:`${t.browseBtn} ${t.cancelBtnRed}`,onClick:()=>f(!1),title:"Cancel creation",children:e.jsx(ga,{size:18})}):e.jsx("button",{type:"button",className:t.browseBtn,onClick:()=>f(!0),title:"Create new category",children:e.jsx(cn,{size:18})})]}),b&&e.jsxs("div",{className:`${t.configItem} ${t.marginBottom16}`,children:[e.jsx("div",{className:`${t.labelRow} ${t.marginBottom8}`,children:e.jsx("label",{className:t.settingsLabel,children:"New Category Name"})}),e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsx("input",{type:"text",className:t.input,placeholder:"e.g. Backend, Frontend, API...",value:I,onChange:W=>$(W.target.value),onKeyDown:W=>{W.key==="Enter"&&Ne()},autoFocus:!0}),e.jsx("button",{type:"button",className:t.saveSettingsBtn,onClick:Ne,disabled:!I.trim(),children:"Create"})]})]}),ce&&!b&&e.jsxs("div",{className:t.flex1,style:{overflowY:"auto",marginRight:"-8px",paddingRight:"8px"},children:[e.jsx("div",{className:`${t.configDivider} ${t.marginBottom20}`}),e.jsxs("div",{className:`${t.configSection} ${t.marginBottom20}`,children:[e.jsxs("div",{className:t.flexBetween,children:[e.jsx("label",{className:`${t.subLabel} ${t.subLabelBlock}`,children:"General"}),e.jsxs("button",{type:"button",onClick:()=>{confirm(`Delete category "${ce.label}"?`)&&(d(ce.value),D(""))},title:"Delete Category",className:`${t.destructiveBtn} ${t.deleteBtnSmall}`,children:[e.jsx(yo,{size:14,className:t.trashIcon})," Delete"]})]}),e.jsxs("div",{className:t.gridConfig,children:[e.jsxs("div",{className:t.flexColGap4,children:[e.jsx("label",{className:`${t.label} ${t.inputLabel}`,children:"Label"}),e.jsx("input",{className:t.input,value:z,onChange:W=>w(W.target.value),onBlur:()=>J(ce),onKeyDown:W=>{W.key==="Enter"&&(J(ce),W.target.blur())}})]}),e.jsxs("div",{className:t.flexColGap4Center,children:[e.jsx("label",{className:`${t.label} ${t.inputLabel}`,children:"Visible"}),e.jsx("input",{type:"checkbox",checked:!ce.disabled,onChange:()=>u({...ce,disabled:!ce.disabled}),className:t.checkboxInput})]})]})]}),e.jsx("div",{className:`${t.configDivider} ${t.configDividerMargin}`}),e.jsxs("div",{className:`${t.configSection} ${t.marginBottom20}`,children:[e.jsx("label",{className:t.subLabel,style:{fontSize:"14px",fontWeight:600,display:"block",marginBottom:"8px"},children:"Context Paths"}),e.jsx("p",{className:t.settingsHint,style:{marginBottom:"12px"},children:"Files in these paths will be included as context for tasks in this category."}),he(ce).length>0&&e.jsx("div",{className:`${t.pathList} ${t.pathListMargin}`,children:he(ce).map((W,U)=>{const Ge=r[W],ye=Ge?.exists,ke=Ge?.isFile;return e.jsxs("div",{className:`${t.pathChip} ${ye===!1?t.pathInvalid:ye?t.pathValid:""}`,children:[ye===void 0?e.jsx(aa,{size:12,className:t.spinner}):ye?ke?e.jsx(Xo,{size:12,className:t.pathValidIcon}):e.jsx(Cl,{size:12,className:t.pathValidIcon}):e.jsx(mo,{size:12,className:t.pathInvalidIcon}),e.jsx("span",{className:t.pathText,title:W,children:W}),e.jsx("button",{type:"button",className:t.removePathBtn,onClick:()=>v(ce.value,W),title:"Remove path",children:e.jsx(ga,{size:10})})]},U)})}),e.jsxs("div",{className:`${t.pathInputGroup} ${t.pathInputGroupStretch}`,children:[e.jsx("input",{type:"text",className:t.input,value:T,onChange:W=>Z(W.target.value),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),T.trim()&&(h(ce.value,T.trim()),Z("")))},placeholder:"Add path (e.g. frontend/src/...)"}),e.jsx("button",{type:"button",className:t.browseBtn,onClick:()=>{T.trim()&&(h(ce.value,T.trim()),Z(""))},disabled:!T.trim(),title:"Add path",children:e.jsx(cn,{size:18})}),e.jsx("button",{type:"button",className:t.browseBtn,onClick:()=>R(ce.value),title:"Browse folders",children:e.jsx(Cl,{size:16})})]})]}),e.jsx("div",{className:`${t.configDivider} ${t.configDividerMargin}`}),e.jsxs("div",{className:t.configSection,children:[e.jsx("label",{className:`${t.subLabel} ${t.subLabelBlock} ${t.subLabelBlock12}`,children:"Visual Style"}),e.jsxs("div",{className:t.categorySubConfig,children:[e.jsx("div",{className:t.colorPickerGrid,children:bc.map(W=>{const U=ys(W)||"#000000",Ge=ce.color===W,ye=ce.icon&&fo[ce.icon]?fo[ce.icon]:ho;return e.jsx("button",{type:"button",className:`${t.colorSwatch} ${Ge?t.colorSwatchActive:""}`,style:{borderColor:Ge?U:void 0,"--swatch-color":U,"--swatch-border-color":`${U}80`},onClick:()=>_(ce.value,W),title:W,children:e.jsx(ye,{size:14,style:{color:U}})},W)})}),e.jsx("div",{className:t.iconGrid,children:jd.map(W=>{const U=fo[W];return e.jsx("button",{type:"button",className:`${t.iconPickerBtn} ${ce.icon===W?t.iconPickerBtnActive:""}`,style:ce.icon===W?{borderColor:ys(ce.color),color:ys(ce.color),background:`${ys(ce.color)}15`}:{},onClick:()=>x(ce.value,W),title:W,children:e.jsx(U,{size:16})},W)})})]})]})]}),!ce&&!b&&e.jsx("div",{className:t.emptyStateItalic,style:{border:"none",background:"transparent"},children:"Select a category above to configure settings"})]})}function Tj(a){const{types:n,onSaveType:r,onRemoveType:u}=a,[d,m]=s.useState(""),[h,v]=s.useState(!1),[x,_]=s.useState(""),[R,j]=s.useState("");s.useEffect(()=>{const f=n.find(I=>I.value===d);f&&j(f.label)},[d,n]);const D=()=>{if(!x.trim())return;r(x);const f=x.trim().toLowerCase().replace(/\s+/g,"-");_(""),v(!1),setTimeout(()=>m(f),100)},b=n.find(f=>f.value===d);return e.jsxs("div",{className:`${t.configPanel} ${t.flex1}`,children:[e.jsxs("div",{className:`${t.headerFlex}`,style:{marginBottom:b&&!h||h?"20px":"0"},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{id:"type-config-label",className:t.label,style:{display:"none"},children:"Select Type"}),e.jsx(Ko,{value:d,options:[{value:"",label:"Select a type to configure...",icon:"HelpCircle",color:"var(--text-secondary)"},...n.map(f=>({value:f.value,label:f.label,icon:ko[f.value]?.icon||"Box",color:ko[f.value]?.color||"violet-500"}))],onChange:f=>{m(String(f)),v(!1)},disabled:h,ariaLabelledBy:"type-config-label"})]}),h?e.jsx("button",{type:"button",className:`${t.browseBtn} ${t.cancelBtnRed}`,onClick:()=>v(!1),title:"Cancel creation",children:e.jsx(ga,{size:18})}):e.jsx("button",{type:"button",className:t.browseBtn,onClick:()=>v(!0),title:"Create new type",children:e.jsx(cn,{size:18})})]}),h&&e.jsxs("div",{className:`${t.configItem} ${t.marginBottom16}`,children:[e.jsx("div",{className:`${t.labelRow} ${t.marginBottom8}`,children:e.jsx("label",{className:t.settingsLabel,children:"New Type Label"})}),e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsx("input",{type:"text",className:t.input,placeholder:"e.g. Bug, Feature, Chore...",value:x,onChange:f=>_(f.target.value),onKeyDown:f=>{f.key==="Enter"&&D()},autoFocus:!0}),e.jsx("button",{type:"button",className:t.saveSettingsBtn,onClick:D,disabled:!x.trim(),children:"Create"})]})]}),b&&!h&&e.jsxs("div",{className:t.flex1,children:[e.jsx("div",{className:`${t.configDivider} ${t.marginBottom20}`}),e.jsx("div",{className:t.flexBetweenCenter,children:e.jsxs("div",{className:`${t.flexColGap4} ${t.flex1}`,children:[e.jsx("label",{className:`${t.label} ${t.inputLabel}`,children:"Label"}),e.jsxs("div",{className:t.gridConfig,children:[e.jsx("input",{className:t.inputDisabledOpacity,value:R,readOnly:!0,disabled:!0}),e.jsxs("button",{type:"button",onClick:()=>{confirm(`Delete type "${b.label}"?`)&&(u(b.value),m(""))},title:"Delete Type",className:`${t.destructiveBtn} ${t.deleteBtnMedium}`,children:[e.jsx(yo,{size:14,className:t.trashIcon})," Delete"]})]})]})}),e.jsx("p",{className:`${t.settingsHint} ${t.marginTop12}`,children:"Note: Renaming types is currently not supported to maintain task integrity. Delete and recreate if necessary."})]}),!b&&!h&&e.jsx("div",{className:t.emptyStateItalic,style:{border:"none",background:"transparent"},children:"Select a type above to manage"})]})}function Nj(a){const{taxonomies:n,onUpdateTaxonomies:r,categories:u,pathValidation:d,onUpdateCategory:m,onRemoveCategory:h,onSaveCategory:v,onAddPath:x,onRemovePath:_,onUpdateCategoryIcon:R,onUpdateCategoryColor:j,onBrowseFolders:D,types:b,onSaveType:f,onRemoveType:I,priorities:$,onUpdatePriorities:z,approaches:w,onUpdateApproaches:T,manualComplexityEnabled:Z,onManualComplexityEnabledChange:Ne,initialTab:J}=a,[he,ce]=s.useState(J||""),[W,U]=s.useState(J?"detail":"list"),[Ge,ye]=s.useState(!1),[ke,Ae]=s.useState(""),se=()=>{if(!ke.trim())return;const ne=ke.toLowerCase().trim().replace(/\s+/g,"-");if(n.some(dt=>dt.id===ne)){alert("A taxonomy with this ID already exists");return}const le={id:ne,label:ke.trim(),options:[],widgetType:"select",isSystem:!1,multiSelect:!1};r([...n,le]),Ae(""),ye(!1),ce(ne),U("detail")},Ye=ne=>{r(n.map(le=>le.id===ne.id?ne:le))},We=ne=>{const le=n.filter(dt=>dt.id!==ne);r(le),U("list")},Fe=ne=>{ce(ne),U("detail")},te=n.find(ne=>ne.id===he);return W==="list"?e.jsxs("div",{className:t.taxonomyDrillDown,children:[e.jsxs("div",{className:t.drillDownList,children:[e.jsxs("div",{className:t.drillDownSection,children:[e.jsx("h4",{className:t.drillDownSectionTitle,children:"System Taxonomies"}),e.jsxs("button",{className:t.drillDownItem,onClick:()=>Fe("categories"),children:[e.jsxs("div",{className:t.drillDownItemInfo,children:[e.jsx(xi,{size:16,className:t.systemIcon}),e.jsxs("div",{className:t.drillDownItemText,children:[e.jsx("span",{className:t.drillDownItemLabel,children:"Categories"}),e.jsxs("span",{className:t.drillDownItemSubtext,children:[u.length," configured"]})]})]}),e.jsx(la,{size:16,className:t.chevron})]}),e.jsxs("button",{className:t.drillDownItem,onClick:()=>Fe("types"),children:[e.jsxs("div",{className:t.drillDownItemInfo,children:[e.jsx(xi,{size:16,className:t.systemIcon}),e.jsxs("div",{className:t.drillDownItemText,children:[e.jsx("span",{className:t.drillDownItemLabel,children:"Task Types"}),e.jsxs("span",{className:t.drillDownItemSubtext,children:[b.length," active"]})]})]}),e.jsx(la,{size:16,className:t.chevron})]}),e.jsxs("button",{className:t.drillDownItem,onClick:()=>Fe("priorities"),children:[e.jsxs("div",{className:t.drillDownItemInfo,children:[e.jsx(xi,{size:16,className:t.systemIcon}),e.jsxs("div",{className:t.drillDownItemText,children:[e.jsx("span",{className:t.drillDownItemLabel,children:"Priority Levels"}),e.jsxs("span",{className:t.drillDownItemSubtext,children:[$.length," levels"]})]})]}),e.jsx(la,{size:16,className:t.chevron})]}),e.jsxs("button",{className:t.drillDownItem,onClick:()=>Fe("approaches"),children:[e.jsxs("div",{className:t.drillDownItemInfo,children:[e.jsx(xi,{size:16,className:t.systemIcon}),e.jsxs("div",{className:t.drillDownItemText,children:[e.jsx("span",{className:t.drillDownItemLabel,children:"Approach Options"}),e.jsxs("span",{className:t.drillDownItemSubtext,children:[w.length," options"]})]})]}),e.jsx(la,{size:16,className:t.chevron})]}),e.jsxs("button",{className:`${t.drillDownItem} ${Z?"":t.drillDownItemDimmed}`,onClick:()=>Fe("complexities"),children:[e.jsxs("div",{className:t.drillDownItemInfo,children:[e.jsx(xi,{size:16,className:t.systemIcon}),e.jsxs("div",{className:t.drillDownItemText,children:[e.jsx("span",{className:t.drillDownItemLabel,children:"Complexity"}),e.jsx("span",{className:t.drillDownItemSubtext,children:Z?"Enabled":"Disabled (default)"})]})]}),e.jsx(la,{size:16,className:t.chevron})]})]}),e.jsxs("div",{className:t.drillDownSection,children:[e.jsxs("div",{className:t.drillDownSectionHeader,children:[e.jsx("h4",{className:t.drillDownSectionTitle,children:"Custom Taxonomies"}),e.jsxs("button",{className:t.addTaxonomyBtnSmall,onClick:()=>ye(!0),title:"Add Custom Taxonomy",children:[e.jsx(cn,{size:14})," New"]})]}),n.length===0?e.jsx("div",{className:t.emptyState,children:e.jsx("p",{children:"No custom taxonomies yet."})}):n.map(ne=>e.jsxs("button",{className:t.drillDownItem,onClick:()=>Fe(ne.id),children:[e.jsxs("div",{className:t.drillDownItemInfo,children:[e.jsx(uu,{size:16}),e.jsxs("div",{className:t.drillDownItemText,children:[e.jsx("span",{className:t.drillDownItemLabel,children:ne.label}),e.jsxs("span",{className:t.drillDownItemSubtext,children:[ne.options.length," options"]})]})]}),e.jsx(la,{size:16,className:t.chevron})]},ne.id))]})]}),Ge&&e.jsx("div",{className:t.createOverlay,children:e.jsxs("div",{className:t.createDialog,children:[e.jsx("h3",{children:"New Taxonomy"}),e.jsxs("div",{className:t.inputGroup,children:[e.jsx("label",{className:t.label,children:"Name"}),e.jsx("input",{className:t.input,placeholder:"e.g. Sprint, Phase",value:ke,onChange:ne=>Ae(ne.target.value),autoFocus:!0})]}),e.jsxs("div",{className:t.dialogActions,children:[e.jsx("button",{className:t.submitBtn,onClick:se,disabled:!ke.trim(),children:"Create"}),e.jsx("button",{className:t.cancelBtn,onClick:()=>{ye(!1),Ae("")},children:"Cancel"})]})]})})]}):e.jsxs("div",{className:t.taxonomyDetailView,children:[e.jsx("div",{className:t.detailHeader,children:e.jsxs("div",{className:t.taxonomyBreadcrumbs,children:[e.jsxs("button",{className:t.breadcrumbPrev,onClick:()=>U("list"),title:"Back to All Taxonomies",children:[e.jsx(kd,{size:16,style:{marginRight:"6px"}}),"Taxonomies"]}),e.jsx(la,{size:14,className:t.breadcrumbDivider}),e.jsx("h3",{className:t.breadcrumbActive,children:he==="categories"?"Categories":he==="types"?"Task Types":he==="priorities"?"Priority Levels":he==="complexities"?"Complexity":he==="approaches"?"Approach Options":te?.label||"Taxonomy"})]})}),e.jsx("div",{className:t.detailContent,children:he==="categories"?e.jsx(jj,{categories:u,pathValidation:d,onUpdateCategory:m,onRemoveCategory:h,onSaveCategory:v,onAddPath:x,onRemovePath:_,onUpdateCategoryIcon:R,onUpdateCategoryColor:j,onBrowseFolders:D}):he==="types"?e.jsx(Tj,{types:b,onSaveType:f,onRemoveType:I}):he==="complexities"?e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h4",{className:t.settingSubtitle,children:"Complexity"}),e.jsx("p",{className:t.settingsHint,children:"Complexity is estimated by AI and system logic by default."}),e.jsx("p",{className:t.settingsHint,children:"Enable this to let users set complexity manually and show the Complexity field in Add/Edit Task. When disabled, the Complexity field is hidden from the task form."}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("input",{type:"checkbox",checked:Z,onChange:ne=>{Ne(ne.target.checked)}}),e.jsx("span",{children:"Manual Complexity"})]})]}):te?e.jsx(wl,{taxonomy:te,onUpdateTaxonomy:Ye,onRemoveTaxonomy:We}):he==="priorities"?e.jsx(wl,{taxonomy:{id:"priorities",label:"Priority Levels",isSystem:!0,widgetType:"level",multiSelect:!1,options:$},onUpdateTaxonomy:ne=>z(ne.options)}):he==="approaches"?e.jsx(wl,{taxonomy:{id:"approaches",label:"Approach Options",isSystem:!0,widgetType:"select",multiSelect:!1,options:w},onUpdateTaxonomy:ne=>T(ne.options)}):e.jsxs("div",{className:t.emptyState,children:[e.jsx("p",{children:"Taxonomy not found."}),e.jsx("button",{className:t.submitBtn,onClick:()=>U("list"),children:"Return to List"})]})})]})}const Ij={do:["aliasesText","dispatchDefault","criticalToolsText","contentDefault"],execute:["aliasesText","dispatchDefault","criticalToolsText","contentDefault"]},nd=["do","evaluate","collaborate","plan","review","execute"];function Fr(a){return{description:a.description||"",aliasesText:(a.dispatch?.aliases||[]).join(", "),dispatchDefault:a.dispatch?.default||"",criticalToolsText:(a.compat?.requiredToolsCritical||[]).join(`
8
- `),optionalToolsText:(a.compat?.requiredToolsOptional||[]).join(`
9
- `),contentDefault:a.content?.default||""}}function uo(a){return a.split(/\n|,/).map(n=>n.trim()).filter(Boolean)}function Aj(a){return Array.from(new Set(a.map(n=>n.trim()).filter(Boolean)))}function Dj(a){const{availableWorkflows:n,onFetchWorkflowTemplate:r,onFetchWorkflowOverrideNames:u,onSaveWorkflowTemplateDraft:d,onResetWorkflowTemplateDraft:m}=a,[h,v]=s.useState(""),[x,_]=s.useState(!1),[R,j]=s.useState(null),[D,b]=s.useState(null),[f,I]=s.useState(null),[$,z]=s.useState(null),[w,T]=s.useState(!1),[Z,Ne]=s.useState(!1),[J,he]=s.useState([]),[ce,W]=s.useState(""),[U,Ge]=s.useState(""),[ye,ke]=s.useState(""),Ae=s.useMemo(()=>{const B=nd.filter(et=>n.includes(et)),oe=n.filter(et=>!nd.includes(et)).sort((et,yt)=>et.localeCompare(yt));return[...B,...oe]},[n]);s.useEffect(()=>{!h&&Ae.length>0&&v(Ae[0])},[Ae,h]),s.useEffect(()=>{let B=!1;return(async()=>{if(!u)return;const et=await u();B||he(et)})(),()=>{B=!0}},[u,n]),s.useEffect(()=>{let B=!1;return(async()=>{if(!h||!r)return;_(!0),j(null);const et=await r(h);if(B)return;if(!et){b(null),I(null),j("Unable to load workflow template. Reload Taskforce, and if needed restart the dev/server process."),_(!1);return}const yt=et;b(yt),I(Fr(yt)),_(!1)})(),()=>{B=!0}},[h,r]);const se=s.useMemo(()=>{if(!f)return[];const B=[];return f.description.trim()||B.push("Description is required."),f.dispatchDefault.trim()||B.push("Dispatch default is required."),uo(f.criticalToolsText).length===0&&B.push("At least one critical tool is required."),f.contentDefault.trim()||B.push("Default content cannot be empty."),B},[f]),Ye=s.useMemo(()=>Ij[h]||[],[h]),We=B=>Ye.includes(B),Fe=s.useMemo(()=>{if(!D||!f)return[];const B=Fr(D),oe=[];return B.description!==f.description&&oe.push("description"),B.aliasesText!==f.aliasesText&&oe.push("aliases"),B.dispatchDefault!==f.dispatchDefault&&oe.push("dispatch.default"),B.criticalToolsText!==f.criticalToolsText&&oe.push("compat.requiredToolsCritical"),B.optionalToolsText!==f.optionalToolsText&&oe.push("compat.requiredToolsOptional"),B.contentDefault!==f.contentDefault&&oe.push("content.default"),oe},[D,f]),te=s.useMemo(()=>!D||!f?"":[`# ${D.name} (Prototype Preview)`,"",`Description: ${f.description}`,`Aliases: ${f.aliasesText||"(none)"}`,`Dispatch default: ${f.dispatchDefault||"(none)"}`,"","## Critical Tools",...uo(f.criticalToolsText).map(B=>`- ${B}`),"","## Optional Tools",...uo(f.optionalToolsText).map(B=>`- ${B}`),"","## Prompt Content Preview",f.contentDefault].join(`
10
- `),[D,f]),ne=s.useMemo(()=>D?Fr(D):null,[D]),le=s.useMemo(()=>{if(!ne||!f)return[];const B=[],oe=(et,yt,ut)=>{yt!==ut&&B.push({field:et,before:yt,after:ut})};return oe("description",ne.description,f.description),oe("aliases",ne.aliasesText,f.aliasesText),oe("dispatch.default",ne.dispatchDefault,f.dispatchDefault),oe("compat.requiredToolsCritical",ne.criticalToolsText,f.criticalToolsText),oe("compat.requiredToolsOptional",ne.optionalToolsText,f.optionalToolsText),oe("content.default",ne.contentDefault,f.contentDefault),B},[ne,f]),dt=()=>{D&&I(Fr(D))},ae=async()=>{te&&await navigator.clipboard.writeText(te)},q=async()=>{if(!h||!f||se.length>0||!d)return;T(!0),z(null);const B=await d(h,f);if(!B.success){z({type:"error",message:B.error||"Failed to save workflow draft."}),T(!1);return}const oe=r?await r(h):null;if(oe&&(b(oe),I(Fr(oe))),z({type:"success",message:"Workflow draft saved and templates regenerated."}),u){const et=await u();he(et)}T(!1)},M=async()=>{if(!h||!m)return;Ne(!0),z(null);const B=await m(h);if(!B.success){z({type:"error",message:B.error||"Failed to reset workflow override."}),Ne(!1);return}const oe=r?await r(h):null;if(oe&&(b(oe),I(Fr(oe))),z({type:"success",message:"Workflow override reset and templates regenerated."}),u){const et=await u();he(et)}Ne(!1)},Q=(B,oe)=>{if(!f)return;const et=Aj(oe).join(`
11
- `);I({...f,[B]:et})},de=(B,oe)=>{const et=uo(f?.[B]||"");Q(B,et.filter(yt=>yt!==oe))},xe=(B,oe,et)=>{if(!f||!oe.trim())return;const yt=uo(f[B]||"");Q(B,[...yt,oe]),et()};return e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Workflow Editor (Prototype)"}),e.jsx("p",{className:t.settingsHint,children:"Prototype editor: inspect workflow structure, edit a draft, validate, preview, and save via override layer. Critical fields are locked for `do` and `execute`."}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,htmlFor:"workflow-editor-select",children:"Workflow"}),e.jsx("select",{id:"workflow-editor-select",className:t.input,value:h,onChange:B=>v(B.target.value),children:Ae.map(B=>e.jsx("option",{value:B,children:J.includes(B)?`${B} (override)`:B},B))})]}),x&&e.jsxs("div",{className:t.settingsHint,children:[e.jsx(aa,{size:14,className:t.spinner})," Loading template..."]}),R&&e.jsx("div",{className:t.errorMessage,children:R}),f&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`${t.exportRow} ${t.exportRowGrid}`,style:{marginTop:12},children:[e.jsxs("div",{className:t.exportItem,children:[e.jsx("label",{className:t.label,children:"Description"}),e.jsx("input",{className:t.input,value:f.description,onChange:B=>I({...f,description:B.target.value}),disabled:We("description")}),e.jsx("label",{className:t.label,children:"Aliases (comma-separated)"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("input",{className:t.input,value:ce,onChange:B=>W(B.target.value),placeholder:"Add alias (e.g. /execute)",disabled:We("aliasesText")}),e.jsx("button",{className:t.secondaryHeaderBtn,onClick:()=>xe("aliasesText",ce,()=>W("")),disabled:We("aliasesText")||!ce.trim(),children:"Add"})]}),e.jsx("div",{className:t.workflowActions,children:uo(f.aliasesText).map(B=>e.jsxs("button",{className:t.textBtn,onClick:()=>de("aliasesText",B),disabled:We("aliasesText"),children:[B," ×"]},B))}),e.jsx("label",{className:t.label,children:"Dispatch Default"}),e.jsx("input",{className:t.input,value:f.dispatchDefault,onChange:B=>I({...f,dispatchDefault:B.target.value}),disabled:We("dispatchDefault")})]}),e.jsxs("div",{className:t.exportItem,children:[e.jsx("label",{className:t.label,children:"Critical Tools (one per line)"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("input",{className:t.input,value:U,onChange:B=>Ge(B.target.value),placeholder:"Add critical tool id",disabled:We("criticalToolsText")}),e.jsx("button",{className:t.secondaryHeaderBtn,onClick:()=>xe("criticalToolsText",U,()=>Ge("")),disabled:We("criticalToolsText")||!U.trim(),children:"Add"})]}),e.jsx("div",{className:t.workflowActions,children:uo(f.criticalToolsText).map(B=>e.jsxs("button",{className:t.textBtn,onClick:()=>de("criticalToolsText",B),disabled:We("criticalToolsText"),children:[B," ×"]},B))}),e.jsx("label",{className:t.label,children:"Optional Tools (one per line)"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("input",{className:t.input,value:ye,onChange:B=>ke(B.target.value),placeholder:"Add optional tool id",disabled:We("optionalToolsText")}),e.jsx("button",{className:t.secondaryHeaderBtn,onClick:()=>xe("optionalToolsText",ye,()=>ke("")),disabled:We("optionalToolsText")||!ye.trim(),children:"Add"})]}),e.jsx("div",{className:t.workflowActions,children:uo(f.optionalToolsText).map(B=>e.jsxs("button",{className:t.textBtn,onClick:()=>de("optionalToolsText",B),disabled:We("optionalToolsText"),children:[B," ×"]},B))})]})]}),e.jsx("label",{className:t.label,children:"Default Prompt Content"}),e.jsx("textarea",{className:t.input,rows:12,value:f.contentDefault,onChange:B=>I({...f,contentDefault:B.target.value}),disabled:We("contentDefault")}),e.jsxs("div",{className:t.pathInputGroup,style:{marginTop:12},children:[e.jsxs("button",{className:t.secondaryHeaderBtn,onClick:dt,children:[e.jsx(zl,{size:14}),"Reset Draft"]}),e.jsxs("button",{className:t.secondaryHeaderBtn,onClick:ae,children:[e.jsx(Wr,{size:14}),"Copy Preview"]}),e.jsxs("button",{className:t.secondaryHeaderBtn,onClick:q,disabled:w||se.length>0||Fe.length===0,children:[w?e.jsx(aa,{size:14,className:t.spinner}):null,"Save Draft"]}),e.jsxs("button",{className:t.secondaryHeaderBtn,onClick:M,disabled:Z,children:[Z?e.jsx(aa,{size:14,className:t.spinner}):null,"Rollback Override"]})]}),Fe.length>0&&e.jsxs("div",{className:t.settingsHint,children:["Changed fields: ",Fe.join(", ")]}),Ye.length>0&&e.jsxs("div",{className:t.settingsHint,children:["Locked fields for `",h,"`: ",Ye.join(", ")]}),se.length===0?e.jsx("div",{className:t.successMessage,children:"Draft validation: ready for prototype review."}):e.jsx("div",{className:t.errorMessage,children:se.map(B=>e.jsx("div",{children:B},B))}),$&&e.jsx("div",{className:$.type==="success"?t.successMessage:t.errorMessage,children:$.message}),le.length>0&&e.jsxs("div",{className:t.codeBlockWrapper,style:{marginTop:12},children:[e.jsx("div",{className:t.codeHeader,children:e.jsx("span",{className:t.codeLabel,children:"Field Diff (Before / After)"})}),le.map(B=>e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("div",{className:t.settingsHint,children:e.jsx("strong",{children:B.field})}),e.jsxs("div",{className:`${t.exportRow} ${t.exportRowGrid}`,children:[e.jsxs("div",{className:t.exportItem,children:[e.jsx("div",{className:t.settingsHint,children:"Before"}),e.jsx("pre",{className:t.codeBlock,children:B.before||"(empty)"})]}),e.jsxs("div",{className:t.exportItem,children:[e.jsx("div",{className:t.settingsHint,children:"After"}),e.jsx("pre",{className:t.codeBlock,children:B.after||"(empty)"})]})]})]},B.field))]}),e.jsxs("div",{className:t.codeBlockWrapper,style:{marginTop:12},children:[e.jsx("div",{className:t.codeHeader,children:e.jsx("span",{className:t.codeLabel,children:"Prototype Preview"})}),e.jsx("pre",{className:t.codeBlock,children:te})]})]})]})}const Bj={};function Gd(a){const{settingsModel:n,onSectionChange:r}=a,{currentTheme:u,globalTheme:d,themeUseGlobalDefault:m,keyShortcut:h,jsonBackupEnabled:v,globalJsonBackupEnabled:x,globalWeekStartsOn:_,locale:R="en-US",supportedLocales:j=["en-US","es-419","pt-BR"],jsonBackupUseGlobalDefault:D,manualComplexityEnabled:b,checklistDropdownEnabled:f=!1,assigneeFilterEnabled:I=!1,exportWorkflowsPath:$,exportSpecialistsPath:z,exportingResource:w,exportResult:T,initialSection:Z,onThemeChange:Ne,onSaveTheme:J,onSaveGlobalTheme:he,onResetProjectToGlobal:ce,onKeyShortcutChange:W,onJsonBackupEnabledChange:U,onSaveGlobalJsonBackupEnabled:Ge,onSaveGlobalWeekStartsOn:ye,onSaveLocale:ke,onManualComplexityEnabledChange:Ae,onChecklistDropdownEnabledChange:se,onAssigneeFilterEnabledChange:Ye,onSaveSettings:We,onExportWorkflowsPathChange:Fe,onExportSpecialistsPathChange:te,onExportResources:ne,onShowFolderBrowserChange:le,onBrowserTargetChange:dt,onFetchFolders:ae,categories:q,pathValidation:M,onUpdateCategory:Q,onRemoveCategory:de,onSaveCategory:xe,onAddPath:B,onRemovePath:oe,onUpdateCategoryIcon:et,onUpdateCategoryColor:yt,types:ut,onSaveType:mt,onRemoveType:kt,taxonomies:Dt,onUpdateTaxonomies:Mt,priorities:Zt,onUpdatePriorities:tt,approaches:pt,onUpdateApproaches:Rt,projectRoot:wt,projectName:Ut,mcpHostRoot:V,serverHostRoot:Pe,mcpScriptPath:_e,tenantId:Le,workspaceId:ze,runtimeMode:N="local",workspaceSwitchingEnabled:G=!1,currentWorkspaceRole:je="member",currentWorkspaceName:Ie="",onDeleteWorkspace:we,onMcpHostRootChange:qe,isAuthenticated:vt=!1,exportEnvironment:st,setupState:Re=null,buildInfo:bt=null,onExportEnvironmentChange:De,onSaveSetupMode:Jt,onSaveWorkspaceProfile:St,availableWorkflows:ls=[],onExportWorkflows:Ee,initiativeTemplates:zt=[],onRefreshInitiativeTemplates:ts,onCreateInitiativeFromTemplate:Et,onCloneChecklistBlocksToChildren:qt,onRefreshWorkflows:Ct,onFetchWorkflowTemplate:As,onFetchWorkflowOverrideNames:ds,onSaveWorkflowTemplateDraft:Ss,onResetWorkflowTemplateDraft:Ds}=n,[us,Cs]=s.useState([]);s.useEffect(()=>{ls.length>0&&us.length===0&&Cs(ls)},[ls]);const L=P=>{Cs(S=>S.includes(P)?S.filter(Y=>Y!==P):[...S,P])},F=()=>Cs(ls),re=()=>Cs([]),[K,H]=s.useState(null),[me,Oe]=s.useState(()=>Re?.mode==="operations"?"operations":"core"),[ie,ve]=s.useState(()=>String(Re?.workspace?.name||"").trim()),[_t,Se]=s.useState(()=>String(Re?.workspace?.description||"")),[Ue,ht]=s.useState("personal"),[nt,It]=s.useState(!1),[jt,Vt]=s.useState(null),[rt,ot]=s.useState(""),[y,ue]=s.useState(""),[Ke,At]=s.useState(""),[ps,Kt]=s.useState(""),[Lt,vs]=s.useState(""),[Ms,Bs]=s.useState(""),[Qe,ft]=s.useState(!1),[ss,Xt]=s.useState(!1),[Xe,at]=s.useState(!1),[Bt,bs]=s.useState("unknown"),[xt,$t]=s.useState("general"),[O,Ve]=s.useState(()=>"project");s.useEffect(()=>{zt.length>0&&!rt&&ot(zt[0].id)},[zt,rt]),s.useEffect(()=>{if(!K)return;const P=setTimeout(()=>H(null),2500);return()=>clearTimeout(P)},[K]),s.useEffect(()=>{Oe(Re?.mode==="operations"?"operations":"core")},[Re?.mode]),s.useEffect(()=>{ve(String(Re?.workspace?.name||"").trim()),Se(String(Re?.workspace?.description||""))},[Re?.workspace?.name,Re?.workspace?.description]),s.useEffect(()=>{if(xt!=="general"||O!=="project"||!vt)return;let P=!1;return(async()=>{It(!0),Vt(null);try{const S=await fetch("/api/taskforce/account/entitlements",{method:"GET",credentials:"include"}),Y=await S.json().catch(()=>({}));if(P)return;if(!S.ok){Vt(String(Y?.error||"Failed to load account entitlements."));return}const pe=String(Y?.planId||"").trim().toLowerCase();ht(pe==="team"?"team":"personal")}catch{P||Vt("Failed to load account entitlements.")}finally{P||It(!1)}})(),()=>{P=!0}},[xt,O,vt]);const Ft=async P=>{Ne(P);const S=await J(P);H({type:S?"success":"error",message:S?"Project theme saved.":"Failed to save project theme."})},[Tt,Ot]=s.useState(!1),[Je,Yt]=s.useState(!0),[Ht,Ls]=s.useState(!1),Us=(P,S)=>String(P||"").toLowerCase().replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"")||S.toLowerCase(),qs=()=>{let P=_e||"",S=wt||"";const Y=V||Pe;if(Y&&wt){if(_e&&_e.startsWith(wt))P=_e.replace(wt,Y);else if(_e&&_e.includes("/node_modules/")){const Ca=_e.indexOf("/node_modules/");P=Y+_e.substring(Ca)}S=Y}const pe=(_e||"").endsWith(".ts"),Te=Ut||(wt?wt.split(/[/\\]/).pop():"project"),Nt=Us(`taskforce-${Te}`,"taskforce-project"),Ze=(Le||"").trim()||"your-tenant-id",$e=(ze||Re?.workspaceId||"").trim(),as={TASKFORCE_TENANT_ID:Ze,TASKFORCE_WORKSPACE_ID:$e&&$e!=="default"?$e:"your-workspace-id"},Ns=Je?{command:"taskforce",args:["mcp",S||"."],env:as}:{command:pe?"npx":"node",args:pe?["-y","tsx",P,S]:[P,S],env:as};return!Je&&!Ns.args[Ns.args.length-1]&&(Ns.args[Ns.args.length-1]=".../path/to/project/root"),{serverId:Nt,serverConfig:Ns}},ya=(P="full")=>{if(!_e&&!Je)return;const{serverId:S,serverConfig:Y}=qs(),pe=P==="full"?JSON.stringify({mcpServers:{[S]:Y}},null,2):`"${S}": ${JSON.stringify(Y,null,2)}`;navigator.clipboard.writeText(pe),Ot(P),setTimeout(()=>Ot(!1),2e3)};s.useEffect(()=>{xt==="initiatives"&&zt.length===0&&ts?.()},[xt,zt.length,ts]),s.useEffect(()=>{if(xt!=="documents")return;let P=!1;return(async()=>{at(!0);try{const Y=await(await fetch("/api/taskforce/config",{credentials:"include"})).json().catch(()=>({}));if(P)return;const pe=Y?.objectStorage?.provider==="r2"?"r2":"local";bs(pe)}catch{P||bs("unknown")}finally{P||at(!1)}})(),()=>{P=!0}},[xt]);const na=()=>{const P=String(Bj?.VITE_TASKFORCE_ADMIN_APP_URL||"").trim();if(P)return P.replace(/\/+$/,"");if(typeof window>"u")return"https://admin.taskforcehq.ai";const{protocol:S,hostname:Y}=window.location;return Y==="localhost"||Y==="127.0.0.1"?"http://localhost:5181":Y.startsWith("app.")?`${S}//admin.${Y.slice(4)}`:`${S}//admin.${Y}`},Vs=n.availableEnvironments||[],ua=P=>{switch(P){case"Bot":return e.jsx(_c,{size:16});case"Terminal":return e.jsx(Ml,{size:16});case"Sparkles":return e.jsx(vc,{size:16});case"Command":return e.jsx(gu,{size:16});case"Wind":return e.jsx(fu,{size:16});case"Github":return e.jsx(mu,{size:16});case"Zap":return e.jsx(Jo,{size:16});case"Box":return e.jsx(Tc,{size:16});default:return e.jsx(hu,{size:16})}};s.useEffect(()=>{Z&&$t(Z==="categories"||Z==="types"?"taxonomy":Z==="documents"?"documents":Z==="workflow-editor"?"workflowEditor":Z==="resources"||Z==="commands"?"commands":Z==="initiatives"?"initiatives":Z==="agents"?"agents":Z)},[Z]);const $s=P=>{dt({type:"category",value:P}),ae(""),le(!0)};return e.jsxs("div",{className:t.settingsTab,children:[e.jsxs("div",{className:t.settingsTabs,children:[e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="general"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("general"),r?.("general")},children:[e.jsx(_i,{size:14})," General"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="documents"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("documents"),r?.("documents")},children:[e.jsx(Cl,{size:14})," Documents"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="commands"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("commands"),r?.("commands")},children:[e.jsx(Ml,{size:14})," Commands"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="initiatives"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("initiatives"),r?.("initiatives")},children:[e.jsx(Jo,{size:14})," Initiatives"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="workflowEditor"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("workflowEditor"),r?.("workflow-editor")},children:[e.jsx(Xo,{size:14})," Workflows"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="agents"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("agents"),r?.("agents")},children:[e.jsx(_c,{size:14})," Agents"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="taxonomy"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("taxonomy"),r?.("taxonomy")},children:[e.jsx(bi,{size:14})," Taxonomies"]}),e.jsxs("button",{className:`${t.settingsTabBtn} ${xt==="mcp"?t.settingsTabBtnActive:""}`,onClick:()=>{$t("mcp"),r?.("mcp")},children:[e.jsx(Tc,{size:14})," MCP"]})]}),e.jsxs("div",{className:t.settingsContent,children:[K&&e.jsxs("div",{className:`${t.settingsToast} ${K.type==="success"?t.settingsToastSuccess:t.settingsToastError}`,children:[K.type==="success"?e.jsx(Sa,{size:14}):e.jsx(mo,{size:14}),e.jsx("span",{children:K.message})]}),xt==="general"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:t.settingGroup,children:e.jsxs("div",{className:t.settingTitleRow,children:[e.jsx("h3",{className:t.settingTitle,children:O==="project"?"Project Settings":"Global Settings"}),e.jsxs("div",{className:t.settingsTabs,children:[e.jsx("button",{className:`${t.settingsTabBtn} ${O==="project"?t.settingsTabBtnActive:""}`,onClick:()=>Ve("project"),children:"Project"}),e.jsx("button",{className:`${t.settingsTabBtn} ${O==="global"?t.settingsTabBtnActive:""}`,onClick:()=>Ve("global"),children:"Global"})]}),O==="project"&&e.jsx("button",{onClick:async()=>{if(!window.confirm("Reset project Theme and Backups to global defaults?"))return;const S=await ce();H({type:S?"success":"error",message:S?"Project settings reset to global.":"Failed to reset project settings."})},className:t.copyBtn,children:"Reset to Global"})]})}),O==="project"&&e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Workspace Profile"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsxs("label",{className:t.label,style:{minWidth:"110px"},children:[me==="operations"?"Mission":"Project"," name:"]}),e.jsx("input",{className:t.input,type:"text",value:ie,onChange:P=>ve(P.target.value),placeholder:me==="operations"?"Mission name":"Project name",style:{maxWidth:"360px"}})]}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"110px"},children:"Description:"}),e.jsx("textarea",{className:t.textarea,value:_t,onChange:P=>Se(P.target.value),placeholder:me==="operations"?"Mission description (optional)":"Project description (optional)",rows:3,style:{maxWidth:"360px"}})]}),e.jsx("div",{className:t.pathInputGroup,children:e.jsx("button",{onClick:async()=>{if(!St)return;const P=await St({workspaceId:Re?.workspaceId,name:ie,description:_t});H({type:P.success?"success":"error",message:P.success?`${me==="operations"?"Mission":"Project"} profile saved.`:P.error||"Failed to save workspace profile."})},className:`${t.saveSettingsBtn} ${t.saveSettingsBtnWrapper}`,disabled:!St,children:"Save Profile"})})]}),O==="project"&&vt&&e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Account Plan"}),e.jsx("p",{className:t.settingHelper,children:"Effective plan state is managed by platform admin and surfaced here as read-only."}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"110px"},children:"Plan mode:"}),e.jsxs("select",{className:t.input,value:Ue,style:{maxWidth:"220px"},disabled:!0,children:[e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"team",children:"Team"})]})]}),nt&&e.jsx("p",{className:t.settingHelper,children:"Loading current account entitlements..."}),jt&&e.jsx("p",{className:t.settingHelper,style:{color:"#fda4af"},children:jt})]}),O==="project"&&e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Theme"}),e.jsxs("div",{className:t.buttonGrid,children:[e.jsxs("button",{className:`${t.themeBtn} ${u==="light"?t.activeTheme:""}`,onClick:()=>{Ft("light")},children:[e.jsx($l,{size:20})," Light"]}),e.jsxs("button",{className:`${t.themeBtn} ${u==="dark"?t.activeTheme:""}`,onClick:()=>{Ft("dark")},children:[e.jsx(Fl,{size:20})," Dark"]}),e.jsxs("button",{className:`${t.themeBtn} ${u==="midnight"?t.activeTheme:""}`,onClick:()=>{Ft("midnight")},children:[e.jsx(vc,{size:20})," Midnight"]})]}),e.jsx("h3",{className:t.settingTitle,children:"Backup"}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("input",{type:"checkbox",checked:v,onChange:async P=>{const S=await U(P.target.checked);H({type:S?"success":"error",message:S?"Project backup setting saved.":"Failed to save project backup setting."})}}),e.jsx("span",{children:"Enable automatic JSON backup (`.taskforce/tasks.json`)"})]}),e.jsx("h3",{className:t.settingTitle,children:"Task Form"}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("input",{type:"checkbox",checked:f,onChange:async P=>{if(!se)return;const S=await se(P.target.checked);H({type:S?"success":"error",message:S?"Checklist dropdown setting saved.":"Failed to save checklist dropdown setting."})},disabled:!se}),e.jsx("span",{children:"Enable checklist dropdown in task form"})]}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("input",{type:"checkbox",checked:I,onChange:async P=>{if(!Ye)return;const S=await Ye(P.target.checked);H({type:S?"success":"error",message:S?"Assignee filter setting saved.":"Failed to save assignee filter setting."})},disabled:!Ye}),e.jsx("span",{children:"Enable assignee filter in task views"})]})]}),O==="global"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Operating Mode"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"110px"},children:"Mode:"}),e.jsxs("select",{className:t.input,value:me,onChange:P=>Oe(P.target.value==="operations"?"operations":"core"),style:{maxWidth:"220px"},children:[e.jsx("option",{value:"core",children:"Core (Project)"}),e.jsx("option",{value:"operations",children:"Operations (Mission)"})]}),e.jsx("button",{onClick:async()=>{if(!Jt)return;const P=await Jt(me);H({type:P?"success":"error",message:P?"Operating mode saved.":"Failed to save operating mode."})},className:`${t.saveSettingsBtn} ${t.saveSettingsBtnWrapper}`,disabled:!Jt,children:"Save"})]})]}),e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Theme"}),e.jsxs("div",{className:t.buttonGrid,children:[e.jsxs("button",{className:`${t.themeBtn} ${d==="light"?t.activeTheme:""}`,onClick:async()=>{const P=await he("light");H({type:P?"success":"error",message:P?"Global theme saved.":"Failed to save global theme."})},children:[e.jsx($l,{size:20})," Light"]}),e.jsxs("button",{className:`${t.themeBtn} ${d==="dark"?t.activeTheme:""}`,onClick:async()=>{const P=await he("dark");H({type:P?"success":"error",message:P?"Global theme saved.":"Failed to save global theme."})},children:[e.jsx(Fl,{size:20})," Dark"]}),e.jsxs("button",{className:`${t.themeBtn} ${d==="midnight"?t.activeTheme:""}`,onClick:async()=>{const P=await he("midnight");H({type:P?"success":"error",message:P?"Global theme saved.":"Failed to save global theme."})},children:[e.jsx(vc,{size:20})," Midnight"]})]}),e.jsx("h3",{className:t.settingTitle,children:"Backup"}),e.jsxs("label",{className:t.archiveToggle,children:[e.jsx("input",{type:"checkbox",checked:x,onChange:async P=>{const S=await Ge(P.target.checked);H({type:S?"success":"error",message:S?"Global backup default saved.":"Failed to save global backup default."})}}),e.jsx("span",{children:"Enable global JSON backup default"})]})]}),e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Regional"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"110px"},children:"Calendar start:"}),e.jsxs("select",{className:t.input,value:_,onChange:async P=>{const S=P.target.value,Y=await ye(S);H({type:Y?"success":"error",message:Y?`Week start saved (${S==="sunday"?"Sunday":"Monday"}).`:"Failed to save week start."})},style:{maxWidth:"220px"},children:[e.jsx("option",{value:"sunday",children:"Sunday"}),e.jsx("option",{value:"monday",children:"Monday"})]})]}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"110px"},children:"Language:"}),e.jsx("select",{className:t.input,value:R,onChange:async P=>{const S=P.target.value;if(!ke)return;const Y=await ke(S);H({type:Y?"success":"error",message:Y?`Language saved (${S}).`:"Failed to save language."})},style:{maxWidth:"220px"},disabled:!ke,children:j.map(P=>e.jsx("option",{value:P,children:P},P))})]})]}),e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Keyboard Shortcut"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsxs("div",{className:t.shortcutInputWrapper,children:[e.jsx(pu,{size:16,className:t.inputIcon}),e.jsx("input",{type:"text",value:h,onChange:P=>W(P.target.value),placeholder:"e.g. Alt+T, Ctrl+Shift+K",className:`${t.input} ${t.shortcutInput}`})]}),e.jsx("button",{onClick:async()=>{const P=await We();H({type:P?"success":"error",message:P?"Global shortcut saved.":"Failed to save global shortcut."})},className:`${t.saveSettingsBtn} ${t.saveSettingsBtnWrapper}`,children:"Save"})]}),e.jsxs("p",{className:t.settingHelper,children:["Supported modifiers: Alt, Option, Ctrl, Shift, Meta (Cmd). Example: ",e.jsx("code",{children:"Alt+T"})," or ",e.jsx("code",{children:"Ctrl+Shift+L"}),"."]})]})]}),O==="project"&&e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Danger Zone"}),N!=="cloud"||!G?e.jsx("p",{className:t.settingHelper,children:"Workspace deletion is available in cloud runtime only."}):vt?je!=="owner"?e.jsx("p",{className:t.settingHelper,children:"Only workspace owners can delete a workspace."}):e.jsx("div",{className:t.pathInputGroup,children:e.jsxs("button",{className:t.destructiveBtn,onClick:async()=>{if(!we)return;const P=String(ze||"").trim();if(!P||P==="default"){H({type:"error",message:"A non-default workspace is required for deletion."});return}const S=String(Ie||"").trim(),Y=window.prompt(`Type "${S}" to permanently delete this workspace.`);if(Y===null)return;if(Y.trim()!==S){H({type:"error",message:"Workspace name confirmation did not match."});return}const pe=await we(P);if(!pe.success){H({type:"error",message:pe.error||"Failed to delete workspace."});return}const Te=Array.isArray(pe.cleanupWarnings)?pe.cleanupWarnings.length:0;H({type:Te>0?"error":"success",message:Te>0?`Workspace deleted with ${Te} cleanup warning(s).`:"Workspace deleted."})},disabled:!we,children:[e.jsx(yo,{size:14,style:{marginRight:8}}),"Delete Workspace"]})}):e.jsx("p",{className:t.settingHelper,children:"Sign in to manage workspace deletion."})]})]}),xt==="documents"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"Local Documents"}),e.jsx("p",{className:t.settingHelper,children:"Local document behavior is available to all users and does not require admin permissions."}),e.jsxs("div",{className:`${t.pathInputGroup} ${t.marginTop12}`,children:[e.jsx("label",{className:t.label,style:{minWidth:"110px"},children:"Storage mode:"}),e.jsx("input",{className:t.input,value:Xe?"Loading...":Bt==="r2"?"Cloud (R2)":Bt==="local"?"Local filesystem":"Unavailable",disabled:!0,style:{maxWidth:"260px"}})]}),e.jsx("p",{className:t.settingHelper,children:"Per-user editor preferences are configured directly from the document editor screen."}),Bt==="local"&&e.jsx("p",{className:t.settingHelper,children:"Local documents are stored in `.taskforce/docs` and `.taskforce/task-data/.../attachments`."})]}),e.jsxs("div",{className:`${t.settingGroup} ${t.marginTop16}`,children:[e.jsx("h3",{className:t.settingTitle,children:"Cloud Document Storage"}),vt&&Bt==="r2"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:t.settingHelper,children:"System-level cloud storage and integrity controls are managed in App Admin."}),e.jsx("div",{className:`${t.pathInputGroup} ${t.marginTop12}`,style:{flexWrap:"wrap",alignItems:"center"},children:e.jsx("button",{className:t.copyBtn,onClick:()=>{window.open(na(),"_blank","noopener,noreferrer")},children:"Open App Admin"})})]}):vt&&Bt==="local"?e.jsx("p",{className:t.settingHelper,children:"Cloud storage is not active in this environment. No cloud document settings are currently applied."}):e.jsx("p",{className:t.settingHelper,children:"Sign in to access cloud document storage controls in App Admin."})]})]}),xt==="commands"&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:t.settingGroup,children:[e.jsxs("div",{className:t.settingTitleRow,children:[e.jsx("h3",{className:t.settingTitle,children:"Command Workflows"}),e.jsx("button",{onClick:()=>{$t("workflowEditor"),r?.("workflow-editor")},className:t.copyBtn,children:"Open Workflows"})]}),e.jsx("p",{className:`${t.settingsHint} ${t.marginBottom12}`,children:"Export standard workflows to your project to verify and commit them."}),e.jsxs("div",{className:`${t.exportRow} ${t.exportRowGrid}`,children:[e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h4",{className:`${t.settingSubtitle} ${t.settingSubtitleCustom}`,children:"Target Environment"}),e.jsx("div",{className:t.buttonGrid,children:Vs.map(P=>e.jsxs("button",{onClick:()=>De(P.id),className:`${t.themeBtn} ${st===P.id?t.activeTheme:""} ${t.capitalize}`,children:[ua(P.icon),P.name]},P.id))})]}),e.jsxs("div",{className:t.exportItem,children:[e.jsxs("div",{className:t.labelGroupFlex,children:[e.jsx("label",{className:t.label,children:"Workflows"}),e.jsxs("span",{className:t.settingDescription,children:["Destination: ",e.jsx("code",{className:t.code,children:$})]})]}),e.jsxs("div",{className:t.workflowList,children:[e.jsxs("div",{className:t.workflowActions,children:[e.jsx("button",{onClick:F,className:t.textBtn,children:"All"}),e.jsx("button",{onClick:re,className:t.textBtn,children:"None"})]}),e.jsx("div",{className:t.workflowGrid,children:ls.length===0?e.jsxs("div",{className:t.emptyState,children:["No workflow templates found.",e.jsx("button",{onClick:()=>Ct?.(!0),className:t.secondaryBtn,style:{marginTop:"8px"},children:"Retry Fetch"})]}):ls.map(P=>e.jsxs("label",{className:t.checkboxLabel,children:[e.jsx("input",{type:"checkbox",checked:us.includes(P),onChange:()=>L(P)}),P]},P))})]}),e.jsxs("button",{className:`${t.secondaryHeaderBtn} ${t.marginTop12}`,onClick:()=>Ee?.(st,us),disabled:w==="workflows"||us.length===0,children:[w==="workflows"?e.jsx(aa,{size:14,className:t.spinner}):e.jsx(Xo,{size:14}),"Export Selected (",us.length,")"]})]})]}),T&&e.jsxs("div",{className:`${T.type==="success"?t.successMessage:t.errorMessage} ${t.marginTop12}`,children:[T.type==="success"?e.jsx(Sa,{size:14}):e.jsx(mo,{size:14}),T.message]})]})}),xt==="initiatives"&&e.jsxs("div",{className:t.settingGroup,children:[e.jsxs("div",{className:t.settingTitleRow,children:[e.jsx("h3",{className:t.settingTitle,children:"Initiative Templates"}),e.jsx("button",{className:t.copyBtn,onClick:()=>{ts?.()},children:"Refresh"})]}),e.jsx("p",{className:`${t.settingsHint} ${t.marginBottom12}`,children:"Create launch, migration, or incident initiatives with checklist-ready child milestones."}),e.jsxs("div",{className:t.exportItem,children:[e.jsx("label",{className:t.label,children:"Template"}),e.jsx("select",{className:t.input,value:rt,onChange:P=>{const S=P.target.value;ot(S);const Y=zt.find(pe=>pe.id===S);Y&&(vs((Y.checklistBlocks?.definitionOfDone||[]).join(`
12
- `)),Bs((Y.checklistBlocks?.rollbackPlan||[]).join(`
13
- `)))},children:zt.map(P=>e.jsx("option",{value:P.id,children:P.name},P.id))})]}),e.jsxs("div",{className:`${t.exportItem} ${t.marginTop12}`,children:[e.jsx("label",{className:t.label,children:"Initiative Title"}),e.jsx("input",{className:t.input,placeholder:"e.g. Taskforce Private Beta Launch",value:y,onChange:P=>ue(P.target.value)})]}),e.jsxs("div",{className:`${t.exportItem} ${t.marginTop12}`,children:[e.jsx("label",{className:t.label,children:"Parent Task ID (optional)"}),e.jsx("input",{className:t.input,placeholder:"task-...",value:Ke,onChange:P=>At(P.target.value)})]}),e.jsxs("button",{className:`${t.secondaryHeaderBtn} ${t.marginTop12}`,disabled:Qe||!rt||!y.trim()||!Et,onClick:async()=>{if(!Et)return;ft(!0);const P=await Et({templateId:rt,title:y.trim(),parentTaskId:Ke.trim()||null});ft(!1),H({type:P.success?"success":"error",message:P.success?"Initiative created from template.":P.error||"Failed to create initiative."})},children:[Qe?e.jsx(aa,{size:14,className:t.spinner}):e.jsx(Jo,{size:14}),"Create Initiative"]}),e.jsxs("div",{className:`${t.exportItem} ${t.marginTop12}`,children:[e.jsx("label",{className:t.label,children:"Clone Checklists to Children"}),e.jsx("input",{className:t.input,placeholder:"Parent task ID to update children (task-...)",value:ps,onChange:P=>Kt(P.target.value)}),e.jsx("textarea",{className:`${t.input} ${t.marginTop12}`,rows:4,placeholder:"Definition of Done items, one per line",value:Lt,onChange:P=>vs(P.target.value)}),e.jsx("textarea",{className:`${t.input} ${t.marginTop12}`,rows:4,placeholder:"Rollback Plan items, one per line",value:Ms,onChange:P=>Bs(P.target.value)})]}),e.jsxs("button",{className:`${t.secondaryHeaderBtn} ${t.marginTop12}`,disabled:ss||!ps.trim()||!qt,onClick:async()=>{if(!qt)return;Xt(!0);const P=await qt({parentTaskId:ps.trim(),checklistBlocks:{definitionOfDone:Lt.split(`
14
- `).map(S=>S.trim()).filter(Boolean),rollbackPlan:Ms.split(`
15
- `).map(S=>S.trim()).filter(Boolean)}});Xt(!1),H({type:P.success?"success":"error",message:P.success?`Checklist blocks cloned to ${P.updated??0} child task(s).`:P.error||"Failed to clone checklist blocks."})},children:[ss?e.jsx(aa,{size:14,className:t.spinner}):e.jsx(Wr,{size:14}),"Clone Checklists"]})]}),xt==="workflowEditor"&&e.jsx(Dj,{availableWorkflows:ls,onFetchWorkflowTemplate:As,onFetchWorkflowOverrideNames:ds,onSaveWorkflowTemplateDraft:Ss,onResetWorkflowTemplateDraft:Ds}),xt==="agents"&&e.jsxs("div",{className:t.settingGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"AI Specialists (Agents)"}),e.jsx("p",{className:`${t.settingsHint} ${t.marginBottom12}`,children:"Export specialist definitions to your project as .md files for AI context."}),e.jsx("div",{className:`${t.exportRow} ${t.exportRowGrid}`,children:e.jsxs("div",{className:t.exportItem,children:[e.jsx("label",{className:t.label,children:"Specialists Path"}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("input",{type:"text",value:z,onChange:P=>te(P.target.value),className:t.input}),e.jsxs("button",{className:t.secondaryHeaderBtn,onClick:()=>ne("specialists",z),disabled:w==="specialists",children:[w==="specialists"?e.jsx(aa,{size:14,className:t.spinner}):e.jsx(xd,{size:14}),"Export"]})]})]})}),T&&e.jsxs("div",{className:`${T.type==="success"?t.successMessage:t.errorMessage} ${t.marginTop12}`,children:[T.type==="success"?e.jsx(Sa,{size:14}):e.jsx(mo,{size:14}),T.message]})]}),xt==="taxonomy"&&e.jsxs("div",{className:`${t.settingGroup} ${t.flex1} ${t.flexCol}`,children:[e.jsx("h3",{className:t.settingTitle,children:"Taxonomy & Classification"}),e.jsx("p",{className:t.settingsHint,children:"Configure categories, task types, and custom classification systems."}),e.jsx(Nj,{taxonomies:Dt,onUpdateTaxonomies:Mt,categories:q,pathValidation:M,onUpdateCategory:Q,onRemoveCategory:de,onSaveCategory:xe,onAddPath:B,onRemovePath:oe,onUpdateCategoryIcon:et,onUpdateCategoryColor:yt,onBrowseFolders:$s,types:ut,onSaveType:mt,onRemoveType:kt,priorities:Zt,onUpdatePriorities:tt,approaches:pt,onUpdateApproaches:Rt,manualComplexityEnabled:b,onManualComplexityEnabledChange:async P=>{const S=await Ae(P);H({type:S?"success":"error",message:S?"Project complexity setting saved.":"Failed to save project complexity setting."})},initialTab:Z==="categories"||Z==="types"||Z==="approaches"||Z==="priorities"?Z:void 0})]}),xt==="mcp"&&e.jsxs("div",{className:t.settingsGroup,children:[e.jsx("h3",{className:t.settingTitle,children:"MCP Integrations"}),e.jsx("p",{className:t.settingsHint,children:"Connect Taskforce context to Claude Desktop, Cursor, or other MCP clients. Generated configs include tenant/workspace scope env vars."}),e.jsxs("div",{className:`${t.settingsItem} ${t.marginTop16}`,children:[e.jsxs("div",{className:t.settingLabelGroup,children:[e.jsxs("div",{className:t.labelGroupFlex,children:[e.jsx("label",{className:t.settingLabel,children:"MCP Path Mapping (Host Root)"}),Pe&&!V&&e.jsx("span",{className:t.configBadge,children:"Server Configured"})]}),e.jsx("span",{className:t.settingDescription,children:"If running in Docker, WSL, or Remote Dev, provide the absolute path to this project as seen by your host OS (e.g. Mac/Windows)."})]}),e.jsx("div",{className:t.pathInputWrapper,children:e.jsx("input",{type:"text",className:t.settingInput,placeholder:Pe||"/Users/username/Projects/my-project or C:\\Projects\\my-project",value:V||"",onChange:P=>qe?.(P.target.value)})})]}),e.jsxs("div",{className:`${t.codeBlockWrapper} ${t.codeBlockWrapperCustom}`,children:[e.jsxs("div",{className:t.codeHeader,children:[e.jsx("span",{className:t.codeLabel,children:"MCP Configuration"}),e.jsxs("div",{className:t.codeHeaderActions,children:[e.jsxs("button",{className:`${t.copyBtn} ${Tt==="snippet"?t.copyBtnActive:""}`,onClick:()=>ya("snippet"),title:"Copy just this server snippet",children:[Tt==="snippet"?e.jsx(Sa,{size:14}):e.jsx(Wr,{size:14}),Tt==="snippet"?"Snippet Copied!":"Copy Snippet"]}),e.jsxs("button",{className:`${t.copyBtn} ${Tt==="full"?t.copyBtnActive:""}`,onClick:()=>ya("full"),title:"Copy full configuration file",children:[Tt==="full"?e.jsx(Sa,{size:14}):e.jsx(Wr,{size:14}),Tt==="full"?"Config Copied!":"Copy Full Config"]})]})]}),e.jsx("pre",{className:t.codeBlock,children:e.jsx("code",{children:(()=>{const{serverId:P,serverConfig:S}=qs(),Y={color:"rgba(166, 172, 205, 0.4)"},pe={color:"violet-500",fontWeight:"bold"},Te={color:"rgba(166, 172, 205, 0.6)"};return e.jsxs(e.Fragment,{children:[e.jsx("span",{style:Te,children:"{"}),`
16
- `,e.jsx("span",{style:Y,children:'"mcpServers"'}),e.jsx("span",{style:Y,children:":"})," ",e.jsx("span",{style:Te,children:"{"}),`
17
- `,e.jsxs("span",{style:pe,children:[`"${P}"`,": ",JSON.stringify(S,null,2).split(`
18
- `).map((Nt,Ze)=>Ze===0?Nt:" "+Nt).join(`
19
- `)]}),`
20
- `,e.jsx("span",{style:Te,children:"}"}),`
21
- `,e.jsx("span",{style:Te,children:"}"})]})})()})})]}),e.jsx("div",{className:`${t.settingGroup} ${t.marginTop12}`,children:e.jsxs("div",{className:t.settingLabelGroup,children:[e.jsx("label",{className:t.settingLabel,children:"Installation"}),e.jsxs("span",{className:t.settingDescription,children:["Taskforce MCP uses the global ",e.jsx("code",{children:"taskforce"})," command. Install with ",e.jsx("code",{children:"npm install -g @taskforcehq/taskforce"}),"."]})]})}),e.jsx("div",{className:t.marginTop12,style:{display:"flex",gap:"8px"},children:e.jsx("button",{className:`${t.copyBtn} ${Ht?t.copyBtnNeutralActive:""}`,onClick:()=>Ls(P=>!P),title:"Show advanced MCP install options",children:Ht?"Hide Advanced":"Show Advanced"})}),Ht&&e.jsxs("div",{className:`${t.settingGroup} ${t.marginTop12}`,children:[e.jsxs("div",{className:t.settingLabelGroup,children:[e.jsx("label",{className:t.settingLabel,children:"Advanced Installation Mode"}),e.jsx("span",{className:t.settingDescription,children:"Global mode is recommended. Local / npx is intended for Taskforce development workflows."})]}),e.jsxs("div",{className:t.buttonGrid,children:[e.jsx("button",{className:`${t.themeBtn} ${Je?t.activeTheme:""}`,onClick:()=>Yt(!0),children:"Global"}),e.jsx("button",{className:`${t.themeBtn} ${Je?"":t.activeTheme}`,onClick:()=>Yt(!1),children:"Local / npx (Dev)"})]})]})]})]})]})}function Pj(a){const{activeTab:n,setActiveTab:r,isOpen:u,setIsOpen:d,currentTheme:m,setCurrentTheme:h,saveSettings:v,pathSaved:x,keyShortcut:_,setKeyShortcut:R,jsonBackupEnabled:j,setJsonBackupEnabled:D,mcpHostRoot:b,setMcpHostRoot:f,settingsSection:I,setSettingsSection:$,projectRoot:z,projectName:w,mcpScriptPath:T,serverHostRoot:Z,showFolderBrowser:Ne,setShowFolderBrowser:J,folders:he,files:ce,currentBrowsePath:W,fetchFolders:U,browserTarget:Ge,setBrowserTarget:ye,contextLinkBrowsePath:ke,handleSelectPath:Ae,handleAddPath:se,handleRemovePath:Ye,tasks:We,loadingTasks:Fe,archivedTasks:te,activeCategories:ne,activeTypes:le,priorities:dt,approaches:ae,availableSpecialists:q,taxonomies:M,searchQuery:Q,setSearchQuery:de,filterCategories:xe,setFilterCategories:B,filterTypes:oe,setFilterTypes:et,filterPriorities:yt,setFilterPriorities:ut,filterStatus:mt,setFilterStatus:kt,filterAssignees:Dt,setFilterAssignees:Mt,parentTaskFilterMode:Zt,setParentTaskFilterMode:tt,filterTaxonomies:pt,setFilterTaxonomies:Rt,sortBy:wt,setSortBy:Ut,sortOrder:V,toggleSortOrder:Pe,showArchive:_e,setShowArchive:Le,clearFilters:ze,filteredTasks:N,filteredArchive:G,groupedTasks:je,collapsedCategories:Ie,setCollapsedCategories:we,handleEdit:qe,handleDelete:vt,handleCopyId:st,handleToggleComplete:Re,handleToggleCancel:bt,handleToggleInProgress:De,handleToggleReview:Jt,handleArchiveTask:St,handleBulkArchive:ls,handleUnarchive:Ee,fetchArchive:zt,editingTaskId:ts,loading:Et,error:qt,title:Ct,setTitle:As,description:ds,setDescription:Ss,category:Ds,setCategory:us,type:Cs,setType:L,priority:F,setPriority:re,complexity:K,setComplexity:H,manualComplexityEnabled:me,checklistDropdownEnabled:Oe,assigneeFilterEnabled:ie,approach:ve,setApproach:_t,assignee:Se,setAssignee:Ue,scheduledDate:ht,setScheduledDate:nt,dueDate:It,setDueDate:jt,parentTaskIdInput:Vt,setParentTaskIdInput:rt,addChildTaskIdInput:ot,setAddChildTaskIdInput:y,formTaxonomies:ue,setFormTaxonomies:Ke,selectedSpecialists:At,setSelectedSpecialists:ps,comments:Kt,newCommentText:Lt,setNewCommentText:vs,screenshots:Ms,setScreenshots:Bs,descriptionFocused:Qe,setDescriptionFocused:ft,showMarkdownHelp:ss,setShowMarkdownHelp:Xt,showSpecialists:Xe,setShowSpecialists:at,showChecklist:Bt,setShowChecklist:bs,showTaskRelationships:xt,setShowTaskRelationships:$t,showChildTasks:O,setShowChildTasks:Ve,showComments:Ft,setShowComments:Tt,handleSubmit:Ot,resetForm:Je,handleAddComment:Yt,handleSetParentForCurrentTask:Ht,handleAddChildToCurrentTask:Ls,handleCreateChildForCurrentTask:Us,handleUnlinkChildTask:qs,handleReorderChildTasks:ya,handleClearParentTask:na,handleOpenTaskById:Vs,unsavedModalOpen:ua,setUnsavedModalOpen:$s,pendingNavigation:P,handleNavigation:S,handleClose:Y,scheduleWarningPrompt:pe,confirmScheduleWarning:Te,cancelScheduleWarning:Nt,successBanner:Ze,returnToParentTaskId:$e,returnFromChildTaskId:hs,clearReturnToParentTask:as,copiedId:Ns,recentlyChangedTaskIds:Ca,tasksScrollRef:ns,setTasksScrollPos:_s,currentTask:_a,currentTaskParent:Rs,currentTaskChildren:xo,exportEnvironment:ms,setExportEnvironment:vo,exportWorkflowsPath:bo,setExportWorkflowsPath:er,exportSpecialistsPath:tr,setExportSpecialistsPath:Ni,exportResult:Za,handleExportResources:sr,exportingResource:ar,availableWorkflows:nr,onExportWorkflows:Pn,availableEnvironments:wo,handleUpdateCategory:or,handleRemoveCategory:ka,handleSaveCategory:So,handleUpdateCategoryIcon:oa,handleUpdateCategoryColor:Ii,handleSaveType:Hr,handleRemoveType:Gr,handleUpdateTaxonomies:zc,handleUpdatePriorities:Lc,handleUpdateApproaches:Ys,pathValidation:Rc,validatePaths:rr,getCategoryPaths:ir,commentsEndRef:Co,settingsModel:cr,onHeaderMouseDown:Ai,isDragging:qr}=a,Vr=s.useRef(null),[lr,Di]=zs.useState(0);s.useLayoutEffect(()=>{if(n==="tasks"&&ns.current&&lr>0){const it=setTimeout(()=>{ns.current&&(ns.current.scrollTop=lr)},50);return()=>clearTimeout(it)}},[n,lr,We]);const Bi=it=>{Ut(it)},Pi=()=>{S(()=>{if(n==="add"||n==="settings"){if(n==="add"&&ts&&$e&&hs===ts){const it=We.find(ws=>ws.id===$e);if(as(),it){qe(it);return}}n==="add"&&Je(),r("tasks")}else a.onClose?a.onClose():Y()})},zi=()=>{$s(!1),P?(n==="add"&&Je(),P()):r("tasks")},Li=async()=>{await Ot({preventDefault:()=>{}}),$s(!1),P&&P()},Ri=(it,ws)=>{Ke(ja=>({...ja,[it]:ws})),it==="approach"&&typeof ws=="string"&&_t(ws)},Kr=s.useCallback(it=>{Je(),us(it),S(()=>{r("add")})},[Je,us,r,S]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:Vr,className:`${be.modal} ${t.coreModal} ${n==="settings"?be.settingsViewModal:""}`,"data-theme":m,children:[e.jsxs("div",{className:be.header,onMouseDown:Ai,style:{cursor:Ai?qr?"grabbing":"grab":"default"},children:[e.jsxs("div",{className:`${be.headerTitle} ${t.headerTitleWidget}`,children:["Taskforce",w&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.projectSlash,children:"/"}),e.jsx("span",{className:t.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:w})]}),e.jsx("span",{className:t.taskCountBadge,title:"Total Tasks",children:We.length}),Ze&&e.jsxs("div",{className:t.headerSuccess,children:[e.jsx(Sa,{size:14}),e.jsx("span",{children:Ze.message})]})]}),e.jsxs("div",{className:be.headerActions,children:[n==="tasks"&&e.jsx(e.Fragment,{children:e.jsx("button",{className:be.headerActionBtn,onClick:()=>{S(()=>{Je(),r("add")})},title:"Add New Task",children:e.jsx(cn,{size:18})})}),e.jsx("button",{className:`${be.headerActionBtn} ${n==="settings"?be.headerActionBtnActive:""}`,onClick:()=>{n!=="settings"&&S(()=>{r("settings")})},title:"Settings",children:e.jsx(_i,{size:18})}),e.jsx("button",{className:be.headerActionBtn,onClick:Pi,title:n==="tasks"?"Close":"Back to Tasks",children:n==="tasks"?e.jsx(ga,{size:20}):e.jsx(kd,{size:20})})]})]}),n==="add"&&e.jsx(Hd,{editingTaskId:ts,loading:Et,title:Ct,currentTask:_a,handleSubmit:Ot,resetForm:Je,handleCopyId:st,copiedId:Ns,tasks:We,handleToggleInProgress:De,handleToggleReview:Jt,handleToggleComplete:Re,handleToggleCancel:bt,handleArchiveTask:St}),n==="tasks"&&e.jsx(Od,{ref:ns,tasks:We,archivedTasks:te,categories:ne,types:le,priorities:dt,approaches:ae,availableSpecialists:q,taxonomies:M,searchQuery:Q,filterCategories:xe,filterTypes:oe,filterPriorities:yt,filterStatus:mt,filterAssignees:Dt,filterTaxonomies:pt,sortBy:wt,sortOrder:V,showArchive:_e,parentTaskFilterMode:Zt,assigneeFilterEnabled:ie,collapsedCategories:Ie,loadingTasks:Fe,filteredTasks:N,filteredArchive:G,groupedTasks:je,copiedId:Ns,recentlyChangedTaskIds:Ca,onSearchChange:de,onFilterCategoriesChange:it=>B(it),onFilterTypesChange:it=>et(it),onFilterPrioritiesChange:ut,onFilterStatusChange:kt,onFilterAssigneesChange:it=>Mt(it),onTaxonomyFilterChange:(it,ws)=>Rt(ja=>({...ja,[it]:ws})),onSortByChange:Bi,onSortOrderChange:Pe,onShowArchiveChange:Le,onParentTaskFilterModeChange:tt,onClearFilters:ze,onToggleCategory:it=>we(ws=>({...ws,[it]:!ws[it]})),onEditTask:qe,onOpenTaskById:Vs,onCopyId:st,onToggleInProgress:De,onToggleReview:Jt,onToggleComplete:Re,onToggleCancel:bt,onArchiveTask:St,onBulkArchive:ls,onUnarchive:Ee,onDelete:vt,onUnlinkChildTask:qs,onClearParentTask:na,onFetchArchive:zt,onAddTaskToCategory:Kr}),n==="add"&&e.jsx(Ud,{editingTaskId:ts,error:qt,title:Ct,description:ds,category:Ds,type:Cs,priority:F,complexity:K,manualComplexityEnabled:me,approach:ve,assignee:Se,scheduledDate:ht,dueDate:It,parentTaskIdInput:Vt,addChildTaskIdInput:ot,formTaxonomies:ue,onTaxonomyChange:Ri,onParentTaskIdInputChange:rt,onAddChildTaskIdInputChange:y,taxonomies:M,selectedSpecialists:At,comments:Kt,newCommentText:Lt,contextFiles:Ms,contextLinkBrowsePath:ke,descriptionFocused:Qe,showMarkdownHelp:ss,showSpecialists:Xe,showChecklist:Bt,checklistEnabled:Oe,showTaskRelationships:xt,showChildTasks:O,showComments:Ft,categories:ne,types:le,priorities:dt,approaches:ae,availableSpecialists:q,copiedId:Ns,onTitleChange:As,onDescriptionChange:Ss,onCategoryChange:us,onTypeChange:L,onPriorityChange:re,onComplexityChange:H,onApproachChange:it=>{_t(it),Ke(ws=>({...ws,approach:it}))},onAssigneeChange:Ue,onScheduledDateChange:nt,onDueDateChange:jt,onSelectedSpecialistsChange:ps,onNewCommentTextChange:vs,onDescriptionFocusedChange:ft,onShowMarkdownHelpChange:Xt,onShowSpecialistsChange:at,onShowChecklistChange:bs,onShowTaskRelationshipsChange:$t,onShowChildTasksChange:Ve,onShowCommentsChange:Tt,onOpenSettings:it=>{S(()=>{$(it),r("settings")})},onSubmit:Ot,commentsEndRef:Co,onAddComment:()=>Yt(Lt),onSetParentForCurrentTask:Ht,onAddChildToCurrentTask:Ls,onCreateChildForCurrentTask:Us,onUnlinkChildTask:qs,onReorderChildTasks:ya,onOpenTaskById:Vs,onAddContextFile:it=>{Bs(ws=>[...ws,it])},onBrowseContextLinkPath:()=>{ye({type:"context-link"}),U(""),J(!0)},onRemoveContextFile:async it=>{const ws=Ms[it],ja=typeof ws=="string"?ws:ws.path;if(Bs(ln=>ln.filter((dr,Jr)=>Jr!==it)),typeof ja=="string"&&ja.startsWith("/api/taskforce/context/"))try{await fetch(ja,{method:"DELETE"})}catch{}},onUpdateContextCaption:(it,ws)=>{Bs(ja=>ja.map((ln,dr)=>dr!==it?ln:typeof ln=="string"?{path:ln,caption:ws,timestamp:new Date().toISOString()}:{...ln,caption:ws}))},onCopyId:st,onToggleInProgress:De,onToggleReview:Jt,onToggleComplete:Re,onToggleCancel:bt,onArchiveTask:St,onUnarchive:Ee,currentTask:_a,currentTaskParent:Rs,currentTaskChildren:xo}),n==="settings"&&e.jsx(Gd,{settingsModel:cr,onSectionChange:$})]}),Ne&&Ci.createPortal(e.jsx("div",{className:t.folderBrowserOverlay,children:e.jsxs("div",{className:t.folderBrowser,children:[e.jsxs("div",{className:t.browserHeader,children:[e.jsxs("div",{className:t.browserPathInfo,children:[e.jsx(ho,{size:14}),e.jsx("span",{children:W||"Project Root"})]}),e.jsxs("div",{className:t.browserActions,children:[W&&e.jsx("button",{className:t.helpLink,onClick:()=>{const it=W.split("/").filter(Boolean);it.pop(),U(it.length?it.join("/")+"/":"")},children:"Back"}),e.jsx("button",{className:t.helpLink,onClick:()=>J(!1),children:"Close"})]})]}),e.jsxs("div",{className:t.browserList,children:[Ge&&typeof Ge=="object"&&Ge.type!=="context-link"&&e.jsxs("div",{className:`${t.browserItem} ${t.browserItemCurrent}`,onClick:()=>Ae(W),children:[e.jsx(Sa,{size:14})," Select Current: ./",W||"(root)"]}),he.map(it=>e.jsxs("div",{className:t.browserItem,onClick:()=>U(W+it+"/"),children:[e.jsx(ho,{size:14})," ",it,"/"]},it)),ce.map(it=>e.jsxs("div",{className:`${t.browserItem} ${t.browserItemFile}`,onClick:()=>Ae(W+it),children:[e.jsx(Xo,{size:14})," ",it]},it)),he.length===0&&ce.length===0&&e.jsx("div",{className:`${t.browserItem} ${t.browserEmpty}`,children:"No items found"})]})]})}),document.body),ua&&e.jsx("div",{className:`${be.overlay} ${be.unsavedOverlay}`,children:e.jsxs("div",{className:`${be.modal} ${be.unsavedModal}`,"data-theme":m,children:[e.jsx("div",{className:`${be.header} ${be.unsavedHeader}`,children:e.jsxs("div",{className:`${be.headerTitle} ${be.unsavedTitle}`,children:[e.jsx(mo,{size:20}),"Unsaved Changes"]})}),e.jsx("div",{className:`${be.form} ${be.unsavedContent}`,children:e.jsx("p",{className:be.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),e.jsxs("div",{className:`${be.formActions} ${be.unsavedActions}`,children:[e.jsx("button",{className:t.cancelBtn,onClick:()=>$s(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),e.jsx("button",{className:t.destructiveBtn,onClick:zi,title:"Discard unsaved changes and leave",children:"Discard"}),e.jsxs("button",{className:t.submitBtn,onClick:Li,disabled:Et,title:"Save changes and leave",children:[Et?e.jsx(aa,{size:16,className:t.spinner}):e.jsx(Bc,{size:16}),"Save"]})]})]})}),pe&&e.jsx("div",{className:`${be.overlay} ${be.unsavedOverlay}`,children:e.jsxs("div",{className:`${be.modal} ${be.unsavedModal}`,"data-theme":m,children:[e.jsx("div",{className:`${be.header} ${be.unsavedHeader}`,children:e.jsxs("div",{className:`${be.headerTitle} ${be.unsavedTitle}`,children:[e.jsx(mo,{size:20}),"Date Warning"]})}),e.jsxs("div",{className:`${be.form} ${be.unsavedContent}`,children:[e.jsx("p",{className:be.unsavedText,children:"Due date is before scheduled date."}),e.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",pe.dueDate," · Scheduled: ",pe.scheduledDate]})]}),e.jsxs("div",{className:`${be.formActions} ${be.unsavedActions}`,children:[e.jsx("button",{className:t.cancelBtn,onClick:Nt,children:"Go Back"}),e.jsx("button",{className:t.submitBtn,onClick:Te,children:"Save Anyway"})]})]})})]})}function zj(a={x:0,y:0}){const[n,r]=s.useState(a),[u,d]=s.useState(!1),[m,h]=s.useState({x:0,y:0}),[v,x]=s.useState(0),_=s.useRef(null),R=s.useCallback(b=>{const f=b.target;if(!(f.closest("button")||f.closest("input")||f.closest("select")||f.closest("textarea")||f.closest('[role="button"]')||f.closest(".no-drag"))){if(_.current){const I=_.current.getBoundingClientRect();x(I.top-n.y)}d(!0),h({x:b.clientX-n.x,y:b.clientY-n.y})}},[n]),j=s.useCallback(b=>{if(u){let f=b.clientX-m.x,I=b.clientY-m.y;I<-v&&(I=-v),r({x:f,y:I})}},[u,m,v]),D=s.useCallback(()=>{d(!1)},[]);return s.useEffect(()=>(u?(window.addEventListener("mousemove",j),window.addEventListener("mouseup",D)):(window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",D)),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",D)}),[u,j,D]),{position:n,isDragging:u,handleMouseDown:R,modalRef:_,setPosition:r}}function Dn({isOpen:a,onClose:n,title:r,children:u,footer:d,size:m="md",theme:h="dark",className:v,draggable:x=!1,isSettings:_=!1,closeOnOverlayClick:R=!0}){const j=s.useRef(null),{position:D,isDragging:b,handleMouseDown:f,modalRef:I}=zj();if(s.useEffect(()=>{const z=w=>{w.key==="Escape"&&a&&n()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[a,n]),s.useEffect(()=>(a?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[a]),!a)return null;const $={sm:be.modalSizeSm,md:be.modalSizeMd,lg:be.modalSizeLg,xl:be.modalSizeXl,full:be.modalSizeFull};return Ci.createPortal(e.jsx("div",{className:`${be.overlay} ${v||""} ${be.overlayHighZ}`,ref:j,onClick:z=>{R&&z.target===j.current&&n()},children:e.jsxs("div",{ref:I,className:`${be.modal} ${$[m]} ${x?be.draggableModal:""} ${_?be.settingsViewModal:""}`,"data-theme":h,style:{transform:x?`translate(${D.x}px, ${D.y}px)`:void 0,transition:b?"none":"transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s ease-out"},children:[e.jsxs("div",{className:`${be.header} ${x?be.draggableHeader:""}`,onMouseDown:x?f:void 0,style:{cursor:x?b?"grabbing":"grab":"default"},children:[e.jsx("div",{className:be.headerTitle,children:r}),e.jsx("div",{className:be.headerActions,children:e.jsx("button",{className:be.headerActionBtn,onClick:n,title:"Close",children:e.jsx(ga,{size:20})})})]}),e.jsx("div",{className:be.modalContent,children:u}),d&&e.jsx("div",{className:`${be.formActions} ${be.modalFooter}`,children:d})]})}),document.body)}const Lj=[{value:"all",label:"All"},{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"other",label:"Other"}];function Rj({docType:a}){switch(a){case"implementation-plan":return e.jsx(xu,{size:13});case"review":return e.jsx(_l,{size:13});case"walkthrough":return e.jsx(ku,{size:13});default:return e.jsx(yu,{size:13})}}function Ej(a){return a<1024?`${a}B`:a<1024*1024?`${(a/1024).toFixed(1)}KB`:`${(a/(1024*1024)).toFixed(1)}MB`}function Mj(a){if(!a)return"";const n=new Date(a),u=new Date().getTime()-n.getTime(),d=Math.floor(u/(1e3*60*60*24));return d===0?"Today":d===1?"Yesterday":d<7?`${d}d ago`:d<30?`${Math.floor(d/7)}w ago`:n.toLocaleDateString()}function $j({documents:a,selectedDocId:n,loading:r,error:u,searchQuery:d,typeFilter:m,taskById:h,onSearchChange:v,onTypeFilterChange:x,onSelect:_,onRefresh:R}){return e.jsxs("div",{className:t.docIndex,children:[e.jsxs("div",{className:t.docIndexHeader,children:[e.jsxs("span",{className:t.docIndexTitle,children:[e.jsx(Xo,{size:14}),"Documents"]}),e.jsx("button",{className:t.docIndexRefreshBtn,onClick:R,title:"Refresh document list",disabled:r,children:e.jsx(vd,{size:13,className:r?t.docSpinning:void 0})})]}),e.jsxs("div",{className:t.docIndexSearch,children:[e.jsx(bd,{size:12,className:t.docIndexSearchIcon}),e.jsx("input",{type:"text",placeholder:"Search documents…",value:d,onChange:j=>v(j.target.value),className:t.docIndexSearchInput})]}),e.jsx("div",{className:t.docIndexFilters,children:Lj.map(j=>e.jsx("button",{className:`${t.docIndexFilterBtn} ${m===j.value?t.docIndexFilterBtnActive:""}`,onClick:()=>x(j.value),children:j.label},j.value))}),e.jsxs("div",{className:t.docIndexList,children:[r&&e.jsx("div",{className:t.docIndexState,children:"Loading documents…"}),!r&&u&&e.jsx("div",{className:t.docIndexStateError,children:u}),!r&&!u&&a.length===0&&e.jsx("div",{className:t.docIndexState,children:d||m!=="all"?"No documents match your filters.":"No documents found. Documents added as task attachments will appear here."}),!r&&a.map(j=>{const D=j.taskId?h.get(j.taskId):null,b=j.id===n;return e.jsxs("button",{className:`${t.docIndexItem} ${b?t.docIndexItemActive:""}`,onClick:()=>_(j),children:[e.jsx("div",{className:t.docIndexItemIcon,children:e.jsx(Rj,{docType:j.docType})}),e.jsxs("div",{className:t.docIndexItemBody,children:[e.jsx("span",{className:t.docIndexItemTitle,children:j.title}),D&&e.jsx("span",{className:t.docIndexItemTask,children:D.title}),e.jsxs("span",{className:t.docIndexItemMeta,children:[Ej(j.sizeBytes),j.updatedAt&&e.jsxs(e.Fragment,{children:[" · ",Mj(j.updatedAt)]})]})]})]},j.id)})]})]})}function od(a){return function(n){return Wu(n,a)}}function qd(a){return typeof a=="string"?a.trim().replace(/\/+$/,""):""}function Vd(a,n){if(!a.startsWith("/"))return a;const r=qd(n);return r?`${r}${a}`:a}async function Ur(a,n,r){const u=Vd(a,r),d=qd(r).length>0;try{const m=await fetch(u,n);if(!(d&&u!==a&&a.startsWith("/api/taskforce/")&&(m.status===401||m.status===403)))return m;try{return await fetch(a,n)}catch{return m}}catch(m){if(!d||!a.startsWith("/"))throw m;return fetch(a,n)}}const rd={feature:"#a78bfa",bug:"#f87171",chore:"#94a3b8",refactor:"#fbbf24",documentation:"#34d399"},Fj={1:"Low",2:"Medium",3:"High",4:"Critical"},id={1:"#64748b",2:"#94a3b8",3:"#f97316",4:"#ef4444"};function Si(a,n){return a.map(r=>({...r,selected:n,children:Si(r.children,n)}))}function Kd(a,n,r){return a.map(u=>u.idempotencyKey===n?{...u,selected:r,children:Si(u.children,r)}:{...u,children:Kd(u.children,n,r)})}function Pl(a){let n=0;for(const r of a)r.selected&&n++,n+=Pl(r.children);return n}function Jd({node:a,depth:n,onToggle:r}){const[u,d]=s.useState(!0),m=a.children.length>0,h=n*20;return e.jsxs("div",{children:[e.jsxs("div",{className:`${t.genTaskRow} ${a.selected?"":t.genTaskRowDimmed}`,style:{paddingLeft:`${12+h}px`},children:[e.jsx("button",{className:t.genTaskCheck,onClick:()=>r(a.idempotencyKey,!a.selected),title:a.selected?"Deselect":"Select",children:a.selected?e.jsx(vu,{size:14,style:{color:"#a78bfa"}}):e.jsx(bu,{size:14,style:{color:"#64748b"}})}),m?e.jsx("button",{className:t.genTaskExpandBtn,onClick:()=>d(v=>!v),children:u?e.jsx(Bn,{size:12}):e.jsx(la,{size:12})}):e.jsx("span",{className:t.genTaskExpandSpacer}),e.jsx("span",{className:t.genTaskTitle,title:a.description||void 0,children:a.title}),e.jsx("span",{className:t.genTaskBadge,style:{color:rd[a.type]??"#a78bfa",borderColor:rd[a.type]??"#a78bfa"},children:a.type}),e.jsx("span",{className:t.genTaskBadge,style:{color:id[a.priority]??"#94a3b8",borderColor:id[a.priority]??"#94a3b8"},children:Fj[a.priority]})]}),m&&u&&e.jsx("div",{children:a.children.map(v=>e.jsx(Jd,{node:v,depth:n+1,onToggle:r},v.idempotencyKey))})]})}function Oj({content:a,docTitle:n,apiBaseUrl:r="",onClose:u,onGenerated:d}){const[m,h]=s.useState("preview"),[v,x]=s.useState(null),[_,R]=s.useState([]),[j,D]=s.useState(!0),[b,f]=s.useState(0),[I,$]=s.useState(null);s.useEffect(()=>{let J=!1;return D(!0),x(null),Ur("/api/taskforce/documents/generate-tasks/preview",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:a})},r).then(he=>he.json()).then(he=>{if(!J){if(he.error)throw new Error(he.error);R(he.tasks||[]),h("preview")}}).catch(he=>{J||(x(he?.message||"Failed to parse plan"),h("error"))}).finally(()=>{J||D(!1)}),()=>{J=!0}},[a,r]);const z=s.useCallback((J,he)=>{R(ce=>Kd(ce,J,he))},[]),w=()=>R(J=>Si(J,!0)),T=()=>R(J=>Si(J,!1)),Z=Pl(_),Ne=async()=>{h("generating"),$(null);try{const J=await Ur("/api/taskforce/documents/generate-tasks/commit",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({tasks:_})},r),he=await J.json().catch(()=>({}));if(!J.ok)throw new Error(he.error||`Generation failed (${J.status})`);f(he.created??0),h("done"),d(he.created??0)}catch(J){$(J?.message||"Generation failed"),h("error")}};return e.jsx("div",{className:t.genModalOverlay,onClick:J=>{J.target===J.currentTarget&&u()},children:e.jsxs("div",{className:t.genModal,children:[e.jsxs("div",{className:t.genModalHeader,children:[e.jsxs("div",{className:t.genModalTitle,children:[e.jsx(Jo,{size:16,style:{color:"#a78bfa"}}),"Generate Tasks from Plan"]}),e.jsx("span",{className:t.genModalDocName,children:n}),e.jsx("button",{className:t.genModalClose,onClick:u,title:"Close",children:e.jsx(ga,{size:16})})]}),e.jsxs("div",{className:t.genModalBody,children:[j&&e.jsxs("div",{className:t.genModalState,children:[e.jsx(Ol,{size:20,className:t.docSpinning}),"Parsing plan…"]}),!j&&m==="error"&&e.jsxs("div",{className:t.genModalStateError,children:[e.jsx(Ll,{size:16}),v||I||"An error occurred"]}),!j&&m==="done"&&e.jsxs("div",{className:t.genModalStateDone,children:[e.jsx(wd,{size:24,style:{color:"#4ade80"}}),e.jsxs("strong",{children:[b," task",b!==1?"s":""," created"]}),e.jsx("p",{children:"Tasks are now in your board. Switch to the Kanban or Hierarchy view to see them."})]}),!j&&(m==="preview"||m==="confirm"||m==="generating")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.genToolbar,children:[e.jsxs("span",{className:t.genToolbarCount,children:[Z," of ",Pl(Si(_,!0))," tasks selected"]}),e.jsx("button",{className:t.genToolbarBtn,onClick:w,children:"Select all"}),e.jsx("button",{className:t.genToolbarBtn,onClick:T,children:"Deselect all"})]}),_.length===0?e.jsx("div",{className:t.genModalState,children:"No tasks could be parsed from this document. Make sure the document uses ## H2 headings for phases and bullet points for tasks."}):e.jsx("div",{className:t.genTaskTree,children:_.map(J=>e.jsx(Jd,{node:J,depth:0,onToggle:z},J.idempotencyKey))})]})]}),!j&&m!=="done"&&m!=="error"&&e.jsxs("div",{className:t.genModalFooter,children:[e.jsx("button",{className:t.genCancelBtn,onClick:u,children:"Cancel"}),e.jsx("button",{className:t.genCommitBtn,onClick:Ne,disabled:Z===0||m==="generating",children:m==="generating"?e.jsxs(e.Fragment,{children:[e.jsx(Ol,{size:13,className:t.docSpinning})," Generating…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Jo,{size:13})," Generate ",Z," task",Z!==1?"s":""]})})]}),!j&&m==="done"&&e.jsx("div",{className:t.genModalFooter,children:e.jsx("button",{className:t.genCommitBtn,onClick:u,children:"Done"})})]})})}const Wj={"implementation-plan":"Implementation Plan",review:"Review",walkthrough:"Walkthrough",planning:"Planning",other:"Document"};function Uj(a){return a<1024?`${a} B`:a<1024*1024?`${(a/1024).toFixed(1)} KB`:`${(a/(1024*1024)).toFixed(1)} MB`}function cd(a){return a?new Date(a).toLocaleString():"—"}function Hj(a,n,r){if(n<0)return a;const u=a.split(`
22
- `);let d=-1;const m=/^(\s*(?:[-*+]|\d+\.)\s+)\[( |x|X)\](.*)$/,h=r?"x":" ";return u.map(x=>{const _=x.match(m);return!_||(d+=1,d!==n)?x:`${_[1]}[${h}]${_[3]}`}).join(`
23
- `)}function Gj({doc:a,taskTitle:n,apiBaseUrl:r="",onSaved:u}){const[d,m]=s.useState(null),[h,v]=s.useState(!1),[x,_]=s.useState(null),[R,j]=s.useState(!1),[D,b]=s.useState(!1),[f,I]=s.useState(""),[$,z]=s.useState("split"),[w,T]=s.useState({type:"idle"}),[Z,Ne]=s.useState(!1),[J,he]=s.useState(!1),ce=D&&f!==(d??""),W=s.useRef(null),U=s.useCallback(async()=>{v(!0),_(null),m(null);try{const q=`/api/taskforce/context-link?path=${encodeURIComponent(a.fsPath)}`,M=await Ur(q,{credentials:"include"},r);if(!M.ok)throw new Error(`Failed to load document (${M.status})`);const Q=await M.text();m(Q),I(Q)}catch(q){_(q?.message||"Failed to load document")}finally{v(!1)}},[a.fsPath,r]);s.useEffect(()=>{U(),b(!1),T({type:"idle"})},[U]),s.useEffect(()=>{if(!D)return;const q=M=>{(M.metaKey||M.ctrlKey)&&M.key==="s"&&(M.preventDefault(),ke())};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[D,f]);const Ge=()=>{I(d??""),T({type:"idle"}),b(!0),setTimeout(()=>W.current?.focus(),50)},ye=()=>{ce&&!window.confirm("Discard unsaved changes?")||(b(!1),I(d??""),T({type:"idle"}))},ke=s.useCallback(async()=>{if(w.type!=="saving"){T({type:"saving"});try{const q=await Ur("/api/taskforce/documents/save",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({fsPath:a.fsPath,content:f})},r),M=await q.json().catch(()=>({}));if(!q.ok)throw new Error(M.error||`Save failed (${q.status})`);const Q=M.updatedAt||new Date().toISOString();m(f),T({type:"saved",savedAt:Q}),u?.(Q),b(!1)}catch(q){T({type:"error",message:q?.message||"Save failed"})}}},[r,a.fsPath,f,w.type,u]),Ae=()=>window.print(),se=async()=>{const q=`/api/taskforce/context-link?path=${encodeURIComponent(a.fsPath)}`,M=new URL(Vd(q,r),window.location.origin).toString();try{await navigator.clipboard.writeText(M)}catch{const Q=document.createElement("textarea");Q.value=M,document.body.appendChild(Q),Q.select(),document.execCommand("copy"),document.body.removeChild(Q)}j(!0),setTimeout(()=>j(!1),2e3)},Ye=()=>{const q=new Blob([D?f:d??""],{type:"text/markdown"}),M=document.createElement("a");M.href=URL.createObjectURL(q),M.download=a.title+".md",M.click(),URL.revokeObjectURL(M.href)},We=s.useCallback(async q=>{T({type:"saving"});try{const M=await Ur("/api/taskforce/documents/save",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({fsPath:a.fsPath,content:q})},r),Q=await M.json().catch(()=>({}));if(!M.ok)throw new Error(Q.error||`Save failed (${M.status})`);const de=Q.updatedAt||new Date().toISOString();return m(q),I(q),T({type:"saved",savedAt:de}),u?.(de),!0}catch(M){return T({type:"error",message:M?.message||"Save failed"}),!1}},[r,a.fsPath,u]),Fe=s.useCallback((q,M)=>{const Q=D?f:d??"",de=Hj(Q,q,M);if(de!==Q){if(D){I(de),T(xe=>xe.type==="saving"?xe:{type:"idle"});return}We(de)}},[d,f,D,We]),te=D?f:d??"";let ne=-1;const le=q=>!q||!Array.isArray(q.children)?!1:q.children.some(M=>M?M.type==="element"&&M.tagName==="input"&&M.properties?.type==="checkbox"?!0:le(M):!1),dt=q=>!q||!Array.isArray(q.children)?!1:q.children.some(M=>typeof M?.checked=="boolean"?!0:le(M)),ae={input({type:q,checked:M,...Q}){if(q!=="checkbox")return e.jsx("input",{type:q,checked:M,...Q});ne+=1;const de=ne;return e.jsx("input",{...Q,type:"checkbox",checked:!!M,disabled:!1,onClick:xe=>xe.stopPropagation(),onChange:xe=>Fe(de,xe.currentTarget.checked)})},ul({children:q,node:M,...Q}){const de=dt(M);return e.jsx("ul",{...Q,style:de?{paddingLeft:"1.25em"}:void 0,"data-task-list":de?"true":void 0,children:q})},ol({children:q,node:M,...Q}){const de=dt(M);return e.jsx("ol",{...Q,style:de?{paddingLeft:"1.25em"}:void 0,"data-task-list":de?"true":void 0,children:q})},li({children:q,node:M,...Q}){const de=typeof M?.checked=="boolean"||le(M);return e.jsx("li",{...Q,style:de?{listStyleType:"none",listStyle:"none",marginLeft:0}:void 0,"data-task-item":de?"true":void 0,children:q})}};return e.jsxs("div",{className:`${t.docViewer} ${D?t.docViewerEditMode:""} ${J?t.docViewerMonochrome:""}`,children:[e.jsxs("div",{className:t.docMeta,children:[e.jsxs("div",{className:t.docMetaLeft,children:[e.jsxs("span",{className:`${t.docTypeBadge} ${t[`docTypeBadge_${a.docType.replace("-","_")}`]}`,children:[e.jsx(wu,{size:10}),Wj[a.docType]]}),n&&e.jsx("span",{className:t.docMetaTaskName,title:`From task: ${n}`,children:n}),a.updatedAt&&e.jsxs("span",{className:t.docMetaDate,title:cd(a.updatedAt),children:[e.jsx(Su,{size:11}),cd(a.updatedAt)]}),e.jsxs("span",{className:t.docMetaSize,children:[e.jsx(Cu,{size:11}),Uj(a.sizeBytes)]}),w.type==="saved"&&e.jsxs("span",{className:t.docSaveStatus,"data-status":"saved",children:[e.jsx(wd,{size:11}),"Saved"]}),w.type==="error"&&e.jsxs("span",{className:t.docSaveStatus,"data-status":"error",title:w.message,children:[e.jsx(Ll,{size:11}),w.message||"Save failed"]}),ce&&w.type!=="saving"&&e.jsx("span",{className:t.docUnsaved,children:"Unsaved changes"})]}),e.jsx("div",{className:t.docActions,children:D?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:t.docLayoutToggle,children:[e.jsx("button",{className:`${t.docLayoutBtn} ${$==="editor"?t.docLayoutBtnActive:""}`,onClick:()=>z("editor"),title:"Editor only",children:e.jsx(Wl,{size:12})}),e.jsx("button",{className:`${t.docLayoutBtn} ${$==="split"?t.docLayoutBtnActive:""}`,onClick:()=>z("split"),title:"Split view",children:e.jsx(_u,{size:12})}),e.jsx("button",{className:`${t.docLayoutBtn} ${$==="preview"?t.docLayoutBtnActive:""}`,onClick:()=>z("preview"),title:"Preview only",children:e.jsx(_l,{size:12})})]}),e.jsxs("button",{className:t.docActionBtn,onClick:ye,title:"Discard changes",children:[e.jsx(ga,{size:13}),"Cancel"]}),e.jsxs("button",{className:`${t.docActionBtn} ${t.docSaveBtn}`,onClick:ke,disabled:w.type==="saving"||!ce,title:"Save (Ctrl+S)",children:[e.jsx(Bc,{size:13}),w.type==="saving"?"Saving…":"Save"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:`${t.docActionBtn} ${t.docEditBtn}`,onClick:Ge,title:"Edit document",children:[e.jsx(Wl,{size:13}),"Edit"]}),e.jsxs("button",{className:t.docActionBtn,onClick:se,title:"Copy link",children:[e.jsx(ju,{size:13}),R?"Copied!":"Copy link"]}),e.jsxs("button",{className:t.docActionBtn,onClick:Ye,title:"Download .md",children:[e.jsx(Tu,{size:13}),"Download"]}),e.jsxs("button",{className:t.docActionBtn,onClick:Ae,title:"Print",children:[e.jsx(Nu,{size:13}),"Print"]}),e.jsxs("button",{className:t.docActionBtn,onClick:()=>he(q=>!q),title:"Toggle black and white style",children:[e.jsx(_l,{size:13}),J?"Color":"B/W"]}),a.docType==="implementation-plan"&&!D&&e.jsxs("button",{className:`${t.docActionBtn} ${t.docGenerateBtn}`,onClick:()=>Ne(!0),title:"Generate tasks from this plan",children:[e.jsx(Jo,{size:13}),"Generate Tasks"]})]})})]}),!D&&e.jsx("div",{className:t.docViewerTitleRow,children:e.jsx("h1",{className:t.docViewerTitle,children:a.title})}),h&&e.jsx("div",{className:t.docViewerState,children:"Loading…"}),!h&&x&&e.jsx("div",{className:t.docViewerStateError,children:x}),!h&&!x&&(D?e.jsxs("div",{className:`${t.docEditorArea} ${t[`docEditorLayout_${$}`]}`,children:[($==="editor"||$==="split")&&e.jsxs("div",{className:t.docEditorPane,children:[e.jsx("div",{className:t.docEditorPaneLabel,children:"Markdown"}),e.jsx("textarea",{ref:W,className:t.docEditorTextarea,value:f,onChange:q=>{I(q.target.value),T(M=>M.type==="saving"?M:{type:"idle"})},spellCheck:!0,placeholder:"Write markdown here…"})]}),($==="preview"||$==="split")&&e.jsxs("div",{className:t.docPreviewPane,children:[e.jsx("div",{className:t.docEditorPaneLabel,children:"Preview"}),e.jsx("div",{className:t.docMarkdown,children:e.jsx(jl,{remarkPlugins:[Tl],rehypePlugins:[od],components:ae,children:te})})]})]}):e.jsx("div",{className:t.docViewerContent,children:e.jsx("div",{className:t.docMarkdown,children:e.jsx(jl,{remarkPlugins:[Tl],rehypePlugins:[od],components:ae,children:te})})})),Z&&d!==null&&e.jsx(Oj,{content:d,docTitle:a.title,apiBaseUrl:r,onClose:()=>Ne(!1),onGenerated:q=>Ne(!1)})]})}function ld(a){let n=a;try{n=decodeURIComponent(a)}catch{n=a}return n.trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/^\.\//,"").replace(/^\.taskforce\//,"")}function qj(a,n){return!!(a===n||a.endsWith(`/${n}`)||n.endsWith(`/${a}`))}function Vj({tasks:a,apiBaseUrl:n="",requestedDocPath:r=null,onRequestedDocHandled:u}){const[d,m]=s.useState([]),[h,v]=s.useState(!0),[x,_]=s.useState(null),[R,j]=s.useState(null),[D,b]=s.useState(""),[f,I]=s.useState("all"),$=s.useCallback(async()=>{v(!0),_(null);try{const T=await Ur("/api/taskforce/documents",{credentials:"include"},n);if(!T.ok)throw new Error(`Failed to load documents (${T.status})`);const Z=await T.json();m(Z.documents||[])}catch(T){_(T?.message||"Failed to load documents")}finally{v(!1)}},[n]);s.useEffect(()=>{$()},[$]),s.useEffect(()=>{!R&&d.length>0&&j(d[0])},[d,R]),s.useEffect(()=>{if(!r||d.length===0)return;const T=ld(r),Z=d.find(Ne=>{const J=ld(Ne.fsPath);return qj(J,T)});if(Z){j(Z),u?.();return}},[r,d,u]);const z=d.filter(T=>{const Z=!D||T.title.toLowerCase().includes(D.toLowerCase()),Ne=f==="all"||T.docType===f;return Z&&Ne}),w=new Map(a.map(T=>[T.id,T]));return e.jsxs("div",{className:t.docWorkspace,children:[e.jsx("div",{className:t.docIndexPanel,children:e.jsx($j,{documents:z,selectedDocId:R?.id??null,loading:h,error:x,searchQuery:D,typeFilter:f,onSearchChange:b,onTypeFilterChange:I,onSelect:j,onRefresh:$,taskById:w})}),e.jsx("div",{className:t.docViewerPanel,children:R?e.jsx(Gj,{doc:R,taskTitle:R.taskId?w.get(R.taskId)?.title??null:null,apiBaseUrl:n,onSaved:T=>$()}):!h&&e.jsx("div",{className:t.docViewerEmpty,children:e.jsx("p",{children:d.length===0?"No documents found.":"Select a document to view it."})})})]})}const Kj=(a,n,r=.56)=>{const u=a.width*r,d=a.height*r,m=a.left+(a.width-u)/2,h=a.top+(a.height-d)/2,v=m+u,x=h+d,_=n.left+n.width/2,R=n.top+n.height/2;return _>=m&&_<=v&&R>=h&&R<=x},Sc="expired::";function Jj({tasks:a,columns:n,groupBy:r,searchQuery:u,copiedId:d,availableSpecialists:m,taxonomies:h,priorities:v,approaches:x,onUpdateTask:_,onTaskClick:R,onOpenTaskById:j,onCopyId:D,onToggleInProgress:b,onToggleReview:f,onToggleComplete:I,onToggleCancel:$,onArchiveTask:z,onUnarchive:w,onDelete:T,onUnlinkChildTask:Z,onClearParentTask:Ne,allTasks:J=[],hierarchyTasks:he=[],onAddTaskToColumn:ce,emptyColumnMode:W="show",filterCategories:U=[],filterTypes:Ge=[],filterPriorities:ye=[],filterStatus:ke=[],filterAssignees:Ae=["agent","user","unassigned"],assigneeFilterEnabled:se=!1,scheduleFilteredTaskIds:Ye,categories:We=[],compressed:Fe=!1,recentlyChangedTaskIds:te=[],scheduleDates:ne,onScheduleDaySelected:le,onScheduleParentDrop:dt,hierarchyChildOrderMode:ae="manual",persistedScrollLeft:q,onScrollLeftChange:M,sortBy:Q="created",sortOrder:de="desc"}){const[xe,B]=s.useState(null),[oe,et]=s.useState([]),[yt,ut]=s.useState(null),[mt,kt]=s.useState(!1),[Dt,Mt]=s.useState(!1),Zt=s.useMemo(()=>new Set(te),[te]),tt=s.useMemo(()=>new Set(a.map(L=>L.id)),[a]),pt=s.useCallback(L=>L.startsWith(Sc)?L.slice(Sc.length):L,[]),Rt=s.useCallback(L=>tt.has(pt(L)),[tt,pt]),wt=s.useMemo(()=>new Set(Ye||[]),[Ye]),Ut=s.useRef(new Map),V=Uu(Gl(Ju,{activationConstraint:{distance:5}}),Gl(Ku,{coordinateGetter:Vu})),Pe=L=>{const F=L.status||"task";return F==="done"||F==="cancelled"?"completed":F},_e=s.useMemo(()=>{const L=new Date,F=L.getFullYear(),re=String(L.getMonth()+1).padStart(2,"0"),K=String(L.getDate()).padStart(2,"0");return`${F}-${re}-${K}`},[]),Le=s.useMemo(()=>{const L=K=>{const H=K.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!H)return null;const me=new Date(Date.UTC(Number(H[1]),Number(H[2])-1,Number(H[3]))),Oe=me.getUTCDay()||7;me.setUTCDate(me.getUTCDate()+4-Oe);const ie=new Date(Date.UTC(me.getUTCFullYear(),0,1)),ve=Math.ceil(((me.getTime()-ie.getTime())/864e5+1)/7);return`${me.getUTCFullYear()}-W${String(ve).padStart(2,"0")}`};return{dates:{...(()=>{const K=new Date,H=K.getDay(),me=H===0?-6:1-H,Oe=new Date(K);Oe.setDate(K.getDate()+me);const ie=Se=>{const Ue=Se.getFullYear(),ht=String(Se.getMonth()+1).padStart(2,"0"),nt=String(Se.getDate()).padStart(2,"0");return`${Ue}-${ht}-${nt}`},ve={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((Se,Ue)=>{const ht=new Date(Oe);ht.setDate(Oe.getDate()+Ue),ve[Se]=ie(ht)}),ve})(),...ne||{}},parseToIsoWeekKey:L}},[ne]),ze=L=>{const F=L.scheduledDate||null;return F?new Map([[Le.dates.mon,"mon"],[Le.dates.tue,"tue"],[Le.dates.wed,"wed"],[Le.dates.thu,"thu"],[Le.dates.fri,"fri"],[Le.dates.sat,"sat"],[Le.dates.sun,"sun"]]).get(F)||"__offweek":"backlog"},N=he.length>0?he:J.length>0?J:a,G=s.useMemo(()=>Nc(N),[N]),je=s.useMemo(()=>{const L=new Set;for(const F of N)F.parentTaskId&&L.add(F.parentTaskId);return L},[N]),Ie=s.useMemo(()=>{const L=new Map;for(const F of N){if(!F.parentTaskId)continue;const re=L.get(F.parentTaskId)||[];re.push(F),L.set(F.parentTaskId,re)}return L},[N]),we=L=>!L.parentTaskId&&!je.has(L.id)?"standalone":String((G.get(L.id)??0)+1),qe=s.useMemo(()=>{const L=new Map;for(const F of n)L.set(String(F.value),F),L.has(F.label)||L.set(F.label,F);return L},[n]),vt=s.useMemo(()=>{const L={};return n.forEach(re=>{L[String(re.value)]=0}),(r==="hierarchy"?a:J).forEach(re=>{let K="";if(r==="status")K=Pe(re);else if(r==="schedule")K=ze(re);else if(r==="hierarchy")K=we(re);else{const me=re[r];K=String(me??"")}const H=qe.get(K);if(H&&L[String(H.value)]++,r==="schedule"){const me=re.status==="done"||re.status==="cancelled";re.scheduledDate&&!me&&re.scheduledDate<_e&&qe.has("expired")&&(L.expired=(L.expired||0)+1)}}),L},[J,a,n,r,G,qe,je,_e]),st=s.useMemo(()=>{const L={};if(n.forEach(F=>{L[String(F.value)]=[]}),a.forEach(F=>{let re="";if(r==="status")re=Pe(F);else if(r==="schedule")re=ze(F);else if(r==="hierarchy")re=we(F);else{const H=F[r];re=String(H??"")}const K=qe.get(re);if(K){if(r==="schedule"&&String(K.value)==="backlog"&&!wt.has(F.id))return;L[String(K.value)].push(F)}if(r==="schedule"){const H=F.status==="done"||F.status==="cancelled";F.scheduledDate&&!H&&F.scheduledDate<_e&&L.expired&&L.expired.push(F)}}),r==="schedule"){const F=(K,H)=>{const me=typeof K.orderInDay=="number"?K.orderInDay:Number.MAX_SAFE_INTEGER,Oe=typeof H.orderInDay=="number"?H.orderInDay:Number.MAX_SAFE_INTEGER;return me!==Oe?me-Oe:String(K.createdAt||"").localeCompare(String(H.createdAt||""))},re=(K,H)=>{let me=0;if(Q==="created")me=new Date(H.createdAt).getTime()-new Date(K.createdAt).getTime();else if(Q==="updated"){const Oe=K.updatedAt||K.createdAt,ie=H.updatedAt||H.createdAt;me=new Date(ie).getTime()-new Date(Oe).getTime()}else if(Q==="priority"){const Oe=typeof K.priority=="number"?K.priority:2;me=(typeof H.priority=="number"?H.priority:2)-Oe,me===0&&(me=new Date(H.createdAt).getTime()-new Date(K.createdAt).getTime())}else if(Q==="complexity"){const Oe=typeof K.complexity=="number"?K.complexity:3;me=(typeof H.complexity=="number"?H.complexity:3)-Oe,me===0&&(me=new Date(H.createdAt).getTime()-new Date(K.createdAt).getTime())}return de==="desc"?me:-me};Object.keys(L).forEach(K=>{if(K==="backlog"||K==="expired"){L[K].sort(re);return}L[K].sort(F)})}else if(r==="hierarchy"&&ae==="manual"){const F=N,re=new Map;F.forEach((Se,Ue)=>re.set(Se.id,Ue));const K=new Map;F.forEach(Se=>K.set(Se.id,Se));const H=new Map;F.forEach(Se=>{if(!Se.parentTaskId)return;const Ue=H.get(Se.parentTaskId)||[];Ue.push(Se),H.set(Se.parentTaskId,Ue)}),H.forEach((Se,Ue)=>{H.set(Ue,Pc(Se))});const me=F.filter(Se=>!Se.parentTaskId||!K.has(Se.parentTaskId));me.sort((Se,Ue)=>{const ht=re.get(Se.id)??Number.MAX_SAFE_INTEGER,nt=re.get(Ue.id)??Number.MAX_SAFE_INTEGER;return ht-nt});const Oe=new Map,ie=new Set,ve=(Se,Ue)=>{if(ie.has(Se.id))return;ie.add(Se.id),Oe.set(Se.id,Ue),(H.get(Se.id)||[]).forEach((nt,It)=>{ve(nt,[...Ue,It])})};me.forEach((Se,Ue)=>{ve(Se,[Ue])}),F.forEach(Se=>{if(!Oe.has(Se.id)){const Ue=re.get(Se.id)??Number.MAX_SAFE_INTEGER;Oe.set(Se.id,[Number.MAX_SAFE_INTEGER,Ue])}});const _t=(Se,Ue)=>{const ht=Oe.get(Se.id)||[Number.MAX_SAFE_INTEGER],nt=Oe.get(Ue.id)||[Number.MAX_SAFE_INTEGER],It=Math.max(ht.length,nt.length);for(let rt=0;rt<It;rt+=1){const ot=ht[rt]??-1,y=nt[rt]??-1;if(ot!==y)return ot-y}const jt=re.get(Se.id)??Number.MAX_SAFE_INTEGER,Vt=re.get(Ue.id)??Number.MAX_SAFE_INTEGER;return jt-Vt};Object.keys(L).forEach(Se=>{L[Se].sort(_t)})}return L},[a,n,r,G,qe,je,wt,_e,ae,N,Q,de]),Re=xe?pt(xe):null,bt=Re?a.find(L=>L.id===Re):null,De=s.useRef(null),Jt=s.useRef(null),St=s.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),ls=s.useRef(-1),Ee=(L,F)=>r==="category"?!U.includes(String(L)):r==="type"?!Ge.includes(String(L)):r==="priority"?!ye.some(re=>Number(re)===Number(L)):r==="status"?String(L)==="completed"?!ke.includes("done")&&!ke.includes("cancelled"):!ke.includes(String(L)):r==="assignee"?se&&!Ae.includes(String(L)):!1,zt=s.useMemo(()=>{let K=0;return n.forEach((H,me)=>{const Oe=st[String(H.value)]||[],ie=Ee(H.value,H.label),ve=r!=="schedule"&&W==="hide"&&Oe.length===0;if(ie||ve)return;const _t=W==="collapse"&&Oe.length===0;K+=_t?72:320,K+=4}),K},[n,st,W,r,U,Ge,ye,ke]),ts=s.useCallback(L=>{if(!M)return;const F=Math.max(0,Math.round(L));F!==ls.current&&(ls.current=F,M(F))},[M]);s.useEffect(()=>{const L=De.current,F=Jt.current;if(!L||!F)return;let re=!1,K=!1;const H=()=>{!L||K||(re=!0,L.scrollLeft=F.scrollLeft,ts(F.scrollLeft),setTimeout(()=>re=!1,0))},me=()=>{!F||re||(K=!0,F.scrollLeft=L.scrollLeft,ts(L.scrollLeft),setTimeout(()=>K=!1,0))};return F.addEventListener("scroll",H),L.addEventListener("scroll",me),()=>{F.removeEventListener("scroll",H),L.removeEventListener("scroll",me)}},[ts]);const Et=s.useRef(!1);s.useEffect(()=>{if(Et.current)return;if(typeof q!="number"||!Number.isFinite(q)){Et.current=!0;return}const L=De.current,F=Jt.current;if(!L||!F)return;const re=Math.max(0,L.scrollWidth-L.clientWidth),K=Math.min(Math.max(0,q),re);L.scrollLeft=K,F.scrollLeft=K,Et.current=!0},[q,zt]),s.useEffect(()=>{const L=()=>{const F=De.current;if(!F){Mt(!1);return}Mt(F.scrollWidth>F.clientWidth+4)};return L(),window.addEventListener("resize",L),()=>{window.removeEventListener("resize",L)}},[zt,n.length,st]),s.useEffect(()=>{const L=re=>{const K=St.current;if(K.pointerId===null||K.pointerId!==re.pointerId)return;const H=re.clientX-K.startX,me=re.clientY-K.startY;if(!K.didPan){if(Math.abs(H)<7||Math.abs(H)<Math.abs(me))return;K.didPan=!0,kt(!0),document.body.style.userSelect="none"}const Oe=K.startScrollLeft-H;De.current&&(De.current.scrollLeft=Oe),Jt.current&&(Jt.current.scrollLeft=Oe),re.preventDefault()},F=()=>{const re=St.current;re.pointerId!==null&&(re.pointerId=null,re.didPan=!1,mt&&(kt(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",L),window.addEventListener("pointerup",F),window.addEventListener("pointercancel",F),()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",F),window.removeEventListener("pointercancel",F),document.body.style.userSelect=""}},[mt]),s.useEffect(()=>()=>{Ut.current.forEach(L=>window.clearTimeout(L)),Ut.current.clear()},[]);const qt=L=>{!Dt||L.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(St.current.pointerId=L.pointerId,St.current.startX=L.clientX,St.current.startY=L.clientY,St.current.startScrollLeft=De.current?.scrollLeft||0,St.current.didPan=!1)},Ct=L=>{B(L.active.id),ut(null)},As=L=>{if(r==="schedule"){ut(null);return}const{active:F,over:re}=L;if(!re){ut(null);return}const K=String(F.id),H=String(re.id),me=pt(K),Oe=pt(H),ie=a.find(_t=>_t.id===me),ve=a.find(_t=>_t.id===Oe);if(!ie||!ve||ie.id===ve.id){ut(null);return}ut(ve.id)},ds=L=>{const{active:F,over:re}=L;B(null),ut(null);const K=String(F.id),H=re?String(re.id):null,me=pt(K),Oe=H?pt(H):null,ie=a.find(jt=>jt.id===me);if(!ie||!H)return;const ve=Oe?a.find(jt=>jt.id===Oe):void 0;if(r!=="schedule"&&ve&&ve.id!==ie.id){const jt=re?.rect,Vt=F.rect.current.translated,rt=F.rect.current.initial,ot=Vt||rt;if(jt&&ot&&Kj(jt,ot)){if(ie.parentTaskId===ve.id)return;const ue=J.length>0?J:a;if(Il(ie.id,ve.id,ue)){window.alert(`Cannot link child ${ie.id} to parent ${ve.id}: link would create a cycle.`);return}if(Nl(ie.parentTaskId,ve.id)&&!window.confirm(`Task ${ie.id} is already parented to ${ie.parentTaskId}. Re-parent it to ${ve.id}?`))return;_(ie.id,{parentTaskId:ve.id}),et(ps=>Array.from(new Set([...ps,ve.id])));const Ke=Ut.current.get(ve.id);Ke&&window.clearTimeout(Ke);const At=window.setTimeout(()=>{Ut.current.delete(ve.id),et(ps=>ps.filter(Kt=>Kt!==ve.id))},1800);Ut.current.set(ve.id,At);return}}const _t=Ss(K),Ue=String(F?.data?.current?.sortable?.containerId||"")||_t,nt=String(re?.data?.current?.sortable?.containerId||"")||Ss(H);if(!nt)return;const It=qe.get(nt)||n.find(jt=>String(jt.value)===nt||jt.label===nt);if(It){if(r==="hierarchy")return;if(r==="schedule"){const rt=String(It.value),ot=["mon","tue","wed","thu","fri","sat","sun"],y=rt==="backlog"||rt==="expired"||ot.includes(rt),ue=Qe=>{let ft=Qe.length;const ss=ve?.id||(H&&Rt(H)?pt(H):null);if(!ss||!tt.has(ss))return ft;const Xt=ss,Xe=Qe.findIndex($t=>$t.id===Xt);if(Xe<0)return ft;const at=re?.rect,bs=F.rect.current.translated||F.rect.current.initial,xt=!!(at&&bs&&bs.top+bs.height/2>at.top+at.height/2);return Xe+(xt?1:0)},Ke=(Qe,ft,ss)=>{if(!Qe||Qe===ft)return;(st[String(Qe)]||[]).filter(Xe=>Xe.id!==me).forEach((Xe,at)=>{ss.set(Xe.id,{...ss.get(Xe.id)||{},orderInDay:at})})};if(rt==="expired"){if(Ue!=="expired")return;const Qe=new Map,ft=(st.expired||[]).filter(Xe=>Xe.id!==me),ss=ue(ft),Xt=[...ft];Xt.splice(ss,0,ie),Xt.forEach((Xe,at)=>{Qe.set(Xe.id,{...Qe.get(Xe.id)||{},orderInDay:at})}),Qe.forEach((Xe,at)=>_(at,Xe));return}if(rt==="backlog"){const Qe=new Map,ft=(st.backlog||[]).filter(Xe=>Xe.id!==me),ss=ue(ft),Xt=[...ft];Xt.splice(ss,0,ie),Xt.forEach((Xe,at)=>{Xe.id===me?ie.scheduledDate?Qe.set(Xe.id,{...Qe.get(Xe.id)||{},scheduledDate:null,scheduledWeekKey:null,orderInDay:at}):Qe.set(Xe.id,{...Qe.get(Xe.id)||{},orderInDay:at}):Qe.set(Xe.id,{...Qe.get(Xe.id)||{},orderInDay:at})}),Ke(Ue,rt,Qe),Qe.forEach((Xe,at)=>_(at,Xe));return}if(!y||!ot.includes(rt))return;const At=Le.dates[rt];if(!At)return;if(!(ie.status==="done"||ie.status==="cancelled")&&At<_e){window.alert("Only completed work can be scheduled in the past.");return}const Kt=Le.parseToIsoWeekKey(At);if(Ie.has(ie.id)){const Qe=[...Ie.get(ie.id)||[]],ft=[];for(;Qe.length>0;){const Bt=Qe.shift();ft.push(Bt);const bs=Ie.get(Bt.id)||[];bs.length>0&&Qe.push(...bs)}const Xt=ft.filter(Bt=>!Ie.has(Bt.id)).filter(Bt=>!Bt.isArchived&&Bt.status!=="done"&&Bt.status!=="cancelled"),Xe=Xt.filter(Bt=>!Bt.scheduledDate),at=Math.max(0,Xt.length-Xe.length);dt?.({parentTaskId:ie.id,parentTitle:ie.title,targetColumn:rt,targetDate:At,toScheduleLeafTaskIds:Xe.map(Bt=>Bt.id),alreadyScheduledLeafCount:at,totalLeafDescendants:Xt.length}),le?.(At);return}const Lt=new Map,vs=(st[rt]||[]).filter(Qe=>Qe.id!==me),Ms=ue(vs),Bs=[...vs];Bs.splice(Ms,0,ie),Bs.forEach((Qe,ft)=>{Qe.id===me?Lt.set(Qe.id,{...Lt.get(Qe.id)||{},scheduledDate:At,scheduledWeekKey:Kt,orderInDay:ft}):Lt.set(Qe.id,{...Lt.get(Qe.id)||{},orderInDay:ft})}),Ke(Ue,rt,Lt),Lt.forEach((Qe,ft)=>_(ft,Qe)),le?.(At);return}let jt=It.value;if(r==="status"){const rt=Pe(ie),ot=String(jt);if(rt!==ot){const y={status:ot};ot==="task"||ot==="on-hold"?(y.inProgress=!1,y.readyForReview=!1,y.completed=!1,y.cancelled=!1):ot==="in-progress"?(y.inProgress=!0,y.readyForReview=!1,y.completed=!1,y.cancelled=!1):ot==="review"?(y.inProgress=!1,y.readyForReview=!0,y.completed=!1,y.cancelled=!1):ot==="done"||ot==="completed"?(y.status="done",y.inProgress=!1,y.readyForReview=!1,y.completed=!0,y.cancelled=!1,y.completedAt=new Date().toISOString()):ot==="cancelled"&&(y.status="cancelled"),_(ie.id,y)}return}(r==="priority"||r==="complexity")&&(jt=Number(jt));const Vt=ie[r];if(String(Vt??"")!==String(jt??"")){const rt={[r]:jt};_(ie.id,rt)}}},Ss=L=>{if(qe.has(L)){const K=qe.get(L);return K?String(K.value):L}if(r==="schedule"&&L.startsWith(Sc))return"expired";const F=pt(L),re=a.find(K=>K.id===F);if(re){let K="";r==="status"?K=Pe(re):r==="schedule"?K=ze(re):r==="hierarchy"?K=we(re):K=String(re[r]??"");const H=qe.get(K);return H?String(H.value):null}return null},Ds={sideEffects:Zu({styles:{active:{opacity:"0"}}})},us=L=>{const F=qu(L);if(F.length>0){const re=L.pointerCoordinates;if(!re)return[F[0]];const K=F.filter(ie=>{const ve=String(ie.id);return Rt(ve)&&ve!==xe});if(K.length===0){const ve=F.filter(Ue=>{const ht=String(Ue.id);return!Rt(ht)}).find(Ue=>!!Ss(String(Ue.id)))||null,_t=ve?Ss(String(ve.id)):null,Se=(L.droppableContainers||[]).filter(Ue=>{const ht=String(Ue.id);return!Rt(ht)||ht===xe?!1:_t?Ss(ht)===_t:!0});if(Se.length>0){const Ue=ql({...L,droppableContainers:Se});if(Ue.length>0)return[Ue[0]]}return ve?[ve]:[F[0]]}const H=K;let me=H[0],Oe=Number.POSITIVE_INFINITY;for(const ie of H){const ve=L.droppableRects?.get(ie.id);if(!ve)continue;const _t=ve.left+ve.width/2,Se=ve.top+ve.height/2,Ue=re.x-_t,ht=re.y-Se,nt=Ue*Ue+ht*ht;nt<Oe&&(Oe=nt,me=ie)}return[me]}return ql(L)},Cs={searchQuery:u,copiedId:d,allTasks:he.length>0?he:J.length>0?J:a,availableSpecialists:m,taxonomies:h,priorities:v,approaches:x,onCopyId:D,onToggleInProgress:b,onToggleReview:f,onToggleComplete:I,onToggleCancel:$,onArchiveTask:z,onUnarchive:w,onDelete:T,onOpenTaskById:j,onUnlinkChildTask:Z,onClearParentTask:Ne,categories:We,changedTaskIdSet:Zt,linkedParentIdSet:new Set(oe),parentDropTargetId:yt,groupBy:r,scheduleParentIdSet:je};return e.jsxs(Hu,{sensors:V,collisionDetection:us,onDragStart:Ct,onDragOver:As,onDragEnd:ds,onDragCancel:()=>{B(null),ut(null)},children:[e.jsxs("div",{className:t.kanbanWrapper,children:[e.jsx("div",{ref:Jt,className:t.kanbanTopScroll,children:e.jsx("div",{className:t.kanbanTopScrollSpacer,style:{width:`${zt}px`}})}),e.jsx("div",{className:t.kanbanContainer,ref:De,children:n.map(L=>{const F=st[String(L.value)]||[],re=Ee(L.value,L.label),K=r!=="schedule"&&W==="hide"&&F.length===0,H=r==="schedule",me=H&&n.some(nt=>String(nt.value)==="backlog"),Oe=H&&String(L.value)==="backlog",ie=H&&String(L.value)==="expired",ve=st.backlog||[],Se=W==="collapse"&&ve.length===0?72:320,Ue=Oe?0:ie?me?Se+4:0:void 0,ht=Oe?6:ie?5:void 0;return re||K?null:e.jsx(Yj,{id:String(L.value),title:L.label,color:L.color,icon:L.icon,tasks:F,activeId:xe,activeTaskId:Re,totalCount:vt[String(L.value)],onAddTask:()=>ce?.(r,L.value),onTaskClick:R,commonCardProps:Cs,collapseEmpty:W==="collapse",compressed:Fe,onHeaderPointerDown:qt,isHeaderPanning:mt,headerPanEnabled:Dt,stickyLeft:Ue,stickyZIndex:ht,isPast:!!L.isPast,isSelected:!!L.isSelected,isWeekend:!!L.isWeekend,disableSorting:!1,scheduleDate:r==="schedule"?Le.dates[String(L.value)]:void 0,onScheduleDaySelected:le},String(L.value))})})]}),Ci.createPortal(e.jsx(Gu,{dropAnimation:Ds,children:bt?e.jsx(Qo,{task:bt,isOverlay:!0,...Cs,isArchived:bt.isArchived,categories:We,compressed:Fe,isRecentlyChanged:Zt.has(bt.id)}):null}),document.body)]})}function Yj({id:a,title:n,color:r,icon:u,tasks:d,activeId:m=null,activeTaskId:h=null,totalCount:v,onAddTask:x,onTaskClick:_,commonCardProps:R,collapseEmpty:j,compressed:D,onHeaderPointerDown:b,isHeaderPanning:f=!1,headerPanEnabled:I=!1,stickyLeft:$,stickyZIndex:z,isPast:w=!1,isSelected:T=!1,isWeekend:Z=!1,disableSorting:Ne=!1,scheduleDate:J,onScheduleDaySelected:he}){const{setNodeRef:ce}=Yu({id:a,data:{type:"Column"}}),W=j&&d.length===0,U=h?d.filter(se=>se.id!==h):d,Ge=typeof $=="number",ye=s.useRef(null),ke=se=>a==="expired"?`${Sc}${se}`:se,Ae=se=>{if(!J||!he)return;const Ye=se.target;Ye&&(Ye.closest(`.${t.taskItem}`)||Ye.closest(`.${t.kanbanCardWrapper}`)||he(J))};return e.jsxs("div",{ref:ce,className:`${t.kanbanColumn} ${W?t.kanbanColumnCollapsed:""} ${Ge?t.kanbanColumnSticky:""} ${w?t.kanbanColumnPast:""} ${T?t.kanbanColumnSelectedDay:""} ${Z?t.kanbanColumnWeekend:""}`,style:Ge?{left:`${$}px`,zIndex:z??4}:void 0,onClick:Ae,children:[e.jsxs("div",{className:`${t.kanbanHeader} ${I?t.kanbanHeaderDraggable:""} ${f?t.kanbanHeaderPanning:""}`,style:{borderTopColor:ys(r)||"var(--color-purple)"},onPointerDown:b,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const se=u&&fo[u]?fo[u]:ho,Ye=ys(r)||"var(--color-purple)";return e.jsx(se,{size:16,style:{color:Ye}})})(),!W&&e.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!W||v>0)&&e.jsx("span",{className:t.kanbanCount,children:W?v:`${d.length} / ${v}`}),e.jsx("button",{className:t.kanbanQuickAdd,onClick:se=>{se.stopPropagation(),x()},title:`Add task to ${n}`,"data-no-header-pan":"true",children:e.jsx(cn,{size:14})})]})]}),e.jsx("div",{className:t.kanbanDroppable,children:e.jsx("div",{className:t.kanbanDroppableScroll,ref:ye,children:Ne?U.map(se=>e.jsx("div",{className:t.kanbanCardWrapper,children:e.jsx(Qo,{task:se,onClick:_,...R,isArchived:se.isArchived,compressed:D,isRecentlyChanged:!1})},se.id)):e.jsx(Xu,{id:a,items:U.map(se=>ke(se.id)),strategy:Qu,children:U.map(se=>e.jsx(Xj,{sortableId:ke(se.id),task:se,onClick:_,commonCardProps:R,compressed:D,isRecentlyChanged:R.changedTaskIdSet?.has(se.id)},ke(se.id)))})})})]})}function Xj({sortableId:a,task:n,onClick:r,commonCardProps:u,compressed:d,isRecentlyChanged:m=!1}){const{attributes:v,listeners:x,setNodeRef:_,transform:R,transition:j,isDragging:D}=ep({id:a,disabled:!1}),b={transform:tp.Transform.toString(R),transition:j,opacity:D?0:1,pointerEvents:D?"none":"auto"},f=u?.groupBy==="schedule",I=!f&&(m||u?.parentDropTargetId===n.id||!!u?.linkedParentIdSet?.has(n.id));return e.jsx("div",{ref:_,style:b,...v,...x,className:`${t.kanbanCardWrapper} ${I?t.kanbanCardWrapperRaised:""}`,children:e.jsx(Qo,{task:n,onClick:r,...u,isArchived:n.isArchived,compressed:d,isRecentlyChanged:f?!1:m})})}const Vo="/taskforce/assets/logo_white_01-0Vx-iIIv.png",dd="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEpklEQVR4AcSWZ6hURxSA774U00hCYkISX4zpf9KEFEhM0/RCEjCNQAwkPxICiViwvmfDJ4gKYvllRWxg7703sKFYsRcsKPZeeH7f3Z1V2XLXP75lvj1n5p45c+7MmZlbFtXwr+YDqK6u/rWmJoGxf3MGKlGq4J7bFQhj1YIqxqs0gCEobWATjX/A3eglF+xToMPypE7Y3QW/Y7cRHHOwAQyj0gfqwWDYhZGz8hjyeep5C88c+Gcezoed0AhyCnb1oDa05+EuGArPQT8YagCvobwO3WAEuBSdkDptRsd28DT1bKH+CJW+MAo+hMOwAbIFmzrQiobmsAO6wH1gH6c/HtcAZtJ4CNrC97AOpsIS2AMnYSXOXKKeyLqpVOoYbfMglP60reZZOXQHg1nDw3OwD1aAPm37Fr0dOObMMjpWU/kH/gMHrY/8Gr6Av+AIOGXOylvoixmgFvI9CKUs07aIhrfBt30W6czo4zN0fb6JXA7/w9+O7QygR2f5awwmkkGMRp8Au6EDLIQ7QEcm7Vj0PyGUrijjwHz6HKmtfTqju+7jkU79YuST8CM4ZhQHQCQXafCNTZAH0F+BF+AhOAMvwnDYDtPgTngQQqmNkoLJsBm0tY/Lpw99ueb2iYPMjJkOgA4RDeeROreTa3+Juh1NUIMwyDq0TQR3DSJbXMbe1KaAU6/tafQ3wEAuI53N48gpjGVuoEbXA7DGA5PH9ZlLfQ44bU7tNvSDoOPHkS6Xa4kal2X8/wI+u4A0wewzBn0k6GsBsiljeAagpku8BGk1/Y+Bb+8WcwbepdUtaF58h+42MiHdhg5KU1yW8u8yeG5o8w11E/IZpMl6Fdkb384C6vWSE4CPMLwEFVAfGoD6ep49BS3A2XB3oMbFbWmytaRWjv0G6Aj21UdbdF+IxzeXvAHcbJKusc1+QtsEn4Jr6/4+gW7O+GbvoH8CG7H1hERNLiUFgEMHr8TdvWCWO1hDdAOSj9Dd/1uQ2lTQp6QgEgPAkVk9CMeubQ+kGT8D6ZTORs4C13g68gpoYxCD6GtO0FS4JAZAVy+R+5EG4l72uPbM8PT0W8LZ+ZfnX8IP4LY1UQ24gnrRUjQA3sAj1wF04hb0zdQDKRRBZIvXubY2NMaHl5t6XooGQI9XwZMREZlodaPkn2/vjtDSmdOHel6SAvBg8UwPa70WL655wPPB88AbVcyD1dgoPVX9VnDr0pS/JAXg8ex979b7ABceTF5IgQa0vQ9eQGIe2Gafr2j/GLLHLnpOSQpgKz3MekTkqeYyqBfD6XcZgo3bNug5smgAnF4H6OGUIqKHoyg6BUnFC0db7dbiY79KIYoGkOnUMyMVOvcMCOvt/W4e2Cauu6ejtuKZoCxIKQGEjxMT61E8PQFhvV1/19xzQfzY0MbPr0nYeRMiCpfEAJhCc6AJLvyYMPm8iPIllt8MTrfBGUSTTF+6Fi6JAdgVR669F00v6t4BLsFR9FDUnSEH98OkIX1uXIpglyNLCsBeOLwAfmK/RH0VDABvRN96ILpf0y9j40eH25em5FJyAMEVA+yFKmgDjcC3bY3sCqVs0+AqlrccQNzrFv6STK8BAAD///S0NyEAAAAGSURBVAMAzDByUNjwlcAAAAAASUVORK5CYII=",Cc="/taskforce/assets/taskforce-BxLPokNB.png",ud=["mon","tue","wed","thu","fri","sat","sun"],Qj={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"},Zj=220,eT=1200,tT=1800;function Or(a){const n=a.getFullYear(),r=String(a.getMonth()+1).padStart(2,"0"),u=String(a.getDate()).padStart(2,"0");return`${n}-${r}-${u}`}function xc(a){const n=a.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const r=new Date(Number(n[1]),Number(n[2])-1,Number(n[3]));return Number.isNaN(r.getTime())?null:r}function Sl(a,n){const r=a.getDay(),u=n==="sunday"?-r:r===0?-6:1-r,d=new Date(a);return d.setHours(0,0,0,0),d.setDate(d.getDate()+u),d}function sT(a,n){return n==="sunday"?{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}[a]:{mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6}[a]}function pd(a,n){const r=new Date(a);return r.setDate(a.getDate()+n),r}function hd(a){const n=a.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!n)return null;const r=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),u=r.getUTCDay()||7;r.setUTCDate(r.getUTCDate()+4-u);const d=new Date(Date.UTC(r.getUTCFullYear(),0,1)),m=Math.ceil(((r.getTime()-d.getTime())/864e5+1)/7);return`${r.getUTCFullYear()}-W${String(m).padStart(2,"0")}`}function aT(a){const n=Sd(),r=Cd(),{activeTab:u,setActiveTab:d,activeCategories:m,groupBy:h,setGroupBy:v,emptyColumnMode:x,setEmptyColumnMode:_,zenMode:R,setZenMode:j,filterStatus:D,setFilterStatus:b,parentTaskFilterMode:f,setParentTaskFilterMode:I,tasks:$,handleEdit:z,handleSubmit:w,resetForm:T,handleUpdateTask:Z,editingTaskId:Ne,loading:J,error:he,title:ce,setTitle:W,description:U,setDescription:Ge,category:ye,setCategory:ke,type:Ae,setType:se,priority:Ye,setPriority:We,complexity:Fe,setComplexity:te,approach:ne,setApproach:le,assignee:dt,setAssignee:ae,scheduledDate:q,setScheduledDate:M,dueDate:Q,setDueDate:de,parentTaskIdInput:xe,setParentTaskIdInput:B,addChildTaskIdInput:oe,setAddChildTaskIdInput:et,manualComplexityEnabled:yt,checklistDropdownEnabled:ut,formTaxonomies:mt,setFormTaxonomies:kt,selectedSpecialists:Dt,setSelectedSpecialists:Mt,comments:Zt,newCommentText:tt,setNewCommentText:pt,screenshots:Rt,setScreenshots:wt,descriptionFocused:Ut,setDescriptionFocused:V,showMarkdownHelp:Pe,setShowMarkdownHelp:_e,showSpecialists:Le,setShowSpecialists:ze,showChecklist:N,setShowChecklist:G,showTaskRelationships:je,setShowTaskRelationships:Ie,showChildTasks:we,setShowChildTasks:qe,showComments:vt,setShowComments:st,handleAddComment:Re,handleSetParentForCurrentTask:bt,handleAddChildToCurrentTask:De,handleCreateChildForCurrentTask:Jt,handleUnlinkChildTask:St,handleReorderChildTasks:ls,handleClearParentTask:Ee,handleOpenTaskById:zt,taxonomies:ts,activeTypes:Et,priorities:qt,approaches:Ct,availableSpecialists:As,copiedId:ds,handleCopyId:Ss,handleToggleInProgress:Ds,handleToggleComplete:us,handleToggleReview:Cs,handleToggleCancel:L,handleArchiveTask:F,handleDelete:re,handleUnarchive:K,fetchTasks:H,searchQuery:me,setSearchQuery:Oe,filterCategories:ie,setFilterCategories:ve,filterTypes:_t,setFilterTypes:Se,filterPriorities:Ue,setFilterPriorities:ht,filterAssignees:nt,setFilterAssignees:It,sortBy:jt,setSortBy:Vt,clearFilters:rt,settingsModel:ot,currentTheme:y,setCurrentTheme:ue,pathSaved:Ke,saveSettings:At,keyShortcut:ps,setKeyShortcut:Kt,globalWeekStartsOn:Lt,locale:vs,jsonBackupEnabled:Ms,setJsonBackupEnabled:Bs,assigneeFilterEnabled:Qe,mcpHostRoot:ft,setMcpHostRoot:ss,settingsSection:Xt,setSettingsSection:Xe,runtimeMode:at,workspaceSwitchingEnabled:Bt,cloudAuthConfigured:bs,authRequiredForApi:xt,authBlocked:$t,isAuthenticated:O,authUserEmail:Ve,authSessionResolved:Ft,realtimeSyncEnabled:Tt,realtimeSyncFlagSource:Ot,workspaceCloudSyncEnabled:Je,realtimeConnectionState:Yt,realtimeTelemetry:Ht,workspaceSyncSourceOfTruth:Ls,workspaceSyncOnboardingCompleted:Us,workspaceSyncReady:qs,workspaceCloudHydrated:ya,saveWorkspaceCloudSyncSettings:na,userGlobalSyncStatus:Vs,userGlobalLastSyncedAt:ua,workspaceLastPullAt:$s,workspaceLastPushAt:P,workspaceLastErrorAt:S,workspaceRetryAt:Y,workspaceBootstrapSyncInProgress:pe,workspaceBootstrapSyncPages:Te,workspaceBootstrapSyncAppliedChanges:Nt,userGlobalSyncPendingChanges:Ze,userGlobalSyncError:$e,workspaceLastErrorMessage:hs,workspaceLastWarningMessage:as,workspaceSyncFailureCount:Ns,workspaceSyncRetryScheduledCount:Ca,workspaceSyncAuthFailureCount:ns,workspaceSyncLastFailureSource:_s,workspaceSyncLastFailureStatusCode:_a,retryWorkspaceCloudSync:Rs,resetWorkspaceSyncCursorAndPull:xo,currentWorkspaceId:ms,availableWorkspaces:vo,createWorkspace:bo,switchWorkspace:er,logout:tr,projectRoot:Ni,projectName:Za,mcpScriptPath:sr,serverHostRoot:ar,showFolderBrowser:nr,setShowFolderBrowser:Pn,folders:wo,files:or,currentBrowsePath:ka,fetchFolders:So,browserTarget:oa,setBrowserTarget:Ii,contextLinkBrowsePath:Hr,handleSelectPath:Gr,handleAddPath:zc,handleRemovePath:Lc,handleUpdateCategory:Ys,handleRemoveCategory:Rc,handleSaveCategory:rr,handleUpdateCategoryIcon:ir,handleUpdateCategoryColor:Co,handleSaveType:cr,handleRemoveType:Ai,handleUpdateTaxonomies:qr,handleUpdatePriorities:Vr,handleUpdateApproaches:lr,pathValidation:Di,exportEnvironment:Bi,setExportEnvironment:Pi,exportWorkflowsPath:zi,setExportWorkflowsPath:Li,exportSpecialistsPath:Ri,setExportSpecialistsPath:Kr,exportResult:it,handleExportResources:ws,exportingResource:ja,availableWorkflows:ln,onExportWorkflows:dr,fetchWorkflows:Jr,availableEnvironments:Gt,successBanner:Fs,returnToParentTaskId:Ps,returnFromChildTaskId:Fa,clearReturnToParentTask:Ec,tasksScrollRef:Ei,setTasksScrollPos:ct,commentsEndRef:Mi,unsavedModalOpen:Mc,setUnsavedModalOpen:Yr,pendingNavigation:ur,handleNavigation:$i,currentTask:_o,currentTaskParent:Xr,currentTaskChildren:Qr,cancellationPromptTask:jo,cancellationOpenDescendantIds:zn,cancellationMode:dn,setCancellationMode:Xs,confirmCancellation:To,cancelCancellationPrompt:es,scheduleWarningPrompt:Ln,confirmScheduleWarning:pr,cancelScheduleWarning:Fi}=a,un=vs||Ad();s.useEffect(()=>{const c=String(Za||"").trim();document.title=c?`Taskforce - ${c}`:"Taskforce"},[Za]);const Ta=()=>{Yr(!1),ur?(u==="add"&&T(),ur()):(u==="add"&&T(),d("tasks"))},Na=async()=>{await w({preventDefault:()=>{}}),Yr(!1),ur&&ur()},[Oa,No]=s.useState(!1),[Wa,hr]=s.useState(!1),[Qs,Zr]=s.useState(!0),[Be,Ks]=s.useState(!1),[Zs,mr]=s.useState(!0),[Ua,fr]=s.useState(!0),[Ce,pn]=s.useState(""),[is,Oi]=s.useState(!0),[Rn,Wi]=s.useState("manual"),[Io,En]=s.useState(""),[hn,Mn]=s.useState(Or(new Date)),[gr,$n]=s.useState(()=>{const c=new Date;return`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}`}),[ei,Ui]=s.useState(0),[Ao,Do]=s.useState(!1),[$c,Hi]=s.useState(null),[Gi,qi]=s.useState(!1),Vi=s.useRef("category"),Ki=s.useRef(""),Fn=s.useMemo(()=>{const c={},k=String(ms||"").trim();return at==="cloud"&&k&&k!=="default"&&(c["x-taskforce-workspace-id"]=k),c},[at,ms]),ti=s.useMemo(()=>`${at}:${String(ms||"default").trim()||"default"}`,[at,ms]);s.useEffect(()=>{const c=k=>{const A=k,fe=A.detail?.fsPath;fe&&(A.preventDefault(),Hi(fe),h!=="docs"&&v("docs"))};return window.addEventListener("taskforce:open-markdown-document",c),()=>{window.removeEventListener("taskforce:open-markdown-document",c)}},[h,v]),s.useEffect(()=>{if(Ki.current===ti)return;Ki.current=ti,qi(!1);let c=!1;return(async()=>{try{const A=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:Fn});if(!A.ok)return;const fe=await A.json().catch(()=>({})),ge=fe?.state&&typeof fe.state=="object"?fe.state:null;if(!ge||c)return;typeof ge.scheduleShowWeekends=="boolean"&&hr(ge.scheduleShowWeekends),typeof ge.scheduleShowBacklog=="boolean"&&Zr(ge.scheduleShowBacklog),typeof ge.scheduleOnlyExpired=="boolean"&&Ks(ge.scheduleOnlyExpired),typeof ge.scheduleSidebarOpen=="boolean"&&mr(ge.scheduleSidebarOpen),typeof ge.hierarchySidebarOpen=="boolean"&&fr(ge.hierarchySidebarOpen),typeof ge.hierarchyRootTaskId=="string"&&pn(ge.hierarchyRootTaskId),typeof ge.hierarchyShowUnlinkedColumn=="boolean"&&Oi(ge.hierarchyShowUnlinkedColumn),(ge.hierarchyChildOrderMode==="manual"||ge.hierarchyChildOrderMode==="auto")&&Wi(ge.hierarchyChildOrderMode),typeof ge.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(ge.scheduleSelectedDate)&&Mn(ge.scheduleSelectedDate),typeof ge.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(ge.scheduleCalendarMonth)&&$n(ge.scheduleCalendarMonth),typeof ge.scheduleScrollLeft=="number"&&Number.isFinite(ge.scheduleScrollLeft)&&ge.scheduleScrollLeft>=0&&Ui(ge.scheduleScrollLeft),typeof ge.showFilters=="boolean"&&Do(ge.showFilters)}catch{}finally{c||qi(!0)}})(),()=>{c=!0}},[ti,Fn]),s.useEffect(()=>{if(!Gi)return;const c=window.setTimeout(async()=>{try{await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json",...Fn},credentials:"include",body:JSON.stringify({stateKey:"layout",patch:{scheduleShowWeekends:Wa,scheduleShowBacklog:Qs,scheduleOnlyExpired:Be,scheduleSidebarOpen:Zs,hierarchySidebarOpen:Ua,hierarchyRootTaskId:Ce,hierarchyShowUnlinkedColumn:is,hierarchyChildOrderMode:Rn,scheduleSelectedDate:hn,scheduleCalendarMonth:gr,scheduleScrollLeft:ei,showFilters:Ao}})})}catch{}},250);return()=>window.clearTimeout(c)},[Gi,Wa,Qs,Be,Zs,Ua,Ce,is,Rn,hn,gr,ei,Ao,Fn]),s.useEffect(()=>{h!=="docs"&&(Vi.current=h)},[h]),s.useEffect(()=>{h==="schedule"&&mr(!0),h==="hierarchy"&&fr(!0)},[h]);const{showArchive:Bo,setShowArchive:Fc,fetchArchive:Oc,filteredArchive:yr}=a,On=s.useMemo(()=>{if(!Bo)return a.filteredTasks;const c=yr.map(k=>({...k,isArchived:!0}));return[...a.filteredTasks,...c]},[a.filteredTasks,yr,Bo]),kr=s.useMemo(()=>a.tasks.filter(c=>!c.isArchived),[a.tasks]),Wc=s.useMemo(()=>new Set(a.filteredTasks.map(c=>c.id)),[a.filteredTasks]),Uc=s.useMemo(()=>Bo?[...a.searchAgnosticTasks,...yr]:a.searchAgnosticTasks,[a.searchAgnosticTasks,yr,Bo]),Os=s.useMemo(()=>{const c=new Map;for(const k of a.archivedTasks)c.set(k.id,k);for(const k of a.tasks)c.set(k.id,k);return Array.from(c.values())},[a.tasks,a.archivedTasks]),pa=s.useMemo(()=>{const c=new Set;for(const k of Os)k.parentTaskId&&c.add(k.parentTaskId);return c},[Os]),Ji=s.useMemo(()=>{const c=new Map;return Os.forEach(k=>c.set(k.id,k)),c},[Os]),Yi=s.useMemo(()=>{const c=new Map;return Os.forEach(k=>{if(!k.parentTaskId)return;const A=c.get(k.parentTaskId)||[];A.push(k),c.set(k.parentTaskId,A)}),c},[Os]),mn=s.useMemo(()=>{const c=Io.trim().toLowerCase();if(!c)return[];const k=A=>{const fe=A.id.toLowerCase(),ge=(A.id.split("-").slice(-1)[0]||A.id).toLowerCase(),gt=A.title.toLowerCase();return fe===c?0:ge===c?1:fe.startsWith(c)||ge.startsWith(c)?2:gt.startsWith(c)?3:gt.includes(c)?4:fe.includes(c)||ge.includes(c)?5:null};return Os.map(A=>({task:A,rank:k(A)})).filter(A=>A.rank!==null).sort((A,fe)=>A.rank!==fe.rank?A.rank-fe.rank:A.task.title.localeCompare(fe.task.title)).map(A=>A.task)},[Os,Io]),Ia=s.useMemo(()=>Ce?wc(Os,Ce):null,[Ce,Os]),Es=s.useMemo(()=>{if(h==="schedule")return kr;if(h!=="hierarchy")return On;const c=A=>!A.parentTaskId&&!pa.has(A.id);let k=On;return f==="parents"?k=On.filter(A=>pa.has(A.id)):f==="linked"?k=On.filter(A=>!!A.parentTaskId||pa.has(A.id)):f==="unlinked"&&(k=On.filter(A=>c(A))),!is&&f!=="unlinked"&&(k=k.filter(A=>!c(A))),Ia&&(k=k.filter(A=>Ia.has(A.id)||is&&(f==="all"||f==="unlinked")&&c(A))),k},[h,f,On,pa,kr,Ia,is]),fs=s.useMemo(()=>{const c=new Date,k=c.getFullYear(),A=String(c.getMonth()+1).padStart(2,"0"),fe=String(c.getDate()).padStart(2,"0");return`${k}-${A}-${fe}`},[]),Xi=s.useMemo(()=>h!=="schedule"||!Be?Es:Es.filter(c=>{if(c.status==="done"||c.status==="cancelled")return!1;const A=!!c.scheduledDate&&c.scheduledDate<fs,fe=!!c.dueDate&&c.dueDate<fs;return A||fe}),[h,Be,Es,fs]),en=s.useMemo(()=>h!=="schedule"?[]:Es.filter(c=>{if(c.status==="done"||c.status==="cancelled")return!1;const A=!!c.scheduledDate&&c.scheduledDate<fs,fe=!!c.dueDate&&c.dueDate<fs;return A||fe}),[h,Es,fs]),xr=s.useMemo(()=>h!=="schedule"?0:Es.filter(c=>c.status==="done"||c.status==="cancelled"?!1:!!c.scheduledDate&&c.scheduledDate<fs).length,[h,Es,fs]),Js=s.useMemo(()=>h!=="schedule"?0:Es.filter(c=>c.status==="done"||c.status==="cancelled"?!1:!!c.dueDate&&c.dueDate<fs).length,[h,Es,fs]),Aa=s.useMemo(()=>h!=="schedule"?[]:Es.filter(c=>c.status==="done"||c.status==="cancelled"?!1:!!c.scheduledDate&&c.scheduledDate<fs),[h,Es,fs]),xa=s.useMemo(()=>en.filter(c=>!pa.has(c.id)),[en,pa]),[Da,fn]=s.useState(!1),[Ha,Po]=s.useState(!1),[ea,Wn]=s.useState(null),Ba=s.useMemo(()=>Es.filter(c=>!!c.parentTaskId||pa.has(c.id)),[Es,pa]),Pa=s.useMemo(()=>Nc(Os),[Os]),zo=s.useMemo(()=>Ba.reduce((c,k)=>{const A=Pa.get(k.id)??0;return A>c?A:c},0),[Ba,Pa]),Un=()=>{if(u==="add"&&Ne&&Ps&&Fa===Ne){const c=$.find(k=>k.id===Ps);if(Ec(),c)return z(c),!0}return!1},vr=()=>{$i(()=>{Un()||(u==="add"&&T(),d("tasks"))})},[gn,Lo]=s.useState(""),Hn=async()=>{await To(gn,dn)&&Lo("")},Ro=()=>{es(),Lo("")},si=async()=>{if(!jo||!window.confirm("Delete this task permanently? This cannot be undone."))return;await re(jo.id,!1,{skipConfirm:!0})&&Ro()},br=s.useCallback((c,k)=>{if(T(),c==="category"){const A=m.find(fe=>String(fe.value)===String(k)||fe.label===String(k));A&&ke(A.label)}else if(c==="type")se(String(k));else if(c==="priority")We(Number(k));else if(c==="approach"){const A=Ct.find(fe=>String(fe.value)===String(k)||fe.label===String(k));A&&(le(A.value),kt(fe=>({...fe,approach:A.value})))}else if(c==="status")k==="inProgress"&&Ds({});else if(c==="complexity"){const A=Number(k);Number.isFinite(A)&&te(A)}d("add")},[T,m,Ct,ke,se,We,te,le,kt,d]);zs.useEffect(()=>{D&&!D.includes("done")&&b(c=>[...c,"done"])},[]);const[Gn,yn]=s.useState(!1),[za,ta]=s.useState(!1),[tn,Ga]=s.useState(!1),[ai,qn]=s.useState(!1),[wr,Vn]=s.useState(!1),[Qi,Kn]=s.useState(null),[Sr,Cr]=s.useState(!1),[ni,_r]=s.useState(""),[Jn,jr]=s.useState(""),[va,Yn]=s.useState(!1),[oi,ba]=s.useState(""),[Tr,ra]=s.useState(!1),[sn,js]=s.useState("members"),[qa,Hs]=s.useState("unknown"),[Xn,Is]=s.useState(null),[Qn,cs]=s.useState(!1),[Eo,kn]=s.useState([]),[xn,La]=s.useState(null),[vn,ia]=s.useState(""),[an,Va]=s.useState("member"),[Zn,Ra]=s.useState("read-write"),[Nr,bn]=s.useState(!1),[Mo,ri]=s.useState(null),[nn,Hc]=s.useState(0),[$o,Zi]=s.useState(!1),[ec,Fo]=s.useState([]),[ii,Gc]=s.useState(!1),[ci,qc]=s.useState(1),[Ka,Oo]=s.useState(null),[Ir,eo]=s.useState(!1),[Wo,Uo]=s.useState(null),[wn,Sn]=s.useState(!1),[Ho,ca]=s.useState(null),[Ar,Ja]=s.useState(null),[to,li]=s.useState("month"),Ts=25,so=s.useRef(null),os=s.useRef(null);s.useEffect(()=>{if(!za)return;const c=k=>{so.current?.contains(k.target)||ta(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[za]),s.useEffect(()=>()=>{os.current&&(window.clearInterval(os.current),os.current=null)},[]);const Ea=at==="cloud"&&Bt&&O,Ma=at==="local"&&O,Go=s.useMemo(()=>{const c=vo.find(A=>A.id===ms);if(!c)return null;const k=String(c.role||"").trim().toLowerCase();return k==="owner"||k==="admin"||k==="member"||k==="read-only"?k:null},[vo,ms]),ao=Ea&&(Go==="owner"||Go==="admin")&&qa==="team",Dr=String(Ve||"").trim(),tc=Dr.length>0,di=bs&&!Ft,Me=s.useCallback(()=>{const c={},k=String(ms||"").trim();return k&&(c["x-taskforce-workspace-id"]=k),c},[ms]),on=s.useCallback(async()=>{if(at!=="cloud"||!O)return Oo(null),null;eo(!0),Uo(null);try{const c=await fetch("/api/taskforce/billing/status",{method:"GET",credentials:"include"}),k=await c.json().catch(()=>({}));return c.ok?(Oo(k),k):(Oo(null),Uo(String(k?.error||"Failed to load billing status.")),null)}catch{return Oo(null),Uo("Failed to load billing status."),null}finally{eo(!1)}},[O,at]),Vc=s.useCallback(async()=>{ca(null),Ja(null),Sn(!0);try{const c=await fetch("/api/taskforce/billing/checkout-session",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({tier:"team",interval:to})}),k=await c.json().catch(()=>({}));if(!c.ok){ca(String(k?.error||"Failed to create checkout session."));return}const A=String(k?.url||"").trim();if(!A){ca("Checkout session did not return a redirect URL.");return}window.location.assign(A)}catch{ca("Failed to start checkout.")}finally{Sn(!1)}},[to]),Kc=s.useCallback(async()=>{ca(null),Ja(null),Sn(!0);try{const c=await fetch("/api/taskforce/billing/portal-session",{method:"POST",credentials:"include"}),k=await c.json().catch(()=>({}));if(!c.ok){ca(String(k?.error||"Failed to create portal session."));return}const A=String(k?.url||"").trim();if(!A){ca("Portal session did not return a redirect URL.");return}window.location.assign(A)}catch{ca("Failed to open billing portal.")}finally{Sn(!1)}},[]),Jc=s.useCallback(async()=>{ca(null),Ja(null),Sn(!0);try{const c=await fetch("/api/taskforce/billing/subscription",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({tier:"team",interval:to})}),k=await c.json().catch(()=>({}));if(!c.ok){ca(String(k?.error||"Failed to update subscription interval."));return}Ja("Subscription updated."),await on()}catch{ca("Failed to update subscription interval.")}finally{Sn(!1)}},[to,on]),Br=s.useCallback(async()=>{if(!Ea||!(Go==="owner"||Go==="admin")){Hs("unknown");return}try{const c=await fetch("/api/taskforce/account/entitlements",{method:"GET",credentials:"include",headers:Me()}),k=await c.json().catch(()=>({}));if(!c.ok){Hs("unknown");return}const A=String(k?.planId||"").trim().toLowerCase(),fe=String(k?.state||"").trim().toLowerCase(),ge=k?.features?.["collaboration.team_management"]?.allowed===!0;Hs(A==="team"&&ge&&(fe==="active"||fe==="trialing"||fe==="grace")?"team":"personal")}catch{Hs("unknown")}},[Ea,Go,Me]);s.useEffect(()=>{!za&&!Tr&&!tn||Br()},[tn,za,Tr,Br]),s.useEffect(()=>{tn&&on()},[on,tn]),s.useEffect(()=>{if(!O||r.pathname!=="/billing/success"&&r.pathname!=="/billing/cancel")return;if(Ga(!0),ta(!1),ca(null),Uo(null),r.pathname==="/billing/cancel"){Ja("Checkout canceled. No billing changes were applied."),n("/",{replace:!0});return}Ja("Checkout complete. Waiting for billing confirmation..."),on();let c=0;const k=30;return os.current&&(window.clearInterval(os.current),os.current=null),os.current=window.setInterval(()=>{c+=1,on().then(A=>{const fe=String(A?.entitlementState||"").trim().toLowerCase();if(fe&&fe!=="free"){Ja("Subscription is active."),os.current&&(window.clearInterval(os.current),os.current=null),n("/",{replace:!0});return}c>=k&&os.current&&(window.clearInterval(os.current),os.current=null,Ja("Checkout finished, but entitlement update is still pending. Refresh Billing Status in a few seconds."),n("/",{replace:!0}))})},1500),()=>{os.current&&(window.clearInterval(os.current),os.current=null)}},[O,on,r.pathname,n]);const qo=s.useCallback(async()=>{if(ao){cs(!0),Is(null);try{const c=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:Me()}),k=await c.json().catch(()=>({}));if(!c.ok){Is(k?.error||"Failed to load workspace users.");return}const A=Array.isArray(k?.users)?k.users:[],fe={owner:0,admin:1,member:2,"read-only":3},ge=A.map(gt=>({userId:String(gt?.userId||""),email:String(gt?.email||""),displayName:typeof gt?.displayName=="string"?gt.displayName:null,role:gt?.role==="owner"||gt?.role==="admin"||gt?.role==="member"||gt?.role==="read-only"?gt.role:"member",permissionMode:gt?.permissionMode==="read-only"?"read-only":"read-write",status:String(gt?.status||"active"),disabled:gt?.disabled===!0}));ge.sort((gt,ks)=>{const Wt=(fe[gt.role]??99)-(fe[ks.role]??99);return Wt!==0?Wt:(gt.displayName||gt.email).localeCompare(ks.displayName||ks.email,void 0,{sensitivity:"base"})}),kn(ge)}catch{Is("Failed to load workspace users.")}finally{cs(!1)}}},[ao,Me]),Cn=s.useCallback(async c=>{if(!ao)return;const k=Math.max(0,Math.floor(c));Zi(!0),Is(null);try{const A=k*Ts,fe=await fetch(`/api/taskforce/admin/audit-logs?limit=${Ts}&offset=${A}`,{method:"GET",credentials:"include",headers:Me()}),ge=await fe.json().catch(()=>({}));if(!fe.ok){Is(ge?.error||"Failed to load workspace audit log.");return}const gt=Array.isArray(ge?.events)?ge.events:[];Fo(gt.map(Wt=>({id:String(Wt?.id||""),action:String(Wt?.action||""),actorUserId:String(Wt?.actorUserId||""),actorRole:String(Wt?.actorRole||""),createdAt:String(Wt?.createdAt||Wt?.ts||"")}))),Hc(k);const ks=Math.max(1,Number(ge?.pages||1));qc(ks),Gc(k+1<ks)}catch{Is("Failed to load workspace audit log.")}finally{Zi(!1)}},[ao,Me]),Pr=s.useCallback(async()=>{await Promise.all([qo(),Cn(nn)])},[qo,Cn,nn]),sc=s.useCallback((c="login")=>{const k=`${r.pathname}${r.search}${r.hash}`,A=!k||k==="/login"||!k.startsWith("/")?"/":k;ta(!1),Ga(!1),qn(!1),n(`/login?mode=${c}&next=${encodeURIComponent(A)}`)},[r.hash,r.pathname,r.search,n]),zr=s.useCallback(()=>{ta(!1),Cr(!1),n("/setup?step=workspace",{replace:!0})},[n]),Yc=s.useCallback(async c=>{if(!(!c||va)){ba(""),Yn(!0);try{const k=await er(c);if(!k.success){if(k.code==="WORKSPACE_NOT_FOUND"||k.code==="WORKSPACE_ID_REQUIRED"){zr();return}ba(k.error||"Failed to switch workspace.");return}await H(!0),ta(!1),Cr(!1)}finally{Yn(!1)}}},[er,va,H,zr]),ac=s.useCallback(async()=>{if(va)return;const c=ni.trim();if(!c){ba("Workspace name is required.");return}ba(""),Yn(!0);try{const k=await bo(c,Jn.trim()||void 0);if(!k.success){if(k.code==="WORKSPACE_NOT_FOUND"||k.code==="WORKSPACE_ID_REQUIRED"){zr();return}ba(k.error||"Failed to create workspace.");return}await H(!0),_r(""),jr(""),Cr(!1),ta(!1)}finally{Yn(!1)}},[va,ni,Jn,bo,H,zr]),Lr=s.useCallback(async()=>{ta(!1),ra(!0),js("members"),await Br(),await qo(),await Cn(0)},[Cn,Br,qo]),no=s.useCallback(async(c,k)=>{Is(null),La(c);try{const A=await k(),fe=await A.json().catch(()=>({}));if(!A.ok){Is(fe?.error||"Team management action failed.");return}await Pr()}catch{Is("Team management action failed.")}finally{La(null)}},[Pr]),$a=s.useCallback(async()=>{const c=vn.trim();if(c){bn(!0),Is(null),ri(null);try{const k=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...Me()},credentials:"include",body:JSON.stringify({workspaceId:ms,email:c,role:an,permissionMode:an==="member"?Zn:"read-write"})}),A=await k.json().catch(()=>({}));if(!k.ok){Is(A?.error||"Failed to send invite.");return}ia(""),A?.inviteEmailSent===!1?ri(`Invite created, but email delivery failed${A?.inviteEmailError?`: ${String(A.inviteEmailError)}`:"."}`):ri("Invite sent."),await Pr()}catch{Is("Failed to send invite.")}finally{bn(!1)}}},[ms,Pr,Me,vn,Zn,an]),nc=s.useMemo(()=>me.trim().length>0,[me]),oc=s.useMemo(()=>Eo.filter(c=>c.status==="invited"),[Eo]),Rr=s.useMemo(()=>{const c=ie.length!==m.length,k=_t.length!==Et.length,A=Ue.length!==qt.length,fe=D.length!==ji.length,ge=Qe&&nt.length!==3;return c||k||A||fe||ge||f!=="all"},[ie,m,_t,Et,Ue,qt,D,Qe,nt,f]),rc=nc||Rr,ic=$.length,Ws=a.filteredTasks.length,Xc=rc?`${Ws}/${ic}`:`${ic}`,Qc=E(rc?"standalone.visibleActiveTasksTitle":"standalone.totalActiveTasksTitle"),Zc=at==="local",cc=s.useMemo(()=>{if(!ua)return"Never";const c=new Date(ua);return Number.isNaN(c.getTime())?"Never":c.toLocaleString()},[ua]),Gs=s.useCallback(c=>{if(!c)return"Never";const k=new Date(c);return Number.isNaN(k.getTime())?"Never":k.toLocaleString()},[]),oo=s.useMemo(()=>Gs($s),[$s,Gs]),wa=s.useMemo(()=>Gs(P),[P,Gs]),lc=s.useMemo(()=>Gs(S),[S,Gs]),ro=s.useMemo(()=>Gs(Y),[Y,Gs]),[ha,el]=s.useState(()=>Je?Vs:"disconnected"),_n=s.useRef(Date.now()),ma=s.useRef(null),sa=s.useMemo(()=>Je?Vs==="error"?"error":Tt&&Yt==="degraded-fallback"?"degraded-fallback":Tt&&Yt==="reconnecting"?"reconnecting":Vs:"disconnected",[Je,Vs,Tt,Yt]);s.useEffect(()=>{ma.current!==null&&(window.clearTimeout(ma.current),ma.current=null);const c=k=>{el(k),_n.current=Date.now()};if(sa!==ha){if(sa==="syncing"||sa==="reconnecting"){ma.current=window.setTimeout(()=>{c(sa)},Zj);return}if(ha==="syncing"||ha==="reconnecting"){const k=Date.now()-_n.current,A=Math.max(0,eT-k);ma.current=window.setTimeout(()=>{c(sa)},A);return}if(ha==="error"&&sa!=="error"){const k=Date.now()-_n.current,A=Math.max(0,tT-k);ma.current=window.setTimeout(()=>{c(sa)},A);return}c(sa)}},[sa,ha]),s.useEffect(()=>()=>{ma.current!==null&&(window.clearTimeout(ma.current),ma.current=null)},[]);const Er=s.useMemo(()=>{if(!Je)return{label:"Sync Off",color:"#94a3b8",border:"rgba(148, 163, 184, 0.45)",background:"rgba(148, 163, 184, 0.12)"};switch(ha){case"syncing":return{label:"Syncing",color:"#f59e0b",border:"rgba(245, 158, 11, 0.45)",background:"rgba(245, 158, 11, 0.16)"};case"reconnecting":return{label:"Reconnecting",color:"#f59e0b",border:"rgba(245, 158, 11, 0.45)",background:"rgba(245, 158, 11, 0.16)"};case"degraded-fallback":return{label:"Fallback Pull",color:"#fb923c",border:"rgba(251, 146, 60, 0.45)",background:"rgba(251, 146, 60, 0.16)"};case"error":return{label:"Sync Error",color:"#f87171",border:"rgba(248, 113, 113, 0.45)",background:"rgba(248, 113, 113, 0.14)"};case"disconnected":return{label:"Disconnected",color:"#94a3b8",border:"rgba(148, 163, 184, 0.45)",background:"rgba(148, 163, 184, 0.12)"};default:return{label:"Synced",color:"#34d399",border:"rgba(52, 211, 153, 0.45)",background:"rgba(52, 211, 153, 0.14)"}}},[ha,Je]),io=s.useMemo(()=>Je?ha==="error"?{label:"Sync Error",color:"#f87171",border:"rgba(248, 113, 113, 0.45)",background:"rgba(248, 113, 113, 0.14)",icon:"off"}:ha==="degraded-fallback"?{label:"Fallback Pull",color:"#fb923c",border:"rgba(251, 146, 60, 0.45)",background:"rgba(251, 146, 60, 0.16)",icon:"off"}:ha==="reconnecting"?{label:"Reconnecting",color:"#f59e0b",border:"rgba(245, 158, 11, 0.45)",background:"rgba(245, 158, 11, 0.16)",icon:"off"}:ha==="disconnected"?{label:"Disconnected",color:"#94a3b8",border:"rgba(148, 163, 184, 0.45)",background:"rgba(148, 163, 184, 0.12)",icon:"off"}:{label:"Synced",color:"#34d399",border:"rgba(52, 211, 153, 0.45)",background:"rgba(52, 211, 153, 0.14)",icon:"cloud"}:{label:"Sync Off",color:"#94a3b8",border:"rgba(148, 163, 184, 0.45)",background:"rgba(148, 163, 184, 0.12)",icon:"off"},[ha,Je]),ui=Ce?"Subtree":E(f==="parents"?"standalone.linksParents":f==="linked"?"standalone.linksLinked":f==="unlinked"?"standalone.linksUnlinked":"standalone.linksAll"),rn=Ce?Ji.get(Ce):void 0,jn=s.useMemo(()=>{if(!Ia||!rn)return null;const c=Os.filter(Wt=>Ia.has(Wt.id));let k=0,A=0,fe=0;c.forEach(Wt=>{Wt.status==="done"||Wt.status==="cancelled"||!!Wt.isArchived?A+=1:(k+=1,Wt.dueDate&&Wt.dueDate<fs&&(fe+=1))});let ge=0;const gt=new Set,ks=[{id:rn.id,depth:0}];for(;ks.length>0;){const Wt=ks.pop();if(gt.has(Wt.id))continue;gt.add(Wt.id),Wt.depth>ge&&(ge=Wt.depth),(Yi.get(Wt.id)||[]).forEach(In=>{!gt.has(In.id)&&Ia.has(In.id)&&ks.push({id:In.id,depth:Wt.depth+1})})}return{total:c.length,active:k,terminal:A,overdue:fe,depth:ge}},[Ia,rn,Os,fs,Yi]),dc=s.useMemo(()=>{const c=new Map;return Ba.forEach(k=>{const A=(Pa.get(k.id)??0)+1;c.set(A,(c.get(A)||0)+1)}),Array.from(c.entries()).sort((k,A)=>k[0]-A[0]).map(([k,A])=>({level:k,count:A}))},[Ba,Pa]),pi=s.useMemo(()=>Es.filter(c=>!c.parentTaskId&&!pa.has(c.id)).length,[Es,pa]),hi=s.useMemo(()=>Es.filter(c=>!c.parentTaskId&&pa.has(c.id)).length,[Es,pa]);s.useMemo(()=>!Ce||!Ia?[]:Os.filter(c=>Ia.has(c.id)).sort((c,k)=>{const A=Pa.get(c.id)??Number.MAX_SAFE_INTEGER,fe=Pa.get(k.id)??Number.MAX_SAFE_INTEGER;return A!==fe?A-fe:c.title.localeCompare(k.title)}),[Ce,Ia,Os,Pa]);const mi=s.useCallback(()=>{const c=mn[0];c&&(pn(c.id),En(""),f==="unlinked"&&I("all"))},[mn,f,I]),Tn=s.useMemo(()=>xc(hn)||new Date,[hn]),Nn=s.useMemo(()=>Sl(Tn,Lt),[Tn,Lt]),Ya=s.useMemo(()=>{const c={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return ud.forEach(k=>{const A=sT(k,Lt);c[k]=Or(pd(Nn,A))}),c},[Nn,Lt]),Mr=s.useCallback(c=>{const k=xc(c);if(!k)return Ya.mon;const A=k.getDay();return Ya[A===1?"mon":A===2?"tue":A===3?"wed":A===4?"thu":A===5?"fri":A===6?Wa?"sat":"fri":Wa?"sun":"fri"]||Ya.mon},[Ya,Wa]),fi=s.useCallback(async()=>{if(!(Da||xa.length===0)){fn(!0);try{for(const c of xa){const k=c.scheduledDate||c.dueDate||fs,A=Mr(k);await Z(c.id,{scheduledDate:A,scheduledWeekKey:hd(A),orderInDay:null})}await H(!0)}finally{fn(!1)}}},[Da,xa,fs,Mr,Z,H]),gi=s.useCallback(async()=>{if(!(Da||en.length===0)){fn(!0);try{for(const c of en)await Z(c.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await H(!0)}finally{fn(!1)}}},[Da,en,Z,H]),tl=s.useCallback(c=>{if(c.targetDate<fs){const k=new Map($.map(fe=>[fe.id,fe]));if(c.toScheduleLeafTaskIds.some(fe=>{const ge=k.get(fe);return ge?ge.status!=="done"&&ge.status!=="cancelled":!0})){window.alert(E("schedule.completedOnlyPastSchedule"));return}}if(c.toScheduleLeafTaskIds.length===0){window.alert(E("schedule.noUnscheduledLeafTasks",{parentTitle:c.parentTitle}));return}Wn(c)},[$,fs]),sl=s.useCallback(async()=>{if(!(!ea||Ha)){Po(!0);try{const{targetDate:c,toScheduleLeafTaskIds:k}=ea;let fe=$.filter(ge=>ge.scheduledDate===c&&!k.includes(ge.id)).sort((ge,gt)=>{const ks=typeof ge.orderInDay=="number"?ge.orderInDay:Number.MAX_SAFE_INTEGER,Wt=typeof gt.orderInDay=="number"?gt.orderInDay:Number.MAX_SAFE_INTEGER;return ks!==Wt?ks-Wt:String(ge.createdAt||"").localeCompare(String(gt.createdAt||""))}).length;for(const ge of k)await Z(ge,{scheduledDate:c,scheduledWeekKey:hd(c),orderInDay:fe++});Wn(null),await H(!0)}finally{Po(!1)}}},[ea,Ha,$,Z,H]),uc=s.useCallback(()=>{Ha||Wn(null)},[Ha]),Xa=s.useMemo(()=>{const[c,k]=gr.split("-"),A=Number(c),fe=Number(k);return!Number.isInteger(A)||!Number.isInteger(fe)||fe<1||fe>12?new Date(Tn.getFullYear(),Tn.getMonth(),1):new Date(A,fe-1,1)},[gr,Tn]),al=s.useMemo(()=>wi(Xa,{month:"long",year:"numeric"},un),[Xa,un]),nl=s.useMemo(()=>wi(Nn,{month:"short",day:"numeric",year:"numeric"},un),[Nn,un]),ol=s.useMemo(()=>{const c=Sl(Xa,Lt);return Array.from({length:42},(k,A)=>pd(c,A))},[Xa,Lt]),rl=s.useMemo(()=>{const c=new Map;for(const k of kr){const A=k.scheduledDate||"";if(!A)continue;const ge=!(k.status==="done"||k.status==="cancelled")&&A<fs,gt=c.get(A);gt?(gt.count+=1,ge&&(gt.hasExpired=!0)):c.set(A,{count:1,hasExpired:ge})}return c},[kr,fs]),il=s.useMemo(()=>Lt==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[Lt]),pc=s.useMemo(()=>{const A=(Wa?Lt==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:ud:["mon","tue","wed","thu","fri"]).map(ge=>{const gt=xc(Ya[ge])||Nn,ks=Ya[ge],Wt=ge==="sat"||ge==="sun";return{value:ge,label:`${Qj[ge]} ${wi(gt,{month:"short",day:"numeric"},un)}`,color:Wt?"#1e3a8a":"#3b82f6",icon:"Calendar",date:ks,isPast:ks<fs,isSelected:ks===hn,isWeekend:Wt}}),fe=Aa.length>0;return[...Qs?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...fe?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...A]},[Wa,Qs,Ya,Nn,Aa.length,fs,hn,Lt,un]),hc=s.useMemo(()=>{switch(h){case"category":return m;case"type":return(Et||[]).map(c=>({...c,icon:ko[c.value]?.icon,color:ko[c.value]?.color}));case"priority":return qt;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 Ct;case"assignee":return[{value:"agent",label:"AI",icon:"Bot",color:"#8b5cf6"},{value:"user",label:"User",icon:"User",color:"#22c55e"},{value:"unassigned",label:"Unassigned",icon:"Circle",color:"#64748b"}];case"status":return[{value:"task",label:"To Do",icon:"Circle",color:"blue-200"},{value:"on-hold",label:"Blocked",icon:"Pause",color:"amber-500"},{value:"in-progress",label:"In Progress",icon:"Play",color:"blue-500"},{value:"review",label:"Ready for Review",icon:"Sparkles",color:"violet-500"},{value:"completed",label:"Completed",icon:"Check",color:"green-500"}];case"hierarchy":{if(f==="unlinked")return[{value:"standalone",label:"Unlinked",icon:"Circle",color:"#64748b"}];const k=Array.from({length:Ba.length>0?zo+1:0},(A,fe)=>fe+1).map(A=>({value:A,label:`Level ${A}`,icon:"Layers",color:A===1?"#3b82f6":"#64748b"}));return f==="all"&&is&&k.push({value:"standalone",label:"Unlinked",icon:"Circle",color:"#64748b"}),k}case"schedule":return pc;default:return m}},[h,m,Et,qt,Ct,zo,f,pc,Ba.length,is]);return e.jsxs("div",{className:`${t.standaloneWrapper} ${R?t.zenModeEnabled:""}`,"data-theme":y,children:[e.jsxs("div",{className:`${t.header} ${t.standaloneHeader} `,children:[e.jsxs("div",{className:`${t.headerTitle} ${t.standaloneTitle}`,children:[e.jsx("img",{src:Vo,alt:"Taskforce Logo",className:t.brandIcon,onError:c=>{const k=c.currentTarget;k.src!==dd?k.src=dd:k.style.display="none"}}),e.jsx("span",{children:"TaskForce"}),Za&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.projectSlash,children:"/"}),e.jsx("span",{className:t.projectName,title:`Workspace ID: ${ms}`,children:Za})]}),e.jsx("span",{className:t.taskCountBadge,title:Qc,children:Xc}),Zc&&e.jsx("button",{className:t.headerActionBtn,onClick:()=>qn(!0),title:`Cloud sync status: ${io.label} | Pull: ${oo} | Push: ${wa}${Tt?` | Realtime: ${Yt} (${Ot}) dup=${Ht.duplicateDiscarded} ooo=${Ht.outOfOrderDiscarded} invalid=${Ht.invalidDiscarded}`:""}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${io.border}`,background:io.background,color:io.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:io.icon==="off"?e.jsx(Iu,{size:12}):e.jsx(Au,{size:12})}),a.loadingTasks&&e.jsx("div",{style:{marginLeft:"8px",display:"flex",alignItems:"center"},children:e.jsx(aa,{size:14,className:t.spinner})}),Fs&&e.jsxs("div",{className:t.headerSuccess,children:[e.jsx(Sa,{size:14}),e.jsx("span",{children:Fs.message})]})]}),e.jsxs("div",{className:t.headerActions,style:{gap:"16px"},children:[e.jsxs("div",{className:t.searchContainer,style:{width:"240px"},children:[e.jsx(bd,{size:16,className:t.searchIcon}),e.jsx("input",{type:"text",className:`${t.searchInput} ${nc?t.searchActive:""}`,placeholder:E("standalone.searchPlaceholder"),value:me,onChange:c=>Oe(c.target.value)}),me&&e.jsx("button",{className:t.clearSearchBtn,onClick:()=>Oe(""),title:E("standalone.clearSearchTitle"),children:e.jsx(ga,{size:14})})]}),e.jsxs("div",{className:t.groupByContainer,children:[e.jsxs("span",{className:t.groupByLabel,children:[e.jsx(Du,{size:12})," ",E("standalone.sortLabel")]}),e.jsxs("select",{className:`${t.select} ${t.groupBySelect} `,value:jt,onChange:c=>Vt(c.target.value),children:[e.jsx("option",{value:"created",children:E("standalone.sortCreated")}),e.jsx("option",{value:"updated",children:E("standalone.sortUpdated")}),e.jsx("option",{value:"priority",children:E("standalone.sortPriority")}),e.jsx("option",{value:"complexity",children:E("standalone.sortComplexity")})]}),e.jsx("button",{className:`${t.headerActionBtn} ${t.sortDirectionBtn}`,onClick:()=>a.toggleSortOrder(),title:a.sortOrder==="desc"?E("standalone.sortDirectionDescTitle"):E("standalone.sortDirectionAscTitle"),children:a.sortOrder==="desc"?e.jsx(fd,{size:14}):e.jsx(gd,{size:14})})]}),e.jsx("div",{className:t.headerDivider}),h!=="docs"&&e.jsxs("div",{className:t.groupByContainer,children:[e.jsxs("span",{className:t.groupByLabel,children:[e.jsx(bi,{size:12})," ",E("standalone.groupLabel")]}),e.jsxs("select",{className:`${t.select} ${t.groupBySelect} `,value:h,onChange:c=>v(c.target.value),children:[e.jsx("option",{value:"category",children:E("standalone.groupCategory")}),e.jsx("option",{value:"type",children:E("standalone.groupType")}),e.jsx("option",{value:"priority",children:E("standalone.groupPriority")}),e.jsx("option",{value:"complexity",children:E("standalone.groupComplexity")}),e.jsx("option",{value:"approach",children:E("standalone.groupApproach")}),e.jsx("option",{value:"assignee",children:E("standalone.groupAssignee")}),e.jsx("option",{value:"status",children:E("standalone.groupStatus")}),e.jsx("option",{value:"hierarchy",children:E("standalone.groupHierarchy")}),e.jsx("option",{value:"schedule",children:E("standalone.groupSchedule")})]})]}),e.jsx("button",{className:`${t.headerActionBtn} ${h==="docs"?t.headerActionBtnActive:""}`,onClick:()=>v(h==="docs"?Vi.current:"docs"),title:h==="docs"?"Exit Docs view":"Open Docs view",children:e.jsx(Xo,{size:15})}),e.jsxs("button",{className:`${t.headerActionBtn} ${x!=="show"?t.headerActionBtnActive:""} `,onClick:()=>{_(c=>c==="show"?"collapse":c==="collapse"?"hide":"show")},title:E(x==="show"?"standalone.showEmptyColumns":x==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),children:[x==="show"&&e.jsx(Bu,{size:16}),x==="collapse"&&e.jsx(Pu,{size:16}),x==="hide"&&e.jsx(zu,{size:16})]}),e.jsx("button",{className:`${t.headerActionBtn} ${Oa?t.headerActionBtnActive:""}`,onClick:()=>No(!Oa),title:E(Oa?"standalone.expandCards":"standalone.compressCards"),children:Oa?e.jsx(Lu,{size:16}):e.jsx(Ru,{size:16})}),e.jsx("button",{className:`${t.headerActionBtn} ${R?t.headerActionBtnActive:""}`,onClick:()=>j(),title:E(R?"standalone.exitZenMode":"standalone.enterZenMode"),children:e.jsx(Jo,{size:16,fill:R?"currentColor":"none"})}),e.jsx("div",{className:t.headerDivider}),e.jsx("button",{className:`${t.headerActionBtn} ${Ao?t.headerActionBtnActive:""} ${Rr?t.filterGlow:""}`,onClick:()=>Do(!Ao),title:E("standalone.toggleFilters"),children:e.jsx(Eu,{size:16})}),e.jsxs("button",{className:t.primaryUpdateBtn,onClick:()=>{T(),d("add")},children:[e.jsx(cn,{size:16})," ",E("standalone.addTask")]}),e.jsxs("div",{className:t.accountMenuWrap,ref:so,children:[e.jsx("button",{className:`${t.headerActionBtn} ${t.avatarBtn}`,onClick:()=>ta(c=>!c),title:O?"Account":"Account (Not signed in)","aria-label":O?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":za,children:e.jsx("span",{className:t.avatarBadge,"aria-hidden":"true",children:O?"U":"?"})}),za&&e.jsxs("div",{className:t.accountMenu,role:"menu","aria-label":"Account menu",children:[e.jsxs("div",{className:t.accountMenuSection,children:[e.jsx("div",{className:t.accountMenuSectionLabel,children:"Account"}),e.jsx("div",{className:t.accountMenuHint,children:di?"Checking sign-in status...":O?e.jsx(e.Fragment,{children:tc?e.jsxs(e.Fragment,{children:["Signed in as ",e.jsx("span",{className:t.accountIdentityEmail,children:Dr})]}):"Signed in"}):"Not signed in"})]}),Ea&&e.jsxs("div",{className:t.accountMenuSection,children:[e.jsx("div",{className:t.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),vo.length===0&&e.jsx("div",{className:t.accountMenuHint,children:"No workspaces found for this account yet."}),vo.map(c=>e.jsxs("button",{className:`${t.accountMenuItem} ${c.id===ms?t.accountMenuItemActive:""}`,onClick:()=>Yc(c.id),role:"menuitem",disabled:va||c.id===ms,title:c.description||c.name,children:[e.jsx(ho,{size:15}),e.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[e.jsx("span",{children:c.name}),e.jsx("span",{className:t.accountMenuMeta,children:c.role})]})]},c.id)),e.jsxs("button",{className:t.accountMenuItem,onClick:()=>{ba(""),Cr(c=>!c)},role:"menuitem",disabled:va,children:[e.jsx(cn,{size:15}),Sr?"Close Workspace Form":"Create Workspace"]}),Sr&&e.jsxs("div",{className:t.accountMenuWorkspaceForm,children:[e.jsx("input",{className:t.input,value:ni,onChange:c=>_r(c.target.value),placeholder:"Workspace name",disabled:va}),e.jsx("input",{className:t.input,value:Jn,onChange:c=>jr(c.target.value),placeholder:"Workspace description (optional)",disabled:va}),e.jsx("button",{className:t.primaryUpdateBtn,onClick:ac,disabled:va,children:va?"Saving...":"Save Workspace"})]}),oi&&e.jsx("div",{className:t.accountMenuError,children:oi})]}),ao&&e.jsxs("button",{className:t.accountMenuItem,onClick:()=>{Lr()},role:"menuitem",children:[e.jsx(xd,{size:15}),"Team Management"]}),e.jsxs("button",{className:t.accountMenuItem,onClick:()=>{ta(!1),d("settings"),Xe("general")},role:"menuitem",children:[e.jsx(_i,{size:15}),"Workspace Settings"]}),e.jsxs("button",{className:t.accountMenuItem,onClick:()=>{ta(!1),Ga(!0)},role:"menuitem",children:[e.jsx(jc,{size:15}),"Account Hub"]}),e.jsxs("button",{className:t.accountMenuItem,onClick:()=>{ta(!1),yn(!0)},role:"menuitem",children:[e.jsx(po,{size:15}),"Help & Tutorial"]}),at==="local"&&!O&&!di&&e.jsxs("button",{className:t.accountMenuItem,onClick:()=>{sc("login")},role:"menuitem",children:[e.jsx(jc,{size:15}),"Sign In / Register"]}),O&&e.jsxs("button",{className:t.accountMenuItem,onClick:async()=>{ta(!1),await tr()},role:"menuitem",children:[e.jsx(Mu,{size:15}),"Sign Out"]})]})]})]})]}),$t&&e.jsx("div",{className:t.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),Ao&&e.jsxs("div",{className:t.filterToolbar,style:{padding:"8px 24px",borderBottom:"1px solid var(--border-color)",background:"var(--bg-secondary)",display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap",position:"relative",zIndex:50},children:[e.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:E("standalone.filtersCaps")}),e.jsx(Qa,{label:E("standalone.categoryLabel"),options:m.filter(c=>!c.disabled),selected:ie,onChange:c=>ve(c),variant:"value"}),e.jsx(Qa,{label:E("standalone.typeLabel"),options:Et.map(c=>({value:c.value,label:c.label})),selected:_t,onChange:c=>Se(c),variant:"value"}),e.jsx(Qa,{label:E("standalone.priorityLabel"),options:qt,selected:Ue,onChange:c=>ht(c),variant:"value"}),e.jsx(Qa,{label:E("standalone.statusLabel"),options:ji,selected:D,onChange:c=>b(c),variant:"value"}),Qe&&e.jsx(Qa,{label:E("standalone.assigneeLabel"),options:[{value:"agent",label:"AI"},{value:"user",label:"User"},{value:"unassigned",label:"Unassigned"}],selected:nt,onChange:c=>It(c),variant:"value"}),e.jsx("div",{className:t.headerDivider,style:{height:"16px",margin:"0 8px"}}),e.jsxs("div",{className:t.groupByContainer,children:[e.jsxs("span",{className:t.groupByLabel,children:[e.jsx(bi,{size:12})," ",E("standalone.linksLabel")]}),e.jsxs("select",{className:`${t.select} ${t.groupBySelect}`,value:f,onChange:c=>I(c.target.value),title:E("standalone.chooseLinksTitle"),children:[e.jsx("option",{value:"all",children:E("standalone.linksAll")}),e.jsx("option",{value:"parents",children:E("standalone.linksParents")}),e.jsx("option",{value:"linked",children:E("standalone.linksLinked")}),e.jsx("option",{value:"unlinked",children:E("standalone.linksUnlinked")})]})]}),e.jsxs("label",{className:t.archiveToggle,title:E("standalone.includeArchiveTitle"),children:[e.jsx("input",{type:"checkbox",checked:Bo,onChange:c=>{Fc(c.target.checked),c.target.checked&&Oc()}}),e.jsx("span",{children:E("standalone.includeArchive")})]}),e.jsx("div",{style:{flex:1}}),e.jsxs("button",{onClick:rt,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[e.jsx(ga,{size:12})," ",E("standalone.clearFilters")]})]}),h==="docs"?e.jsx("div",{className:`${t.standalonePage} ${t.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden"},children:e.jsx(Vj,{tasks:$,apiBaseUrl:a.config?.apiBaseUrl||"",requestedDocPath:$c,onRequestedDocHandled:()=>Hi(null)})}):e.jsxs("div",{className:`${t.standalonePage} ${t.standaloneContent} `,style:{position:"relative",opacity:a.loadingTasks?.7:1,transition:"opacity 0.2s ease, padding-right 220ms cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",flex:1,minHeight:0,paddingRight:h==="schedule"&&Zs||h==="hierarchy"&&Ua?"332px":0},children:[e.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",top:0,right:0,width:"100%",height:"100%",backgroundImage:`url(${Cc})`,backgroundRepeat:"no-repeat",backgroundPosition:"top right",backgroundSize:"60%",opacity:.2,pointerEvents:"none",zIndex:0}}),Xi.length===0&&h!=="schedule"?e.jsxs("div",{className:t.emptyState,children:[e.jsx(bi,{size:48}),e.jsx("p",{children:h==="hierarchy"&&Ce?"No tasks match this subtree with current filters.":E("standalone.noTasksMatchFilters")}),e.jsx("p",{style:{fontSize:"12px",color:"var(--text-secondary)"},children:h==="hierarchy"&&Ce?`Focused on ${rn?.title||Ce}. Try clearing subtree focus or broadening filters.`:E("standalone.showingWithLinksHint",{parentFilterLabel:ui})})]}):e.jsx(Jj,{tasks:Xi,allTasks:Uc,hierarchyTasks:Os,columns:hc,groupBy:h,scheduleDates:Ya,searchQuery:me,filterCategories:ie,filterTypes:_t,filterPriorities:Ue,filterStatus:D,filterAssignees:nt,assigneeFilterEnabled:Qe,scheduleFilteredTaskIds:Array.from(Wc),copiedId:ds,availableSpecialists:As,taxonomies:ts,priorities:qt,approaches:Ct,onUpdateTask:Z,onTaskClick:c=>z(c),onOpenTaskById:zt,onCopyId:Ss,onToggleInProgress:Ds,onToggleReview:Cs,onToggleComplete:us,onToggleCancel:L,onArchiveTask:F,onUnarchive:K,onDelete:re,onUnlinkChildTask:St,onClearParentTask:Ee,onAddTaskToColumn:br,onScheduleParentDrop:tl,onScheduleDaySelected:c=>{Mn(c);const k=xc(c);k&&$n(`${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:h==="schedule"?ei:void 0,onScrollLeftChange:c=>{h==="schedule"&&Ui(c)},emptyColumnMode:x,categories:m,compressed:Oa,recentlyChangedTaskIds:a.recentlyChangedTaskIds,hierarchyChildOrderMode:Rn,sortBy:jt,sortOrder:a.sortOrder},`${h}-${hc.map(c=>String(c.value)).join("|")}-${Ya.mon}`),h==="schedule"&&!Zs&&e.jsx("button",{type:"button",className:t.headerActionBtn,onClick:()=>mr(!0),title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20,border:"1px solid var(--border-color)",background:"var(--bg-secondary)"},children:e.jsx(Ul,{size:16})}),h==="hierarchy"&&!Ua&&e.jsx("button",{type:"button",className:t.headerActionBtn,onClick:()=>fr(!0),title:"Show Hierarchy Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20,border:"1px solid var(--border-color)",background:"var(--bg-secondary)"},children:e.jsx(Ul,{size:16})})]}),h==="hierarchy"&&e.jsxs("aside",{className:t.appScrollbar,style:{position:"absolute",top:0,right:0,bottom:0,width:"320px",minWidth:"320px",borderLeft:"1px solid var(--border-color)",background:"var(--bg-secondary)",padding:"12px",display:"flex",flexDirection:"column",gap:"12px",zIndex:40,overflowY:"auto",transform:Ua?"translateX(0)":"translateX(108%)",pointerEvents:Ua?"auto":"none",transition:"transform 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",fontWeight:600},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(bi,{size:16}),e.jsx("span",{children:"Hierarchy Controls"})]}),e.jsx("button",{type:"button",className:t.headerActionBtn,onClick:()=>fr(!1),title:"Hide Hierarchy Sidebar",children:e.jsx(Hl,{size:16})})]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"10px",padding:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx("div",{style:{fontSize:"12px",fontWeight:600},children:"Focus Subtree"}),e.jsx("input",{type:"text",className:t.input,placeholder:"Search parent tasks...",value:Io,onChange:c=>En(c.target.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),mi())}}),e.jsx("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"8px",display:"flex",flexDirection:"column",gap:"6px",minHeight:"190px"},children:Io.trim().length>0?e.jsxs("div",{className:t.appScrollbar,style:{maxHeight:"180px",minHeight:"180px",overflowY:"auto",border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px",display:"flex",flexDirection:"column",gap:"6px"},children:[mn.slice(0,24).map(c=>e.jsxs("button",{type:"button",className:t.headerActionBtn,onClick:()=>{pn(c.id),En(""),f==="unlinked"&&I("all")},style:{justifyContent:"space-between",border:"1px solid var(--border-color)"},title:c.title,children:[e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.title}),e.jsx("span",{style:{opacity:.75},children:c.id.split("-").slice(-1)[0]})]},c.id)),mn.length===0&&e.jsxs("div",{style:{fontSize:"12px",color:"var(--text-secondary)",padding:"4px 2px"},children:['No matches for "',Io,'".']})]}):Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:"var(--text-primary)"},title:rn?.title||Ce,children:rn?.title||Ce}),jn&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",fontSize:"12px",color:"var(--text-secondary)"},children:[e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:jn.total})," total"]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:jn.active})," active"]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:jn.terminal})," done/cancelled"]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:jn.overdue>0?"var(--color-error, #ef4444)":"var(--text-primary)"},children:jn.overdue})," overdue"]}),e.jsxs("div",{style:{gridColumn:"1 / -1",border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:jn.depth})," levels deep"]})]}),e.jsx("button",{className:t.headerActionBtn,onClick:()=>{pn(""),En("")},style:{justifyContent:"center",border:"1px solid var(--border-color)",background:"rgba(59,130,246,0.12)"},children:"Clear subtree focus"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",fontSize:"12px",color:"var(--text-secondary)"},children:[e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:Es.length})," visible"]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:hi})," root parents"]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:pi})," unlinked"]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"8px",padding:"6px"},children:[e.jsx("strong",{style:{color:"var(--text-primary)"},children:Ba.length>0?zo+1:0})," levels"]})]}),e.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)"},children:dc.length>0?dc.map(c=>`L${c.level}: ${c.count}`).join(" • "):"No linked hierarchy tasks in current filters."})]})})]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"10px",padding:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx("div",{style:{fontSize:"12px",fontWeight:600},children:"Display"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"13px"},children:[e.jsx("input",{type:"checkbox",checked:is,onChange:c=>{const k=c.target.checked;Oi(k),!k&&f==="unlinked"&&I("all")}}),"Show unlinked column"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"13px"},children:[e.jsx("input",{type:"checkbox",checked:Rn==="manual",onChange:c=>Wi(c.target.checked?"manual":"auto")}),"Sort by parent task order"]}),e.jsx("div",{style:{fontSize:"11px",color:"var(--text-tertiary)"},children:"Keeps siblings in the order defined on the parent task."})]})]}),h==="schedule"&&e.jsxs("aside",{className:t.appScrollbar,style:{position:"absolute",top:0,right:0,bottom:0,width:"320px",minWidth:"320px",borderLeft:"1px solid var(--border-color)",background:"var(--bg-secondary)",padding:"12px",display:"flex",flexDirection:"column",gap:"12px",zIndex:40,overflowY:"auto",transform:Zs?"translateX(0)":"translateX(108%)",pointerEvents:Zs?"auto":"none",transition:"transform 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",fontWeight:600},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx($u,{size:16}),e.jsx("span",{children:"Schedule Controls"})]}),e.jsx("button",{type:"button",className:t.headerActionBtn,onClick:()=>mr(!1),title:"Hide Schedule Sidebar",children:e.jsx(Hl,{size:16})})]}),e.jsxs("div",{style:{fontSize:"12px",color:"var(--text-secondary)"},children:["Week of ",nl]}),e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"10px",padding:"10px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"},children:[e.jsx("button",{className:t.headerActionBtn,onClick:()=>{const c=new Date(Xa);c.setMonth(Xa.getMonth()-1),$n(`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:e.jsx(Fu,{size:14})}),e.jsx("div",{style:{fontSize:"12px",fontWeight:600},children:al}),e.jsx("button",{className:t.headerActionBtn,onClick:()=>{const c=new Date(Xa);c.setMonth(Xa.getMonth()+1),$n(`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:e.jsx(la,{size:14})})]}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))",gap:"4px",marginBottom:"4px"},children:il.map(c=>e.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)",textAlign:"center"},children:c},c))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))",gap:"4px"},children:ol.map(c=>{const k=Or(c),A=c.getMonth()!==Xa.getMonth(),fe=Sl(c,Lt),ge=Or(fe)===Or(Nn),gt=k===hn,ks=k===fs,Wt=k<fs,co=rl.get(k),In=!!co,yi=!!co?.hasExpired;return e.jsxs("button",{onClick:()=>{Mn(k),$n(`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}`)},style:{border:gt?"1px solid #2563eb":ks?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent",borderRadius:"8px",padding:"6px 0",fontSize:"12px",position:"relative",background:gt?"rgba(59,130,246,0.22)":ks?"rgba(245,158,11,0.16)":ge?"rgba(59,130,246,0.18)":"transparent",color:A?"var(--text-tertiary)":"var(--text-primary)",cursor:"pointer",fontWeight:gt||ks?700:500,opacity:Wt?.42:1},title:`${ks?`${k} (Today)`:k}`+(In?` • ${co?.count} scheduled`:"")+(yi?" • includes expired":""),children:[c.getDate(),In&&e.jsx("span",{style:{position:"absolute",left:"50%",bottom:"3px",transform:"translateX(-50%)",width:"5px",height:"5px",borderRadius:"999px",background:yi?"#ef4444":"#3b82f6",opacity:A?.6:.95}})]},k)})}),e.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"10px"},children:e.jsx("button",{className:t.headerActionBtn,onClick:()=>{const c=new Date;Mn(Or(c)),$n(`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"13px"},children:[e.jsx("input",{type:"checkbox",checked:Wa,onChange:c=>hr(c.target.checked)}),"Show weekends"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"13px"},children:[e.jsx("input",{type:"checkbox",checked:Qs,onChange:c=>Zr(c.target.checked)}),"Show backlog"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"13px"},children:[e.jsx("input",{type:"checkbox",checked:Be,onChange:c=>Ks(c.target.checked)}),"Only expired/overdue"]}),xr>0&&e.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:"10px",padding:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx("div",{style:{fontSize:"12px",fontWeight:600},children:"Expired Tasks"}),e.jsxs("div",{style:{fontSize:"12px",color:"var(--text-secondary)",display:"flex",flexDirection:"column",gap:"2px"},children:[e.jsxs("span",{children:[xr," expired"]}),e.jsxs("span",{children:[Js," overdue"]})]}),e.jsx("button",{className:t.headerActionBtn,onClick:fi,disabled:Da||xa.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",style:{justifyContent:"flex-start",border:"1px solid var(--border-color)"},children:Da?"Working...":"Schedule to selected week"}),e.jsx("button",{className:t.headerActionBtn,onClick:gi,disabled:Da||en.length===0,title:"Unschedule expired/overdue tasks back to backlog",style:{justifyContent:"flex-start",border:"1px solid var(--border-color)"},children:Da?"Working...":"Unschedule to backlog"})]})]})]}),e.jsxs(Dn,{isOpen:u==="add",onClose:vr,title:Ne?"Edit Task":"New Task",size:"md",theme:y,draggable:!0,closeOnOverlayClick:!1,children:[e.jsx(Hd,{editingTaskId:Ne,loading:J,title:ce,currentTask:_o,handleSubmit:w,resetForm:T,handleCopyId:Ss,copiedId:ds,tasks:$,handleToggleInProgress:Ds,handleToggleReview:Cs,handleToggleComplete:us,handleToggleCancel:L,handleArchiveTask:F}),e.jsx(Ud,{editingTaskId:Ne,error:he,title:ce,description:U,category:ye,type:Ae,priority:Ye,complexity:Fe,manualComplexityEnabled:yt,approach:ne,assignee:dt,scheduledDate:q,dueDate:Q,parentTaskIdInput:xe,addChildTaskIdInput:oe,formTaxonomies:mt,onTaxonomyChange:(c,k)=>kt(A=>({...A,[c]:k})),onParentTaskIdInputChange:B,onAddChildTaskIdInputChange:et,taxonomies:ts,selectedSpecialists:Dt,comments:Zt,newCommentText:tt,contextFiles:Rt,contextLinkBrowsePath:Hr,descriptionFocused:Ut,showMarkdownHelp:Pe,showSpecialists:Le,showChecklist:N,checklistEnabled:ut,showTaskRelationships:je,showChildTasks:we,showComments:vt,categories:m,types:Et,priorities:qt,approaches:Ct,availableSpecialists:As,copiedId:ds,onTitleChange:W,onDescriptionChange:Ge,onCategoryChange:ke,onTypeChange:se,onPriorityChange:We,onComplexityChange:te,onApproachChange:c=>{le(c),kt(k=>({...k,approach:c}))},onAssigneeChange:ae,onScheduledDateChange:M,onDueDateChange:de,onSelectedSpecialistsChange:Mt,onNewCommentTextChange:pt,onDescriptionFocusedChange:V,onShowMarkdownHelpChange:_e,onShowSpecialistsChange:ze,onShowChecklistChange:G,onShowTaskRelationshipsChange:Ie,onShowChildTasksChange:qe,onShowCommentsChange:st,onOpenSettings:c=>{Xe(c),d("settings")},onSubmit:w,commentsEndRef:Mi,onAddComment:()=>Re(tt),onSetParentForCurrentTask:bt,onAddChildToCurrentTask:De,onCreateChildForCurrentTask:Jt,onUnlinkChildTask:St,onReorderChildTasks:ls,onOpenTaskById:zt,onAddContextFile:c=>{wt(k=>[...k,c])},onBrowseContextLinkPath:()=>{Ii({type:"context-link"}),So(""),Pn(!0)},onRemoveContextFile:async c=>{const k=Rt[c],A=typeof k=="string"?k:k.path;if(wt(fe=>fe.filter((ge,gt)=>gt!==c)),typeof A=="string"&&A.startsWith("/api/taskforce/context/"))try{await fetch(A,{method:"DELETE"})}catch{}},onUpdateContextCaption:(c,k)=>{wt(A=>A.map((fe,ge)=>ge!==c?fe:typeof fe=="string"?{path:fe,caption:k,timestamp:new Date().toISOString()}:{...fe,caption:k}))},onCopyId:Ss,onToggleInProgress:Ds,onToggleReview:Cs,onToggleComplete:us,onToggleCancel:L,onArchiveTask:F,onUnarchive:K,currentTask:_o,currentTaskParent:Xr,currentTaskChildren:Qr})]}),e.jsx(Dn,{isOpen:u==="settings",onClose:vr,title:"Settings",size:"md",theme:y,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:e.jsx(Gd,{settingsModel:ot,onSectionChange:Xe})}),e.jsx(Dn,{isOpen:!!Ln,onClose:Fi,title:"Date Warning",size:"sm",theme:y,draggable:!1,closeOnOverlayClick:!1,children:e.jsxs("div",{className:t.form,style:{padding:"16px",gap:"12px"},children:[e.jsx("p",{style:{margin:0,fontSize:"13px",color:"var(--text-secondary)"},children:"Due date is before scheduled date."}),Ln&&e.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",Ln.dueDate," · Scheduled: ",Ln.scheduledDate]}),e.jsxs("div",{className:t.formActions,children:[e.jsx("button",{className:t.cancelBtn,onClick:Fi,children:"Go Back"}),e.jsx("button",{className:t.submitBtn,onClick:pr,children:"Save Anyway"})]})]})}),e.jsx(Dn,{isOpen:!!ea,onClose:uc,title:"Schedule Descendants",size:"sm",theme:y,draggable:!1,closeOnOverlayClick:!1,children:e.jsxs("div",{className:t.form,style:{padding:"16px",gap:"12px"},children:[ea&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{style:{margin:0,fontSize:"13px",color:"var(--text-secondary)"},children:["Schedule unscheduled leaf tasks under ",e.jsx("strong",{children:ea.parentTitle})," to ",e.jsx("strong",{children:ea.targetDate}),"?"]}),e.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:[ea.toScheduleLeafTaskIds.length," leaf task",ea.toScheduleLeafTaskIds.length===1?"":"s"," will be scheduled.",ea.alreadyScheduledLeafCount>0?` ${ea.alreadyScheduledLeafCount} already scheduled leaf task${ea.alreadyScheduledLeafCount===1?"":"s"} will be skipped.`:""]})]}),e.jsxs("div",{className:t.formActions,children:[e.jsx("button",{className:t.cancelBtn,onClick:uc,disabled:Ha,children:"Cancel"}),e.jsx("button",{className:t.submitBtn,onClick:sl,disabled:Ha,children:Ha?"Scheduling...":"Schedule"})]})]})}),e.jsx(Dn,{isOpen:Gn,onClose:()=>yn(!1),title:"Quick Start",size:"md",theme:y,draggable:!0,children:e.jsxs("div",{className:be.form,style:{paddingTop:"18px"},children:[e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"Use this quick guide to get productive in Taskforce dashboard mode."}),e.jsxs("div",{children:[e.jsx("strong",{children:"1. Capture work"}),e.jsxs("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:["Click ",e.jsx("code",{children:"Add Task"}),", write a short title, and save."]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"2. Plan the board"}),e.jsxs("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:["Use ",e.jsx("code",{children:"Sort"}),", ",e.jsx("code",{children:"Group"}),", and ",e.jsx("code",{children:"Filters"})," in the header."]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"3. Execute and stage"}),e.jsxs("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:["Move tasks through ",e.jsx("code",{children:"Task"}),", ",e.jsx("code",{children:"In Progress"}),", ",e.jsx("code",{children:"Review"}),", and ",e.jsx("code",{children:"Done"}),"."]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"4. Archive finished work"}),e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:"Archive completed/cancelled tasks to keep active board signal high."})]}),e.jsxs("div",{className:be.formActions,style:{display:"flex",justifyContent:"flex-end",gap:"10px"},children:[e.jsx("button",{className:t.cancelBtn,onClick:()=>{yn(!1),d("settings"),Xe("general")},children:"Open Settings"}),e.jsx("button",{className:t.submitBtn,onClick:()=>yn(!1),children:"Close Tutorial"})]})]})}),e.jsx(Dn,{isOpen:tn,onClose:()=>Ga(!1),title:"Account Hub",size:"md",theme:y,draggable:!0,children:e.jsxs("div",{className:be.form,style:{paddingTop:"18px"},children:[e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"Manage sign in, profile, and workspace controls from one place."}),e.jsxs("div",{className:t.accountHubCard,children:[e.jsx("strong",{children:"Authentication"}),e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:at==="cloud"?xt?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."}),e.jsx("p",{style:{margin:"6px 0 0 0",color:"var(--text-secondary)"},children:O?tc?e.jsxs(e.Fragment,{children:["Signed in as ",e.jsx("span",{className:t.accountIdentityEmail,children:Dr})]}):"Signed in":"Signed in as: not signed in"}),at==="cloud"&&xt&&!O&&e.jsx("p",{style:{marginTop:"10px",color:"var(--text-secondary)"},children:"Use the `/login` screen to sign in."})]}),e.jsxs("div",{className:t.accountHubCard,children:[e.jsx("strong",{children:"Profile & Account"}),e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:"Profile editing and account preferences will live here."})]}),e.jsxs("div",{className:t.accountHubCard,children:[e.jsx("strong",{children:"Billing"}),at!=="cloud"?e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:"Billing actions are available in cloud runtime only."}):O?e.jsxs(e.Fragment,{children:[Ir&&e.jsx("p",{style:{margin:"6px 0 0 0",color:"var(--text-secondary)"},children:"Loading billing status..."}),Wo&&e.jsx("p",{className:t.loginError,style:{marginTop:"8px"},children:Wo}),Ho&&e.jsx("p",{className:t.loginError,style:{marginTop:"8px"},children:Ho}),Ar&&e.jsx("p",{style:{margin:"8px 0 0 0",color:"var(--text-secondary)"},children:Ar}),e.jsxs("p",{style:{margin:"6px 0 0 0",color:"var(--text-secondary)"},children:["Plan: ",e.jsx("code",{children:String(Ka?.planId||"free")})," · ","Entitlement: ",e.jsx("code",{children:String(Ka?.entitlementState||"free")})]}),e.jsxs("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:["Stripe status: ",e.jsx("code",{children:String(Ka?.stripeStatus||"n/a")}),Ka?.effectiveUntil?` · Effective until ${new Date(Ka.effectiveUntil).toLocaleString()}`:""]}),e.jsx("div",{style:{marginTop:"10px",display:"flex",gap:"8px",flexWrap:"wrap"},children:e.jsxs("label",{className:t.accountMenuMeta,style:{display:"inline-flex",alignItems:"center",gap:"8px"},children:["Interval",e.jsxs("select",{className:t.input,value:to,onChange:c=>li(c.target.value==="year"?"year":"month"),disabled:wn,children:[e.jsx("option",{value:"month",children:"Monthly"}),e.jsx("option",{value:"year",children:"Yearly"})]})]})}),e.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px",justifyContent:"flex-end",flexWrap:"wrap"},children:[e.jsx("button",{className:t.cancelBtn,onClick:()=>{on()},disabled:wn||Ir,children:"Refresh Billing"}),e.jsx("button",{className:t.cancelBtn,onClick:()=>{Jc()},disabled:wn||!Ka?.stripeSubscriptionId,children:"Update Interval"}),e.jsx("button",{className:t.cancelBtn,onClick:()=>{Kc()},disabled:wn||!Ka?.stripeCustomerId,children:"Manage Billing"}),e.jsx("button",{className:t.submitBtn,onClick:()=>{Vc()},disabled:wn,children:wn?"Working...":"Start Checkout"})]})]}):e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:"Sign in to manage subscription billing."})]}),e.jsxs("div",{className:t.accountHubCard,children:[e.jsx("strong",{children:"Workspace Audit Log"}),e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:"Audit entries are workspace-scoped for the active workspace, not global account history."}),e.jsxs("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:["Active workspace: ",e.jsx("code",{children:ms})]}),e.jsx("div",{style:{marginTop:"10px",display:"flex",gap:"10px",justifyContent:"flex-end"},children:e.jsx("button",{className:t.cancelBtn,onClick:()=>{Ga(!1),Lr(),js("audit")},disabled:!ao,children:"Open Workspace Audit"})})]}),e.jsxs("div",{className:t.accountHubCard,children:[e.jsx("strong",{children:"Workspace Cloud Sync"}),e.jsx("p",{style:{margin:"4px 0 0 0",color:"var(--text-secondary)"},children:Ma?Je?`Enabled${Ls?` · Source: ${Ls}`:""}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),Qi&&e.jsx("p",{className:t.loginError,style:{marginTop:"8px"},children:Qi}),e.jsx("div",{style:{marginTop:"10px",display:"flex",gap:"10px",justifyContent:"flex-end"},children:e.jsx("button",{className:t.cancelBtn,disabled:!Ma||wr,onClick:async()=>{if(!Ma)return;if(Kn(null),!Je){Vn(!0);const k=await na({enabled:!0,onboardingCompleted:!1});k.success||Kn(k.error||"Failed to enable sync."),Vn(!1);return}Vn(!0);const c=await na({enabled:!1,sourceOfTruth:Ls,onboardingCompleted:Us});c.success||Kn(c.error||"Failed to disable sync."),Vn(!1)},children:Je?"Disable Sync":"Enable Sync"})})]}),e.jsxs("div",{className:be.formActions,style:{display:"flex",justifyContent:"flex-end",gap:"10px"},children:[e.jsx("button",{className:t.cancelBtn,onClick:()=>{Ga(!1),yn(!0)},children:"Help & Tutorial"}),e.jsx("button",{className:t.submitBtn,onClick:()=>Ga(!1),children:"Close"})]})]})}),e.jsx(Dn,{isOpen:Tr,onClose:()=>ra(!1),title:"Team Management",size:"md",theme:y,draggable:!0,children:e.jsxs("div",{className:be.form,style:{paddingTop:"18px"},children:[qa!=="team"&&e.jsx("p",{className:t.loginError,children:"Team management is only available in TEAM accounts."}),Xn&&e.jsx("p",{className:t.loginError,children:Xn}),e.jsxs("div",{className:t.settingsTabs,children:[e.jsx("button",{className:`${t.settingsTabBtn} ${sn==="members"?t.settingsTabBtnActive:""}`,onClick:()=>{js("members"),qo()},children:"Members"}),e.jsx("button",{className:`${t.settingsTabBtn} ${sn==="invites"?t.settingsTabBtnActive:""}`,onClick:()=>js("invites"),children:"Invites"}),e.jsx("button",{className:`${t.settingsTabBtn} ${sn==="audit"?t.settingsTabBtnActive:""}`,onClick:()=>{js("audit"),Cn(nn)},children:"Audit Log"})]}),sn==="members"&&e.jsxs("div",{className:t.accountHubCard,children:[Qn&&e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"Loading members..."}),!Qn&&Eo.length===0&&e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"No users found."}),!Qn&&Eo.map(c=>e.jsxs("div",{style:{borderTop:"1px solid var(--border-color)",paddingTop:"8px",marginTop:"8px"},children:[e.jsx("div",{style:{fontWeight:600},children:c.displayName||c.email}),e.jsxs("div",{className:t.accountMenuMeta,children:[c.email," · ",c.status,c.disabled?" · deactivated":""]}),e.jsxs("div",{style:{marginTop:"6px",display:"flex",gap:"8px",flexWrap:"wrap"},children:[e.jsxs("select",{className:t.input,value:c.role,onChange:k=>{no(c.userId,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c.userId)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...Me()},credentials:"include",body:JSON.stringify({workspaceId:ms,role:k.target.value})}))},disabled:xn===c.userId,style:{maxWidth:"160px"},children:[e.jsx("option",{value:"owner",children:"Owner"}),e.jsx("option",{value:"admin",children:"Admin"}),e.jsx("option",{value:"member",children:"Member"})]}),c.role==="member"&&e.jsxs("select",{className:t.input,value:c.permissionMode,onChange:k=>{no(c.userId,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c.userId)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...Me()},credentials:"include",body:JSON.stringify({workspaceId:ms,mode:k.target.value})}))},disabled:xn===c.userId,style:{maxWidth:"170px"},children:[e.jsx("option",{value:"read-write",children:"Read / Write"}),e.jsx("option",{value:"read-only",children:"Read Only"})]}),e.jsx("button",{className:t.cancelBtn,disabled:xn===c.userId,onClick:()=>{no(c.userId,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c.userId)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...Me()},credentials:"include",body:JSON.stringify({workspaceId:ms,disabled:!c.disabled})}))},children:c.disabled?"Reactivate":"Deactivate"}),c.status==="invited"&&e.jsx("button",{className:t.cancelBtn,disabled:xn===c.userId,onClick:()=>{no(c.userId,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c.userId)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...Me()},credentials:"include",body:JSON.stringify({workspaceId:ms})}))},children:"Revoke Invite"}),e.jsx("button",{className:t.cancelBtn,disabled:xn===c.userId,onClick:()=>{no(c.userId,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(c.userId)}?workspaceId=${encodeURIComponent(ms)}`,{method:"DELETE",headers:Me(),credentials:"include"}))},children:"Remove"})]})]},c.userId))]}),sn==="invites"&&e.jsxs("div",{className:t.accountHubCard,children:[Mo&&e.jsx("p",{style:{margin:"0 0 8px 0",color:"var(--text-secondary)"},children:Mo}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"90px"},children:"Email"}),e.jsx("input",{className:t.input,value:vn,onChange:c=>ia(c.target.value),placeholder:"name@company.com"})]}),e.jsxs("div",{className:t.pathInputGroup,children:[e.jsx("label",{className:t.label,style:{minWidth:"90px"},children:"Role"}),e.jsxs("select",{className:t.input,value:an,onChange:c=>Va(c.target.value==="admin"?"admin":"member"),style:{maxWidth:"150px"},children:[e.jsx("option",{value:"member",children:"Member"}),e.jsx("option",{value:"admin",children:"Admin"})]}),an==="member"&&e.jsxs("select",{className:t.input,value:Zn,onChange:c=>Ra(c.target.value==="read-only"?"read-only":"read-write"),style:{maxWidth:"170px"},children:[e.jsx("option",{value:"read-write",children:"Read / Write"}),e.jsx("option",{value:"read-only",children:"Read Only"})]}),e.jsx("button",{className:t.submitBtn,disabled:Nr||!vn.trim()||qa!=="team",onClick:()=>{$a()},children:Nr?"Sending...":"Send Invite"})]}),e.jsxs("div",{style:{marginTop:"12px"},children:[e.jsx("div",{style:{fontWeight:600,marginBottom:"6px"},children:"Pending Invites"}),oc.length===0&&e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"No pending invites."}),oc.map(c=>e.jsxs("div",{style:{borderTop:"1px solid var(--border-color)",paddingTop:"8px",marginTop:"8px"},children:[e.jsx("div",{style:{fontWeight:600},children:c.displayName||c.email}),e.jsxs("div",{className:t.accountMenuMeta,children:[c.email," · ",c.role]})]},c.userId))]})]}),sn==="audit"&&e.jsxs("div",{className:t.accountHubCard,children:[$o&&e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"Loading audit entries..."}),!$o&&ec.length===0&&e.jsx("p",{style:{margin:0,color:"var(--text-secondary)"},children:"No audit events for this workspace."}),!$o&&e.jsx("div",{style:{maxHeight:"320px",overflowY:"auto",paddingRight:"4px"},children:ec.map(c=>e.jsxs("div",{style:{borderTop:"1px solid var(--border-color)",paddingTop:"8px",marginTop:"8px"},children:[e.jsx("div",{className:t.accountMenuMeta,children:new Date(c.createdAt).toLocaleString()}),e.jsx("div",{style:{fontWeight:600},children:c.action}),e.jsxs("div",{className:t.accountMenuMeta,children:[c.actorUserId," (",c.actorRole,")"]})]},c.id))}),e.jsxs("div",{style:{marginTop:"10px",display:"flex",justifyContent:"space-between",gap:"8px"},children:[e.jsx("button",{className:t.cancelBtn,disabled:$o||nn===0,onClick:()=>{Cn(nn-1)},children:"Previous"}),e.jsxs("span",{className:t.accountMenuMeta,children:["Page ",nn+1," of ",ci]}),e.jsx("button",{className:t.cancelBtn,disabled:$o||!ii||nn+1>=ci,onClick:()=>{Cn(nn+1)},children:"Next"})]})]}),e.jsx("div",{className:be.formActions,style:{display:"flex",justifyContent:"flex-end",gap:"10px"},children:e.jsx("button",{className:t.cancelBtn,onClick:()=>ra(!1),children:"Close"})})]})}),e.jsx(Dn,{isOpen:ai,onClose:()=>{qn(!1)},title:"Cloud Sync Status",size:"md",theme:y,draggable:!0,children:e.jsxs("div",{className:`${be.form} ${t.syncStatusModal}`,children:[e.jsxs("div",{className:t.syncStatusTop,children:[e.jsxs("div",{children:[e.jsx("div",{className:t.syncStatusHeading,children:"Current Status"}),e.jsx("div",{className:t.syncStatusSubtext,children:e.jsx("code",{children:ms})}),pe&&e.jsxs("div",{className:t.syncStatusPausedHint,children:["Initial sync in progress: ",Nt," changes across ",Te," page",Te===1?"":"s","."]}),at==="local"&&!O&&e.jsx("div",{className:t.syncStatusPausedHint,children:"Sync is paused. Sign in on cloud to resume."})]}),e.jsx("div",{className:t.syncStatusBadge,style:{borderColor:Er.border,background:Er.background,color:Er.color},children:Er.label})]}),e.jsxs("div",{className:t.syncStatusGrid,children:[e.jsxs("div",{className:t.syncStatusItem,children:[e.jsx("span",{className:t.syncStatusLabel,children:"Last successful sync"}),e.jsx("span",{className:t.syncStatusValue,children:cc})]}),e.jsxs("div",{className:t.syncStatusItem,children:[e.jsx("span",{className:t.syncStatusLabel,children:"Pending local changes"}),e.jsx("span",{className:t.syncStatusValue,children:Ze})]}),e.jsxs("div",{className:t.syncStatusItem,children:[e.jsx("span",{className:t.syncStatusLabel,children:"Last pull from cloud"}),e.jsx("span",{className:t.syncStatusValue,children:oo})]}),e.jsxs("div",{className:t.syncStatusItem,children:[e.jsx("span",{className:t.syncStatusLabel,children:"Last push to cloud"}),e.jsx("span",{className:t.syncStatusValue,children:wa})]}),e.jsxs("div",{className:t.syncStatusItem,children:[e.jsx("span",{className:t.syncStatusLabel,children:"Scheduled retry"}),e.jsx("span",{className:t.syncStatusValue,children:Y?ro:"None"})]}),e.jsxs("div",{className:t.syncStatusItem,children:[e.jsx("span",{className:t.syncStatusLabel,children:"Last error time"}),e.jsx("span",{className:t.syncStatusValue,children:S?lc:"None"})]})]}),e.jsxs("div",{className:t.syncStatusDetailsGrid,children:[e.jsx("div",{className:t.syncStatusTableWrap,children:e.jsx("table",{className:t.syncStatusTable,children:e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{children:"Runtime mode"}),e.jsx("td",{children:at})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Sync source of truth"}),e.jsx("td",{children:Ls||"unset"})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Ready"}),e.jsx("td",{children:qs?"yes":"no"})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Hydrated"}),e.jsx("td",{children:ya?"yes":"no"})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Failure count"}),e.jsx("td",{children:Ns})]})]})})}),e.jsx("div",{className:t.syncStatusTableWrap,children:e.jsx("table",{className:t.syncStatusTable,children:e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{children:"Auth failures"}),e.jsx("td",{children:ns})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Last failure source"}),e.jsx("td",{children:_s||"none"})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Last failure status"}),e.jsx("td",{children:_a??"none"})]}),e.jsxs("tr",{children:[e.jsx("th",{children:"Retries scheduled"}),e.jsx("td",{children:Ca})]})]})})})]}),e.jsx("div",{className:t.syncStatusTableWrap,children:e.jsx("table",{className:t.syncStatusTable,children:e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{className:t.syncStatusTableNarrowLabel,children:"Last error"}),e.jsx("td",{className:t.syncStatusTableError,style:{color:hs||$e?"#fda4af":"var(--text-secondary)"},children:hs||$e||"None"})]}),e.jsxs("tr",{children:[e.jsx("th",{className:t.syncStatusTableNarrowLabel,children:"Last warning"}),e.jsx("td",{style:{color:as?"#fcd34d":"var(--text-secondary)"},children:as||"None"})]})]})})}),e.jsxs("div",{className:`${be.formActions} ${t.syncStatusActions}`,children:[e.jsx("button",{className:t.cancelBtn,onClick:()=>{xo()},disabled:Vs==="syncing",title:"Clear pull cursor and fetch full cloud state into local workspace",children:"Reset Cursor + Full Pull"}),at==="local"&&!O&&e.jsx("button",{className:t.submitBtn,onClick:()=>{sc("login")},children:"Sign In / Register"}),e.jsx("button",{className:t.cancelBtn,onClick:()=>{qn(!1)},children:"Close"}),e.jsx("button",{className:t.submitBtn,onClick:()=>{Rs()},disabled:Vs==="syncing",children:Vs==="syncing"?e.jsxs(e.Fragment,{children:[e.jsx(aa,{size:14,className:t.spinner}),"Syncing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vd,{size:14}),"Retry Now"]})})]})]})}),Mc&&Ci.createPortal(e.jsx("div",{className:`${be.overlay} ${be.unsavedOverlay}`,style:{zIndex:2e3},children:e.jsxs("div",{className:`${be.modal} ${be.unsavedModal}`,"data-theme":y,children:[e.jsx("div",{className:`${be.header} ${be.unsavedHeader}`,children:e.jsxs("div",{className:`${be.headerTitle} ${be.unsavedTitle}`,children:[e.jsx(mo,{size:20}),"Unsaved Changes"]})}),e.jsx("div",{className:`${be.form} ${be.unsavedContent}`,children:e.jsx("p",{className:be.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),e.jsxs("div",{className:`${be.formActions} ${be.unsavedActions}`,children:[e.jsx("button",{className:t.cancelBtn,onClick:()=>Yr(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),e.jsx("button",{className:t.destructiveBtn,onClick:Ta,title:"Discard unsaved changes and leave",children:"Discard"}),e.jsxs("button",{className:t.submitBtn,onClick:Na,disabled:J,title:"Save changes and leave",children:[J?e.jsx(aa,{size:16,className:t.spinner}):e.jsx(Bc,{size:16}),"Save"]})]})]})}),document.body),nr&&Ci.createPortal(e.jsx("div",{className:t.folderBrowserOverlay,children:e.jsxs("div",{className:t.folderBrowser,children:[e.jsxs("div",{className:t.browserHeader,children:[e.jsxs("div",{className:t.browserPathInfo,children:[e.jsx(ho,{size:14}),e.jsx("span",{children:ka||"Project Root"})]}),e.jsxs("div",{className:t.browserActions,children:[ka&&e.jsx("button",{className:t.helpLink,onClick:()=>{const c=ka.split("/").filter(Boolean);c.pop(),So(c.length?c.join("/")+"/":"")},children:"Back"}),e.jsx("button",{className:t.helpLink,onClick:()=>Pn(!1),children:"Close"})]})]}),e.jsxs("div",{className:t.browserList,children:[oa&&typeof oa=="object"&&oa.type!=="context-link"&&e.jsxs("div",{className:`${t.browserItem} ${t.browserItemFile} ${t.browserSelectCurrent}`,onClick:()=>Gr(ka),children:[e.jsx(Sa,{size:14})," Select Current: ./",ka||"(root)"]}),wo.map(c=>e.jsxs("div",{className:t.browserItem,onClick:()=>So(ka+c+"/"),children:[e.jsx(ho,{size:14})," ",c,"/"]},c)),or.map(c=>e.jsxs("div",{className:`${t.browserItem} ${t.browserItemFile}`,onClick:()=>Gr(ka+c),children:[e.jsx(Xo,{size:14})," ",c]},c)),wo.length===0&&or.length===0&&e.jsx("div",{className:`${t.browserItem} ${t.browserEmpty}`,children:"No items found"})]})]})}),document.body),e.jsx(Dn,{isOpen:!!jo,onClose:Ro,title:"Cancel Task",size:"sm",theme:y,draggable:!0,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{className:t.cancelBtn,onClick:Ro,title:"Close and continue working on this task",children:"Back"}),e.jsxs("button",{className:`${t.warningBtn} ${t.cancelTaskConfirmBtn}`,onClick:Hn,title:"Keep the task, set status to cancelled, and save a cancellation reason",style:{gap:"8px"},disabled:zn.length>0&&!dn,children:[e.jsx(yd,{size:16})," Confirm Cancellation"]}),e.jsxs("button",{className:`${t.destructiveBtn} ${t.cancelTaskDeleteBtn}`,onClick:si,title:"Permanently delete this task and all of its data",style:{gap:"8px"},children:[e.jsx(yo,{size:16})," Delete Permanently"]})]}),children:e.jsxs("div",{className:t.form,style:{padding:"20px 24px",display:"flex",flexDirection:"column",gap:"8px",overflow:"hidden"},children:[zn.length>0&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsxs("p",{style:{margin:0,fontSize:"14px",color:"var(--text-secondary)"},children:["This parent has ",zn.length," open descendant task",zn.length===1?"":"s","."]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("input",{type:"radio",name:"cancel-mode",checked:dn==="cascade",onChange:()=>Xs("cascade")}),"Cancel parent and cancel open descendants"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("input",{type:"radio",name:"cancel-mode",checked:dn==="unlink",onChange:()=>Xs("unlink")}),"Cancel parent and unlink open descendants"]})]}),e.jsx("p",{style:{margin:0,fontSize:"14px",color:"var(--text-secondary)"},children:"Why is this task being cancelled?"}),e.jsx("textarea",{className:t.textarea,placeholder:"Reason for record (e.g., No longer relevant, duplicate, etc.)",value:gn,onChange:c=>Lo(c.target.value),autoFocus:!0,style:{minHeight:"60px",width:"100%",resize:"none",boxSizing:"border-box"},rows:2})]})})]})}function nT(a){const n=a.setupState,r=a.runtimeMode,u=a.isAuthenticated,d=!!(n&&r==="cloud"&&u&&n.globalSetupState==="missing"),m=!!(n&&r==="local"&&n.globalSetupState==="missing"),h=!!(n&&r==="cloud"&&u&&n.workspaceSetupState==="missing"),v=!!(n&&r==="local"&&n.workspaceSetupState==="missing"),x=!!(n&&(n.forceSetup||n.forceGlobalSetup||n.forceWorkspaceSetup||d||h||m||v));if(!x)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const _=!!(n&&(n.forceSetup||n.forceGlobalSetup||d||m)),R=!!(n&&(n.forceSetup||n.forceWorkspaceSetup||h||v)),j=!!(_&&n?.globalSetupState==="missing"),D=!!(R&&n?.workspaceSetupState==="missing"),b=!!(_&&n?.globalSetupState==="unreadable"),f=!!(R&&n?.workspaceSetupState==="unreadable"),I=b||f;return{setupGateActive:x,needsGlobalSetup:j,needsWorkspaceSetup:D,hasSetupReadError:I,phase:I?"setup-read-error":j?"needs-global-setup":D?"needs-workspace-setup":"ready"}}function md({config:a={},initialTaskId:n,onTaskCountChange:r,onHeaderMouseDown:u,isDragging:d,onClose:m,mode:h="standalone"}){const v=Cd(),x=Sd(),[_,R]=s.useState(""),[j,D]=s.useState(""),[b,f]=s.useState("login"),[I,$]=s.useState(""),[z,w]=s.useState(""),[T,Z]=s.useState(""),[Ne,J]=s.useState(null),[he,ce]=s.useState(null),[W,U]=s.useState(null),[Ge,ye]=s.useState(null),[ke,Ae]=s.useState(null),[se,Ye]=s.useState(!1),[We,Fe]=s.useState(0),[te,ne]=s.useState(0),[le,dt]=s.useState(()=>Date.now()),[ae,q]=s.useState("core"),[M,Q]=s.useState(!1),[de,xe]=s.useState(null),[B,oe]=s.useState(null),[et,yt]=s.useState(""),[ut,mt]=s.useState(""),[kt,Dt]=s.useState("local"),[Mt,Zt]=s.useState([]),[tt,pt]=s.useState(""),[Rt,wt]=s.useState(!1),[Ut,V]=s.useState(null),[Pe,_e]=s.useState(!1),[Le,ze]=s.useState(!1),N=ch({config:a,initialTaskId:n,onTaskCountChange:r,onClose:m}),{runtimeMode:G,workspaceSwitchingEnabled:je,currentWorkspaceId:Ie,configLoaded:we,cloudAuthConfigured:qe,authRequiredForApi:vt,authBlocked:st,isAuthenticated:Re,hasBetaAccess:bt,authSessionResolved:De,workspaceBootstrapPending:Jt,bootstrapPhase:St,bootstrapError:ls,setupState:Ee,runtimeCapabilities:zt,refreshSetupContext:ts,retryBootstrapChecks:Et,saveWorkspaceProfile:qt,fetchWorkspaces:Ct,applyWorkspaceSyncStateSnapshot:As,loginWithCredentials:ds,registerWithCredentials:Ss,requestEmailVerification:Ds,confirmEmailVerification:us,requestPasswordReset:Cs,confirmPasswordReset:L,inspectInviteAcceptance:F,acceptInviteWithToken:re,currentTheme:K,logout:H}=N,me=s.useMemo(()=>{const O=String(a.cloudAuthBaseUrl||a.apiBaseUrl||"").trim();return O?O.replace(/\/+$/,""):""},[a.apiBaseUrl,a.cloudAuthBaseUrl]),Oe=G==="cloud"||zt?.runtimeMode==="cloud",ie=!Oe&&qe&&!!me,ve=typeof window<"u"&&/^app\./i.test(window.location.hostname),Ue=ve?!Re||st:G==="cloud"&&vt&&!Re||G==="cloud"&&st,ht=G==="cloud"&&Re&&!bt,nt=v.pathname==="/login",It=v.pathname==="/setup",jt=v.pathname==="/coming-soon",Vt=s.useMemo(()=>String(new URLSearchParams(v.search).get("step")||"").trim().toLowerCase(),[v.search]),rt=h!=="widget"&&!De&&!nt&&!It&&(G==="cloud"||ve),ot=s.useMemo(()=>nT({setupState:Ee?{globalSetupState:Ee.globalSetupState,workspaceSetupState:Ee.workspaceSetupState,runtimeMode:Ee.runtimeMode,workspaceId:Ee.workspaceId,mode:Ee.mode,forceSetup:Ee.forceSetup,forceGlobalSetup:Ee.forceGlobalSetup,forceWorkspaceSetup:Ee.forceWorkspaceSetup}:null,runtimeMode:G,isAuthenticated:Re}),[Ee,G,Re]),y=ot.setupGateActive,ue=ot.needsGlobalSetup,Ke=ot.needsWorkspaceSetup,At=ot.hasSetupReadError,ps=h!=="widget"&&De&&!Ue&&!ht&&(!we||Jt||St==="stalled")&&(It||G==="cloud"||ve),Kt=s.useMemo(()=>St==="auth"?"Verifying session...":St==="workspace"?"Resolving workspace access...":St==="config"?"Loading configuration...":"Checking account, workspace access, and setup status...",[St]),Lt=s.useCallback((O,Ve,Ft)=>{const Tt=String(O||"").trim().toLowerCase(),Ot=String(Ve||"").trim().toLowerCase();return!!(!Tt||Tt==="system default workspace"||Ot&&Tt===Ot)},[]);s.useEffect(()=>{const O=Ee?.mode==="operations"?"operations":"core";q(O)},[Ee?.mode]),s.useEffect(()=>{if(!Ee)return;const O=String(Ee.workspace?.name||"").trim(),Ve=String(Ee.suggestedWorkspaceName||"").trim(),Ft=Lt(O,Ee.workspaceId,Ee.workspace?.description)?Ve:O;yt(Ft||Ve||O),mt(String(Ee.workspace?.description||""))},[Ee?.workspace?.name,Ee?.workspace?.description,Ee?.suggestedWorkspaceName,Ee?.workspaceId,Lt]),s.useEffect(()=>{if(!It||Vt!=="workspace")return;if(String(new URLSearchParams(v.search).get("source")||"").trim().toLowerCase()==="cloud"&&ie){Dt("cloud"),_e(!1);return}Dt("local")},[ie,It,v.search,Vt]);const vs=s.useCallback(async()=>{if(!ie||!Re){Zt([]),pt("");return}wt(!0),V(null);try{const O=await fetch(`${me}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),Ve=await O.json().catch(()=>({}));if(!O.ok||Ve?.success===!1){Zt([]),pt(""),V(Ve?.error||`Failed to load cloud projects (${O.status})`);return}const Ft=Array.isArray(Ve?.workspaces)?Ve.workspaces.map(Tt=>({id:String(Tt?.id||"").trim(),name:String(Tt?.name||Tt?.id||"").trim(),description:typeof Tt?.description=="string"?Tt.description:null})).filter(Tt=>Tt.id.length>0):[];Zt(Ft),pt(Tt=>Tt&&Ft.some(Ot=>Ot.id===Tt)?Tt:Ft[0]?.id||"")}catch{Zt([]),pt(""),V("Failed to load cloud projects.")}finally{wt(!1)}},[ie,Re,me]);s.useEffect(()=>{kt==="cloud"&&vs()},[vs,kt]);const Ms=s.useMemo(()=>{const O=new URLSearchParams(v.search).get("next")||"/";return!O.startsWith("/")||O==="/login"?"/":O},[v.search]),Bs=s.useMemo(()=>{const O=String(new URLSearchParams(v.search).get("mode")||"").trim().toLowerCase();return O==="register"||O==="verify"||O==="forgot"||O==="reset"||O==="invite"?O:"login"},[v.search]),Qe=s.useMemo(()=>String(new URLSearchParams(v.search).get("token")||"").trim(),[v.search]),ft=s.useCallback(O=>{const Ve=new URLSearchParams(v.search);O==="login"?Ve.delete("mode"):Ve.set("mode",O);const Ft=Ve.toString();x(`/login${Ft?`?${Ft}`:""}`,{replace:!0})},[v.search,x]),ss=s.useCallback(async O=>{if(!je)return!1;const Ve=await Ct();return Ve.success?(Array.isArray(Ve.workspaces)?Ve.workspaces.length:0)===0?(x("/setup?step=workspace",{replace:!0}),!0):!1:O?(x("/setup?step=workspace",{replace:!0}),!0):!1},[Ct,x,je]);s.useEffect(()=>{nt&&(f(Bs),Bs==="verify"&&Qe&&$(Qe),Bs==="reset"&&Qe&&w(Qe),Bs==="invite"&&Qe&&Z(Qe))},[nt,Bs,Qe]),s.useEffect(()=>{if(!nt||b!=="invite"||!T.trim())return;let O=!0;return(async()=>{const Ve=await F(T);O&&(Ve.success?(J(Ve.email||null),ce(Ve.workspaceId||null),U("Invite ready. Set your password to join."),ye(null),Ae(null)):(J(null),ce(null),ye(bs(Ve)),Ae(Ve.code||Ve.state||null)))})(),()=>{O=!1}},[nt,b,T,F]),s.useEffect(()=>{if(!(We>Date.now()||te>Date.now()))return;const Ve=window.setInterval(()=>dt(Date.now()),1e3);return()=>window.clearInterval(Ve)},[We,te]);const Xt=Math.max(0,Math.ceil((We-le)/1e3)),Xe=Math.max(0,Math.ceil((te-le)/1e3)),at=Xt>0,Bt=Xe>0,bs=O=>{const Ve=O.error||"Request failed.",Ft=O.code||O.state;return Ft?`[${Ft}] ${Ve}`:Ve};s.useEffect(()=>{if(h!=="widget"&&!Jt){if(ht){jt||x("/coming-soon",{replace:!0});return}if(jt&&!ht){x("/",{replace:!0});return}if(!Ue)nt&&Re&&x(Ms,{replace:!0});else{if(!nt){const O=`${v.pathname}${v.search}${v.hash}`;x(`/login?next=${encodeURIComponent(O||"/")}`,{replace:!0});return}return}if(y){if(At){(!It||Vt!=="error")&&x("/setup?step=error",{replace:!0});return}if(ue){(!It||Vt!=="global")&&x("/setup?step=global",{replace:!0});return}if(Ke){(!It||Vt!=="workspace")&&x("/setup?step=workspace",{replace:!0});return}It&&x("/",{replace:!0});return}It&&Ee&&x("/",{replace:!0})}},[h,Ue,ht,nt,It,jt,y,Ee,At,ue,Ke,Vt,Jt,v.pathname,v.search,v.hash,x,Ms]),s.useEffect(()=>{if(h==="widget"||G!=="local"||!we||nt||It)return;const O=String(Ie||"").trim().toLowerCase();(!O||O==="default")&&x("/setup?step=workspace",{replace:!0})},[h,G,we,nt,It,Ie,x]);const xt=s.useCallback(async()=>{ze(!0);try{await Et()}finally{ze(!1)}},[Et]),$t=s.useCallback(async()=>{await H(),x("/login",{replace:!0})},[H,x]);if(h==="widget")return e.jsx(Pj,{...N,onHeaderMouseDown:u,isDragging:d,onClose:m});if(rt)return e.jsx("div",{className:t.standaloneWrapper,"data-theme":K,children:e.jsx("div",{className:t.loginView,children:e.jsxs("div",{className:t.loginCard,children:[e.jsxs("div",{className:t.authBrandRow,children:[e.jsx("img",{src:Vo,alt:"Taskforce",className:t.loginLogo}),e.jsx("h1",{className:t.loginTitle,children:"Loading Taskforce"})]}),e.jsx("p",{className:t.loginSubtitle,children:"Checking your session..."})]})})});if(ps)return e.jsx("div",{className:t.standaloneWrapper,"data-theme":K,children:e.jsx("div",{className:t.loginView,children:e.jsxs("div",{className:t.loginCard,children:[e.jsxs("div",{className:t.authBrandRow,children:[e.jsx("img",{src:Vo,alt:"Taskforce",className:t.loginLogo}),e.jsx("h1",{className:t.loginTitle,children:"Loading Taskforce"})]}),e.jsx("p",{className:t.loginSubtitle,children:Kt}),St==="stalled"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:t.loginError,children:ls||"Startup checks timed out."}),e.jsx("button",{className:t.submitBtn,disabled:Le,onClick:xt,children:Le?"Retrying...":"Retry checks"}),Oe&&e.jsx("button",{className:t.cancelBtn,disabled:Le,onClick:$t,children:"Go to sign-in"})]})]})})});if(nt)return e.jsx("div",{className:t.standaloneWrapper,"data-theme":K,children:e.jsx("div",{className:t.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Cc})`},children:e.jsxs("div",{className:t.loginCard,children:[!Oe&&!Ue&&e.jsx("button",{className:t.loginCloseBtn,"aria-label":"Close sign in",onClick:()=>x(Ms,{replace:!0}),children:"×"}),e.jsxs("div",{className:t.authBrandRow,children:[e.jsx("img",{src:Vo,alt:"Taskforce",className:t.loginLogo}),e.jsxs("h1",{className:t.loginTitle,children:["TASKFORCE ",e.jsx("span",{className:t.loginTitleAccent,children:"HQ"})]})]}),e.jsxs("p",{className:t.loginSubtitle,children:[b==="login"&&"Sign in with your account credentials.",b==="register"&&"Create your Taskforce account.",b==="verify"&&"Enter your verification token.",b==="forgot"&&"Request a password reset link.",b==="reset"&&"Set a new password using your reset token.",b==="invite"&&"Accept your invite and create a password."]}),(b==="login"||b==="register"||b==="forgot")&&e.jsx("input",{className:t.input,type:"email",value:_,placeholder:"Email",onChange:O=>R(O.target.value)}),(b==="login"||b==="register"||b==="reset")&&e.jsx("input",{className:t.input,type:"password",value:j,placeholder:b==="reset"?"New password":"Password",onChange:O=>D(O.target.value)}),b==="verify"&&e.jsx("input",{className:t.input,type:"text",value:I,placeholder:"Verification token",onChange:O=>$(O.target.value)}),b==="reset"&&e.jsx("input",{className:t.input,type:"text",value:z,placeholder:"Reset token",onChange:O=>w(O.target.value)}),b==="invite"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{className:t.input,type:"text",value:T,placeholder:"Invite token",onChange:O=>Z(O.target.value)}),Ne&&e.jsxs("p",{className:t.loginSubtitle,children:["Invite for: ",e.jsx("strong",{children:Ne}),he?` · Workspace: ${he}`:""]})]}),W&&e.jsx("p",{className:t.loginSubtitle,children:W}),Ge&&e.jsx("p",{className:t.loginError,children:Ge}),b==="login"&&ke==="EMAIL_NOT_VERIFIED"&&_.trim()&&e.jsx("button",{className:t.authModeLink,disabled:se||at,onClick:async()=>{Ye(!0),U(null);const O=await Ds(_);O.success?(Fe(Date.now()+3e4),ft("verify"),O.verificationToken&&$(O.verificationToken),U("Verification email resent."),ye(null),Ae(null)):ye(bs(O)),Ye(!1)},children:at?`Resend in ${Xt}s`:"Resend Verification Email"}),e.jsx("button",{className:t.submitBtn,disabled:se||b==="verify"&&at||b==="forgot"&&Bt,onClick:async()=>{Ye(!0),U(null),ye(null),Ae(null);let O={success:!1};if(b==="login"?O=await ds(_,j):b==="register"?O=await Ss(_,j):b==="verify"?O=await us(I):b==="forgot"?O=await Cs(_):b==="reset"?O=await L(z,j):b==="invite"&&(O=await re(T,j)),O.success)if(b==="register"){if(await ss(O.workspaceSetupRequired)){Ye(!1);return}O.verificationToken&&$(O.verificationToken),Fe(Date.now()+3e4),ft("verify"),U(O.emailSent===!1?`Account created, but verification email failed to send. ${O.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")}else if(b==="verify")ft("login"),U("Email verified. You can sign in now.");else if(b==="forgot")O.resetToken&&w(O.resetToken),ne(Date.now()+3e4),ft("reset"),U(O.emailSent===!1?`Password reset email failed to send. ${O.emailError||"Try again in a minute."}`:"Password reset instructions sent.");else if(b==="reset")ft("login"),U("Password updated. Sign in with your new password.");else if(b==="invite"){if(O.workspaceSetupRequired){x("/setup?step=workspace",{replace:!0}),Ye(!1);return}x(Ms,{replace:!0})}else if(b==="login"){if(O.workspaceSetupRequired){x("/setup?step=workspace",{replace:!0}),Ye(!1);return}R(""),D(""),x(Ms,{replace:!0})}else R(""),D(""),x(Ms,{replace:!0});else{if(ye(bs(O)),Ae(O.code||null),b==="login"&&(O.code==="WORKSPACE_NOT_FOUND"||O.code==="WORKSPACE_ID_REQUIRED")){x("/setup?step=workspace",{replace:!0}),Ye(!1);return}if(b==="login"&&O.code==="EMAIL_NOT_VERIFIED"&&_.trim()){const Ve=await Ds(_);Ve.success&&(Fe(Date.now()+3e4),ft("verify"),Ve.verificationToken&&$(Ve.verificationToken),U("Email not verified. A verification token was sent."),ye(null),Ae(null))}}Ye(!1)},children:se?"Working...":b==="login"?"Sign In":b==="register"?"Create Account":b==="verify"?at?`Resend in ${Xt}s`:"Resend Verification":b==="forgot"?Bt?`Retry in ${Xe}s`:"Send Reset Link":b==="reset"?"Reset Password":"Accept Invite"}),(b==="login"||b==="register")&&e.jsxs("p",{className:t.authModeSwitch,children:[b==="login"?"Need an account?":"Already have an account?"," ",e.jsx("button",{className:t.authModeSwitchLink,disabled:se,onClick:()=>{ye(null),Ae(null),U(null),ft(b==="login"?"register":"login")},children:b==="login"?"Register":"Sign In"})]}),e.jsxs("div",{className:t.authModeLinks,children:[(b==="login"||b==="register")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:t.authModeLink,disabled:se||Bt,onClick:()=>{ye(null),Ae(null),U(null),ft("forgot")},children:Bt?`Forgot Password (${Xe}s)`:"Forgot Password"}),e.jsx("button",{className:t.authModeLink,disabled:se||at,onClick:()=>{ye(null),Ae(null),U(null),ft("verify")},children:at?`Resend Verification (${Xt}s)`:"Resend Verification"}),e.jsx("button",{className:t.authModeLink,disabled:se,onClick:()=>{ye(null),Ae(null),U(null),ft("invite")},children:"Accept Invite"})]}),b!=="login"&&b!=="register"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:t.authModeLink,disabled:se,onClick:()=>{ye(null),Ae(null),U(null),ft("login")},children:"Sign In"}),e.jsx("button",{className:t.authModeLink,disabled:se,onClick:()=>{ye(null),Ae(null),U(null),ft("register")},children:"Register"}),b==="reset"&&e.jsx("button",{className:t.authModeLink,disabled:se||Bt,onClick:()=>{ye(null),Ae(null),U(null),ft("forgot")},children:Bt?`Forgot Password (${Xe}s)`:"Forgot Password"})]})]})]})})});if(Ue&&!nt)return e.jsx("div",{className:t.standaloneWrapper,"data-theme":K,children:e.jsx("div",{className:t.loginView,children:e.jsxs("div",{className:t.loginCard,children:[e.jsxs("div",{className:t.authBrandRow,children:[e.jsx("img",{src:Vo,alt:"Taskforce",className:t.loginLogo}),e.jsx("h1",{className:t.loginTitle,children:"Loading Taskforce"})]}),e.jsx("p",{className:t.loginSubtitle,children:"Redirecting to sign in..."})]})})});if(jt&&ht)return e.jsx("div",{className:t.standaloneWrapper,"data-theme":K,children:e.jsx("div",{className:t.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Cc})`},children:e.jsxs("div",{className:t.loginCard,children:[e.jsxs("div",{className:t.authBrandRow,children:[e.jsx("img",{src:Vo,alt:"Taskforce",className:t.loginLogo}),e.jsx("h1",{className:t.loginTitle,children:"Private Beta"})]}),e.jsx("p",{className:t.loginSubtitle,children:"You are signed in, but your account is not in the beta allowlist yet."}),e.jsx("p",{className:t.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),e.jsx("button",{className:t.cancelBtn,onClick:async()=>{await N.logout(),x("/login",{replace:!0})},children:"Sign Out"})]})})});if(It&&y&&(At||ue||Ke)){const O=At||Vt==="error",Ve=!O&&(ue||Vt==="global"),Ft=E(O?"setup.headingCheckFailed":Ve?"setup.headingGlobalRequired":"setup.headingWorkspaceRequired"),Tt=E(O?"setup.subtitleUnreadable":Ve?"setup.subtitleGlobalRequired":"setup.subtitleWorkspaceRequired"),Ot=E(ae==="operations"?"setup.workspaceTermMission":"setup.workspaceTermProject");return e.jsx("div",{className:t.standaloneWrapper,"data-theme":K,children:e.jsx("div",{className:t.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Cc})`},children:e.jsxs("div",{className:t.loginCard,children:[e.jsxs("div",{className:t.authBrandRow,children:[e.jsx("img",{src:Vo,alt:"Taskforce",className:t.loginLogo}),e.jsxs("h1",{className:t.loginTitle,children:["TASKFORCE ",e.jsx("span",{className:t.loginTitleAccent,children:"HQ"})]})]}),e.jsx("p",{className:t.loginSubtitle,children:e.jsx("strong",{children:Ft})}),e.jsx("p",{className:t.loginSubtitle,children:Tt}),zt&&e.jsxs("p",{className:t.loginSubtitle,children:[E("setup.runtimeLabel"),": ",e.jsx("strong",{children:zt.runtimeMode})]}),B&&e.jsx("p",{className:t.loginSubtitle,children:B}),de&&e.jsx("p",{className:t.loginError,children:de}),Ve&&e.jsxs("div",{style:{display:"grid",gap:10,textAlign:"left"},children:[e.jsxs("label",{className:t.authModeLink,style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer"},children:[e.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:ae==="core",onChange:()=>q("core"),disabled:M}),e.jsx("span",{children:E("setup.coreModeOption",{workspaceLabel:Ot})})]}),e.jsxs("label",{className:t.authModeLink,style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer"},children:[e.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:ae==="operations",onChange:()=>q("operations"),disabled:M}),e.jsx("span",{children:E("setup.operationsModeOption")})]})]}),!O&&!Ve&&e.jsxs("div",{style:{display:"grid",gap:10,textAlign:"left"},children:[!Oe&&ie&&e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsxs("label",{className:t.authModeLink,style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer"},children:[e.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:kt==="local",onChange:()=>Dt("local"),disabled:M}),e.jsxs("span",{children:["Create new local ",Ot.toLowerCase()]})]}),e.jsxs("label",{className:t.authModeLink,style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer"},children:[e.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:kt==="cloud",onChange:()=>Dt("cloud"),disabled:M}),e.jsxs("span",{children:["Sync existing cloud ",Ot.toLowerCase()]})]})]}),!Oe&&kt==="cloud"&&ie?e.jsxs("div",{style:{display:"grid",gap:8},children:[!Re&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:t.loginSubtitle,style:{margin:0},children:"Sign in to choose one of your cloud projects."}),e.jsx("button",{className:t.cancelBtn,disabled:M,onClick:()=>{x(`/login?mode=login&next=${encodeURIComponent("/setup?step=workspace&source=cloud")}`,{replace:!0})},children:"Sign In"})]}),Re&&e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:t.input,value:tt,onChange:Je=>pt(Je.target.value),disabled:M||Rt||Mt.length===0,children:[Mt.length===0&&e.jsx("option",{value:"",children:Rt?"Loading cloud projects...":"No cloud projects found"}),Mt.map(Je=>e.jsxs("option",{value:Je.id,children:[Je.name," (",Je.id,")"]},Je.id))]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:e.jsx("button",{className:t.cancelBtn,disabled:M||Rt,onClick:()=>{vs()},children:"Refresh Cloud Projects"})}),Ut&&e.jsx("p",{className:t.loginError,children:Ut})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{className:t.input,type:"text",value:et,placeholder:E("setup.workspaceNamePlaceholder",{workspaceLabel:Ot}),onChange:Je=>yt(Je.target.value),disabled:M}),e.jsx("textarea",{className:t.textarea,value:ut,placeholder:E("setup.workspaceDescriptionPlaceholder",{workspaceLabel:Ot}),onChange:Je=>mt(Je.target.value),disabled:M,rows:4}),!Oe&&ie&&Re&&e.jsxs("div",{style:{display:"grid",gap:4},children:[e.jsxs("label",{className:t.authModeLink,style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:Pe,onChange:Je=>_e(Je.target.checked),disabled:M}),e.jsx("span",{children:"Sync to cloud after setup"})]}),e.jsx("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"12px"},children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),e.jsxs("div",{className:t.authModeLinks,children:[Ve?e.jsx("button",{className:t.submitBtn,disabled:M,onClick:async()=>{Q(!0),oe(null),xe(null);try{const Je=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:ae}})}),Yt=await Je.json().catch(()=>({}));!Je.ok||Yt?.success===!1?xe(Yt?.error||E("setup.saveFailedWithStatus",{status:Je.status})):(oe(E("setup.globalSetupSaved")),await ts())}catch{xe(E("setup.saveFailed"))}finally{Q(!1)}},children:E(M?"setup.saving":"setup.saveGlobalSetup")}):O?e.jsx("button",{className:t.submitBtn,disabled:M,onClick:ts,children:E("setup.retrySetupCheck")}):e.jsx("button",{className:t.submitBtn,disabled:M,onClick:async()=>{if(Q(!0),oe(null),xe(null),!Oe&&kt==="cloud"&&ie){if(!Re){xe("Sign in is required before syncing a cloud project."),Q(!1);return}const Je=Mt.find(qs=>qs.id===tt);if(!Je){xe("Select a cloud project to sync."),Q(!1);return}const Yt=await qt({workspaceId:Je.id,name:Je.name||Je.id,description:Je.description||void 0});if(!Yt.success){xe(Yt.error||E("setup.saveWorkspaceFailed")),Q(!1);return}const Ht=String(Yt.workspaceId||Je.id||"").trim();if(!Ht){xe("Failed to resolve workspace id for sync setup."),Q(!1);return}const Ls=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Ht,stateKey:"workspace-sync",patch:{cloudSyncEnabled:!0,sourceOfTruth:"cloud",onboardingCompleted:!1,pullCursor:null,updatedAt:new Date().toISOString()}})}),Us=await Ls.json().catch(()=>({}));if(!Ls.ok||Us?.success===!1){xe(Us?.error||`Failed to configure workspace sync (${Ls.status})`),Q(!1);return}As({cloudSyncEnabled:!0,sourceOfTruth:"cloud",onboardingCompleted:!1,pullCursor:null}),await ts(),oe(`Cloud project synced setup ready: ${Je.name}`)}else{const Je=Ee?.workspaceSetupState==="missing",Yt=await qt({workspaceId:Je?void 0:Ee?.workspaceId,name:et,description:ut});if(!Yt.success)xe(Yt.error||E("setup.saveWorkspaceFailed"));else{const Ht=!!(!Oe&&Pe&&ie&&Re),Ls=String(Yt.workspaceId||Ee?.workspaceId||"").trim();if(!Ls){xe("Failed to resolve workspace id for sync setup."),Q(!1);return}const Us=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Ls,stateKey:"workspace-sync",patch:{cloudSyncEnabled:Ht,sourceOfTruth:Ht?"local":null,onboardingCompleted:!1,pullCursor:null,updatedAt:new Date().toISOString()}})}),qs=await Us.json().catch(()=>({}));if(!Us.ok||qs?.success===!1){xe(qs?.error||`Failed to configure workspace sync (${Us.status})`),Q(!1);return}As({cloudSyncEnabled:Ht,sourceOfTruth:Ht?"local":null,onboardingCompleted:!1,pullCursor:null}),oe(Ht?`${Ot} setup saved. Cloud sync enabled.`:E("setup.workspaceSetupSaved",{workspaceLabel:Ot}))}}Q(!1)},children:M?E("setup.saving"):E("setup.saveWorkspaceSetup",{workspaceLabel:Ot})}),G==="cloud"&&e.jsx("button",{className:t.cancelBtn,onClick:async()=>{await N.logout(),x("/login",{replace:!0})},children:E("setup.signOut")})]})]})})})}return e.jsx(aT,{...N,onHeaderMouseDown:u,isDragging:d,onClose:m})}function oT(a){return sp()?e.jsx(md,{...a}):e.jsx(ap,{children:e.jsx(md,{...a})})}function rT(){const a="".trim(),n="".trim();if(n)return n;if(a)return a}function iT(a){const n="".trim(),r="".trim();if(r)if(typeof window<"u"){const u=window.location.hostname.toLowerCase(),d=u==="localhost"||u==="127.0.0.1"||u==="::1",m="".trim().toLowerCase()==="true";if(!d&&!m)try{const h=new URL(r,window.location.origin);if(h.origin!==window.location.origin)console.warn(`[Taskforce] Ignoring cross-origin cloud auth base in hosted runtime: ${h.origin}`);else return r}catch{}else return r}else return r;if(n)return n;if(a)return a}function cT(){const a=rT(),n=iT(a);return e.jsx(np,{children:e.jsx(oT,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:a,cloudAuthBaseUrl:n}})})}su.createRoot(document.getElementById("root")).render(e.jsx(zs.StrictMode,{children:e.jsx(cT,{})}));