@bitcobblers/wod-wiki-tools 0.43.2153 → 0.44.2155

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 (609) hide show
  1. package/dist/bin/wod.cjs +77 -3
  2. package/dist/bin/wod.cjs.map +1 -1
  3. package/dist/bin/wod.mjs +3 -3
  4. package/dist/{chunk-IEW74LUO.mjs → chunk-BQ6HTRH3.mjs} +77 -6
  5. package/dist/chunk-BQ6HTRH3.mjs.map +1 -0
  6. package/dist/{chunk-CFNE6XRA.mjs → chunk-PLUG6UUI.mjs} +6 -6
  7. package/dist/{chunk-CFNE6XRA.mjs.map → chunk-PLUG6UUI.mjs.map} +1 -1
  8. package/dist/{chunk-JDZB5NGY.mjs → chunk-X47RW7XN.mjs} +3 -3
  9. package/dist/chunk-X47RW7XN.mjs.map +1 -0
  10. package/dist/{compiler-E6HYL477.mjs → compiler-V2BLOB2B.mjs} +3 -3
  11. package/dist/{compiler-E6HYL477.mjs.map → compiler-V2BLOB2B.mjs.map} +1 -1
  12. package/dist/index.cjs +77 -3
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.mjs +3 -3
  15. package/dist/{scaffoldCatalog-MEB5DEPL.mjs → scaffoldCatalog-GZUXAEGJ.mjs} +3 -3
  16. package/dist/{scaffoldCatalog-MEB5DEPL.mjs.map → scaffoldCatalog-GZUXAEGJ.mjs.map} +1 -1
  17. package/dist/web/playground/assets/main-DyocvczK.js +209 -0
  18. package/dist/web/playground/assets/main-ff0QOvsL.css +2 -0
  19. package/dist/web/playground/assets/seedSync.worker-CNP45WoU.js +16 -0
  20. package/dist/web/playground/assets/{statementBuilderFlow-JlPDGxmn.js → statementBuilderFlow-BVI_QsJW.js} +2 -2
  21. package/dist/web/playground/assets/{vendor-BFExl-KH.js → vendor-C_ZAMcXI.js} +62 -62
  22. package/dist/web/{server/assets/vendor-codemirror-BojMZ9SI.js → playground/assets/vendor-codemirror--vyd63e6.js} +2 -2
  23. package/dist/web/playground/index.html +4 -4
  24. package/dist/web/playground/seed/core/apps/playground/app/templates/new-playground.json +39 -0
  25. package/dist/web/playground/seed/core/chunks/canvas.ebabc629.json +1 -0
  26. package/dist/web/playground/seed/core/chunks/efforts.cf4c4fbf.json +1 -0
  27. package/dist/web/playground/seed/core/chunks/equipment.6a969adc.json +1 -0
  28. package/dist/web/playground/seed/core/chunks/{template.0120276c.json → template.148e1868.json} +1 -1
  29. package/dist/web/playground/seed/core/indexes/notebooks/canvas.json +792 -0
  30. package/dist/web/playground/seed/core/indexes/notebooks/efforts.json +1458 -0
  31. package/dist/web/playground/seed/core/indexes/notebooks/equipment.json +216 -0
  32. package/dist/web/playground/seed/core/indexes/notebooks/template.json +18 -0
  33. package/dist/web/playground/seed/core/manifest.json +2501 -15
  34. package/dist/web/playground/seed/core/markdown/canvas/ai-first/README.json +11 -0
  35. package/dist/web/playground/seed/core/markdown/canvas/guide/README.json +62 -0
  36. package/dist/web/playground/seed/core/markdown/canvas/guide/clock.json +11 -0
  37. package/dist/web/playground/seed/core/markdown/canvas/guide/dashboards.json +39 -0
  38. package/dist/web/playground/seed/core/markdown/canvas/guide/metrics.json +195 -0
  39. package/dist/web/playground/seed/core/markdown/canvas/guide/protocols.json +313 -0
  40. package/dist/web/playground/seed/core/markdown/canvas/guide/sessions.json +431 -0
  41. package/dist/web/playground/seed/core/markdown/canvas/guide/start.json +177 -0
  42. package/dist/web/playground/seed/core/markdown/canvas/guide/structure.json +335 -0
  43. package/dist/web/playground/seed/core/markdown/canvas/guide/wql.json +117 -0
  44. package/dist/web/playground/seed/core/markdown/canvas/home/README.json +11 -0
  45. package/dist/web/playground/seed/core/markdown/canvas/home/sample-script.json +62 -0
  46. package/dist/web/playground/seed/core/markdown/canvas/home/welcome-1.json +40 -0
  47. package/dist/web/playground/seed/core/markdown/canvas/syntax/actions-comments.json +62 -0
  48. package/dist/web/playground/seed/core/markdown/canvas/syntax/alternating-emom.json +72 -0
  49. package/dist/web/playground/seed/core/markdown/canvas/syntax/basic-emom.json +62 -0
  50. package/dist/web/playground/seed/core/markdown/canvas/syntax/calculated-metrics.json +62 -0
  51. package/dist/web/playground/seed/core/markdown/canvas/syntax/classic-amrap.json +82 -0
  52. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +62 -0
  53. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-full-session.json +112 -0
  54. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +92 -0
  55. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-partner-workout.json +92 -0
  56. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-swimming.json +51 -0
  57. package/dist/web/playground/seed/core/markdown/canvas/syntax/core-rules.json +61 -0
  58. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +109 -0
  59. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-intervals.json +62 -0
  60. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-1.json +62 -0
  61. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-2.json +72 -0
  62. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-3.json +40 -0
  63. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-4.json +62 -0
  64. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-5.json +62 -0
  65. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +41 -0
  66. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +41 -0
  67. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +41 -0
  68. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-log.json +62 -0
  69. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-plan.json +102 -0
  70. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-wod.json +71 -0
  71. package/dist/web/playground/seed/core/markdown/canvas/syntax/distance-intervals.json +51 -0
  72. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-1.json +61 -0
  73. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-2.json +72 -0
  74. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-3.json +139 -0
  75. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-4.json +62 -0
  76. package/dist/web/playground/seed/core/markdown/canvas/syntax/effort-notes.json +62 -0
  77. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-1.json +71 -0
  78. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-2.json +82 -0
  79. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-3.json +51 -0
  80. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-4.json +51 -0
  81. package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-duration.json +62 -0
  82. package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-intervals.json +62 -0
  83. package/dist/web/playground/seed/core/markdown/canvas/syntax/measurements.json +62 -0
  84. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-1.json +71 -0
  85. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-2.json +92 -0
  86. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-3.json +102 -0
  87. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-4.json +72 -0
  88. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-5.json +72 -0
  89. package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-sections.json +102 -0
  90. package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-timers.json +71 -0
  91. package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +92 -0
  92. package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-sets.json +62 -0
  93. package/dist/web/playground/seed/core/markdown/canvas/syntax/named-groups.json +72 -0
  94. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-1.json +82 -0
  95. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-2.json +62 -0
  96. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-3.json +82 -0
  97. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-4.json +51 -0
  98. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-5.json +62 -0
  99. package/dist/web/playground/seed/core/markdown/canvas/syntax/single-movement.json +51 -0
  100. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-1.json +62 -0
  101. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-2.json +72 -0
  102. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-3.json +62 -0
  103. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-4.json +62 -0
  104. package/dist/web/playground/seed/core/markdown/canvas/syntax/time-cap.json +82 -0
  105. package/dist/web/playground/seed/core/markdown/canvas/syntax/timer-modifiers.json +82 -0
  106. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-1.json +82 -0
  107. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-2.json +62 -0
  108. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-3.json +51 -0
  109. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-4.json +62 -0
  110. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-5.json +71 -0
  111. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-rest.json +61 -0
  112. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +38 -0
  113. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +38 -0
  114. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/content-fran.json +38 -0
  115. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/filter-combos.json +38 -0
  116. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/pipes-limit.json +38 -0
  117. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/session-rpe.json +38 -0
  118. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/source-journal.json +38 -0
  119. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/tis-trend.json +38 -0
  120. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/where-join.json +38 -0
  121. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/air-squat.json +11 -0
  122. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/box-jump.json +11 -0
  123. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/broad-jump.json +11 -0
  124. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +11 -0
  125. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +11 -0
  126. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee.json +11 -0
  127. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +11 -0
  128. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +11 -0
  129. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ground-kong.json +11 -0
  130. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/jumping-jack.json +11 -0
  131. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/kong-walk.json +11 -0
  132. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/lunge.json +11 -0
  133. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/overhead-squat.json +11 -0
  134. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-roll.json +11 -0
  135. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-squat.json +11 -0
  136. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/pistol-squat.json +11 -0
  137. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/plank.json +11 -0
  138. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-burpee.json +11 -0
  139. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-jump.json +11 -0
  140. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +11 -0
  141. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/russian-twist.json +11 -0
  142. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/sit-up.json +11 -0
  143. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-clean.json +11 -0
  144. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-hold.json +11 -0
  145. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-snatch.json +11 -0
  146. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/tuck-jump.json +11 -0
  147. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-ball.json +11 -0
  148. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-burpee.json +11 -0
  149. package/dist/web/playground/seed/core/markdown/efforts/cycling/assault-bike.json +11 -0
  150. package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-moderate.json +11 -0
  151. package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-vigorous.json +11 -0
  152. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +11 -0
  153. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +11 -0
  154. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +11 -0
  155. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/dip.json +11 -0
  156. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/double-under.json +11 -0
  157. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-hold.json +11 -0
  158. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +11 -0
  159. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-walk.json +11 -0
  160. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jump-rope.json +11 -0
  161. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +11 -0
  162. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +11 -0
  163. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +11 -0
  164. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/muscle-up.json +11 -0
  165. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/pull-up.json +11 -0
  166. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/push-up.json +11 -0
  167. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +11 -0
  168. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/rope-climb.json +11 -0
  169. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +11 -0
  170. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +11 -0
  171. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +11 -0
  172. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +11 -0
  173. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +11 -0
  174. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +11 -0
  175. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +11 -0
  176. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +11 -0
  177. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +11 -0
  178. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +11 -0
  179. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +11 -0
  180. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +11 -0
  181. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +11 -0
  182. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +11 -0
  183. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +11 -0
  184. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +11 -0
  185. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +11 -0
  186. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +11 -0
  187. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +11 -0
  188. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +11 -0
  189. package/dist/web/playground/seed/core/markdown/efforts/recovery/rest.json +11 -0
  190. package/dist/web/playground/seed/core/markdown/efforts/recovery/stretching.json +11 -0
  191. package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing-sprint.json +11 -0
  192. package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing.json +11 -0
  193. package/dist/web/playground/seed/core/markdown/efforts/rowing/ski-erg.json +11 -0
  194. package/dist/web/playground/seed/core/markdown/efforts/running/backward-running.json +11 -0
  195. package/dist/web/playground/seed/core/markdown/efforts/running/running-6-mph.json +11 -0
  196. package/dist/web/playground/seed/core/markdown/efforts/running/running-8-mph.json +11 -0
  197. package/dist/web/playground/seed/core/markdown/efforts/running/running-sprint.json +11 -0
  198. package/dist/web/playground/seed/core/markdown/efforts/snatch.json +40 -0
  199. package/dist/web/playground/seed/core/markdown/efforts/strength/back-squat.json +11 -0
  200. package/dist/web/playground/seed/core/markdown/efforts/strength/bench-press.json +11 -0
  201. package/dist/web/playground/seed/core/markdown/efforts/strength/box-step-up.json +11 -0
  202. package/dist/web/playground/seed/core/markdown/efforts/strength/carioca.json +11 -0
  203. package/dist/web/playground/seed/core/markdown/efforts/strength/clean-and-jerk.json +11 -0
  204. package/dist/web/playground/seed/core/markdown/efforts/strength/cluster.json +11 -0
  205. package/dist/web/playground/seed/core/markdown/efforts/strength/dead-hang.json +11 -0
  206. package/dist/web/playground/seed/core/markdown/efforts/strength/deadlift.json +11 -0
  207. package/dist/web/playground/seed/core/markdown/efforts/strength/devils-press.json +11 -0
  208. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +11 -0
  209. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-clean.json +11 -0
  210. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-fly.json +11 -0
  211. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-row.json +11 -0
  212. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-snatch.json +11 -0
  213. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-thruster.json +11 -0
  214. package/dist/web/playground/seed/core/markdown/efforts/strength/elbows-to-knees.json +11 -0
  215. package/dist/web/playground/seed/core/markdown/efforts/strength/farmer-carry.json +11 -0
  216. package/dist/web/playground/seed/core/markdown/efforts/strength/frog-stand.json +11 -0
  217. package/dist/web/playground/seed/core/markdown/efforts/strength/front-squat.json +11 -0
  218. package/dist/web/playground/seed/core/markdown/efforts/strength/good-morning.json +11 -0
  219. package/dist/web/playground/seed/core/markdown/efforts/strength/hanging-leg-raise.json +11 -0
  220. package/dist/web/playground/seed/core/markdown/efforts/strength/hollow-rock.json +11 -0
  221. package/dist/web/playground/seed/core/markdown/efforts/strength/knees-to-elbows.json +11 -0
  222. package/dist/web/playground/seed/core/markdown/efforts/strength/l-sit.json +11 -0
  223. package/dist/web/playground/seed/core/markdown/efforts/strength/man-maker.json +11 -0
  224. package/dist/web/playground/seed/core/markdown/efforts/strength/medicine-ball-clean.json +11 -0
  225. package/dist/web/playground/seed/core/markdown/efforts/strength/overhead-press.json +11 -0
  226. package/dist/web/playground/seed/core/markdown/efforts/strength/parkour-vault.json +11 -0
  227. package/dist/web/playground/seed/core/markdown/efforts/strength/pig-flip.json +11 -0
  228. package/dist/web/playground/seed/core/markdown/efforts/strength/power-clean.json +11 -0
  229. package/dist/web/playground/seed/core/markdown/efforts/strength/power-snatch.json +11 -0
  230. package/dist/web/playground/seed/core/markdown/efforts/strength/push-jerk.json +11 -0
  231. package/dist/web/playground/seed/core/markdown/efforts/strength/push-press.json +11 -0
  232. package/dist/web/playground/seed/core/markdown/efforts/strength/romanian-deadlift.json +11 -0
  233. package/dist/web/playground/seed/core/markdown/efforts/strength/single-leg-deadlift.json +11 -0
  234. package/dist/web/playground/seed/core/markdown/efforts/strength/skull-crusher.json +11 -0
  235. package/dist/web/playground/seed/core/markdown/efforts/strength/slam-ball.json +11 -0
  236. package/dist/web/playground/seed/core/markdown/efforts/strength/sled-pull.json +11 -0
  237. package/dist/web/playground/seed/core/markdown/efforts/strength/sled-push.json +11 -0
  238. package/dist/web/playground/seed/core/markdown/efforts/strength/sumo-deadlift.json +11 -0
  239. package/dist/web/playground/seed/core/markdown/efforts/strength/thruster.json +11 -0
  240. package/dist/web/playground/seed/core/markdown/efforts/strength/triceps-extension.json +11 -0
  241. package/dist/web/playground/seed/core/markdown/efforts/strength/v-sit-hold.json +11 -0
  242. package/dist/web/playground/seed/core/markdown/efforts/strength/wall-walk.json +11 -0
  243. package/dist/web/playground/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +11 -0
  244. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +11 -0
  245. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-backstroke.json +11 -0
  246. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +11 -0
  247. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +11 -0
  248. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-butterfly.json +11 -0
  249. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +11 -0
  250. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +11 -0
  251. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dive-start.json +11 -0
  252. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +11 -0
  253. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-drafting.json +11 -0
  254. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +11 -0
  255. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-freestyle.json +11 -0
  256. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +11 -0
  257. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-kick.json +11 -0
  258. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-pull.json +11 -0
  259. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +11 -0
  260. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +11 -0
  261. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-sighting.json +11 -0
  262. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +11 -0
  263. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +11 -0
  264. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +11 -0
  265. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-vigorous.json +11 -0
  266. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming.json +11 -0
  267. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +11 -0
  268. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-circles.json +11 -0
  269. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-mill.json +11 -0
  270. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +11 -0
  271. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +11 -0
  272. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +11 -0
  273. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +11 -0
  274. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +11 -0
  275. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-flow.json +11 -0
  276. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +11 -0
  277. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +11 -0
  278. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +11 -0
  279. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +11 -0
  280. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +11 -0
  281. package/dist/web/playground/seed/core/markdown/efforts/walking/walking-3-mph.json +11 -0
  282. package/dist/web/playground/seed/core/markdown/equipment/air-bike.json +11 -0
  283. package/dist/web/playground/seed/core/markdown/equipment/barbell.json +11 -0
  284. package/dist/web/playground/seed/core/markdown/equipment/bench.json +11 -0
  285. package/dist/web/playground/seed/core/markdown/equipment/bike-erg.json +11 -0
  286. package/dist/web/playground/seed/core/markdown/equipment/climbing-rope.json +11 -0
  287. package/dist/web/playground/seed/core/markdown/equipment/clubs.json +11 -0
  288. package/dist/web/playground/seed/core/markdown/equipment/dumbbell.json +11 -0
  289. package/dist/web/playground/seed/core/markdown/equipment/ghd.json +11 -0
  290. package/dist/web/playground/seed/core/markdown/equipment/gymnastic-rings.json +11 -0
  291. package/dist/web/playground/seed/core/markdown/equipment/jump-rope.json +11 -0
  292. package/dist/web/playground/seed/core/markdown/equipment/kettlebell.json +11 -0
  293. package/dist/web/playground/seed/core/markdown/equipment/macebell.json +11 -0
  294. package/dist/web/playground/seed/core/markdown/equipment/medicine-ball.json +11 -0
  295. package/dist/web/playground/seed/core/markdown/equipment/parallettes.json +11 -0
  296. package/dist/web/playground/seed/core/markdown/equipment/plyo-box.json +11 -0
  297. package/dist/web/playground/seed/core/markdown/equipment/pull-up-bar.json +11 -0
  298. package/dist/web/playground/seed/core/markdown/equipment/rower.json +11 -0
  299. package/dist/web/playground/seed/core/markdown/equipment/sandbag.json +11 -0
  300. package/dist/web/playground/seed/core/markdown/equipment/ski-erg.json +11 -0
  301. package/dist/web/playground/seed/core/markdown/equipment/slam-ball.json +11 -0
  302. package/dist/web/playground/seed/core/markdown/equipment/sled.json +11 -0
  303. package/dist/web/playground/seed/core/markdown/equipment/sledgehammer.json +11 -0
  304. package/dist/web/playground/seed/core/markdown/equipment/weight-vest.json +11 -0
  305. package/dist/web/playground/seed/core/report.html +14 -14
  306. package/dist/web/server/assets/main-DAOSDjmL.js +209 -0
  307. package/dist/web/server/assets/main-ff0QOvsL.css +2 -0
  308. package/dist/web/server/assets/seedSync.worker-CNP45WoU.js +16 -0
  309. package/dist/web/server/assets/{statementBuilderFlow-CSr1SnnN.js → statementBuilderFlow-BzUkv_67.js} +2 -2
  310. package/dist/web/server/assets/{vendor-BFExl-KH.js → vendor-C_ZAMcXI.js} +62 -62
  311. package/dist/web/{playground/assets/vendor-codemirror-BojMZ9SI.js → server/assets/vendor-codemirror--vyd63e6.js} +2 -2
  312. package/dist/web/server/index.html +4 -4
  313. package/dist/web/server/seed/core/apps/playground/app/templates/new-playground.json +39 -0
  314. package/dist/web/server/seed/core/chunks/canvas.ebabc629.json +1 -0
  315. package/dist/web/server/seed/core/chunks/efforts.cf4c4fbf.json +1 -0
  316. package/dist/web/server/seed/core/chunks/equipment.6a969adc.json +1 -0
  317. package/dist/web/server/seed/core/chunks/{template.0120276c.json → template.148e1868.json} +1 -1
  318. package/dist/web/server/seed/core/indexes/notebooks/canvas.json +792 -0
  319. package/dist/web/server/seed/core/indexes/notebooks/efforts.json +1458 -0
  320. package/dist/web/server/seed/core/indexes/notebooks/equipment.json +216 -0
  321. package/dist/web/server/seed/core/indexes/notebooks/template.json +18 -0
  322. package/dist/web/server/seed/core/manifest.json +2501 -15
  323. package/dist/web/server/seed/core/markdown/canvas/ai-first/README.json +11 -0
  324. package/dist/web/server/seed/core/markdown/canvas/guide/README.json +62 -0
  325. package/dist/web/server/seed/core/markdown/canvas/guide/clock.json +11 -0
  326. package/dist/web/server/seed/core/markdown/canvas/guide/dashboards.json +39 -0
  327. package/dist/web/server/seed/core/markdown/canvas/guide/metrics.json +195 -0
  328. package/dist/web/server/seed/core/markdown/canvas/guide/protocols.json +313 -0
  329. package/dist/web/server/seed/core/markdown/canvas/guide/sessions.json +431 -0
  330. package/dist/web/server/seed/core/markdown/canvas/guide/start.json +177 -0
  331. package/dist/web/server/seed/core/markdown/canvas/guide/structure.json +335 -0
  332. package/dist/web/server/seed/core/markdown/canvas/guide/wql.json +117 -0
  333. package/dist/web/server/seed/core/markdown/canvas/home/README.json +11 -0
  334. package/dist/web/server/seed/core/markdown/canvas/home/sample-script.json +62 -0
  335. package/dist/web/server/seed/core/markdown/canvas/home/welcome-1.json +40 -0
  336. package/dist/web/server/seed/core/markdown/canvas/syntax/actions-comments.json +62 -0
  337. package/dist/web/server/seed/core/markdown/canvas/syntax/alternating-emom.json +72 -0
  338. package/dist/web/server/seed/core/markdown/canvas/syntax/basic-emom.json +62 -0
  339. package/dist/web/server/seed/core/markdown/canvas/syntax/calculated-metrics.json +62 -0
  340. package/dist/web/server/seed/core/markdown/canvas/syntax/classic-amrap.json +82 -0
  341. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +62 -0
  342. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-full-session.json +112 -0
  343. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +92 -0
  344. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-partner-workout.json +92 -0
  345. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-swimming.json +51 -0
  346. package/dist/web/server/seed/core/markdown/canvas/syntax/core-rules.json +61 -0
  347. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +109 -0
  348. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-intervals.json +62 -0
  349. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-1.json +62 -0
  350. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-2.json +72 -0
  351. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-3.json +40 -0
  352. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-4.json +62 -0
  353. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-5.json +62 -0
  354. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +41 -0
  355. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +41 -0
  356. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +41 -0
  357. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-log.json +62 -0
  358. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-plan.json +102 -0
  359. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-wod.json +71 -0
  360. package/dist/web/server/seed/core/markdown/canvas/syntax/distance-intervals.json +51 -0
  361. package/dist/web/server/seed/core/markdown/canvas/syntax/document-1.json +61 -0
  362. package/dist/web/server/seed/core/markdown/canvas/syntax/document-2.json +72 -0
  363. package/dist/web/server/seed/core/markdown/canvas/syntax/document-3.json +139 -0
  364. package/dist/web/server/seed/core/markdown/canvas/syntax/document-4.json +62 -0
  365. package/dist/web/server/seed/core/markdown/canvas/syntax/effort-notes.json +62 -0
  366. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-1.json +71 -0
  367. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-2.json +82 -0
  368. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-3.json +51 -0
  369. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-4.json +51 -0
  370. package/dist/web/server/seed/core/markdown/canvas/syntax/longer-duration.json +62 -0
  371. package/dist/web/server/seed/core/markdown/canvas/syntax/longer-intervals.json +62 -0
  372. package/dist/web/server/seed/core/markdown/canvas/syntax/measurements.json +62 -0
  373. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-1.json +71 -0
  374. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-2.json +92 -0
  375. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-3.json +102 -0
  376. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-4.json +72 -0
  377. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-5.json +72 -0
  378. package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-sections.json +102 -0
  379. package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-timers.json +71 -0
  380. package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +92 -0
  381. package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-sets.json +62 -0
  382. package/dist/web/server/seed/core/markdown/canvas/syntax/named-groups.json +72 -0
  383. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-1.json +82 -0
  384. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-2.json +62 -0
  385. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-3.json +82 -0
  386. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-4.json +51 -0
  387. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-5.json +62 -0
  388. package/dist/web/server/seed/core/markdown/canvas/syntax/single-movement.json +51 -0
  389. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-1.json +62 -0
  390. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-2.json +72 -0
  391. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-3.json +62 -0
  392. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-4.json +62 -0
  393. package/dist/web/server/seed/core/markdown/canvas/syntax/time-cap.json +82 -0
  394. package/dist/web/server/seed/core/markdown/canvas/syntax/timer-modifiers.json +82 -0
  395. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-1.json +82 -0
  396. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-2.json +62 -0
  397. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-3.json +51 -0
  398. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-4.json +62 -0
  399. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-5.json +71 -0
  400. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-rest.json +61 -0
  401. package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +38 -0
  402. package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +38 -0
  403. package/dist/web/server/seed/core/markdown/canvas/wql-presets/content-fran.json +38 -0
  404. package/dist/web/server/seed/core/markdown/canvas/wql-presets/filter-combos.json +38 -0
  405. package/dist/web/server/seed/core/markdown/canvas/wql-presets/pipes-limit.json +38 -0
  406. package/dist/web/server/seed/core/markdown/canvas/wql-presets/session-rpe.json +38 -0
  407. package/dist/web/server/seed/core/markdown/canvas/wql-presets/source-journal.json +38 -0
  408. package/dist/web/server/seed/core/markdown/canvas/wql-presets/tis-trend.json +38 -0
  409. package/dist/web/server/seed/core/markdown/canvas/wql-presets/where-join.json +38 -0
  410. package/dist/web/server/seed/core/markdown/efforts/bodyweight/air-squat.json +11 -0
  411. package/dist/web/server/seed/core/markdown/efforts/bodyweight/box-jump.json +11 -0
  412. package/dist/web/server/seed/core/markdown/efforts/bodyweight/broad-jump.json +11 -0
  413. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +11 -0
  414. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +11 -0
  415. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee.json +11 -0
  416. package/dist/web/server/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +11 -0
  417. package/dist/web/server/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +11 -0
  418. package/dist/web/server/seed/core/markdown/efforts/bodyweight/ground-kong.json +11 -0
  419. package/dist/web/server/seed/core/markdown/efforts/bodyweight/jumping-jack.json +11 -0
  420. package/dist/web/server/seed/core/markdown/efforts/bodyweight/kong-walk.json +11 -0
  421. package/dist/web/server/seed/core/markdown/efforts/bodyweight/lunge.json +11 -0
  422. package/dist/web/server/seed/core/markdown/efforts/bodyweight/overhead-squat.json +11 -0
  423. package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-roll.json +11 -0
  424. package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-squat.json +11 -0
  425. package/dist/web/server/seed/core/markdown/efforts/bodyweight/pistol-squat.json +11 -0
  426. package/dist/web/server/seed/core/markdown/efforts/bodyweight/plank.json +11 -0
  427. package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-burpee.json +11 -0
  428. package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-jump.json +11 -0
  429. package/dist/web/server/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +11 -0
  430. package/dist/web/server/seed/core/markdown/efforts/bodyweight/russian-twist.json +11 -0
  431. package/dist/web/server/seed/core/markdown/efforts/bodyweight/sit-up.json +11 -0
  432. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-clean.json +11 -0
  433. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-hold.json +11 -0
  434. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-snatch.json +11 -0
  435. package/dist/web/server/seed/core/markdown/efforts/bodyweight/tuck-jump.json +11 -0
  436. package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-ball.json +11 -0
  437. package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-burpee.json +11 -0
  438. package/dist/web/server/seed/core/markdown/efforts/cycling/assault-bike.json +11 -0
  439. package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-moderate.json +11 -0
  440. package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-vigorous.json +11 -0
  441. package/dist/web/server/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +11 -0
  442. package/dist/web/server/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +11 -0
  443. package/dist/web/server/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +11 -0
  444. package/dist/web/server/seed/core/markdown/efforts/gymnastics/dip.json +11 -0
  445. package/dist/web/server/seed/core/markdown/efforts/gymnastics/double-under.json +11 -0
  446. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-hold.json +11 -0
  447. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +11 -0
  448. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-walk.json +11 -0
  449. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jump-rope.json +11 -0
  450. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +11 -0
  451. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +11 -0
  452. package/dist/web/server/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +11 -0
  453. package/dist/web/server/seed/core/markdown/efforts/gymnastics/muscle-up.json +11 -0
  454. package/dist/web/server/seed/core/markdown/efforts/gymnastics/pull-up.json +11 -0
  455. package/dist/web/server/seed/core/markdown/efforts/gymnastics/push-up.json +11 -0
  456. package/dist/web/server/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +11 -0
  457. package/dist/web/server/seed/core/markdown/efforts/gymnastics/rope-climb.json +11 -0
  458. package/dist/web/server/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +11 -0
  459. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +11 -0
  460. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +11 -0
  461. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +11 -0
  462. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +11 -0
  463. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +11 -0
  464. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +11 -0
  465. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +11 -0
  466. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +11 -0
  467. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +11 -0
  468. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +11 -0
  469. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +11 -0
  470. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +11 -0
  471. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +11 -0
  472. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +11 -0
  473. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +11 -0
  474. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +11 -0
  475. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +11 -0
  476. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +11 -0
  477. package/dist/web/server/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +11 -0
  478. package/dist/web/server/seed/core/markdown/efforts/recovery/rest.json +11 -0
  479. package/dist/web/server/seed/core/markdown/efforts/recovery/stretching.json +11 -0
  480. package/dist/web/server/seed/core/markdown/efforts/rowing/rowing-sprint.json +11 -0
  481. package/dist/web/server/seed/core/markdown/efforts/rowing/rowing.json +11 -0
  482. package/dist/web/server/seed/core/markdown/efforts/rowing/ski-erg.json +11 -0
  483. package/dist/web/server/seed/core/markdown/efforts/running/backward-running.json +11 -0
  484. package/dist/web/server/seed/core/markdown/efforts/running/running-6-mph.json +11 -0
  485. package/dist/web/server/seed/core/markdown/efforts/running/running-8-mph.json +11 -0
  486. package/dist/web/server/seed/core/markdown/efforts/running/running-sprint.json +11 -0
  487. package/dist/web/server/seed/core/markdown/efforts/snatch.json +40 -0
  488. package/dist/web/server/seed/core/markdown/efforts/strength/back-squat.json +11 -0
  489. package/dist/web/server/seed/core/markdown/efforts/strength/bench-press.json +11 -0
  490. package/dist/web/server/seed/core/markdown/efforts/strength/box-step-up.json +11 -0
  491. package/dist/web/server/seed/core/markdown/efforts/strength/carioca.json +11 -0
  492. package/dist/web/server/seed/core/markdown/efforts/strength/clean-and-jerk.json +11 -0
  493. package/dist/web/server/seed/core/markdown/efforts/strength/cluster.json +11 -0
  494. package/dist/web/server/seed/core/markdown/efforts/strength/dead-hang.json +11 -0
  495. package/dist/web/server/seed/core/markdown/efforts/strength/deadlift.json +11 -0
  496. package/dist/web/server/seed/core/markdown/efforts/strength/devils-press.json +11 -0
  497. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +11 -0
  498. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-clean.json +11 -0
  499. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-fly.json +11 -0
  500. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-row.json +11 -0
  501. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-snatch.json +11 -0
  502. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-thruster.json +11 -0
  503. package/dist/web/server/seed/core/markdown/efforts/strength/elbows-to-knees.json +11 -0
  504. package/dist/web/server/seed/core/markdown/efforts/strength/farmer-carry.json +11 -0
  505. package/dist/web/server/seed/core/markdown/efforts/strength/frog-stand.json +11 -0
  506. package/dist/web/server/seed/core/markdown/efforts/strength/front-squat.json +11 -0
  507. package/dist/web/server/seed/core/markdown/efforts/strength/good-morning.json +11 -0
  508. package/dist/web/server/seed/core/markdown/efforts/strength/hanging-leg-raise.json +11 -0
  509. package/dist/web/server/seed/core/markdown/efforts/strength/hollow-rock.json +11 -0
  510. package/dist/web/server/seed/core/markdown/efforts/strength/knees-to-elbows.json +11 -0
  511. package/dist/web/server/seed/core/markdown/efforts/strength/l-sit.json +11 -0
  512. package/dist/web/server/seed/core/markdown/efforts/strength/man-maker.json +11 -0
  513. package/dist/web/server/seed/core/markdown/efforts/strength/medicine-ball-clean.json +11 -0
  514. package/dist/web/server/seed/core/markdown/efforts/strength/overhead-press.json +11 -0
  515. package/dist/web/server/seed/core/markdown/efforts/strength/parkour-vault.json +11 -0
  516. package/dist/web/server/seed/core/markdown/efforts/strength/pig-flip.json +11 -0
  517. package/dist/web/server/seed/core/markdown/efforts/strength/power-clean.json +11 -0
  518. package/dist/web/server/seed/core/markdown/efforts/strength/power-snatch.json +11 -0
  519. package/dist/web/server/seed/core/markdown/efforts/strength/push-jerk.json +11 -0
  520. package/dist/web/server/seed/core/markdown/efforts/strength/push-press.json +11 -0
  521. package/dist/web/server/seed/core/markdown/efforts/strength/romanian-deadlift.json +11 -0
  522. package/dist/web/server/seed/core/markdown/efforts/strength/single-leg-deadlift.json +11 -0
  523. package/dist/web/server/seed/core/markdown/efforts/strength/skull-crusher.json +11 -0
  524. package/dist/web/server/seed/core/markdown/efforts/strength/slam-ball.json +11 -0
  525. package/dist/web/server/seed/core/markdown/efforts/strength/sled-pull.json +11 -0
  526. package/dist/web/server/seed/core/markdown/efforts/strength/sled-push.json +11 -0
  527. package/dist/web/server/seed/core/markdown/efforts/strength/sumo-deadlift.json +11 -0
  528. package/dist/web/server/seed/core/markdown/efforts/strength/thruster.json +11 -0
  529. package/dist/web/server/seed/core/markdown/efforts/strength/triceps-extension.json +11 -0
  530. package/dist/web/server/seed/core/markdown/efforts/strength/v-sit-hold.json +11 -0
  531. package/dist/web/server/seed/core/markdown/efforts/strength/wall-walk.json +11 -0
  532. package/dist/web/server/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +11 -0
  533. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +11 -0
  534. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-backstroke.json +11 -0
  535. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +11 -0
  536. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +11 -0
  537. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-butterfly.json +11 -0
  538. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +11 -0
  539. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +11 -0
  540. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dive-start.json +11 -0
  541. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +11 -0
  542. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-drafting.json +11 -0
  543. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +11 -0
  544. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-freestyle.json +11 -0
  545. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +11 -0
  546. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-kick.json +11 -0
  547. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-pull.json +11 -0
  548. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +11 -0
  549. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +11 -0
  550. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-sighting.json +11 -0
  551. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +11 -0
  552. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +11 -0
  553. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +11 -0
  554. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-vigorous.json +11 -0
  555. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming.json +11 -0
  556. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +11 -0
  557. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-circles.json +11 -0
  558. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-mill.json +11 -0
  559. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +11 -0
  560. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +11 -0
  561. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +11 -0
  562. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +11 -0
  563. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +11 -0
  564. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-flow.json +11 -0
  565. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +11 -0
  566. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +11 -0
  567. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +11 -0
  568. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +11 -0
  569. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +11 -0
  570. package/dist/web/server/seed/core/markdown/efforts/walking/walking-3-mph.json +11 -0
  571. package/dist/web/server/seed/core/markdown/equipment/air-bike.json +11 -0
  572. package/dist/web/server/seed/core/markdown/equipment/barbell.json +11 -0
  573. package/dist/web/server/seed/core/markdown/equipment/bench.json +11 -0
  574. package/dist/web/server/seed/core/markdown/equipment/bike-erg.json +11 -0
  575. package/dist/web/server/seed/core/markdown/equipment/climbing-rope.json +11 -0
  576. package/dist/web/server/seed/core/markdown/equipment/clubs.json +11 -0
  577. package/dist/web/server/seed/core/markdown/equipment/dumbbell.json +11 -0
  578. package/dist/web/server/seed/core/markdown/equipment/ghd.json +11 -0
  579. package/dist/web/server/seed/core/markdown/equipment/gymnastic-rings.json +11 -0
  580. package/dist/web/server/seed/core/markdown/equipment/jump-rope.json +11 -0
  581. package/dist/web/server/seed/core/markdown/equipment/kettlebell.json +11 -0
  582. package/dist/web/server/seed/core/markdown/equipment/macebell.json +11 -0
  583. package/dist/web/server/seed/core/markdown/equipment/medicine-ball.json +11 -0
  584. package/dist/web/server/seed/core/markdown/equipment/parallettes.json +11 -0
  585. package/dist/web/server/seed/core/markdown/equipment/plyo-box.json +11 -0
  586. package/dist/web/server/seed/core/markdown/equipment/pull-up-bar.json +11 -0
  587. package/dist/web/server/seed/core/markdown/equipment/rower.json +11 -0
  588. package/dist/web/server/seed/core/markdown/equipment/sandbag.json +11 -0
  589. package/dist/web/server/seed/core/markdown/equipment/ski-erg.json +11 -0
  590. package/dist/web/server/seed/core/markdown/equipment/slam-ball.json +11 -0
  591. package/dist/web/server/seed/core/markdown/equipment/sled.json +11 -0
  592. package/dist/web/server/seed/core/markdown/equipment/sledgehammer.json +11 -0
  593. package/dist/web/server/seed/core/markdown/equipment/weight-vest.json +11 -0
  594. package/dist/web/server/seed/core/report.html +14 -14
  595. package/package.json +6 -6
  596. package/dist/chunk-IEW74LUO.mjs.map +0 -1
  597. package/dist/chunk-JDZB5NGY.mjs.map +0 -1
  598. package/dist/web/playground/assets/main-Ci0N8cZU.js +0 -209
  599. package/dist/web/playground/assets/main-ClG3yglx.css +0 -2
  600. package/dist/web/playground/assets/seedSync.worker-Dr-OnZN0.js +0 -16
  601. package/dist/web/playground/seed/core/chunks/canvas.f44b5df1.json +0 -1
  602. package/dist/web/playground/seed/core/chunks/efforts.8a53092f.json +0 -1
  603. package/dist/web/playground/seed/core/chunks/equipment.c45026fc.json +0 -1
  604. package/dist/web/server/assets/main-CWl-p48m.js +0 -209
  605. package/dist/web/server/assets/main-ClG3yglx.css +0 -2
  606. package/dist/web/server/assets/seedSync.worker-Dr-OnZN0.js +0 -16
  607. package/dist/web/server/seed/core/chunks/canvas.f44b5df1.json +0 -1
  608. package/dist/web/server/seed/core/chunks/efforts.8a53092f.json +0 -1
  609. package/dist/web/server/seed/core/chunks/equipment.c45026fc.json +0 -1
@@ -0,0 +1,209 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-C_ZAMcXI.js","assets/rolldown-runtime-C0FnF6B9.js","assets/statementBuilderFlow-BVI_QsJW.js"])))=>i.map(i=>d[i]);
2
+ import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{$ as n,$n as r,$r as i,$t as a,A as o,An as s,Ar as c,B as l,Bn as u,Br as d,Bt as f,C as p,Cn as m,Cr as h,Ct as g,D as _,Dn as v,Dr as y,Dt as b,E as x,En as S,Er as C,Et as w,F as T,Fn as E,Fr as D,Ft as O,G as k,Gn as A,Gr as j,Gt as M,H as N,Hn as P,Hr as F,Ht as I,I as L,In as R,Ir as ee,It as te,J as ne,Jn as re,Jr as ie,Jt as ae,K as oe,Kn as se,Kr as ce,Kt as le,L as z,Ln as ue,Lr as de,Lt as fe,M as B,Mn as pe,Mr as me,N as he,Nn as ge,Nr as _e,O as ve,On as ye,Or as be,P as xe,Pn as Se,Pr as Ce,Pt as we,Q as Te,Qn as Ee,Qr as De,Qt as Oe,R as ke,Rn as Ae,Rr as je,Rt as Me,S as Ne,Sn as Pe,Sr as Fe,St as Ie,T as Le,Tn as Re,Tr as ze,U as Be,Un as Ve,Ur as He,Ut as Ue,V as We,Vn as Ge,Vr as Ke,Vt as qe,W as Je,Wn as Ye,Wr as Xe,Wt as Ze,X as Qe,Xn as $e,Xr as et,Xt as tt,Y as nt,Yn as rt,Yr as it,Yt as at,Z as ot,Zn as st,Zr as ct,Zt as lt,_ as ut,_n as dt,_r as ft,_t as pt,a as mt,ai as ht,an as gt,ar as _t,at as vt,b as yt,bn as bt,br as xt,bt as St,c as Ct,ci as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,di as kt,dn as At,dr as jt,dt as Mt,ei as Nt,en as Pt,er as Ft,et as It,f as Lt,fn as Rt,fr as zt,ft as Bt,g as Vt,gn as Ht,gr as Ut,gt as Wt,h as Gt,hn as Kt,hr as qt,ht as Jt,i as Yt,ii as Xt,in as Zt,ir as Qt,it as $t,j as en,jn as tn,jr as nn,k as rn,kn as an,kr as on,l as sn,li as cn,ln,lr as un,lt as dn,m as fn,mn as pn,mr as mn,mt as hn,n as gn,ni as V,nn as _n,nr as vn,nt as yn,o as bn,oi as xn,on as Sn,or as Cn,ot as wn,p as Tn,pn as En,pr as Dn,pt as On,q as kn,qn as An,qr as jn,qt as Mn,r as Nn,ri as Pn,rn as Fn,rr as In,rt as Ln,s as Rn,si as zn,sn as Bn,sr as Vn,st as Hn,t as Un,ti as Wn,tn as Gn,tr as Kn,tt as qn,u as Jn,ui as Yn,un as Xn,ur as Zn,ut as Qn,v as $n,vn as er,vr as tr,vt as nr,w as rr,wn as ir,wr as ar,wt as or,x as sr,xn as cr,xr as lr,xt as ur,y as dr,yn as fr,yr as pr,yt as mr,z as hr,zn as gr,zr as _r,zt as vr}from"./vendor-C_ZAMcXI.js";import{$ as yr,A as br,B as H,C as xr,D as Sr,E as Cr,F as wr,G as Tr,H as Er,I as Dr,J as Or,K as kr,L as Ar,M as jr,N as Mr,O as Nr,P as Pr,Q as Fr,R as Ir,S as Lr,T as Rr,U as zr,V as Br,W as Vr,X as Hr,Y as Ur,Z as Wr,_ as Gr,a as Kr,at as qr,b as Jr,c as Yr,ct as Xr,d as Zr,et as Qr,f as $r,g as ei,h as ti,i as ni,it as ri,j as ii,k as ai,l as oi,lt as si,m as ci,n as li,nt as ui,o as di,ot as fi,p as pi,q as mi,r as hi,rt as gi,s as _i,st as vi,t as yi,tt as bi,u as xi,ut as Si,v as Ci,w as wi,x as Ti,y as Ei,z as Di}from"./vendor-codemirror--vyd63e6.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Oi=cn(),U=e(kt(),1),W=ct(),ki=(0,U.createContext)({theme:`system`,setTheme:()=>null});function Ai({children:e,defaultTheme:t=`system`,storageKey:n=`vite-ui-theme`}){let[r,i]=(0,U.useState)(()=>localStorage.getItem(n)||t);(0,U.useEffect)(()=>{let e=window.document.documentElement,t=()=>{if(e.classList.remove(`light`,`dark`),r===`system`){let t=window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`;e.classList.add(t);return}e.classList.add(r)};if(t(),r===`system`){let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>t();return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)}},[r]);let a=(0,U.useCallback)(e=>{localStorage.setItem(n,e),i(e)},[n]),o=(0,U.useMemo)(()=>({theme:r,setTheme:a}),[r,a]);return(0,W.jsx)(ki.Provider,{value:o,children:e})}var ji=()=>{let e=(0,U.useContext)(ki);if(e===void 0)throw Error(`useTheme must be used within a ThemeProvider`);return e};function G(...e){return C(et(e))}function Mi(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t&=t}return Math.abs(t)}var Ni=y(`inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-input bg-background hover:bg-accent hover:text-accent-foreground`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-10 px-4 py-2`,sm:`h-9 rounded-md px-3`,lg:`h-11 rounded-md px-8`,icon:`h-10 w-10`}},defaultVariants:{variant:`default`,size:`default`}}),K=U.memo(U.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...i},a)=>{let o=r?be:`button`;return(0,W.jsx)(it,{as:o,className:G(Ni({variant:t,size:n,className:e})),ref:a,...i})}));K.displayName=`Button`;var Pi=[`parser`,`dialect`,`user-plan`,`runtime`,`user-entry`],Fi={parser:`parser`,compiler:`dialect`,dialect:`dialect`,hinted:`dialect`,"user-plan":`user-plan`,runtime:`runtime`,tracked:`runtime`,analyzed:`runtime`,"analyzed-estimated":`runtime`,execution:`runtime`,user:`user-entry`,collected:`user-entry`};function Ii(e){return Fi[e??`parser`]??`parser`}var q=function(e){return e.Duration=`duration`,e.Spans=`spans`,e.SystemTime=`system-time`,e.Time=`time`,e.Elapsed=`elapsed`,e.Total=`total`,e.Rep=`rep`,e.Effort=`effort`,e.Equipment=`equipment`,e.Distance=`distance`,e.Rounds=`rounds`,e.CurrentRound=`current-round`,e.Action=`action`,e.Increment=`increment`,e.Group=`group`,e.Text=`text`,e.Resistance=`resistance`,e.Sound=`sound`,e.System=`system`,e.Label=`label`,e.Lap=`lap`,e.Metric=`metric`,e.Hint=`hint`,e.Custom=`custom`,e.Volume=`volume`,e.Intensity=`intensity`,e.Grade=`grade`,e.Load=`load`,e.Work=`work`,e.RIR=`rir`,e.SessionRPE=`session-rpe`,e.SessionLoad=`session-load`,e.METScore=`met-score`,e.TIS=`tis`,e.Calculated=`calculated`,e.Choice=`choice`,e}({}),Li={parser:0,dialect:1,"user-plan":2,runtime:3,"user-entry":4};function Ri(e){return e.ownershipLayer??Ii(e.origin)}function zi(e){return Li[Ri(e)]??0}function Bi(e){return e.map((e,t)=>{let n=Ri(e);return{metric:e,type:e.type,layer:n,layerRank:Li[n]??0,index:t,isSuppressor:e.action===`suppress`}})}function Vi(e,t){return t?e.filter(e=>!(t.types&&!t.types.includes(e.type)||t.layers&&!t.layers.includes(e.layer))):[...e]}function Hi(e){let t=new Map;for(let n of e){let e=t.get(n.type);if(e){e.push(n);continue}t.set(n.type,[n])}return t}function Ui(e){let t;for(let n of e)n.isSuppressor||(t==null||n.layerRank>t)&&(t=n.layerRank);return t}function Wi(e,t){return{metric:e.metric,type:e.type,layer:e.layer,outcome:t}}function Gi(e,t){return e.index-t.index}function Ki(e){let t=Bi(e);return{raw(e){return Vi(t,e).map(e=>e.metric)},visible(e){let n=Hi(Vi(t,e)),r=[];for(let e of n.values()){if(e.some(e=>e.isSuppressor))continue;let t=Ui(e);if(t!=null)for(let n of e)!n.isSuppressor&&n.layerRank===t&&r.push(n)}return r.sort(Gi),r.map(e=>e.metric)},byLayer(e){let n=Vi(t,e),r={};for(let e of Pi)r[e]=[];for(let e of n)r[e.layer].push(e.metric);for(let e of Pi)r[e]?.length===0&&delete r[e];return r},promotionCandidates(e){let n=Hi(Vi(t,e)),r=[];for(let e of n.values()){let t=e.filter(e=>e.isSuppressor),n=e.filter(e=>!e.isSuppressor);if(n.length===0)continue;if(t.length>0){let e=Math.max(...n.map(e=>e.layerRank)),i=Math.max(...t.map(e=>e.layerRank));for(let t of n)t.layerRank===e&&r.push({metric:t.metric,type:t.type,layer:t.layer,reason:`suppressed`,blockedByLayer:Pi[i]});continue}let i=Ui(n);if(i==null)continue;let a=n.filter(e=>e.layerRank<i);if(a.length===0)continue;let o=Math.max(...a.map(e=>e.layerRank));for(let e of a)e.layerRank===o&&r.push({metric:e.metric,type:e.type,layer:e.layer,reason:`shadowed-by-higher-layer`,blockedByLayer:Pi[i]})}return r.sort((e,t)=>{let n=(Li[t.layer]??0)-(Li[e.layer]??0);return n===0?0:n}),r},explain(e){let n=Hi(Vi(t,e)),r=[];for(let[e,t]of n.entries()){let n=t.some(e=>e.isSuppressor),i=n?void 0:Ui(t),a=t.map(e=>e.isSuppressor?Wi(e,`suppressor`):n?Wi(e,`hidden-by-suppressor`):i!=null&&e.layerRank===i?Wi(e,`visible`):Wi(e,`hidden-by-layer`));r.push({type:e,winnerLayer:i==null?void 0:Pi[i],suppressed:n,entries:a})}return r}}}function qi(e,t){let n=[...e];return(t?.types?.includes(q.Hint)??!1)||(n=n.filter(e=>e.type!==q.Hint)),t?(t.origins&&(n=n.filter(e=>t.origins.includes(e.origin??`parser`))),t.types&&(n=n.filter(e=>t.types.includes(e.type))),t.excludeTypes&&(n=n.filter(e=>!t.excludeTypes.includes(e.type))),n):n}var Ji=class{resolve(e,t){return Ki(qi(e,t)).visible()}resolveOne(e,t){return this.resolve(e,{types:[t]})[0]}resolveAll(e,t){let n=e.filter(e=>e.type===t);return n.length<=1?n:[...n].sort((e,t)=>zi(t)-zi(e))}};function Yi(e){let t=e.split(/[\s_\-\u2010-\u2015]+/).filter(Boolean),n=[];for(let e of t){let t=e.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu,`$1\0$2`).replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu,`$1\0$2`);for(let e of t.split(`\0`))e&&n.push(e)}return n}function Xi(e){let t=Yi(e);return t.length===0?``:t.map((e,t)=>{let n=e.toLowerCase();return t===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join(``)}function Zi(e){return e.split(`.`).map(Xi).filter(e=>e.length>0).join(`.`)}function Qi(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(Array.isArray(e))return`array`;switch(typeof e){case`number`:return`number`;case`string`:return`string`;case`boolean`:return`boolean`;case`object`:return`object`;default:return`undefined`}}function $i(e){return JSON.stringify([e.path,e.kind,e.dimension??null])}var ea=class extends Error{code;constructor(e,t){super(t),this.name=`UnitConversionError`,this.code=e}},ta=[{canonical:`m`,dimension:`distance`,factor:1,aliases:[`meter`,`meters`,`metre`,`metres`]},{canonical:`km`,dimension:`distance`,factor:1e3,aliases:[`kilometer`,`kilometers`,`kilometre`,`kilometres`]},{canonical:`cm`,dimension:`distance`,factor:.01,aliases:[`centimeter`,`centimeters`]},{canonical:`mm`,dimension:`distance`,factor:.001,aliases:[`millimeter`,`millimeters`]},{canonical:`ft`,dimension:`distance`,factor:.3048,aliases:[`foot`,`feet`]},{canonical:`in`,dimension:`distance`,factor:.0254,aliases:[`inch`,`inches`]},{canonical:`yd`,dimension:`distance`,factor:.9144,aliases:[`yard`,`yards`]},{canonical:`mi`,dimension:`distance`,factor:1609.344,aliases:[`mile`,`miles`]},{canonical:`kg`,dimension:`mass`,factor:1,aliases:[`kilogram`,`kilograms`,`kilo`,`kilos`]},{canonical:`g`,dimension:`mass`,factor:.001,aliases:[`gram`,`grams`]},{canonical:`lb`,dimension:`mass`,factor:.45359237,aliases:[`lbs`,`pound`,`pounds`]},{canonical:`ms`,dimension:`duration`,factor:.001,aliases:[`millisecond`,`milliseconds`]},{canonical:`s`,dimension:`duration`,factor:1,aliases:[`sec`,`secs`,`second`,`seconds`]},{canonical:`min`,dimension:`duration`,factor:60,aliases:[`mins`,`minute`,`minutes`]},{canonical:`h`,dimension:`duration`,factor:3600,aliases:[`hr`,`hrs`,`hour`,`hours`]},{canonical:`count`,dimension:`count`,factor:1},{canonical:`rep`,dimension:`count`,factor:1,aliases:[`reps`]},{canonical:`pull-up`,dimension:`count`,factor:1},{canonical:`thruster`,dimension:`count`,factor:1},{canonical:`problem`,dimension:`count`,factor:1},{canonical:`count/s`,dimension:`count-rate`,factor:1},{canonical:`bpm`,dimension:`count-rate`,factor:1/60},{canonical:`cal`,dimension:`energy`,factor:1,aliases:[`calorie`,`calories`]},{canonical:`kcal`,dimension:`energy`,factor:1e3,aliases:[`kilocalorie`,`kilocalories`]},{canonical:`m/s`,dimension:`speed`,factor:1},{canonical:`km/h`,dimension:`speed`,factor:1e3/3600,aliases:[`kmh`,`kph`]},{canonical:`mph`,dimension:`speed`,factor:1609.344/3600},{canonical:`min/km`,dimension:`pace`,factor:1},{canonical:`min/mi`,dimension:`pace`,factor:1e3/1609.344},{canonical:`s/m`,dimension:`pace`,factor:1/60},{canonical:`ratio`,dimension:`ratio`,factor:1,aliases:[`x`]},{canonical:`%`,dimension:`ratio`,factor:.01,aliases:[`pct`,`percent`]},{canonical:`au`,dimension:`ratio`,factor:1,aliases:[`AU`]},{canonical:`pts`,dimension:`ratio`,factor:1,aliases:[`point`,`points`]},{canonical:`rating`,dimension:`ratio`,factor:1,aliases:[`ratings`]}],na=(()=>{let e=new Map;for(let t of ta){e.set(t.canonical.toLowerCase(),t);for(let n of t.aliases??[])e.has(n.toLowerCase())||e.set(n.toLowerCase(),t)}return e})();function ra(e){if(typeof e==`string`)return na.get(e.trim().toLowerCase())}function ia(e){return ra(e)?.dimension}var aa=Object.freeze({mass:`kg`,distance:`m`,duration:`s`,count:`count`,"count-rate":`count/s`,energy:`cal`,speed:`m/s`,pace:`min/km`,ratio:void 0});function oa(e){return aa[e]}function sa(e,t,n){let r=ra(t);if(!r)throw new ea(`unknown-unit`,`Unknown unit "${t}"`);let i=ra(n);if(!i)throw new ea(`unknown-unit`,`Unknown unit "${n}"`);if(r.dimension!==i.dimension)throw new ea(`dimension-mismatch`,`Cannot convert ${t} (${r.dimension}) to ${n} (${i.dimension})`);if(r.dimension===`ratio`&&r.canonical!==i.canonical&&r.canonical!==`ratio`&&i.canonical!==`ratio`)throw new ea(`scale-mismatch`,`Named scales ${t} and ${n} are not interchangeable`);if(!Number.isFinite(e))throw new ea(`non-finite`,`Non-finite value cannot be converted`);return e*r.factor/i.factor}var ca=`references`,la=[`explicit`,`split`,`whole`,`default`,`none`];function ua(e){if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`effort`||t.kind===`equipment`)&&typeof t.slug==`string`&&!!t.slug&&typeof t.label==`string`}function da(e){return!e||typeof e!=`object`?!1:typeof e.reason==`string`}function fa(e){let t=e?.[ca];if(!t||typeof t!=`object`)return;let n=t;if(!(typeof n.matched!=`string`||!la.includes(n.matched))&&typeof n.source==`string`&&!(n.refs!==void 0&&(!Array.isArray(n.refs)||!n.refs.every(ua)))&&!(n.diagnostics!==void 0&&(!Array.isArray(n.diagnostics)||!n.diagnostics.every(da))))return t}var pa=class{line;startOffset;endOffset;length;columnStart;columnEnd;raw;constructor(e,t,n,r,i=0,a=0,o=``){this.line=e,this.startOffset=t,this.endOffset=n,this.length=r,this.columnStart=i,this.columnEnd=a,this.raw=o}},J=class e{_metrics;_indexedLength=0;_resolver=new Ji;id;constructor(t,n=`metrics`){if(this.id=n,t instanceof e){this._metrics=t.toArray(),this.syncIndexProperties();return}this._metrics=Array.isArray(t)?[...t]:[],this.syncIndexProperties()}static from(t,n=`metrics`){if(t instanceof e)return t.clone(n);if(Array.isArray(t))return new e(t,n);if(typeof t==`object`&&t&&`_metrics`in t){let r=t._metrics;if(Array.isArray(r))return new e(r,n)}return e.empty(n)}static empty(t=`metrics`){return new e(void 0,t)}clone(t=this.id){return new e(this._metrics,t)}get all(){return[...this._metrics]}get length(){return this._metrics.length}get size(){return this._metrics.length}get isEmpty(){return this._metrics.length===0}getByType(e){let t=this._metrics.filter(t=>t.type===e||t.name===e);return t.length<=1?t:[...t].sort((e,t)=>zi(t)-zi(e))}getFirst(e){let t=this.getByType(e);return t.length>0?t[0]:void 0}get(e){return this.getFirst(e)}has(e){return this._metrics.some(t=>t.type===e||t.name===e)}hasMetric(e){return this.has(e)}getDisplayMetrics(e){return this.resolve(e)}getMetric(e){return this._resolver.resolveOne(this._metrics,e)}getAllMetricsByType(e){return this.getByType(e)}get rawMetrics(){return this.toArray()}getAll(){return this.toArray()}getByOrigin(e){return this._metrics.filter(t=>(t.origin??`parser`)===e)}resolve(e){return this._resolver.resolve(this._metrics,e)}add(...e){return this._metrics.push(...e),this.syncIndexProperties(),this}remove(e){let t=[];return this._metrics=this._metrics.filter(n=>!e(n)||(t.push(n),!1)),this.syncIndexProperties(),t}removeByType(e){return this.remove(t=>t.type===e||t.name===e)}clear(){return this._metrics=[],this.syncIndexProperties(),this}replaceByType(e,...t){let n=this.removeByType(e);return this._metrics.push(...t),this.syncIndexProperties(),n}merge(t){let n=t instanceof e?t._metrics:Array.isArray(t)?t:t.metrics.toArray(),r=new Map;for(let e of n){let t=r.get(e.type)??[];t.push(e),r.set(e.type,t)}for(let[e,t]of r){let n=this._metrics.filter(t=>t.type===e);if(n.length===0){this._metrics.push(...t);continue}let r=Math.max(...n.map(e=>zi(e))),i=Math.max(...t.map(e=>zi(e)));i>r?(this._metrics=this._metrics.filter(t=>t.type!==e),this._metrics.push(...t)):i===r&&this._metrics.push(...t)}return this.syncIndexProperties(),this}[Symbol.iterator](){return this._metrics[Symbol.iterator]()}filter(e){return this._metrics.filter(e)}map(e){return this._metrics.map(e)}flatMap(e){return this._metrics.flatMap(e)}find(e){return this._metrics.find(e)}some(e){return this._metrics.some(e)}every(e){return this._metrics.every(e)}toArray(){return[...this._metrics]}get raw(){return this._metrics}syncIndexProperties(){for(let e=0;e<this._indexedLength;e++)delete this[e];for(let e=0;e<this._metrics.length;e++)this[e]=this._metrics[e];this._indexedLength=this._metrics.length}toString(){return`MetricContainer(${this._metrics.length})[${this._metrics.map(e=>e.type).join(`, `)}]`}},ma=class{exerciseId;line;text;raw;dialect;hasMetric(e){return this.metricContainer.hasMetric(e)}getDisplayMetrics(e){return this.metricContainer.getDisplayMetrics(e)}getMetric(e){return this.metricContainer.getMetric(e)}getAllMetricsByType(e){return this.metricContainer.getAllMetricsByType(e)}get rawMetrics(){return this.metricContainer.rawMetrics}get metricContainer(){return this.metrics instanceof J?this.metrics:J.from(this.metrics,this.id)}},ha=class extends ma{id=0;parent;children=[];meta=new pa(0,0,0,0);_metrics=J.empty();metricMeta=new Map;isLeaf;get metrics(){return this._metrics}set metrics(e){this._metrics=J.from(e,this.id)}constructor(e){super(),e&&(Object.assign(this,e),e.metrics&&(this.metrics=J.from(e.metrics,this.id)),this.metricMeta||=new Map)}},ga=class e extends ma{static nextId=1e6;id;outputType;timeSpan;sourceStatementId;sourceBlockKey;stackLevel;metrics;metricMeta;completionReason;parent;children;isLeaf;meta;statement;timestamp;constructor(t,n,r){if(super(),t&&`outputType`in t&&`timeSpan`in t){let n=t;this.id=e.nextId++,this.outputType=n.outputType,this.timeSpan=n.timeSpan,this.sourceBlockKey=n.sourceBlockKey??``,this.sourceStatementId=n.sourceStatementId,this.line=n.line,this.text=n.text,this.dialect=n.dialect,this.stackLevel=n.stackLevel??0,this.metrics=J.from(n.metrics,this.id),this.metricMeta=n.metricMeta??new Map,this.completionReason=n.completionReason,this.parent=n.parent,this.children=n.children??[],this.isLeaf=this.children.length===0,this.meta=new pa(0,0,0,0)}else{let i=t;this.id=e.nextId++,this.statement=i,this.outputType=`segment`,this.timeSpan={started:r??Date.now()},this.sourceBlockKey=``,this.sourceStatementId=typeof i?.id==`number`?i.id:void 0,this.stackLevel=0,this.metrics=J.from(n,this.id),this.metricMeta=new Map,this.children=[],this.isLeaf=!0,this.meta=i?.meta??new pa(0,0,0,0),this.line=i?.line,this.text=i?.text,this.dialect=i?.dialect,this.timestamp=r??Date.now()}}static resetIdCounter(t=1e6){e.nextId=t}},_a=class{value;constructor(e){this.value=e??(typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2))}toString(){return this.value}valueOf(){return this.value}equals(e){return this.value===e?.value}};function va(e){let t=new Map;for(let n of e)t.set(n.slug,n);return{resolve:e=>t.get(e),list:()=>[...t.values()]}}var ya=`tagReference`;function ba(e){let t=e?.[ya];if(!t||typeof t!=`object`)return;let n=t;if(!(typeof n.slug!=`string`||!n.slug)&&typeof n.label==`string`&&!(n.functions!==void 0&&!Array.isArray(n.functions))&&(n.soundProfileId===void 0||typeof n.soundProfileId==`string`))return t}function xa(e){let t=e.trim(),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return`bc-${(n>>>0).toString(16).padStart(8,`0`)}`}var Sa=[`segment`,`system`,`load`,`event`,`compiler`,`completion`,`analytics`,`wellness`];function Ca(e){return e===`time`?`run`:e===`log`?`log`:null}function wa(e){let t=e.trim();return t.startsWith(`notebook/`)||t.startsWith(`notebook:`)?t.slice(9):t}function Ta(e){return`notebook/${wa(e)}`}function Ea(e){return e.seedOrigin!==`seed`}var Da=[`playground-run-tip`,`attention`,`code-example`,`syntax-group`];function Oa(e){let t=e.match(/^`{3,}(time|log)(?::([\w-]+))?\s*$/i);return t?{dialect:t[1].toLowerCase()===`time`?`time`:`log`,...t[2]?{sport:t[2]}:{}}:null}function ka(e){let t=e.type?.toLowerCase();if(t===`youtube`||t===`strava`||t===`amazon`||t===`file`||t===`effort`||t===`equipment`)return t;let n=(e.url||e.link||``).replace(/^[a-z][a-z0-9+.-]*:\/\//i,``).split(/[/?#:]/,1)[0].toLowerCase();return n===`youtu.be`||n===`youtube.com`||n.endsWith(`.youtube.com`)?`youtube`:n===`strava.com`||n.endsWith(`.strava.com`)?`strava`:n===`amzn.to`||n===`amazon.com`||n.endsWith(`.amazon.com`)?`amazon`:[`baseAttributes`,`discipline`,`effortType`,`targetRPE`,`equipment`,`aliases`,`derivation`].some(t=>t in e)?`effort`:[`slug`,`label`,`registrySource`,`ownerNoteId`,`sourcePath`].some(t=>t in e)?`equipment`:`default`}function Aa(e){return/^#{1,6}\s/.test(e)?`heading`:/^[-*+]\s|^\d+\.\s/.test(e)?`list`:/^>\s?/.test(e)?`blockquote`:e.startsWith(`|`)&&/^\|[\s:]*-+/m.test(e)?`table`:`paragraph`}function ja(e,t={}){if(!e)return[];let n=e.split(/\r\n|\n|\r/),r=[],i=[],a=0;for(let t of n){r.push(a),a+=t.length;let n=e.startsWith(`\r
3
+ `,a)?`\r
4
+ `:/[\r\n]/.test(e[a]??``)?e[a]:``;i.push(n),a+=n.length}let o=[],s=Date.now(),c=!0,l=0;function u(t,a,o){let c=r[a],l=r[o]+n[o].length;return{id:crypto.randomUUID(),type:t,from:c,to:l,rawContent:e.slice(c,l),displayContent:e.slice(c,l),startLine:a,endLine:o,lineCount:o-a+1,version:1,createdAt:s,separatorAfter:i[o]}}for(;l<n.length;){let a=n[l].trim(),d=a.match(/^(`{3,}|~{3,})(.*)$/);if(d){let a=d[1],c=l+1,f=RegExp(`^${a[0]}{${a.length},}\\s*$`);for(;c<n.length&&!f.test(n[c].trim());)c++;let p=c<n.length,m=p?c:n.length-1,h=d[2].trim(),g=a[0]==="`"?Oa(`\`\`\`${h}`):null,_=a[0]==="`"?h.match(/^widget:([\w-]+)$/):null,v=a[0]==="`"?h.match(/^query(?:[:\s](.*))?$/i):null,y=t.registeredWidgets??Da,b=_&&(`has`in y?y.has(_[1]):y.includes(_[1])),x=p&&g?g.dialect:p&&b?`widget`:p&&v?`query`:`code`,S=u(x,l,m);S.contentFrom=r[l]+n[l].length+i[l].length,S.contentTo=p?r[c]:S.to,S.displayContent=e.slice(S.contentFrom,S.contentTo),g&&p&&(S.sport=g.sport,S.contentId=xa(S.displayContent),S.scriptBlock={id:S.id,contentId:S.contentId,dialect:g.dialect,sport:g.sport,startLine:l,endLine:m,content:S.displayContent,state:`idle`,version:1,createdAt:s}),x===`widget`&&_&&(S.widgetName=_[1]),x===`query`&&v&&(S.querySuffix=(v[1]??``).trim()),o.push(S),l=m+1;continue}if(a===`---`&&n[l+1]?.trim()){let t=l+1;for(;t<n.length&&n[t].trim()!==`---`&&!/^(`{3,}|~{3,})/.test(n[t].trim());)t++;let i=n.slice(l+1,t);if(n[t]?.trim()===`---`&&i.some(e=>/^[A-Za-z_][\w-]*\s*:/.test(e.trim()))){let n=u(`frontmatter`,l,t);n.contentFrom=r[l+1],n.contentTo=r[t],n.displayContent=e.slice(n.contentFrom,n.contentTo),n.properties={};for(let e of i){let t=e.match(/^([^:]+):\s*(.*)$/);t&&(n.properties[t[1].trim()]=t[2].trim())}n.frontmatterType=ka(n.properties),o.push(n),l=t+1;continue}}let f=a.match(/^(!)?\[([^\]]*)\]\((https?:\/\/[^)\s]+|\/[^)\s]+)\)$/);if(f){let e=u(`embed`,l,l),t=!!f[1];e.embed={type:t?`image`:/(?:youtube\.com|youtu\.be)/i.test(f[3])?`youtube`:`link`,label:f[2],url:f[3],isImage:t},o.push(e),l++;continue}let p=l;if(a)for(;p+1<n.length&&n[p+1].trim()&&!/^(?:`{3,}|~{3,}|---\s*$|!?\[[^\]]*\]\()/.test(n[p+1].trim());)p++;let m=u(a&&c?`title`:`markdown`,l,p);m.subtype=Aa(m.displayContent.trim()),a&&(c=!1),o.push(m),l=p+1}return o}function Ma(e){return e.type===`time`||e.type===`log`?`wod`:e.type===`query`||e.type===`widget`||e.type===`embed`?e.type:null}function Na(e,t){if(!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw Error(`Invalid source revision`);let n=Object.create(null),r=Object.values(t.blocks??{}).filter(e=>e&&typeof e==`object`),i=t.createId??(()=>crypto.randomUUID());for(let a of ja(e,t)){let e=Ma(a);if(!e)continue;let o=r.filter(t=>t.from===a.from&&t.to===a.to&&t.kind===e),s=o.length===1?o[0]:void 0,c=s?.id??i();if(!c||Object.hasOwn(n,c))throw Error(`Duplicate block occurrence ID`);n[c]={id:c,kind:e,from:a.from,to:a.to,sourceRevision:t.sourceRevision,version:s?.version??1,...e===`wod`&&(a.type===`time`||a.type===`log`)?{dialect:a.type,...a.sport?{sport:a.sport}:{}}:{}}}return n}function Pa(e,t,n,r={}){if(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))throw Error(`Invalid Note source or blocks`);for(let[e,r]of Object.entries(t))if(!r||r.id!==e||!e||!Number.isSafeInteger(r.version)||r.version<1||r.sourceRevision!==n||!Number.isSafeInteger(r.from)||!Number.isSafeInteger(r.to))throw Error(`Invalid block identity, version or source revision`);let i=Na(e,{...r,sourceRevision:n,blocks:t});if(Object.keys(i).length!==Object.keys(t).length)throw Error(`Incomplete actionable block map`);for(let[e,n]of Object.entries(t)){let t=i[e];if(!t||t.from!==n.from||t.to!==n.to||t.kind!==n.kind||t.dialect!==n.dialect||t.sport!==n.sport)throw Error(`Block does not match authored source`)}}function Fa(e,t){let n=0;for(let e of t){if(!Number.isSafeInteger(e.from)||!Number.isSafeInteger(e.to)||e.from<n||e.to<e.from||typeof e.insert!=`string`)throw Error(`Invalid source changes`);n=e.to}let r={};for(let n of Object.values(e)){let e=n.from,i=n.to,a=!1;for(let r of t){let t=r.insert.length-(r.to-r.from);if(r.from<=n.from&&r.to>=n.to||r.from<n.from&&r.to>n.from||r.from<n.to&&r.to>n.to){a=!0;break}r.to<=n.from?(e+=t,i+=t):r.from<n.to&&(i+=t)}a||(r[n.id]={...n,from:e,to:i})}return r}var Ia=/^[A-Za-z][\w.-]*$/,La=/^---\r?\n([\s\S]*?)\r?\n---/;function Ra(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function za(e){let t=e.trim();return t===``||t.startsWith(`#`)}function Ba(e){return Array.isArray(e)}function Va(e){if(e===``)return`""`;let t=!isNaN(Number(e)),n=/^(true|false|null|yes|no|on|off)$/i.test(e);return/[:"'\n#{}[\],&*?|<>=%!@`]/.test(e)||e!==e.trim()||e.startsWith(`-`)||t||n?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}"`:e}function Ha(e,t,n){let r=` `.repeat(e);return Ba(n)?n.length===0?[`${r}${t}: []`]:[`${r}${t}:`,...n.map(e=>`${r} - ${typeof e==`number`?String(e):Va(e)}`)]:[`${r}${t}: ${typeof n==`number`?String(n):Va(n)}`]}function Ua(e,t,n,r){let i=[],a=r;for(let r=t;r<e.length;r++)r===e.length-1?i.push(...Ha(a,e[r],n)):i.push(`${` `.repeat(a)}${e[r]}:`),a+=2;return i}function Wa(e){let t=!1,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){i===`\\`?r++:i===`"`&&(n=!1);continue}if(t){i===`'`&&(t=!1);continue}if(i===`"`)n=!0;else if(i===`'`)t=!0;else if(i===`#`&&(r===0||/\s/.test(e[r-1])))return r}return-1}function Ga(e,t,n){let r=[t],i=[];for(let a=t+1;a<e.length;a++){let t=e[a];if(za(t)){i.push(a);continue}if(t.length-t.trimStart().length>n)r.push(...i,a),i=[];else break}return r}function Ka(e,t,n,r,i){let a=RegExp(`^ {${n}}${Ra(t)}\\s*:`);for(let t=r;t<i;t++)if(a.test(e[t]))return t;return-1}function qa(e,t,n){if(t.length===0||!t.every(e=>typeof e==`string`&&Ia.test(e)))return e;let r=e.includes(`\r
5
+ `)?`\r
6
+ `:`
7
+ `,i=e.match(La);if(!i){if(n===null)return e;let i=`---${r}${Ua(t,0,n,0).join(r)}${r}---${r}`;return e.length?i+e:i}let a=i[1]===``?[]:i[1].split(/\r?\n/),o=0,s=a.length,c=-1,l=-1,u=[];for(let e=0;e<t.length;e++){let n=e*2,r=Ka(a,t[e],n,o,s);if(r===-1)break;c=e,l=r,u=Ga(a,r,n),o=r+1,s=u[u.length-1]+1}if(n===null){if(c!==t.length-1)return e;let n=new Set(u);for(let e=c-1;e>=0;e--){let r=e*2,i=Ka(a,t[e],r,0,a.length);if(i===-1||n.has(i))break;let o=!1;for(let e=i+1;e<a.length;e++){if(n.has(e))continue;let t=a[e];if(!za(t)){t.length-t.trimStart().length>r&&(o=!0);break}}if(o)break;n.add(i)}let o=a.filter((e,t)=>!n.has(t));return`---${r}${o.length?o.join(r)+r:``}---`+e.slice(i[0].length)}let d,f,p;if(c===t.length-1){if(p=Ha(c*2,t[c],n),!Ba(n)){let e=Wa(a[l]);if(e!==-1){let t=a[l].slice(e).trim();p[0]=`${p[0]} ${t}`}}d=u[0],f=u.length}else d=c===-1?a.length:s,f=0,p=Ua(t,c+1,n,(c+1)*2);let m=[...a];return m.splice(d,f,...p),`---${r}${m.length?m.join(r)+r:``}---`+e.slice(i[0].length)}var Ja=class{items=new Map;constructor(e=[]){for(let t of e)this.items.set(t.id,t)}register(e){this.items.set(e.id,e)}unregister(e){this.items.delete(e)}has(e){return this.items.has(e)}get(e){return this.items.get(e)}list(){return[...this.items.values()].sort((e,t)=>(t.priority??0)-(e.priority??0))}get size(){return this.items.size}},Ya={REPEATING_INTERVAL:`behavior.repeating_interval`,REQUIRED_TIMER:`behavior.required_timer`,INJECT_REST:`behavior.inject_rest`,LABEL_AMRAP:`workout.amrap`,LABEL_EMOM:`workout.emom`,LABEL_TABATA:`workout.tabata`,LABEL_FOR_TIME:`workout.for_time`};Object.values(Ya);function Xa(e){if(!e)return[];if(Array.isArray(e.rawMetrics))return e.rawMetrics;let t=e.metrics;return t?Array.isArray(t)?t:t.rawMetrics??[]:[]}function Za(e,t=`dialect`,n){return{type:q.Hint,value:e,image:e,origin:t,...n?{icon:n}:{}}}function Qa(e,t,n=`dialect`){let r=t??J.empty(`dialect`),i=new Set($a(r));for(let t of e)i.has(t)||(i.add(t),r.add(Za(t,n)));return r}function $a(e){return Xa(e).filter(e=>e.type===q.Hint&&typeof e.value==`string`).map(e=>e.value)}function eo(e,t){return Xa(e).some(e=>e.type===q.Hint&&e.value===t)}var to=/^([a-zA-Z]+)([\s\S]*)$/,no=class e{defs;byToken;constructor(e=[]){this.defs=e,this.byToken=new Map;for(let t of e){this.byToken.set(t.canonical.toLowerCase(),t);for(let e of t.aliases)this.byToken.set(e.toLowerCase(),t)}}get(e){return this.byToken.get(e.trim().toLowerCase())}has(e){return this.byToken.has(e.trim().toLowerCase())}consumeLeading(e){let t=to.exec(e.trimStart());if(!t)return null;let n=t[1],r=this.get(n);return r?{unit:r,token:n,rest:t[2].trim()}:null}extend(...t){return new e([...this.defs,...t])}toArray(){return[...this.defs]}},ro=[{canonical:`m`,dimension:`length`,aliases:[`meter`,`meters`,`metre`,`metres`]},{canonical:`km`,dimension:`length`,aliases:[`kilometer`,`kilometers`,`kilometre`,`kilometres`]},{canonical:`cm`,dimension:`length`,aliases:[`centimeter`,`centimeters`,`centimetre`,`centimetres`]},{canonical:`mm`,dimension:`length`,aliases:[`millimeter`,`millimeters`,`millimetre`,`millimetres`]},{canonical:`ft`,dimension:`length`,aliases:[`foot`,`feet`]},{canonical:`in`,dimension:`length`,aliases:[`inch`,`inches`]},{canonical:`yd`,dimension:`length`,aliases:[`yard`,`yards`]},{canonical:`mi`,dimension:`length`,aliases:[`mile`,`miles`]},{canonical:`kg`,dimension:`mass`,aliases:[`kilo`,`kilos`,`kilogram`,`kilograms`]},{canonical:`g`,dimension:`mass`,aliases:[`gram`,`grams`]},{canonical:`lb`,dimension:`mass`,aliases:[`lbs`,`pound`,`pounds`]},{canonical:`bw`,dimension:`mass`,aliases:[`bodyweight`]},{canonical:`cal`,dimension:`energy`,aliases:[`cals`,`calorie`,`calories`]},{canonical:`kcal`,dimension:`energy`,aliases:[`kcals`,`kilocalorie`,`kilocalories`]}],io={standard(){return new no(ro)},of(e){return new no(e)}},ao=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/60),i=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},oo=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},so=e=>e==null||!Number.isFinite(e)?`--:--`:Math.floor(Math.abs(e)/1e3)>=3600?oo(e):ao(e),co=new Set([q.Duration,q.Time,q.Elapsed,q.Total]);function lo(e){return co.has(e)}function uo(e){if(e.image)return e.image;if(e.value===void 0||e.value===null)return e.type;if(typeof e.value==`object`){let t=e.value;return`text`in t?String(t.text):`current`in t?`Round ${t.current}`:JSON.stringify(e.value)}return String(e.value)}function fo(e,t){if(lo(e.type)&&typeof e.value==`number`)return so(e.value);let n=uo(e);if(e.type===q.Rounds||e.type===`rounds`){let e=n.trim();if(/^\d+$/.test(e))return`${n} ${Number(e)===1?`Round`:`Rounds`}`}return n}function po(e){let t=[];return t.push(`Type: ${e.type}`),e.value!==void 0&&t.push(`Value: ${e.value}`),e.origin&&t.push(`Origin: ${e.origin}`),e.sourceBlockKey&&t.push(`Block: ${e.sourceBlockKey}`),e.timestamp&&t.push(`Time: ${e.timestamp.toISOString()}`),t.join(`
8
+ `)}var mo={duration:`Duration`,rep:`Reps`,effort:`Effort`,distance:`Distance`,rounds:`Rounds`,resistance:`Resistance`,action:`Action`,increment:`Increment`,metric:`Metric`,label:`Label`,text:`Text`,custom:`Custom`,calculated:`Calculated`,"current-round":`Current Round`,volume:`Volume`,intensity:`Intensity`,load:`Load`,work:`Work`,lap:`Lap`,group:`Group`,time:`Time`,elapsed:`Elapsed`,total:`Total`,"system-time":`System Time`,spans:`Spans`,system:`System`,rir:`RIR`,"session-rpe":`Session RPE`,"session-load":`Session Load`,"met-score":`MET Score`,tis:`TIS`,sound:`Sound`};function ho(e){let t=e.replace(/[_-]+/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).trim();return t.length===0?``:t.split(/\s+/).map(e=>e===e.toUpperCase()||/^[A-Z]{2,}$/.test(e)?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(` `)}function go(e){let t=String(e).trim();return mo[t.toLowerCase()]??ho(t)}function _o(e,t){let n=xo(e,t),r=n.metrics.find(e=>e.type===q.Sound&&typeof e.value==`string`);return{slug:t,label:t,...n.functions.length>0?{functions:[...n.functions]}:{},...r?{soundProfileId:r.value}:{}}}function vo(e,t=[]){for(let n of e){let e=ba(n.metadata);e&&(t.some(t=>t.slug===e.slug)||t.push(e))}return t}var yo=`tag.`,bo={metrics:[],functions:[],tags:[]};function xo(e,t){if(!e)return bo;let n=[],r=[],i=[],a=new Set,o=new Set,s=(t,c)=>{if(c>8||o.has(t))return;let l=e.resolve(t);if(l){o.add(t),i.push(t);for(let e of l.contributions)e.kind===`metric`?n.push(e):e.kind===`function`&&(a.has(e.name)||(a.add(e.name),r.push(e.name)));for(let e of l.contributions)e.kind===`tag`&&s(e.slug,c+1)}};return s(t,0),{metrics:n,functions:r,tags:i}}function So(e){if(!e)return[];let t=[],n=new Set,r=(i,a,o)=>{if(o.has(i)){let e=a.indexOf(i);if(e>=0){let r=[...a.slice(e),i],o=Co(r);n.has(o)||(n.add(o),t.push(r))}return}let s=e.resolve(i);if(!s)return;let c=[...a,i],l=new Set(o);l.add(i);for(let e of s.contributions)e.kind===`tag`&&r(e.slug,c,l)};for(let t of e.list())r(t.slug,[],new Set);return t}function Co(e){let t=e.slice(0,-1);if(t.length===0)return``;let n=0;for(let e=1;e<t.length;e++)t[e]<t[n]&&(n=e);return[...t.slice(n),...t.slice(0,n)].join(`>`)}function wo(e){return`${yo}${e}`}function To(e){if(!e.startsWith(`tag.`))return;let t=e.slice(4);return t.length>0?t:void 0}function Eo(e){let t=[];for(let n of e){let e=To(n.type);e!==void 0&&!t.includes(e)&&t.push(e)}return t}function Do(e,t=`parser`){return e.map(e=>({type:e.type,value:e.value,origin:t,image:String(e.value),...e.unit?{unit:e.unit}:{}}))}function Oo(e){return e.type.toLowerCase()===`effort`&&(e.value??e.image??``).trim().toLowerCase()===`rest`}function ko(e,t){return t?`rest`:{time:`time`,duration:`time`,elapsed:`time`,total:`time`,spans:`time`,rep:`rep`,effort:`effort`,distance:`distance`,rounds:`rounds`,increment:`rounds`,"current-round":`rounds`,action:`action`,resistance:`resistance`,text:`muted`,label:`muted`,group:`muted`,lap:`muted`,system:`system`,"system-time":`system`,volume:`rep`,intensity:`effort`,load:`resistance`,work:`effort`,rir:`effort`,"session-rpe":`effort`,"session-load":`resistance`,"met-score":`distance`,tis:`action`,sound:`system`,metric:`effort`,custom:`muted`,calculated:`effort`}[e.type.toLowerCase()]??`unknown`}function Ao(){return{isStructural(e){let t=e.type;if(t===q.Group||t===`group`){let t=e.image??``;return t===`+`||t===`-`}return t===q.Lap||t===`lap`},isHidden(e,t){if(this.isStructural(e))return t!==`debug`;let n=e.type;return!!((n===q.Sound||n===`sound`)&&t!==`debug`||n.startsWith(`tag.`)&&t!==`debug`||t===`review-grid-column`&&(n===q.Elapsed||n===`elapsed`||n===q.Total||n===`total`||n===q.System||n===`system`))},present(e,t){let n=this.isStructural(e),r=this.isHidden(e,t),i=Oo(e),a=(e.type===q.Text||e.type===`text`)&&e.origin===`parser`,o=e.origin===`user`,s;return s=r?`hidden`:a?`comment`:t===`timer-subtitle`||t===`history-label`||t===`label-composer`?`plain-text`:t===`review-grid-column`?`column-heading`:`badge`,{metric:e,label:fo(e,t),tooltip:po(e),renderKind:s,tone:ko(e,i),iconKey:i?`rest`:e.type,visible:!r,structural:n,rest:i,comment:a,userEntered:o,columnLabel:go(e.type)}},presentGroup(e,t){return e.map(e=>this.present(e,t))},columnLabel(e){return go(e)}}}var jo=Ao(),Mo=class{effort;value;image;origin=`parser`;metadata;constructor(e,t){this.effort=e,this.value=t?.resolvedSlug??e,this.image=e,t?.references&&(this.metadata={[ca]:t.references})}type=q.Effort},No=class{unit;value;image;origin;constructor(e,t){this.unit=t,this.value={amount:e,unit:t},this.image=e===void 0?`? ${t}`:`${e} ${t}`,this.origin=e===void 0?`hinted`:`parser`}type=q.Distance},Po=class{unit;value;image;origin;constructor(e,t){this.unit=t,this.value={amount:e,unit:t},this.image=e===void 0?`? ${t}`:`${e} ${t}`,this.origin=e===void 0?`hinted`:`parser`}type=q.Resistance},Fo=class{unit;dimension;value;image;origin;type;constructor(e,t,n){this.unit=t,this.dimension=n,this.value={amount:e,unit:t},this.image=e===void 0?`? ${t}`:`${e} ${t}`,this.origin=e===void 0?`hinted`:`parser`,this.type=n===`energy`?`energy`:q.Custom}};function Io(e,t,n){switch(n){case`length`:return new No(e,t);case`mass`:return new Po(e,t);default:return new Fo(e,t,n)}}var Lo=class{alternatives;type=q.Choice;origin=`parser`;value;image;constructor(e){this.alternatives=e,this.value={alternatives:e},this.image=e.map(e=>e.image??String(e.value??``)).join(` | `)}},Ro=class{unit;value;image;origin;constructor(e,t=`%`){this.unit=t,this.value={amount:e,unit:t},this.image=e===void 0?`?${t}`:`${e}${t}`,this.origin=e===void 0?`hinted`:`parser`}type=q.Intensity};function zo(e){return e.type===q.Rep&&(typeof e.value==`number`||e.value===void 0)}function Bo(e){return e.type===q.Effort&&(typeof e.value==`string`?e.value:e.image)===`/`}function Vo(e){return e.type===q.Effort&&(typeof e.value==`string`?e.value:e.image)===`|`}function Ho(e){return e.type!==q.Effort&&e.type!==q.Text?null:typeof e.value==`string`?e.value:typeof e.image==`string`?e.image:null}function Uo(e){if(e.type!==q.Distance&&e.type!==q.Resistance)return!1;let t=e.value;return!!t&&t.amount!==void 0&&(!t.unit||t.unit===``)}function Wo(e,t,n){if(!e||!t)return e??t;let r=e.startOffset,i=(t.startOffset??0)+n.length,a=(t.startOffset??0)-(e.endOffset??0),o=e.raw===void 0?void 0:e.raw+` `.repeat(Math.max(0,a))+n,s=r===void 0?void 0:i-r;return{line:e.line,startOffset:r,endOffset:i,columnStart:e.columnStart,columnEnd:e.columnStart!==void 0&&s!==void 0?e.columnStart+s:e.columnEnd,length:s,raw:o}}function Go(e,t){if(!e||e.raw===void 0)return e&&{...e,raw:t};let n=e.raw.indexOf(t),r=n>=0?n:0,i=(e.startOffset??0)+r;return{line:e.line,startOffset:i,endOffset:e.endOffset,columnStart:(e.columnStart??0)+r,columnEnd:e.columnEnd,length:t.length,raw:t}}function Ko(e,t){if(!e||!t)return e??t;let n=e.startOffset,r=t.endOffset,i=n!==void 0&&r!==void 0?r-n:void 0;return{line:e.line,startOffset:n,endOffset:r,columnStart:e.columnStart,columnEnd:t.columnEnd,length:i,raw:e.raw}}function qo(e,t){let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=e[r+1];if(!(Bo(i.metric)||Vo(i.metric))){if(a){let t=Ho(i.metric),o=e[r+2]?Ho(e[r+2].metric):null;if(t!==null&&Vo(a.metric)&&o!==null){let t=[i.metric],a=r+1;for(;a+1<e.length&&Vo(e[a].metric)&&Ho(e[a+1].metric)!==null;)t.push(e[a+1].metric),a+=2;n.push({metric:new Lo(t),meta:Ko(i.meta,e[a-1].meta)}),r=a-1;continue}}if(a&&e[r+2]&&e[r+3]){let o=e[r+2],s=e[r+3],c=zo(i.metric)||Uo(i.metric),l=zo(o.metric)||Uo(o.metric);if(c&&Vo(a.metric)&&l){let e=Ho(s.metric),a=e===null?null:t.consumeLeading(e);if(a){let e=zo(i.metric)?i.metric.value:i.metric.value.amount,t=zo(o.metric)?o.metric.value:o.metric.value.amount,c=Io(e,a.token,a.unit.dimension),l=Io(t,a.token,a.unit.dimension);if(c.type===l.type){let e=Wo(i.meta,s.meta,a.token);n.push({metric:new Lo([c,l]),meta:e}),a.rest&&n.push({metric:new Mo(a.rest),meta:Go(s.meta,a.rest)}),r+=3;continue}}}}if(a&&e[r+2]&&e[r+3]){let o=e[r+2],s=e[r+3],c=zo(i.metric)||Uo(i.metric),l=zo(o.metric)||Uo(o.metric);if(c&&Bo(a.metric)&&l){let e=Ho(s.metric),a=e===null?null:t.consumeLeading(e);if(a){let e=zo(i.metric)?i.metric.value:i.metric.value.amount,t=zo(o.metric)?o.metric.value:o.metric.value.amount;if(e!==void 0&&t!==void 0&&t!==0){let o=Io(e/t,a.token,a.unit.dimension),c=Wo(i.meta,s.meta,a.token);n.push({metric:o,meta:c}),a.rest&&n.push({metric:new Mo(a.rest),meta:Go(s.meta,a.rest)}),r+=3;continue}}}}if(a&&zo(i.metric)){let e=Ho(a.metric);if(e!==null&&e.trim()===`%`){n.push({metric:new Ro(i.metric.value),meta:Wo(i.meta,a.meta,`%`)}),r++;continue}}if(a&&(zo(i.metric)||Uo(i.metric))){let e=Ho(a.metric),o=e===null?null:t.consumeLeading(e);if(o){let e=zo(i.metric)?i.metric.value:i.metric.value.amount;n.push({metric:Io(e,o.token,o.unit.dimension),meta:Wo(i.meta,a.meta,o.token)}),o.rest&&n.push({metric:new Mo(o.rest),meta:Go(a.meta,o.rest)}),r++;continue}}n.push(i)}}return n}function Jo(e,t){let n=e.metrics.toArray(),r=qo(n.map(t=>({metric:t,meta:e.metricMeta?.get(t)})),t);if((r.length!==n.length||r.some((e,t)=>e.metric!==n[t]))&&(e.metrics.clear().add(...r.map(e=>e.metric)),e.metricMeta)){let t=new Map(e.metricMeta);for(let e of n)r.some(t=>t.metric===e)||t.delete(e);for(let e of r)e.meta&&t.set(e.metric,e.meta);e.metricMeta=t}}var Yo=class{id=`units`;name=`Units Dialect`;units;constructor(e=io.standard()){this.units=e}transform(e){Jo(e,this.units)}analyze(e){return{}}},Xo=class{id=`crossfit`;name=`CrossFit Dialect`;hasKeyword(e,t){return e.some(e=>(e.type===q.Action||e.type===q.Effort)&&typeof e.value==`string`&&e.value.toUpperCase().includes(t))}hasChildren(e){return e.children&&e.children.length>0}analyze(e){let t=[],n=J.from(e.metrics),r=this.hasKeyword(n,`AMRAP`);r&&(t.push(`behavior.time_bound`),t.push(`workout.amrap`));let i=this.hasKeyword(n,`EMOM`);if(i&&(t.push(`behavior.repeating_interval`),t.push(`workout.emom`)),!i&&!r){let r=n.some(e=>e.type===q.Rounds),i=n.some(e=>e.type===q.Duration),a=this.hasChildren(e);r&&i&&a&&(t.push(`behavior.repeating_interval`),t.push(`workout.emom`),t.push(`workout.implicit_emom`))}return this.hasKeyword(n,`FOR TIME`)&&(t.push(`behavior.time_bound`),t.push(`workout.for_time`)),this.hasKeyword(n,`TABATA`)&&(t.push(`behavior.repeating_interval`),t.push(`workout.tabata`)),{metrics:Qa(t)}}},Zo=class{id=`wod`;name=`WOD Dialect`;hasKeyword(e,t){return e.some(e=>(e.type===q.Action||e.type===q.Effort)&&typeof e.value==`string`&&e.value.toUpperCase().includes(t.toUpperCase()))}analyze(e){let t=[],n=J.from(e.metrics);return this.hasKeyword(n,`STRENGTH`)&&(t.push(`domain.wod`),t.push(`workout.strength`),t.push(`behavior.load_bearing`)),(this.hasKeyword(n,`METCON`)||this.hasKeyword(n,`METABOLIC`))&&(t.push(`domain.wod`),t.push(`workout.metcon`)),(this.hasKeyword(n,`SKILL`)||this.hasKeyword(n,`TECHNIQUE`))&&(t.push(`domain.wod`),t.push(`workout.skills`)),this.hasKeyword(n,`WOD`)&&t.push(`domain.wod`),this.hasKeyword(n,`SUPERSET`)&&(t.push(`domain.wod`),t.push(`workout.superset`)),{metrics:Qa(t)}}},Qo=class{id=`cardio`;name=`Cardio Dialect`;hasKeyword(e,t){return e.some(e=>(e.type===q.Action||e.type===q.Effort)&&typeof e.value==`string`&&e.value.toUpperCase().includes(t.toUpperCase()))}hasDistance(e){return e.some(e=>e.type===q.Distance)}analyze(e){let t=[],n=J.from(e.metrics);return(this.hasKeyword(n,`RUN`)||this.hasKeyword(n,`JOG`)||this.hasKeyword(n,`SPRINT`))&&(t.push(`domain.cardio`),t.push(`workout.run`),t.push(`behavior.aerobic`)),(this.hasKeyword(n,`ROW`)||this.hasKeyword(n,`ROWING`))&&(t.push(`domain.cardio`),t.push(`workout.row`),t.push(`behavior.aerobic`)),(this.hasKeyword(n,`BIKE`)||this.hasKeyword(n,`CYCLE`)||this.hasKeyword(n,`CYCLING`))&&(t.push(`domain.cardio`),t.push(`workout.bike`),t.push(`behavior.aerobic`)),(this.hasKeyword(n,`SWIM`)||this.hasKeyword(n,`SWIMMING`))&&(t.push(`domain.cardio`),t.push(`workout.swim`),t.push(`behavior.aerobic`)),(this.hasKeyword(n,`WALK`)||this.hasKeyword(n,`WALKING`))&&(t.push(`domain.cardio`),t.push(`workout.walk`)),t.length===0&&this.hasDistance(n)&&(t.push(`domain.cardio`),t.push(`behavior.distance_based`)),t.includes(`domain.cardio`)&&this.hasDistance(n)&&(t.push(`behavior.distance_based`),t.push(`behavior.pace_based`)),{metrics:Qa(t)}}},$o=class e{id=`yoga`;name=`Yoga Dialect`;static POSE_KEYWORDS=[`WARRIOR`,`DOWNWARD`,`UPWARD`,`CHILD'S POSE`,`COBRA`,`PIGEON`,`TRIANGLE`,`MOUNTAIN`,`TREE POSE`,`LOTUS`,`CORPSE`,`SAVASANA`,`TADASANA`,`VIRABHADRASANA`,`BALASANA`,`ADHO`,`URDHVA`,`UTTANASANA`,`VRKSASANA`];static FLOW_KEYWORDS=[`SUN SALUTATION`,`VINYASA`,`FLOW`,`SEQUENCE`];static BREATHING_KEYWORDS=[`PRANAYAMA`,`BREATH`,`BREATHING`,`NADI SHODHANA`,`KAPALABHATI`,`UJJAYI`,`BOX BREATH`,`WIM HOF`];static MEDITATION_KEYWORDS=[`MEDITATION`,`MEDITATE`,`MINDFULNESS`,`BODY SCAN`,`VISUALIZATION`];hasAnyKeyword(e,t){return e.some(e=>(e.type===q.Action||e.type===q.Effort||e.type===q.Text)&&typeof e.value==`string`&&t.some(t=>e.value.toString().toUpperCase().includes(t)))}analyze(t){let n=[],r=J.from(t.metrics),i=r.some(e=>e.type===q.Duration);return this.hasAnyKeyword(r,e.POSE_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.pose`),i&&n.push(`behavior.hold`)),this.hasAnyKeyword(r,e.FLOW_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.flow`)),this.hasAnyKeyword(r,e.BREATHING_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.breathing`),n.push(`behavior.mindful`)),this.hasAnyKeyword(r,e.MEDITATION_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.meditation`),n.push(`behavior.mindful`)),{metrics:Qa(n)}}},es=class e{id=`habits`;name=`Habits Dialect`;static HABIT_KEYWORDS=[`DAILY`,`HABIT`,`STREAK`,`CHECK`,`LOG`,`MORNING`,`EVENING`,`ROUTINE`];static STREAK_KEYWORDS=[`STREAK`,`CONSECUTIVE`,`IN A ROW`];hasAnyKeyword(e,t){return e.some(e=>(e.type===q.Action||e.type===q.Effort||e.type===q.Text||e.type===q.Label)&&typeof e.value==`string`&&t.some(t=>e.value.toString().toUpperCase().includes(t)))}analyze(t){let n=[],r=J.from(t.metrics),i=r.some(e=>e.type===q.Duration),a=r.some(e=>e.type===q.Rep);return this.hasAnyKeyword(r,e.HABIT_KEYWORDS)&&(n.push(`domain.habits`),n.push(`behavior.completable`),i?n.push(`workout.habit_timed`):a?n.push(`workout.habit_rep`):(n.push(`workout.habit_check`),n.push(`behavior.daily`))),this.hasAnyKeyword(r,e.STREAK_KEYWORDS)&&(n.includes(`domain.habits`)||n.push(`domain.habits`),n.push(`behavior.streak`),n.push(`behavior.recurring`)),{metrics:Qa(n)}}},ts={Discipline:`climb-discipline`,Grade:`climb-grade`,SendType:`climb-send-type`,AttemptCount:`climb-attempt-count`,RouteName:`climb-route-name`,HighPoint:`climb-high-point`},ns={onsight:`onsight`,os:`onsight`,flash:`flash`,fl:`flash`,redpoint:`redpoint`,rp:`redpoint`,sent:`redpoint`,send:`redpoint`,repeat:`repeat`,"re-send":`repeat`,resend:`repeat`,dogged:`dogged`,hangdog:`dogged`,a0:`dogged`,tr:`top-rope`,toprope:`top-rope`,"top-rope":`top-rope`,dnf:`did-not-finish`,attempted:`did-not-finish`},rs={boulder:`bouldering`,bouldering:`bouldering`,sport:`sport`,trad:`trad`,"top rope":`top-rope`,toprope:`top-rope`,hangboard:`hangboard`,moonboard:`training-board`,kilter:`training-board`,board:`training-board`};function is(e){return e?typeof e.value==`string`?e.value:e.value&&typeof e.value==`object`&&`text`in e.value?String(e.value.text??``):typeof e.value==`number`?String(e.value):``:``}function as(e){return e.toLowerCase().replace(/[_\s]+/g,`-`).trim()}function os(e,t,n,r){e.add({type:t,value:n,origin:`dialect`,unit:r})}function ss(e,t){e.includes(t)||e.push(t)}var cs=class{id=`climb`;name=`Climb Dialect`;analyze(e){let t=[],n=J.empty(`climb-dialect`),r=J.from(e.metrics).toArray(),i=r.map(is).filter(Boolean).join(` `),a=this.findRouteName(r);a&&os(n,ts.RouteName,a);let o=this.findGrade(r);o&&os(n,ts.Grade,o);let s=this.findSendType(i);s&&os(n,ts.SendType,s);let c=this.findAttemptCount(r);c!==void 0&&os(n,ts.AttemptCount,c);let l=this.findHighPoint(i);l&&os(n,ts.HighPoint,l);let u=this.findDisciplines(i,o);for(let e of u)os(n,ts.Discipline,e);(a||o||s||l||u.length>0)&&(t.push(`domain.climb`),t.push(`behavior.route_based`)),o&&t.push(`behavior.grade_based`),c!==void 0&&t.push(`behavior.attempt_based`),s===`did-not-finish`&&t.push(`climb.project`);for(let e of u)t.push(`climb.${e.replace(`-`,`_`)}`);return{metrics:Qa(t,n)}}findRouteName(e){let t=e.find(e=>e.type===q.Action&&typeof e.value==`string`);return t?.value?String(t.value):void 0}findGrade(e){for(let t=0;t<e.length;t+=1){let n=e[t],r=is(n),i=is(e[t+1]),a=r.match(/\bV(\d{1,2})(?:[-+])?\b/i);if(a){let e=Number(a[1]);return{raw:a[0].toUpperCase(),system:`v-scale`,normalizedRank:e}}if(typeof n.value==`number`&&n.value>=5&&n.value<6){let e=i.match(/^\s*([abcd])\b/i)?.[1],t=e?`${n.value}${e}`:String(n.value);if(/^5\.\d{1,2}[abcd]?$/i.test(t))return{raw:t,system:`yds`,normalizedRank:this.ydsRank(t)}}let o=r.match(/\b5\.(\d{1,2})([abcd])?\b/i);if(o)return{raw:o[0],system:`yds`,normalizedRank:this.ydsRank(o[0])};let s=r.match(/\b([3-9][ABC](?:\+)?)\b/);if(s)return{raw:s[1],system:`font`};if(typeof n.value==`number`&&n.value>=3&&n.value<=9){let e=i.match(/^\s*([ABC]\+?)\b/)?.[1];if(e)return{raw:`${n.value}${e}`,system:`font`}}let c=r.match(/\b([3-9][abc](?:\+)?)\b/);if(c)return{raw:c[1],system:`french`}}}ydsRank(e){let t=e.match(/^5\.(\d{1,2})([abcd])?$/i);if(!t)return;let n=Number(t[1]),r=t[2]?.toLowerCase();return n+(r?[`a`,`b`,`c`,`d`].indexOf(r)/4:0)}findSendType(e){let t=e.toLowerCase().match(/[a-z0-9-]+/g)??[];for(let e of t){let t=as(e);if(t in ns)return ns[t]}if(/\bnot\s+sent\b/i.test(e))return`did-not-finish`;if(/\bwith\s+falls\b/i.test(e))return`dogged`}findAttemptCount(e){return e.find(e=>{if(e.type!==q.Resistance)return!1;let t=e.value;return t&&typeof t.amount==`number`&&String(t.unit??e.unit??``)===``})?.value?.amount}findHighPoint(e){let t=e.match(/\b(?:bolt|move|crux|high\s*point)\s*\d+\b/i)?.[0];return t?t.toLowerCase().replace(/\s+/g,` `):void 0}findDisciplines(e,t){let n=[],r=e.toLowerCase();for(let[e,t]of Object.entries(rs))r.includes(e)&&ss(n,t);return(t?.system===`v-scale`||t?.system===`font`)&&ss(n,`bouldering`),(t?.system===`yds`||t?.system===`french`)&&ss(n,`sport`),n}};function ls(e){console.warn(e)}var us=`units`,ds={climbing:`climb`},fs=new Set,ps=new class{dialects;registry;constructor(e){e instanceof Ja?this.registry=e:this.dialects=e}get effectiveDialects(){return this.registry?this.registry.list():this.dialects??[]}dialectsFor(e){let t=this.effectiveDialects;if(!e)return t;let n=ds[e]??e;return t.some(e=>e.id===n)?t.filter(e=>e.id===us||e.id===n):(fs.has(e)||(fs.add(e),ls(`[DialectStack] Unknown :sport suffix "${e}" — falling back to the full dialect stack. Known dialect ids: ${t.map(e=>e.id).join(`, `)}.`)),t)}process(e,t){this.applyDialects(e,this.dialectsFor(t))}processAll(e,t){let n=this.dialectsFor(t);for(let t of e)this.applyDialects(t,n)}applyDialects(e,t){for(let n of t){n.transform?.(e);let t=n.analyze(e);t?.metrics?.length&&e.metrics.add(...t.metrics)}}get list(){return this.effectiveDialects}}(new Ja([new Yo,new Xo,new Zo,new Qo,new $o,new es,new cs])),ms=class{value;image;raw;name;isPinned;origin=`parser`;constructor(e,t={}){this.raw=t.raw??e,this.isPinned=t.isPinned??this.raw.trim().startsWith(`!`),this.name=t.name??(this.raw.trim().replace(/^!/,``)||e),this.value=this.name,this.image=this.raw}type=q.Action},hs=class{image;forceCountUp;required;value;origin;constructor(e,t=!1,n=!1){if(this.image=e,this.forceCountUp=t,this.required=n,this.image===`:?`)this.days=0,this.hours=0,this.minutes=0,this.seconds=0,this.original=void 0,this.value=void 0,this.origin=`hinted`;else{let e=this.image.split(`:`).map(e=>1*(e===``?0:Number(e))).reverse();for(;e.length<4;)e.push(0);if(this.days=e[3],this.hours=e[2],this.minutes=e[1],this.seconds=e[0],this.seconds<0||this.minutes<0||this.hours<0||this.days<0)throw Error(`Timer components cannot be negative: ${this.image}`);if(this.seconds>59&&(this.minutes>0||this.hours>0||this.days>0))throw Error(`Invalid seconds component: ${this.seconds} (must be < 60 if other components present)`);if(this.minutes>59&&(this.hours>0||this.days>0))throw Error(`Invalid minutes component: ${this.minutes} (must be < 60 if hours/days present)`);this.original=(this.seconds+this.minutes*60+this.hours*60*60+this.days*60*60*24)*1e3,this.value=this.original,this.origin=`parser`}}days;hours;minutes;seconds;original;type=q.Duration;get direction(){return this.forceCountUp||this.value===void 0?`up`:this.value>0?`down`:`up`}},gs=class{type=q.Equipment;origin;value;image;name=`equipment`;metadata;constructor(e,t){this.value=[...new Set(e)],this.image=t?.source??this.value.join(` `),this.origin=t?.origin??`parser`;let n={matched:t?.matched??`whole`,source:t?.source??this.image,...t?.refs?{refs:t.refs}:{},...t?.diagnostics?.length?{diagnostics:t.diagnostics}:{}};this.metadata={[ca]:n}}},_s=class{group;image;value;constructor(e,t){this.group=e,this.image=t,this.value=e}type=q.Group;origin=`parser`};function vs(e){return e===null?`null`:String(e)}var ys=class{key;value;image;origin;constructor(e,t,n={}){this.key=e,this.value=t,this.image=n.image??`${e}: ${vs(t)}`,this.origin=n.origin??`parser`,this.type=n.type??q.Custom;let r=Qi(t);this.metadata={originalKey:e,...r!==`object`&&r!==`undefined`?{fieldRef:{path:Zi(e),kind:r,...n.dimension?{dimension:n.dimension}:{}}}:{}}}type;metadata},bs=class{reps;value;image;origin;constructor(e){if(this.reps=e,e!==void 0&&e<0)throw Error(`Rep count cannot be negative: ${e}`);this.value=e,this.image=e===void 0?`?`:e.toString(),this.origin=e===void 0?`hinted`:`parser`}type=q.Rep},xs=class{count;value;image;origin=`parser`;constructor(e){this.count=e,this.value=e,this.image=e.toString()}type=q.Rounds},Ss=class{text;level;value;image;origin=`parser`;constructor(e,t){this.text=e,this.level=t,this.value={text:e,level:t},this.image=e}type=q.Text},Cs={rpe:q.SessionRPE,rir:q.RIR,intensity:q.Intensity,load:q.Load,volume:q.Volume,work:q.Work,sound:q.Sound},ws=new Set([`rest`,`amrap`,`emom`,`tabata`,`for time`]),Ts=io.standard(),Es=new Set([`effort`,`equipment`]);function Ds(e){return{matched:e.matched,source:e.label,...e.effortRef||e.equipment.length>0?{refs:[...e.effortRef?[e.effortRef]:[],...e.equipment]}:{},...e.remaining?{remaining:e.remaining}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}}function Os(e,t){return e.statements.map(e=>{let n=new ha,r=[];for(let n of e.primitives)r.push(...Ms(n,t));let i=new Set;for(let e of r)e.kind===`explicit`&&i.add(e.pair.metrics.type);let a=new Set,o=[];for(let e of r){if(e.kind!==`contributed`){o.push(e.pair);continue}let t=e.pair.metrics.type;i.has(t)||a.has(t)||(a.add(t),o.push(e.pair))}let s=Rs(o),c=t?As(s,e,t):s;return n.metrics=c.map(e=>e.metrics),n.metricMeta=new Map(c.map(e=>[e.metrics,e.meta])),n.id=e.id,n.line=e.line,n.text=e.meta.raw,n.raw=e.meta.raw,n.meta=e.meta,n.parent=e.parentId,n.children=e.children,n.isLeaf=e.isLeaf,n})}function ks(e,t,n){if(e.matched!==`split`||!e.remaining)return n;let r=t.trimEnd().length-e.remaining.length;if(r<=0)return n;let i=n.raw.slice(0,r).trimEnd(),a=i.length;return a<=0?n:{...n,endOffset:n.startOffset+a,length:a,columnEnd:n.columnStart+a,raw:i}}function As(e,t,n){let{index:r,defaults:i}=n,a=[],o=(e,t,n)=>{(e.effortRef||e.matched!==`none`||e.diagnostics.length>0)&&a.push({metrics:new Mo(t,{resolvedSlug:e.effortRef?.slug,references:Ds(e)}),meta:n}),e.equipment.length>0&&a.push({metrics:new gs(e.equipment.map(e=>e.slug),{refs:e.equipment,source:t,matched:e.matched,diagnostics:e.diagnostics}),meta:ks(e,t,n)})},s=new Set,c=[];for(let e of t.primitives){if(e.kind!==`metric_object`||s.has(e.raw))continue;if(s.add(e.raw),e.pairs.length===0){c.push({metrics:{...Za(`reference.malformed_json`,`parser`),metadata:Ds(r.resolve(e.raw))},meta:e.meta});continue}if(!e.pairs.some(e=>Es.has(e.key.toLowerCase())))continue;let t=r.resolve(e.raw);t.matched===`explicit`&&o(t,e.raw,e.meta);for(let t of e.pairs){if(Es.has(t.key.toLowerCase()))continue;let n=Cs[t.key.toLowerCase()]??q.Custom,r=Array.isArray(t.value)?t.value.join(`, `):t.value;a.push({metrics:new ys(t.key,r,{type:n,image:`${t.key}: ${r}`}),meta:e.meta})}}let l=!1,u=!1,d=!1,f;for(let t of e){let e=t.metrics;if(!(e.type===q.Custom&&s.has(t.meta.raw))){if(e.type===q.Effort){let n=e instanceof Mo?e.effort:String(e.value??``),s=n.trim().toLowerCase();if(ws.has(s)||Ts.has(s)){a.push(t);continue}l=!0;let c=r.resolve(n,i);if(c.matched===`none`&&c.diagnostics.length===0){a.push(t);continue}o(c,n,t.meta);continue}e.type===q.Duration&&(u=!0),(e.type===q.Rep||e.type===q.Rounds||e.type===q.Resistance||e.type===q.Distance)&&(d=!0),a.push(t),f??=t.meta}}if(i&&!l&&t.isLeaf&&d&&!u){let e=r.resolve(``,i);e.effortRef&&o(e,e.effortRef.label,f??t.meta)}return a.push(...c),a}function js(e){switch(e.kind){case`lap`:return[{metrics:new _s(e.lapType,e.raw),meta:e.meta}];case`duration`:{let t=[];return e.timerRaw&&t.push({metrics:new hs(e.timerRaw,e.hasTrend,e.isRequired),meta:e.meta}),e.isRequired&&t.push({metrics:Za(`behavior.required_timer`,`parser`),meta:e.meta}),t}case`rounds`:return e.sequence?e.sequence.length===1?[{metrics:new xs(e.sequence[0]),meta:e.meta}]:[{metrics:new xs(e.sequence.length),meta:e.meta},...e.sequence.map(t=>({metrics:new bs(t),meta:e.meta}))]:e.label?[{metrics:new xs(e.label),meta:e.meta}]:[];case`round_scheme`:return[{metrics:new xs(e.rounds),meta:e.meta},{metrics:new bs(e.reps),meta:e.meta}];case`action`:{let t=e.hasColonPrefix?e.raw.substring(2,e.raw.length-1).trim():e.raw.substring(1,e.raw.length-1).trim();return[{metrics:new ms(t,{raw:t}),meta:e.meta}]}case`text`:return[{metrics:new Ss(e.raw.substring(2).trim(),void 0),meta:e.meta}];case`heading`:{let t=e.raw.match(/^(#+)\s*(.*)$/),n=t?String(t[1].length):`1`;return[{metrics:new Ss(t?t[2].trim():e.raw.substring(1).trim(),n),meta:e.meta}]}case`quantity`:return e.hasAtSign?[{metrics:new Po(e.value,``),meta:e.meta}]:[{metrics:new bs(e.value),meta:e.meta}];case`effort`:return[{metrics:new Mo(e.raw),meta:e.meta}];case`property`:return[Ls(e)];case`metric_object`:return e.pairs.map(t=>{let n=Cs[t.key.toLowerCase()]??q.Custom,r=Array.isArray(t.value)?t.value.join(`, `):t.value;return{metrics:new ys(t.key,r,{type:n,image:`${t.key}: ${r}`}),meta:e.meta}});default:return[]}}function Ms(e,t){return e.kind===`property`&&e.tagRefs!==void 0?Ns(e,t):e.kind===`tag_ref`?Ps(e,t):js(e).map(e=>({kind:`explicit`,pair:e}))}function Ns(e,t){let{slots:n,resolved:r}=Fs(e.tagRefs??[],e.meta,t);return r?n:[{kind:`explicit`,pair:Ls(e)}]}function Ps(e,t){let{slots:n,resolved:r}=Fs([e.slug],e.meta,t);return r?n:[{kind:`explicit`,pair:{metrics:{type:q.Custom,value:e.raw,origin:`parser`,image:e.raw},meta:e.meta}}]}function Fs(e,t,n){let r=[],i=!1;for(let a of e){let e=xo(n?.tags,a),o=_o(n?.tags,a),s=Do(e.metrics);s.length>0&&(i=!0);for(let e of s)r.push({kind:`contributed`,pair:{metrics:Is(e,o),meta:t}});for(let s of e.tags){i=!0;let e=s===a?o:_o(n?.tags,s);r.push({kind:`marker`,pair:{metrics:Is({type:wo(s),value:s,origin:`parser`,image:s},e),meta:t}})}}return{slots:r,resolved:i}}function Is(e,t){return{...e,metadata:{...e.metadata??{},[ya]:t}}}function Ls(e){let t=Cs[e.key.toLowerCase()]??q.Custom;return{metrics:new ys(e.key,e.value,{type:t,image:e.raw}),meta:e.meta}}function Rs(e){if(e.length<2)return e;let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];if(n.metrics instanceof Mo&&i.metrics instanceof Mo){if(n.metrics.effort===`/`||n.metrics.effort===`|`||i.metrics.effort===`/`||i.metrics.effort===`|`){t.push(n),n=i;continue}let e=i.meta.startOffset-n.meta.endOffset;if(e<=1){let t={...n.meta,endOffset:i.meta.endOffset,columnEnd:i.meta.columnEnd,length:i.meta.endOffset-n.meta.startOffset,raw:n.meta.raw+(e===1?` `:``)+i.meta.raw};n={metrics:new Mo(n.metrics.effort+(e===1?` `:``)+i.metrics.effort),meta:t};continue}}if(n.metrics instanceof bs&&i.metrics instanceof Mo&&/^(reps?)$/i.test(i.metrics.effort)){let e=i.meta.startOffset-n.meta.endOffset;if(e<=1){let t={...n.meta,endOffset:i.meta.endOffset,columnEnd:i.meta.columnEnd,length:i.meta.endOffset-n.meta.startOffset,raw:n.meta.raw+(e===1?` `:``)+i.meta.raw};n={metrics:n.metrics,meta:t};continue}}if(n.metrics instanceof bs&&(i.metrics instanceof Po||i.metrics instanceof No)){let e=i.meta.startOffset-n.meta.endOffset;if(e<=1){let t={...n.meta,endOffset:i.meta.endOffset,columnEnd:i.meta.columnEnd,length:i.meta.endOffset-n.meta.startOffset,raw:n.meta.raw+(e===1?` `:``)+i.meta.raw};if(i.metrics instanceof Po&&i.metrics.value.amount===void 0){n={metrics:new Po(n.metrics.reps,i.metrics.unit),meta:t};continue}if(i.metrics instanceof No&&i.metrics.value.amount===void 0){n={metrics:new No(n.metrics.reps,i.metrics.unit),meta:t};continue}}}t.push(n),n=i}return t.push(n),t}var zs=Si.deserialize({version:14,states:`(dQVQPOOO!mQPO'#DPO$TQPO'#CdOOQO'#Cd'#CdOOQO'#Cg'#CgOOQO'#Ch'#ChOOQO'#Cf'#CfO%hQPO'#CfO%pQPO'#CjOOQO'#Cl'#ClOOQO'#DP'#DPOOQO'#Cu'#CuO%xQPO'#CmOOQO'#Cn'#CnOOQO'#Co'#CoOOQO'#Cq'#CqOOQO'#Cr'#CrOOQO'#Cp'#CpO%}QPO'#CpOOQO'#Cs'#CsOOQO'#Ct'#CtO&tQPO'#CvOOQO'#Ce'#CeOOQO'#C|'#C|O(]QPO'#CcO&{QPO'#CcOOQO'#Cz'#CzQVQPOOO(dQPO,58xOOQO,59Q,59QO(rQPO'#CkOOQO'#C}'#C}O)QQPO,59UOOQO-E6}-E6}O)]QPO,59XOOQO,59[,59[OOQO'#DQ'#DQO)hQPO,59bOOQO,59b,59bOOQO-E6z-E6zOOQO,58},58}O)oQPO,58}OOQO-E6x-E6xOOQO'#C{'#C{OOQO1G.d1G.dO)vQPO'#DOO){QPO,59VOOQO-E6{-E6{OOQO1G.p1G.pO*ZQPO1G.sOOQO-E7O-E7OOOQO1G.|1G.|OOQO1G.i1G.iPOQO-E6y-E6yOOQO,59j,59jOOQO-E6|-E6|OOQO7+$_7+$_`,stateData:"+V~OwOS~ORPOTaOUfO]UOyQOzRO{SO|VO}TO!OWO!QXO!RXO!S[O!TYO!V]O!W^O!X_O!Y`O!ZcO![dO!]eO!`jO~OxlORsXTsXUsX]sXysX{sX|sX}sX!OsX!QsX!RsX!SsX!TsX!VsX!WsX!XsX!YsX!ZsX![sX!]sX!`sX~ORWXTWXUWX]WXyWX{WX|WX}WX!OWX!QWX!RWX!SWX!TWX!VWX!WWX!XWX!YWX!ZWX![WX!]WX!`sX~O]mO}TO~ORoOTnO~OxrO~OTsO!Y`O~ORtOStOTtOktOltOmtOxtO!TtO!^tO~O!_vO~P&VORYOTaOUfO]UOyYO{SO|VO}TO!OWO!QXO!RXO!S[O!TYO!V]O!W^O!X_O!Y`O!ZcO![dO!]eO~O!`xO~P&{OR|OS|OT|OU{O~Oy}OR_XT_X!P_X~ORoOTnO!P!QO~ORYOyYO!TYO~O!_!TO~P&VO!`!UO~P&{OT!WO~Oy}OR_aT_a!P_a~ORYOyYO!TYO!U!YO~O!VU!W!Q!R}]!X{|x!Z![!T!]!_!^klmRyzT!`w!T~",goto:`$ZuPPvPPPPvz!O!V!^!eP!V!o!V!V!V!V!V!s!z!V!V!V!VPPP#U#[#_#j#p#v$TTjOkTiOkZgOhikyZfOhikyZVOhikyYUOhikyRmVToWpZbOhikyYaOhikyRsbQkORzkR|lShOkSwhyRyiQpWR!PpQ!OnR!X!OYZOhikyQq!RR!RrQueR!Su`,nodeNames:`⚠ Program Property Identifier String Number TagRef Block Lap Fragment Duration Trend CollectibleTimer Timer Rounds Sequence RoundScheme Action Text Heading Quantity AtSign Question Slash Pipe Effort MetricObject True False Null`,maxTerm:62,skippedNodes:[0],repeatNodeCount:7,tokenData:"7o~RvXY#iYZ#z]^$Ppq#iqr$Vrs$}st'dtu$Vuv$Vvw$Vxy)Pyz)Uz{)Z{|*T|}*Y}!O+S!O!P+X!P!Q,[!Q![-R![!]/U!_!`$V!a!b/n!b!c/s!c!}0m!}#O0{#O#P$V#P#Q1Q#Q#R1V#T#Y0m#Y#Z2P#Z#b0m#b#c4Q#c#h0m#h#i5p#i#o0m#o#p7`#p#q7e#q#r7j~#nSw~XY#iYZ#z]^$Ppq#i~$PO!`~~$SPYZ#z~$[Z!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~%QXOY$}Z]$}^r$}rs%ms#O$}#O#P&_#P;'S$};'S;=`'^<%lO$}~%rXS~OY$}Z]$}^r$}rs%ms#O$}#O#P&_#P;'S$};'S;=`'^<%lO$}~&bRO;'S$};'S;=`&k;=`O$}~&nYOY$}Z]$}^r$}rs%ms#O$}#O#P&_#P;'S$};'S;=`'^;=`<%l$}<%lO$}~'aP;=`<%l$}~'gXO!Q(S!Q![(n![!c(S!c!}(n!}#T(S#T#o(n#o;'S(S;'S;=`(h<%lO(S~(XT!W~OY(SZ](S^;'S(S;'S;=`(h<%lO(S~(kP;=`<%l(S~(sSU~}!O(n!Q![(n!c!}(n#T#o(n~)UO!O~~)ZO!P~~)bZ|~!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~*YOz~~*aZ!T~!^~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~+XOy~~+^[!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!Q![,S!_!`$V!b!c$V#O#P$V#Q#R$V~,XPT~!Q![,S~,aP!Z~!P!Q,d~,iU!V~OY,dZ],d^s,dt;'S,d;'S;=`,{<%lO,d~-OP;=`<%l,d~-WUT~pq-j!O!P._!Q![-R![!].e!z!{.v#l#m.v~-mRpq-j!z!{-v#l#m-v~-yPpq-|~.PQpq-|!Q![.V~.[P!R~!Q![.V~.bP!Q![,S~.hP!Q![.k~.pQ]~!Q![.k![!].e~.yP!Q![.|~/RP!Q~!Q![.|~/ZQx~!Q![/a!a!b/i~/fP]~!Q![/a~/nO}~~/sO!Y~~/zZ!X~!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~0rRR~!Q![0m!c!}0m#T#o0m~1QO!S~~1VO!U~~1^Z{~!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~2USR~!Q![0m!c!}0m#T#U2b#U#o0m~2gTR~!Q![0m!c!}0m#T#`0m#`#a2v#a#o0m~2{TR~!Q![0m!c!}0m#T#g0m#g#h3[#h#o0m~3aTR~!Q![0m!c!}0m#T#X0m#X#Y3p#Y#o0m~3wRl~R~!Q![0m!c!}0m#T#o0m~4VTR~!Q![0m!c!}0m#T#i0m#i#j4f#j#o0m~4kTR~!Q![0m!c!}0m#T#`0m#`#a4z#a#o0m~5PTR~!Q![0m!c!}0m#T#`0m#`#a5`#a#o0m~5gRm~R~!Q![0m!c!}0m#T#o0m~5uTR~!Q![0m!c!}0m#T#f0m#f#g6U#g#o0m~6ZTR~!Q![0m!c!}0m#T#i0m#i#j6j#j#o0m~6oTR~!Q![0m!c!}0m#T#X0m#X#Y7O#Y#o0m~7VRk~R~!Q![0m!c!}0m#T#o0m~7eO!]~~7jO![~~7oO!_~",tokenizers:[0],topRules:{Program:[0,1]},tokenPrec:439});function Bs(e){let t=[0];for(let n=0;n<e.length;n++)e[n]===`
9
+ `&&t.push(n+1);return e=>{let n=0,r=t.length-1;for(;n<=r;){let i=Math.floor((n+r)/2);t[i]<=e?n=i+1:r=i-1}let i=r>=0?r:0;return{lineNumber:i+1,lineStart:t[i]}}}function Vs(e,t){let n=typeof e==`string`?e:e.doc.toString(),r=n.endsWith(`
10
+ `)?n:n+`
11
+ `,i=t??zs.parse(r),a=Bs(n),o=[],s=null;return i.iterate({enter(e){if(e.name===`⚠`){s&&s.to===e.from&&o.splice(s.index,1),s=null;return}if(e.name===`Property`){let t=Hs(a,n,e.from,e.to);if(t){let n=t.meta;o.push({id:o.length,line:n.line,meta:n,primitives:[t],children:[],isLeaf:!0}),s={to:e.to,index:o.length-1}}return}if(e.name!==`Block`)return;s=null;let t=Js(a,e.from,e.to,n.slice(e.from,e.to)),r={id:o.length,line:t.line,meta:t,primitives:[],children:[],isLeaf:!0},i=e.node.cursor();if(i.firstChild())do{let e=i.node,t=n.slice(e.from,e.to);if(e.type.id===8){let n={kind:`lap`,raw:t,meta:Js(a,e.from,e.to,t),lapType:t===`+`?`compose`:`round`};r.primitives.push(n);continue}if(e.type.id!==9||!e.firstChild)continue;let o=e.firstChild,s=Gs(a,n,o);s&&r.primitives.push(s)}while(i.nextSibling());o.push(r)}}),Ks(o),{statements:o}}function Hs(e,t,n,r){let i=t.slice(n,r),a=Js(e,n,r,i),o=i.match(/^\s*([A-Za-z][A-Za-z0-9]*)\s*:\s*(.*?)\s*$/);if(!o)return null;let[,s,c]=o,l=Us(c);return{kind:`property`,raw:i,meta:a,key:s,valueRaw:c,value:l===void 0?Ws(c):c.trim(),...l===void 0?{}:{tagRefs:l}}}function Us(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0);if(t.length===0)return;let n=[];for(let e of t){let t=e.match(/^#([a-zA-Z0-9][a-zA-Z0-9-]*)$/);if(!t)return;n.push(t[1])}return n}function Ws(e){let t=e.trim();return/^"(?:[^"\\]|\\.)*"$/.test(t)?t.slice(1,-1).replace(/\\(["\\/bfnrt])/g,`$1`):/^-?(?:\d+\.\d+|\d+)$/.test(t)?Number(t):t===`true`?!0:t===`false`?!1:t===`null`?null:t}function Gs(e,t,n){let r=t.slice(n.from,n.to),i=Js(e,n.from,n.to,r);switch(n.type.id){case 10:{let e=n.getChild(`Trend`),a=n.getChild(`Timer`)||n.getChild(`CollectibleTimer`);return{kind:`duration`,raw:r,meta:i,timerRaw:a?t.slice(a.from,a.to):void 0,hasTrend:!!e,isRequired:r.includes(`*`)}}case 14:{let e=n.getChild(`Sequence`),a=n.getChild(`Identifier`);return{kind:`rounds`,raw:r,meta:i,sequence:e?t.slice(e.from,e.to).split(`-`).map(e=>parseInt(e.trim(),10)):void 0,label:a?t.slice(a.from,a.to):void 0}}case 16:{let e=r.match(/^(\d+)\s*[xX]\s*(\d+)$/);return e?{kind:`round_scheme`,raw:r,meta:i,rounds:parseInt(e[1],10),reps:parseInt(e[2],10)}:null}case 17:return{kind:`action`,raw:r,meta:i,hasColonPrefix:r.startsWith(`[:`)};case 18:return{kind:`text`,raw:r,meta:i};case 19:return{kind:`heading`,raw:r,meta:i};case 20:{let e=!!n.getChild(`AtSign`),a=n.getChild(`Number`);return{kind:`quantity`,raw:r,meta:i,value:a?parseFloat(t.slice(a.from,a.to)):void 0,hasAtSign:e}}case 25:return{kind:`effort`,raw:r,meta:i};case 6:{let e=r.match(/^#([a-zA-Z0-9][a-zA-Z0-9-]*)$/);return e?{kind:`tag_ref`,raw:r,meta:i,slug:e[1]}:null}case 23:return{kind:`effort`,raw:r,meta:i};case 24:return{kind:`effort`,raw:r,meta:i};case 26:{let e=[];try{let t=JSON.parse(r);t&&typeof t==`object`&&!Array.isArray(t)&&(e=Object.entries(t).map(([e,t])=>({key:e,value:t})))}catch{}return{kind:`metric_object`,raw:r,meta:i,pairs:e}}default:return null}}function Ks(e){let t=new Map,n=[];for(let r of e){if(n=n.filter(e=>e.columnStart<r.meta.columnStart),n.length>0)for(let e of n)t.has(e.statement.id)||t.set(e.statement.id,[]),t.get(e.statement.id).push(r.id),r.parentId=e.statement.id;n.push({columnStart:r.meta.columnStart,statement:r})}for(let n of e)n.children=qs(t.get(n.id)??[],e),n.isLeaf=n.children.length===0}function qs(e,t){if(e.length===0)return[];let n=new Map(t.map(e=>[e.id,e])),r=[];for(let t of e)n.get(t)?.primitives.find(e=>e.kind===`lap`)?.lapType===`compose`&&r.length>0?r[r.length-1].push(t):r.push([t]);return r}function Js(e,t,n,r){let{lineNumber:i,lineStart:a}=e(t);return{line:i,startOffset:t,endOffset:n,columnStart:t-a,columnEnd:n-a,length:n-t,raw:r}}function Ys(e,t){return typeof e==`string`?{source:e,tree:t}:`source`in e?{source:e.source,tree:t??e.tree}:`doc`in e?{source:e.doc.toString(),tree:t}:{source:``}}function Xs(e,t,n){let{source:r,tree:i}=Ys(e,t);return ec(Os(Vs(r,i),n))}function Zs(e,t,n,r){let i,a;typeof t==`string`?i=t:t&&typeof t==`object`&&(a=t,i=n);let o=Ys(e,a),s=Os(Vs(o.source,o.tree),r);return ps.processAll(s,i),ec(s)}function Qs(e){return e.children.length>0?!1:e.metrics.some(e=>e.type===q.Rounds)&&e.metrics.some(e=>e.type===q.Rep)&&!e.metrics.some(e=>e.type===q.Duration)}function $s(e){let t=Object.create(Object.getPrototypeOf(e));return Object.assign(t,e),t}function ec(e){if(!e.some(Qs))return e;let t=[],n=new Map,r=new Map,i=new Map,a=new Map;for(let o of e){if(!Qs(o)){n.set(o.id,t.length),t.push(o);continue}o.parent!==void 0&&r.set(o.id,o.parent);let e=$s(o),s=$s(o),c=e=>e.type===q.Rounds||e.type===q.Rep;e.metrics=J.from(o.metrics.filter(c),e.id),s.metrics=J.from(o.metrics.filter(e=>!c(e)),s.id),e.metricMeta=new Map([...o.metricMeta].filter(([e])=>c(e))),s.metricMeta=new Map([...o.metricMeta].filter(([e])=>!c(e))),e.isLeaf=!1,s.isLeaf=!0,e.children=[],s.children=[],i.set(s,e),a.set(e,o.id),n.set(o.id,t.length),t.push(e,s)}return t.map((e,t)=>{let o=e.id;if(e.id=t,e.metrics=J.from(e.metrics,e.id),i.get(e))return e.parent=t-1,e;if(a.has(e)){e.children=[[t+1]];let i=r.get(a.get(e));return e.parent=i===void 0?void 0:n.get(i),e}return e.parent=e.parent===void 0?void 0:n.get(e.parent),e.children=e.children.map(e=>e.filter(e=>!r.has(e)||r.get(e)===o).map(e=>n.get(e)??e)).filter(e=>e.length>0),e})}var tc=class{source;statements;errors;_idMap;constructor(e,t,n=[]){this.source=e,this.statements=t,this.errors=n}getIdMap(){return this._idMap||=new Map(this.statements.map(e=>[e.id,e])),this._idMap}getIds(e){let t=this.getIdMap();return e.map(e=>t.get(e)).filter(Boolean)}getId(e){return this.getIdMap().get(e)}getAt(e){return this.statements[e]}getFlatChildren(e){return this.getIds(e.flat())}getChildGroups(e){return e.map(e=>this.getIds(e))}},nc={core:0,community:1,imported:2,user:3};function rc(e,t){if(t)return t;if(!e)return`core`;if(e===`user`)return`user`;let n=e.startsWith(`seed:`)?e.slice(5):e;return n===`core`||n===`efforts`||n===`equipment`?`core`:n===`community`||n.startsWith(`community-`)||n===`common`?`community`:`imported`}function ic(e){return e.registrySource===`user`?`user`:rc(e.sourceId)}function ac(e){return nc[ic(e)]}function oc(e){let t=new Map;for(let n of e){let e=n.slug.toLowerCase(),r=t.get(e);(!r||ac(n)>=ac(r))&&t.set(e,n)}return Array.from(t.values())}var sc=[`low`,`moderate`,`high`],cc={defaultMet:5,defaultThreshold:2};function lc(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;if(e.length>t.length){let n=e;e=t,t=n}let n=e.length,r=t.length,i=new Uint32Array(n+1),a=new Uint32Array(n+1);for(let e=0;e<=n;e++)i[e]=e;for(let o=1;o<=r;o++){a[0]=o;let r=t.charCodeAt(o-1);for(let t=1;t<=n;t++){let n=e.charCodeAt(t-1)===r?0:1;a[t]=Math.min(i[t]+1,a[t-1]+1,i[t-1]+n)}let s=i;i=a,a=s}return i[n]}function uc(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,` `).replace(/[-_]+/g,` `).trim().replace(/\s+/g,` `)}function dc(e,t,n){let r=uc(e),i=null;for(let e of t){let t=uc(e);if(Math.abs(r.length-t.length)>n)continue;let a=lc(r,t);if(!(a>n)&&(!i||a<i.distance)&&(i={target:e,distance:a},a===0))break}return i}function fc(e){let t=oc(e),n=new Map,r=(e,t)=>{if(!e)return;let r=n.get(e);r?r.includes(t)||r.push(t):n.set(e,[t])};for(let e of t){r(e.slug.toLowerCase(),e),r(uc(e.label),e);for(let t of e.aliases)r(uc(t),e)}return{byKey:n,lookup(e){let t=n.get(e)??n.get(uc(e));if(!t||t.length===0)return{entity:null,ambiguous:[]};if(t.length===1)return{entity:t[0],ambiguous:[]};let r=-1;for(let e of t){let t=ac(e);t>r&&(r=t)}let i=t.filter(e=>ac(e)===r);return i.length===1?{entity:i[0],ambiguous:[]}:{entity:null,ambiguous:i}}}}function pc(e){return{kind:`equipment`,slug:e.slug,label:e.label}}function mc(e){let t=new Set,n=[];for(let r of e){let e=`${r.kind}:${r.slug}`;t.has(e)||(t.add(e),n.push(r))}return n}function hc(e,t){let n=oc(e.equipment??[]),r=fc(e.efforts??[]),i=fc(n),a=n.flatMap(e=>[e.label,...e.aliases].filter(e=>!!e&&!!e.trim()).map(t=>({lower:t.trim().toLowerCase(),entity:e}))).sort((e,t)=>t.lower.length-e.lower.length),o=t??(e=>({effort:e,definition:e,slug:e.slug,label:e.label,met:e.baseAttributes.met,baseAttributes:e.baseAttributes,discipline:e.baseAttributes.discipline,disciplineFactor:e.baseAttributes.disciplineFactor??1,intensityTier:e.baseAttributes.intensityTier,modifiers:{},registrySource:e.registrySource,resolvedFrom:e.registrySource===`user`?`user`:e.registrySource===`bundled`?`bundled`:`default`,isEstimated:!1})),s=e=>{let t=r.lookup(e.trim());return t.entity?{entity:t.entity}:t.ambiguous.length>0?{entity:null,diagnostic:{reason:`ambiguous-effort`,message:`"${e}" matches multiple efforts.`,token:e,candidates:t.ambiguous.map(e=>e.slug)}}:{entity:null,diagnostic:{reason:`unknown-effort`,message:`Unknown effort "${e}".`,token:e}}},c=e=>{let t=[],n=[];for(let r of e){if(typeof r!=`string`||!r.trim()){n.push({reason:`invalid-explicit`,message:`Equipment reference must be a slug string, got ${JSON.stringify(r)??`null`}.`,token:String(r)});continue}let e=i.lookup(r.trim());e.entity?t.push(pc(e.entity)):e.ambiguous.length>0?n.push({reason:`ambiguous-equipment`,message:`"${r}" matches multiple equipment entries.`,token:r,candidates:e.ambiguous.map(e=>e.slug)}):n.push({reason:`invalid-explicit`,message:`Unknown equipment "${r}".`,token:r})}return{refs:mc(t),diagnostics:n}};return{resolveEffort(e){return r.lookup(e).entity},resolveEquipment(e){return i.lookup(e).entity},materialize(e){return o(e)},resolve(e,t){let n=(e??``).trim(),r=[],l=e=>{e&&r.push(e)},u=`none`,d=null,f=``,p=[],m=!1,h=()=>{if(!(p.length>0||m)&&d!==null){if(t?.equipment?.length){let e=c(t.equipment);p=e.refs;for(let t of e.diagnostics)l({...t,reason:`unknown-equipment`});if(p.length>0)return}if(d.equipment?.length){let e=c(d.equipment);p=e.refs;for(let t of e.diagnostics)l({...t,reason:`unknown-equipment`})}}};if(!n){if(t?.effort){let e=s(t.effort);e.entity?(d=e.entity,u=`default`):l({reason:e.diagnostic?.reason===`ambiguous-effort`?`ambiguous-effort`:`unknown-effort`,message:`Default effort "${t.effort}" is not in the catalog.`,token:t.effort,candidates:e.diagnostic?.candidates})}return h(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:``,diagnostics:r}}if(n.startsWith(`{`)){let e;try{e=JSON.parse(n)}catch{return{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:[{reason:`malformed-json`,message:`Reference object is not valid JSON.`,token:n}]}}if(e&&typeof e==`object`&&!Array.isArray(e)&&(`effort`in e||`equipment`in e)){u=`explicit`;let t=e;if(t.effort!==void 0){if(typeof t.effort==`string`&&t.effort.trim()){let e=s(t.effort);d=e.entity,e.diagnostic&&l(e.diagnostic.reason===`ambiguous-effort`?e.diagnostic:{...e.diagnostic,reason:`invalid-explicit`,message:`Explicit effort "${t.effort}" is not in the catalog.`})}else l({reason:`invalid-explicit`,message:`Explicit "effort" must be a slug string.`,token:String(t.effort)})}if(t.equipment!==void 0){m=!0;let e=Array.isArray(t.equipment)?t.equipment:[t.equipment],i=c(e);if(p=i.refs,r.push(...i.diagnostics),d?.equipment?.length){let e=new Set(d.equipment),t=p.map(e=>e.slug);t.length>0&&t.some(t=>!e.has(t))&&l({reason:`conflict`,message:`Explicit equipment [${t.join(`, `)}] contradicts effort "${d.slug}" definition equipment [${d.equipment.join(`, `)}].`,token:n})}}return h(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:``,diagnostics:r}}}let g=n.toLowerCase();for(let e of a){if(!g.startsWith(e.lower))continue;let t=n.slice(e.lower.length);if(t&&!/^\s/.test(t))continue;let a=t.trim();if(!a)continue;let o=i.lookup(e.lower);if(o.ambiguous.length>0)return l({reason:`ambiguous-equipment`,message:`"${e.lower}" matches multiple equipment entries.`,token:n,candidates:o.ambiguous.map(e=>e.slug)}),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};if(!o.entity)continue;let c=s(a);if(c.entity){u=`split`,d=c.entity,p=[pc(o.entity)],m=!0,f=a;break}if(c.diagnostic?.reason===`ambiguous-effort`)return l(c.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r}}if(u===`none`){let e=s(n);if(e.entity)d=e.entity,u=`whole`;else if(e.diagnostic?.reason===`ambiguous-effort`)return l(e.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};else e.diagnostic&&l(e.diagnostic)}return h(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:f,diagnostics:r}}}}function gc(e){let t=[],n=[],r=new Set,i=new Set,a=(e,t,n)=>{n&&(t.has(n)||(t.add(n),e.push(n)))};for(let o of e??[]){let e=Array.isArray(o.metrics)?o.metrics:o.metrics?.toArray?.()??[];for(let o of e){let e=fa(o.metadata)?.refs;if(e)for(let o of e)o.kind===`effort`&&a(t,r,o.slug),o.kind===`equipment`&&a(n,i,o.slug)}}return{efforts:t,equipment:n}}function _c(e,t={}){if(!e||!e.trim())return new tc(e,[],[]);try{let n=e.endsWith(`
12
+ `)?e:e+`
13
+ `,r=zs.parse(n),i=t.sport??t.dialect,a=t.references||t.tags?{index:t.references??hc({efforts:[],equipment:[]}),defaults:t.defaults,tags:t.tags}:void 0;return new tc(e,t.withoutDialects?Xs(e,r,a):Zs(e,r,i,a),[])}catch(t){return new tc(e,[],[{message:t instanceof Error?t.message:`Unknown parse error`}])}}var vc=class{config;constructor(e){this.config=e}read(e,t){return _c(e,{sport:t,...this.config})}readWithoutDialects(e){return _c(e,{withoutDialects:!0,...this.config})}};function yc(e){return new vc(e)}var bc=Mr.define({parser:zs.configure({props:[Di({Identifier:H.variableName,String:H.string,Number:H.number,"schemeNumber schemeSpaced":H.number,Timer:H.keyword,collectibleTimer:H.keyword,textComment:H.lineComment,heading:H.heading,minus:H.operator,plus:H.operator,trend:H.operator,atSign:H.operator,"Slash/slash":H.operator,question:H.keyword,actionOpen:H.bracket,actionClose:H.bracket,groupOpen:H.bracket,groupClose:H.bracket,colon:H.punctuation,Property:H.propertyName,"Block/Lap":H.keyword})]}),languageData:{commentTokens:{line:`//`},closeBrackets:{brackets:[`(`,`[`,`'`,`"`]}}}),xc=[`bodyweight`,`cycling`,`gymnastics`,`kettlebell`,`recovery`,`rowing`,`running`,`strength`,`swimming`,`walking`];function Sc(e){return typeof e==`string`&&xc.includes(e.toLowerCase())}var Cc={strength:1.2,kettlebell:1.2,gymnastics:1.2,recovery:.9,bodyweight:1,cycling:1,rowing:1,running:1,swimming:1,walking:1};function wc(e){if(!e)return 1;let t=e.toLowerCase();return Sc(t)?Cc[t]:1}var Tc=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/,Ec=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Dc(e){return e.replace(/^(['"])(.*)\1$/,(e,t,n)=>t===`"`?n.replace(/\\(["\\nrt])/g,(e,t)=>t===`n`?`
14
+ `:t===`r`?`\r`:t===`t`?` `:t):n)}function Oc(e){return e?/[:"'\n#{}[\],&*?|\-<>=%!@`]/.test(e)||e!==e.trim()?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}"`:e:`""`}function kc(e){let t=e.match(Tc);if(!t)return{meta:{},body:e};let n=t[1].split(/\r?\n/),r={};for(let e=0;e<n.length;e++){let t=n[e].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!t)continue;let i=t[1],a=t[2].trim();if(a===``){let t=[];for(;e+1<n.length;){let r=n[e+1].match(/^\s+-\s+(.+)$/);if(!r)break;t.push(Dc(r[1].trim())),e++}r[i]=t.length>0?t:``}else{let e=/^(['"])(.*)\1$/.test(a),t=Dc(a),n=Number(t);r[i]=!e&&t!==``&&!isNaN(n)?n:t}}return{meta:r,body:e.slice(t[0].length)}}function Ac(e,t){let n=e[t];return typeof n==`string`||typeof n==`number`?n:void 0}function jc(e,t){let n=e[t];return n===void 0||typeof n==`string`&&n===`[]`?[]:Array.isArray(n)?n:void 0}function Mc(e){return e===`true`?!0:e===`false`?!1:e!==``&&!Number.isNaN(Number(e))?Number(e):Dc(e)}function Nc(e,t){let n=e.findIndex(e=>RegExp(`^${t}:\\s*$`).test(e));if(n===-1)return;let r={},i=null;for(let t=n+1;t<e.length;t++){let n=e[t];if(/^\S/.test(n))break;let a=n.trim();if(!a||a.startsWith(`#`))continue;let o=n.length-n.trimStart().length,s=a.match(/^([\w.-]+):\s*(.*)$/);if(!s)continue;let[,c,l]=s;o===2?l===``?(i=c,r[c]={}):(i=null,r[c]=Mc(l)):o>=4&&i!==null&&(r[i][c]=Mc(l))}return Object.keys(r).length>0?r:void 0}function Pc(e){if(!e)return;let t=Dc(e.trim()).toLowerCase();if(Sc(t))return t;console.warn(`[definition-markdown] unknown discipline '${e}' — expected one of the canonical values; treating as unset`)}function Fc(e,t){let n=[],r=e===void 0?``:String(e);return r?Ec.test(r)||n.push(`Invalid slug: must be lowercase letters, numbers, and hyphens only`):n.push(`Missing required field: slug`),(t===void 0||!String(t).trim())&&n.push(`Missing required field: label`),n}function Ic(e,t){let n=[];for(let r of e)r.trim()?t===`equipment`&&!Ec.test(r)&&n.push(`Invalid ${t}: '${r}' must be a canonical slug (lowercase letters, numbers, hyphens)`):n.push(`Invalid ${t}: blank entries are not allowed`);let r=e.find((t,n)=>e.indexOf(t)!==n);return r!==void 0&&n.push(`Invalid ${t}: duplicate entry '${r}'`),n}function Lc(e){return e===void 0?`Missing required field: baseAttributes.met`:typeof e!=`number`||!Number.isFinite(e)||e<=0?`Invalid baseAttributes.met: must be a positive number`:null}function Rc(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return null;let n=t[1].split(/\r?\n/),{meta:r,body:i}=kc(e),a=Ac(r,`type`);if(a!==void 0&&a!==`effort`)return null;let o=Ac(r,`id`),s=Ac(r,`slug`),c=Ac(r,`label`),l=jc(r,`aliases`),u=jc(r,`equipment`);if(l===void 0||u===void 0||Fc(s,c).length>0||Ic(l,`aliases`).length>0||u.length>0&&Ic(u,`equipment`).length>0)return null;let d=Nc(n,`baseAttributes`)??{};if(Lc(d.met)!==null)return null;let f=d.met,p=Pc(typeof d.discipline==`string`?d.discipline:void 0),m=d.intensityTier,h=typeof d.disciplineFactor==`number`&&Number.isFinite(d.disciplineFactor)?d.disciplineFactor:void 0,g=Nc(n,`hints`),_=Nc(n,`derivation`),v=i.trim();return{id:String(o??``),slug:String(s),label:String(c),aliases:l,baseAttributes:{met:f,...p?{discipline:p}:{},...h===void 0?{}:{disciplineFactor:h},...m?{intensityTier:m}:{}},registrySource:`bundled`,...u.length>0?{equipment:u}:{},...v?{body:v}:{},...g?{hints:g}:{},..._?{derivation:_}:{}}}function zc(e){let{meta:t,body:n}=kc(e);if(Ac(t,`type`)!==`equipment`)return null;let r=Ac(t,`id`),i=Ac(t,`slug`),a=Ac(t,`label`),o=jc(t,`aliases`);if(r===void 0||o===void 0||Fc(i,a).length>0||Ic(o,`aliases`).length>0)return null;let s=n.trim();return{id:String(r),slug:String(i),label:String(a),aliases:o,registrySource:`bundled`,...s?{body:s}:{}}}function Bc(){return{id:`effort-user-${b()}`,slug:``,label:``,aliases:[],baseAttributes:{met:5},registrySource:`user`}}function Vc(e,t){let n=[],r=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!r)return n.push(`Missing YAML frontmatter delimiters (---)`),{effort:t??Bc(),errors:n};let i=r[1].split(/\r?\n/),{meta:a,body:o}=kc(e),s=o.replace(/^\r?\n+/,``)||void 0,c=Ac(a,`id`),l=Ac(a,`slug`),u=Ac(a,`label`),d=Ac(a,`registrySource`),f=Ac(a,`createdAt`),p=Ac(a,`updatedAt`),m=jc(a,`aliases`),h=a.equipment,g=jc(a,`equipment`);m===void 0&&n.push("Invalid aliases: must be a list (`aliases:` followed by `- item` lines)"),g===void 0&&n.push("Invalid equipment: must be a list (`equipment:` followed by `- slug` lines)");let _=Nc(i,`baseAttributes`)??{},v={},y=_.met;if(y===void 0){let e=t?.baseAttributes.met,r=e===void 0?null:Lc(e);r?n.push(r):e===void 0?n.push(`Missing required field: baseAttributes.met`):v.met=e}else{let e=Lc(y);e?n.push(e):v.met=Number(y)}Ac(a,`met`)!==void 0&&n.push(`Invalid met placement: 'met' must be nested under baseAttributes (missing baseAttributes.met)`);let x=Pc(typeof _.discipline==`string`?_.discipline:void 0);x&&(v.discipline=x),typeof _.disciplineFactor==`number`&&Number.isFinite(_.disciplineFactor)&&(v.disciplineFactor=_.disciplineFactor),_.intensityTier&&(v.intensityTier=_.intensityTier);let S=Nc(i,`hints`)??t?.hints,C=Nc(i,`derivation`);n.push(...Fc(l,u)),m!==void 0&&n.push(...Ic(m,`aliases`)),g!==void 0&&g.length>0&&n.push(...Ic(g,`equipment`));let w=h===void 0?t?.equipment?.length?t.equipment:void 0:g??[];return{effort:{id:String(c??``)||t?.id||`effort-user-${b()}`,slug:String(l??``),label:String(u??``),aliases:m??[],baseAttributes:v,registrySource:d||t?.registrySource||`user`,...w?{equipment:w}:{},...f?{createdAt:String(f)}:{},...p?{updatedAt:String(p)}:{},...s?{body:s}:{},...S&&Object.keys(S).length>0?{hints:S}:{},...C?{derivation:C}:{}},errors:n}}function Hc(e){let t=[`---`];if(t.push(`id: ${e.id}`),t.push(`slug: ${e.slug}`),t.push(`label: ${Oc(e.label)}`),e.aliases.length>0){t.push(`aliases:`);for(let n of e.aliases)t.push(` - ${Oc(n)}`)}else t.push(`aliases: []`);if(t.push(`baseAttributes:`),t.push(` met: ${e.baseAttributes.met}`),e.baseAttributes.discipline&&t.push(` discipline: ${e.baseAttributes.discipline}`),e.baseAttributes.disciplineFactor!==void 0&&t.push(` disciplineFactor: ${e.baseAttributes.disciplineFactor}`),e.baseAttributes.intensityTier&&t.push(` intensityTier: ${e.baseAttributes.intensityTier}`),t.push(`registrySource: ${e.registrySource}`),e.equipment&&e.equipment.length>0){t.push(`equipment:`);for(let n of e.equipment)t.push(` - ${Oc(n)}`)}if(e.derivation){if(t.push(`derivation:`),e.derivation.parentSlug&&t.push(` parentSlug: ${e.derivation.parentSlug}`),e.derivation.coefficients&&Object.keys(e.derivation.coefficients).length>0){t.push(` coefficients:`);for(let[n,r]of Object.entries(e.derivation.coefficients))t.push(` ${n}: ${r}`)}if(e.derivation.hardOverrides&&Object.keys(e.derivation.hardOverrides).length>0){t.push(` hardOverrides:`);for(let[n,r]of Object.entries(e.derivation.hardOverrides))t.push(` ${n}: ${JSON.stringify(r)}`)}}if(e.createdAt&&t.push(`createdAt: ${e.createdAt}`),e.updatedAt&&t.push(`updatedAt: ${e.updatedAt}`),e.hints&&Object.keys(e.hints).length>0){t.push(`hints:`);for(let[n,r]of Object.entries(e.hints))t.push(` ${n}: ${typeof r==`object`&&r?JSON.stringify(r):String(r)}`)}return t.push(`---`),e.body&&(t.push(``),t.push(e.body)),t.join(`
15
+ `)}function Uc(){return{id:`equipment-user-${b()}`,slug:``,label:``,aliases:[],registrySource:`user`}}function Wc(e,t){let n=[];if(!e.match(Tc))return n.push(`Missing YAML frontmatter delimiters (---)`),{equipment:t??Uc(),errors:n};let{meta:r,body:i}=kc(e),a=i.replace(/^\r?\n+/,``)||void 0,o=Ac(r,`type`),s=Ac(r,`id`),c=Ac(r,`slug`),l=Ac(r,`label`),u=Ac(r,`registrySource`),d=Ac(r,`createdAt`),f=Ac(r,`updatedAt`),p=jc(r,`aliases`);return o!==`equipment`&&n.push("Missing or invalid discriminator: frontmatter must declare `type: equipment`"),(!c||!Ec.test(String(c)))&&n.push(`Invalid slug: must be a canonical slug (lowercase letters, numbers, hyphens)`),l||n.push(`Missing required field: label`),p===void 0?n.push("Invalid aliases: must be a list (`aliases:` followed by `- item` lines)"):n.push(...Ic(p,`aliases`)),u!==void 0&&u!==`bundled`&&u!==`user`&&n.push(`Invalid registrySource: must be 'bundled' or 'user'`),{equipment:{id:String(s??``)||t?.id||`equipment-user-${b()}`,slug:String(c??``),label:String(l??``),aliases:p??[],registrySource:u||t?.registrySource||`user`,...d?{createdAt:String(d)}:{},...f?{updatedAt:String(f)}:{},...a?{body:a}:{}},errors:n}}function Gc(e){let t=[`---`];if(t.push(`type: equipment`),t.push(`id: ${e.id}`),t.push(`slug: ${e.slug}`),t.push(`label: ${Oc(e.label)}`),e.aliases.length>0){t.push(`aliases:`);for(let n of e.aliases)t.push(` - ${Oc(n)}`)}else t.push(`aliases: []`);return t.push(`registrySource: ${e.registrySource}`),e.createdAt&&t.push(`createdAt: ${e.createdAt}`),e.updatedAt&&t.push(`updatedAt: ${e.updatedAt}`),t.push(`---`),e.body&&(t.push(``),t.push(e.body)),t.join(`
16
+ `)}function Kc(e){return uc(e).replace(/\s+/g,`-`)}var qc=class{registry;options;constructor(e,t){this.registry=e,this.options={defaultMet:t?.defaultMet??cc.defaultMet,defaultThreshold:t?.defaultThreshold??cc.defaultThreshold}}resolveBySlug(e){return this.registry.resolve(e)}resolveByAlias(e){let t=uc(e);for(let e of this.registry.list()){if(uc(e.label)===t)return e;for(let n of e.aliases)if(uc(n)===t)return e}return null}resolveFuzzy(e,t){let n=t?.threshold??this.options.defaultThreshold,r=uc(e),i=this.resolveByAlias(e);if(i)return i;let a=[];for(let e of this.registry.list())for(let t of[e.label,...e.aliases])a.push({alias:t,effort:e});let o=dc(r,a.map(e=>e.alias),n);if(o){let e=a.find(e=>uc(e.alias)===uc(o.target));if(e)return e.effort}return this.createSyntheticEffort(e)}resolveEffort(e,t){let n=this.resolveBySlug(e)??this.resolveByAlias(e)??this.resolveFuzzy(e,{threshold:t?.threshold});return this.resolveDefinition(n,t)}resolveDefinition(e,t){return this.materialize(e,t?.modifiers??{},new Set)}list(){return this.registry.list()}materialize(e,t,n){if(n.has(e.slug))throw Error(`EffortResolver: circular effort derivation detected at "${e.slug}"`);n.add(e.slug);let r=e.derivation?.parentSlug?this.registry.resolve(e.derivation.parentSlug):null,i=r?this.materialize(r,t,n):null,a=i?.met??e.baseAttributes.met,o=e.derivation?.coefficients??{};for(let[e,n]of Object.entries(o))this.shouldApplyCoefficient(e,t)&&(a*=n);let s=e.derivation?.hardOverrides?.met;typeof s==`number`&&Number.isFinite(s)&&(a=s);let c=e.baseAttributes.discipline??i?.discipline,l=this.resolveDisciplineFactor(e,i),u=e.registrySource,d=u===`user`?`user`:u===`bundled`?`bundled`:`default`,f=u===`synthetic-unresolved`,p={...e,baseAttributes:{...e.baseAttributes,met:a,discipline:c,disciplineFactor:l,intensityTier:e.baseAttributes.intensityTier??i?.intensityTier}};return{effort:p,definition:e,slug:p.slug,label:p.label,met:a,baseAttributes:p.baseAttributes,discipline:c,disciplineFactor:l,intensityTier:p.baseAttributes.intensityTier,modifiers:{...t},registrySource:u,resolvedFrom:d,isEstimated:f}}shouldApplyCoefficient(e,t){if(e===`met`||e===`*`)return!0;for(let[n,r]of Object.entries(t))if(e===n||e===r||e===`${n}:${r}`||e===`${n}=${r}`)return!0;return!1}resolveDisciplineFactor(e,t){let n=e.derivation?.hardOverrides?.disciplineFactor;if(typeof n==`number`&&Number.isFinite(n))return n;let r=e.baseAttributes.disciplineFactor;if(typeof r==`number`&&Number.isFinite(r))return r;let i=e.baseAttributes.discipline??t?.discipline;return!i&&t?t.disciplineFactor:wc(i)}createSyntheticEffort(e){let t=uc(e),n=Kc(e);return{id:`synthetic-${b()}`,slug:n,label:t,aliases:[t],baseAttributes:{met:this.options.defaultMet,discipline:void 0,intensityTier:void 0},registrySource:`synthetic-unresolved`}}},Jc=[{id:`fixture-running`,slug:`running-6-mph`,label:`Running (6 mph)`,aliases:[`run`,`jogging`,`treadmill`],baseAttributes:{met:9.8,discipline:`running`,intensityTier:`moderate`},registrySource:`bundled`},{id:`fixture-rowing`,slug:`rowing`,label:`Rowing`,aliases:[`row`,`rower`,`erg`],baseAttributes:{met:7,discipline:`rowing`,intensityTier:`high`},registrySource:`bundled`},{id:`fixture-back-squat`,slug:`back-squat`,label:`Back Squat`,aliases:[`squat`,`barbell squat`,`bs`],baseAttributes:{met:6,discipline:`strength`,intensityTier:`moderate`},registrySource:`bundled`},{id:`fixture-burpee`,slug:`burpee`,label:`Burpee`,aliases:[`burpees`],baseAttributes:{met:10,discipline:`bodyweight`,intensityTier:`high`},registrySource:`bundled`},{id:`fixture-plank`,slug:`plank`,label:`Plank`,aliases:[`planks`],baseAttributes:{met:3.5,discipline:`bodyweight`,intensityTier:`low`},registrySource:`bundled`}];[...Jc];var Yc=Jc;Yc.length;var Xc=class{efforts=new Map;sourceFilter=null;initialized=!1;constructor(e){this.sourceFilter=e??null}async loadBundled(){for(let e of Yc)(!this.sourceFilter||e.registrySource===this.sourceFilter)&&this.efforts.set(e.slug,e);this.initialized=!0}isInitialized(){return this.initialized}seed(e){for(let t of e)this.efforts.set(t.slug,t)}clear(){this.efforts.clear(),this.initialized=!1}resolve(e){return this.efforts.get(e)??null}resolveByAlias(e){let t=uc(e);for(let e of this.efforts.values()){if(uc(e.label)===t)return e;for(let n of e.aliases)if(uc(n)===t)return e}return null}list(){return Array.from(this.efforts.values())}listByOrigin(e){return this.list().filter(t=>t.registrySource===e)}async upsert(e){if(e.registrySource!==`user`)throw Error(`InMemoryEffortRegistry.upsert: only user efforts can be written. Received registrySource="${e.registrySource}"`);this.efforts.set(e.slug,e)}async delete(e){let t=this.efforts.get(e);if(t&&t.registrySource!==`user`)throw Error(`InMemoryEffortRegistry.delete: cannot delete non-user effort "${e}"`);this.efforts.delete(e)}},Zc=class{userEfforts=new Map;bundledEfforts=new Map;initialized=!1;initialBundled;storage;constructor(e){e&&(this.initialBundled=e.bundled,this.storage=e.storage)}async loadBundled(e){this.bundledEfforts.clear();let t=e??this.initialBundled??Yc;for(let e of t){let t=this.bundledEfforts.get(e.slug);(!t||ac(e)>=ac(t))&&this.bundledEfforts.set(e.slug,e)}if(this.userEfforts.clear(),this.storage)try{let e=await this.storage.load();for(let t of e)t.registrySource===`user`&&this.userEfforts.set(t.slug,t)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to load user efforts from storage adapter:`,e)}this.initialized=!0}isInitialized(){return this.initialized}resolve(e){return this.userEfforts.get(e)??this.bundledEfforts.get(e)??null}resolveByAlias(e){let t=uc(e);for(let e of this.userEfforts.values()){if(uc(e.label)===t)return e;for(let n of e.aliases)if(uc(n)===t)return e}let n=Array.from(this.bundledEfforts.values()).filter(e=>!this.userEfforts.has(e.slug)).sort((e,t)=>ac(t)-ac(e));for(let e of n){if(uc(e.label)===t)return e;for(let n of e.aliases)if(uc(n)===t)return e}return null}list(){let e=new Map(this.bundledEfforts);for(let[t,n]of this.userEfforts)e.set(t,n);return Array.from(e.values())}listByOrigin(e){return e===`user`?Array.from(this.userEfforts.values()):e===`bundled`?Array.from(this.bundledEfforts.values()):this.list().filter(t=>t.registrySource===e)}async upsert(e){if(e.registrySource!==`user`)throw Error(`CompositeEffortRegistry.upsert: only user efforts can be written. Received registrySource="${e.registrySource}"`);if(this.userEfforts.set(e.slug,e),this.storage)try{await this.storage.save(e)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to persist effort to storage adapter:`,e)}}async delete(e){let t=this.resolve(e);if(t&&t.registrySource!==`user`)throw Error(`CompositeEffortRegistry.delete: cannot delete non-user effort "${e}"`);if(this.userEfforts.delete(e),this.storage)try{await this.storage.delete(e)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to delete effort from storage adapter:`,e)}}};async function Qc(e,t,n){let r=n.trim();if(!r)throw Error(`Alias cannot be empty`);let i=e.resolve(t);if(!i)throw Error(`Effort "${t}" not found in registry`);let a=uc(r);if(uc(i.label)===a||i.aliases.some(e=>uc(e)===a))return i;let o=[...i.aliases,r],s=new Date().toISOString();if(i.registrySource===`bundled`){let t=typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`effort-user-${crypto.randomUUID()}`:`effort-user-${Date.now()}`,n={...i,id:t,registrySource:`user`,aliases:o,updatedAt:s,derivation:i.derivation??{parentSlug:i.slug,coefficients:{},hardOverrides:{}}};return await e.upsert(n),n}let c={...i,aliases:o,updatedAt:s};return await e.upsert(c),c}var $c={debugMode:!1,enableLogging:!1,maxActionDepth:20},el=class e{started;ended;constructor(e,t){this.started=e,this.ended=t}static fromJSON(t){return new e(t.started,t.ended)}static fromDates(t,n){return new e(t.getTime(),n?.getTime())}get duration(){let e=this.ended??Date.now();return Math.max(0,e-this.started)}get isOpen(){return this.ended===void 0}get startDate(){return new Date(this.started)}get endDate(){return this.ended?new Date(this.ended):void 0}},tl=class e{_underlying;_frozenTime;constructor(e,t){this._underlying=e,this._frozenTime=t}get currentDate(){return this._frozenTime}now(){return this._frozenTime}nowMs(){return this._frozenTime.getTime()}get elapsed(){return this._underlying.elapsed}get isRunning(){return this._underlying.isRunning}get spans(){return this._underlying.spans}start(){return this._underlying.start()}stop(){return this._underlying.stop()}static at(t,n){return new e(t,n)}static now(t){return new e(t,t.currentDate)}},nl=class{_spans=[];get currentDate(){return new Date}now(){return this.currentDate}nowMs(){return this.currentDate.getTime()}get isRunning(){return this._spans.length!==0&&this._spans[this._spans.length-1].isOpen}get spans(){return this._spans}get elapsed(){return this._spans.reduce((e,t)=>e+t.duration,0)}start(){let e=new Date;return this.isRunning?this._spans[this._spans.length-1].startDate:(this._spans.push(new el(e.getTime())),e)}stop(){let e=new Date;return this.isRunning&&(this._spans[this._spans.length-1].ended=e.getTime()),e}reset(){this._spans=[]}},rl={now:()=>new Date,nowMs:()=>Date.now()},il=class{options;now;type=`next`;constructor(e,t=rl){this.options=e,this.now=t}do(e){if(!this.validateRuntimeState(e))return[];let t=e.stack.current;if(!t)return[];try{let n={...e.clock?{clock:tl.now(e.clock)}:void 0,...this.options};return t.next(e,n)}catch(n){return e.errors&&Array.isArray(e.errors)&&e.errors.push({error:n,source:`NextAction`,timestamp:this.now.now(),blockKey:t.key.toString()}),[]}}validateRuntimeState(e){return!!e.stack}},al=class{error;source;context;type=`error`;constructor(e,t,n){this.error=e,this.source=t,this.context=n}do(e){let t=e;t.errors||=[];let n={error:this.error,source:this.source,timestamp:new Date,context:this.context};t.errors.push(n),console.error(`❌ Runtime Error from ${this.source}:`,this.error.message),this.context&&console.error(` Context:`,this.context)}},ol=class{error;source;type=`throw-error`;constructor(e,t){this.error=e,this.source=t}do(e){new al(this.error,this.source).do(e),e.eventBus.dispatch({name:`workout:error`,timestamp:e.clock.currentDate,data:{error:this.error,source:this.source}},e)}};function sl(e,t){return new ol(e,t)}var cl=class{_id;_name;constructor(e){this._id=e,this._name=`next-handler`}get id(){return this._id}set id(e){throw Error(`Cannot modify readonly property id`)}get name(){return this._name}set name(e){throw Error(`Cannot modify readonly property name`)}handler(e,t){return e.name===`next`?!t||!t.stack||t.stack.count===0?[sl(Error(`Invalid runtime state for next event`),`NextEventHandler`)]:[new il(void 0,t.nowProvider)]:[]}},ll=class{type=`abort-session`;do(e){let t=0,n=[];for(;t<100&&e.stack.count>0;){let r=e.stack.current;if(!r)break;!r.isComplete&&typeof r.markComplete==`function`&&r.markComplete(`user-abort`);let i=(r.unmount(e,{createdAt:e.clock.currentDate})??[]).filter(e=>e.type!==`emit-event`);n.push(...i);let a=e.stack.pop();if(!a)break;a.dispose(e),a.context?.release?.(),t++}return n}},ul=class{_id;constructor(e){this._id=e}get id(){return this._id}set id(e){throw Error(`Cannot modify readonly property id`)}get name(){return`abort-handler`}set name(e){throw Error(`Cannot modify readonly property name`)}handler(e,t){return e.name!==`abort`||!t||!t.stack||t.stack.count===0?[]:[new ll]}},dl=class{message;event;blockKey;blockLabel;stackLevel;extra;type=`emit-system-output`;constructor(e,t,n,r,i,a){this.message=e,this.event=t,this.blockKey=n,this.blockLabel=r,this.stackLevel=i,this.extra=a}do(e){let t=e.clock.currentDate,n={event:this.event,blockKey:this.blockKey,blockLabel:this.blockLabel,...this.extra},r={type:q.System,image:this.message,value:n,origin:`runtime`,timestamp:t},i=new ga({outputType:`system`,timeSpan:new el(t.getTime(),t.getTime()),sourceBlockKey:this.blockKey,stackLevel:this.stackLevel??e.stack.count,metrics:[r]});return e.addOutput(i),[]}},fl=class{_runtime;_workList=[];_iteration=0;_maxIterations;_snapshotClock;constructor(e,t=20){this._runtime=e,this._maxIterations=t,this._snapshotClock=tl.at(e.clock,e.clock.currentDate)}get script(){return this._runtime.script}get eventBus(){return this._runtime.eventBus}get stack(){return this._runtime.stack}get options(){return this._runtime.options}get jit(){return this._runtime.jit}get errors(){return this._runtime.errors}get analyticsContext(){return this._runtime.analyticsContext}get clock(){return this._snapshotClock}get nowProvider(){return this._runtime.nowProvider}addOutput(e){this._runtime.addOutput(e)}do(e){this._workList.unshift(e)}doAll(e){e.length!==0&&this._workList.unshift(...e)}handle(e){let t=this.eventBus.dispatch(e,this);if(t.length>0){let n=`source`in e&&typeof e.source==`string`?e.source:`event-bus`,r=new dl(`event: ${e.name} → ${t.length} action(s)`,`event-action`,n,void 0,this.stack.count,{eventName:e.name,actionTypes:t.map(e=>e.type)});this.doAll([r,...t])}else this.doAll(t)}execute(e){for(this._workList.push(e);this._workList.length>0;){if(this._iteration>=this._maxIterations)throw Error(`[ExecutionContext] Max iterations reached (${this._maxIterations}). Aborting to prevent infinite loop.`);let e=this._workList.shift();this._iteration++;let t=e.do(this);t&&t.length>0&&this._workList.unshift(...t)}}},pl=e=>String(e).padStart(2,`0`),ml=e=>String(e).padStart(3,`0`);function hl(e){return`${pl(e.getHours())}:${pl(e.getMinutes())}:${pl(e.getSeconds())}.${ml(e.getMilliseconds())}`}function gl(e){return(e+` `).slice(0,5)}function _l(e){return(e+` `.repeat(24)).slice(0,24)}function vl(e){if(!e)return`─`.repeat(52);let t=` ${e} `,n=Math.max(0,Math.floor((52-t.length)/2)),r=Math.max(0,52-t.length-n);return`${`─`.repeat(n)}${t}${`─`.repeat(r)}`}var yl=class{_console=console;_enabled=!1;_history=[];_maxHistory=500;EVENT_STYLES={BOOT:`color: #3b82f6; font-weight: bold`,PUSH:`color: #a855f7; font-weight: bold`,POP:`color: #64748b`,NEXT:`color: #b45309; font-weight: bold`,EVNT:`color: #a855f7; font-weight: bold`,OUT:`color: #16a34a; font-weight: bold`,MEM:`color: #f59e0b`,TIME:`color: #3b82f6; font-weight: bold`,HALT:`color: #ef4444; font-weight: bold`,WARN:`color: #f59e0b; font-weight: bold`,ERR:`color: #ef4444; font-weight: bold`};constructor(){if(typeof window<`u`){let e=window;this._enabled=!!e.__WOD_DEBUG__}}get enabled(){return this._enabled}enable(){this._enabled=!0,this.writeLine(`BOOT`,`runtime:ready`,`logging enabled`)}disable(){this.writeLine(`HALT`,`runtime:logger`,`logging disabled`),this._enabled=!1}getHistory(){return[...this._history]}clearHistory(){this._history=[]}logBoot(e){this._enabled&&this.writeLine(`BOOT`,`runtime:ready`,e)}logPush(e,t,n){if(!this._enabled)return;let r=this.getBehaviorNames(e),i=[`d${n??`?`} ${e.blockType??`block`}`,r.length>0?`behaviors [${r.join(`, `)}]`:void 0,t?`parent ${t.slice(0,8)}`:void 0].filter(Boolean).join(` · `);this.writeLine(`PUSH`,e.label||e.blockType||`Block`,i),this.addToHistory(`info`,`push`,`PUSH ${e.label}`,{key:e.key.toString(),parentKey:t,behaviors:r,sourceIds:e.sourceIds})}logPop(e,t,n){this._enabled&&(this.writeLine(`POP`,e.label||e.blockType||`Block`,`d${n??`?`}${t?` `+t:``}`),this.addToHistory(`info`,`pop`,`POP ${e.label}`,{key:e.key.toString(),reason:t}))}logNext(e,t){if(!this._enabled||t.length===0)return;let n=t.map(e=>e.type||e.constructor?.name||`Action`);this.writeLine(`NEXT`,e.label||`Block`,`${n.length} action(s): [${n.join(`, `)}]`),this.addToHistory(`info`,`next`,`NEXT ${e.label}`,{key:e.key.toString(),actions:n})}logEvent(e,t){if(!this._enabled||t.length===0)return;let n=t.map(e=>e.type||e.constructor?.name||`Action`);this.writeLine(`EVNT`,e.name,`${n.length} action(s): [${n.join(`, `)}]`),this.addToHistory(`info`,`event`,`EVENT ${e.name}`,{eventName:e.name,eventData:e.data,actions:n})}logOutput(e){if(!this._enabled||e.outputType!==`segment`&&e.outputType!==`milestone`)return;let t=e.text||this.outputSubject(e.metrics);t&&(this.writeLine(`OUT`,t,e.outputType),this.addToHistory(`info`,`output`,`OUT ${t}`,{outputType:e.outputType,label:t}))}outputSubject(e){if(e){for(let t of e)if(t.type===`label`)return t.image||(t.value==null?``:String(t.value))||void 0}}logMemoryUpdate(e,t,n){if(!this._enabled)return;let r=typeof n==`object`&&n?this.summarizeObject(n):n;this.writeLine(`MEM`,t,`[${e.slice(0,8)}] ${bl(r)}`),this.addToHistory(`debug`,`memory`,`MEMORY ${t}`,{blockKey:e,memoryType:t,value:r})}logAction(e,t){if(!this._enabled)return;let n=e.type||e.constructor?.name||`Action`;this.writeLine(`EVNT`,n,`d${t}`)}logMessage(e,t,n,r){this._enabled&&(this.writeLine(e===`error`?`ERR`:e===`warn`?`WARN`:`EVNT`,t,n),this.addToHistory(e,t,n,r))}logAlways(e,t,n,r){this.writeLine(e===`error`?`ERR`:e===`warn`?`WARN`:`EVNT`,t,n),this.addToHistory(e,t,n,r)}logRule(e){this._enabled&&this._console.log(`%c${vl(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=hl(new Date);this._console.log(`${r} %c${gl(e)}%c ${_l(t)}${n?` `+n:``}`,this.EVENT_STYLES[e],`color: inherit`)}getBehaviorNames(e){let t=e.behaviors;return!t||!Array.isArray(t)?[]:t.map(e=>e.constructor?.name||`Behavior`)}summarizeObject(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?`[${r.length} items]`:typeof r==`object`&&r?`{...}`:r;return t}addToHistory(e,t,n,r){this._history.push({timestamp:new Date,level:e,category:t,message:n,data:r}),this._history.length>this._maxHistory&&(this._history=this._history.slice(-this._maxHistory))}};function bl(e){try{return JSON.stringify(e)??``}catch{return String(e)}}var xl=new yl;typeof window<`u`&&(window.RuntimeLogger=xl);var Sl=class{_outputStatements=[];_outputListeners=new Set;_analyticsEngine=null;_analyticsFinalized=!1;_liveAnalytics=[];_clock=null;_stack=null;_script=null;attach(e){this._clock=e.clock,this._stack=e.stack,this._script=e.script}_requireClock(){if(!this._clock)throw Error(`[OutputEmitter] emission helper called before attach() — clock is not wired`);return this._clock}add(e){if(e.outputType===`system`&&this._outputListeners.size===0)return;let t=this._analyticsEngine?this._analyticsEngine.run(e):e;this._propagateSourceLine(t),xl.logOutput(t),this._outputStatements.push(t);for(let e of this._outputListeners)try{e(t)}catch(e){console.error(`[OutputEmitter] Listener error:`,e)}}subscribe(e){this._outputListeners.add(e);let t=[...this._outputStatements];return t.length>0&&setTimeout(()=>{if(this._outputListeners.has(e))for(let n of t)e(n)},0),()=>this._outputListeners.delete(e)}getAll(){return[...this._outputStatements]}hasListeners(){return this._outputListeners.size>0}setAnalyticsEngine(e){this._analyticsEngine=e,e.setLiveOutputEmitter(e=>this.emitLiveAnalytics(e))}finalizeAnalytics(){if(!this._analyticsEngine||this._analyticsFinalized)return[];this._analyticsFinalized=!0;let e=this._analyticsEngine.finalize(),t=e.length>0?e:this._liveAnalytics;for(let e of t){this._outputStatements.push(e);for(let t of this._outputListeners)try{t(e)}catch(e){console.error(`[OutputEmitter] Finalize listener error:`,e)}}return this._liveAnalytics=[],t}emitLiveAnalytics(e){this._liveAnalytics=e;for(let t of e)for(let e of this._outputListeners)try{e(t)}catch(e){console.error(`[OutputEmitter] Live analytics listener error:`,e)}}getLiveAnalytics(){return[...this._liveAnalytics]}dispose(){this._outputStatements=[],this._outputListeners.clear(),this._analyticsFinalized=!1,this._liveAnalytics=[]}emitLoad(){if(!this._script)throw Error(`[OutputEmitter] emitLoad() called before attach() — script is not wired`);let e=this._script,t=this._requireClock().currentDate;for(let n of e.statements){let r=e.source.substring(n.meta.startOffset,n.meta.endOffset+1),i=J.from(n.metrics,n.id);i.add({type:q.Label,image:r||`Statement`,value:r,origin:`runtime`,timestamp:t});let a=0,o=n.parent,s=new Set;for(;o!==void 0&&!s.has(o);){s.add(o);let t=e.getId(o);if(t)a++,o=t.parent;else break}this.add(new ga({outputType:`load`,timeSpan:new el(t.getTime(),t.getTime()),sourceBlockKey:`root`,sourceStatementId:n.id,stackLevel:a,metrics:i}))}}emitStackEvent(e){if(!this.hasListeners())return;let t=this._requireClock().currentDate,n=e.block,r=this._stack?.blocks??[],i={event:e.type,blockKey:n.key.toString(),blockLabel:n.label,actionType:e.type===`push`?`push-block`:`pop-block`};if(e.type===`push`){let e=r.length>1?r[1]:void 0;e&&(i.parentKey=e.key.toString())}else i.completionReason=n.completionReason??`normal`;let a={type:q.System,image:e.type===`push`?`push: ${n.label??n.blockType??`Block`} [${n.key.toString().slice(0,8)}]`:`pop: ${n.label??n.blockType??`Block`} [${n.key.toString().slice(0,8)}] reason=${n.completionReason??`normal`}`,value:i,origin:`runtime`,timestamp:t};this.add(new ga({outputType:`system`,timeSpan:new el(t.getTime(),t.getTime()),sourceBlockKey:n.key.toString(),stackLevel:e.depth,metrics:J.empty(n.key.toString()).add(a)}))}emitSegmentFromResultMemory(e,t){let n=e.getMemoryByTag(`metric:result`),r=e.getMemoryByTag(`metric:display`);if(n.length===0)return;let i=this._requireClock().currentDate.getTime();for(let a=0;a<n.length;a++){let o=J.from(n[a].metrics,e.key.toString()),s=J.from(r[a]?.metrics,e.key.toString()),c=J.empty(e.key.toString()).add(...s.toArray()).add(...o.toArray());if(c.length===0)continue;let l=new el(e.executionTiming?.startTime?.getTime()??i,i);this.add(new ga({outputType:`segment`,completionReason:e.completionReason,timeSpan:l,sourceBlockKey:e.key.toString(),sourceStatementId:e.sourceIds?.[a]??e.sourceIds?.[0],stackLevel:t,metrics:c}))}}emitRuntimeEvent(e){let t=this._requireClock().currentDate,n=this._stack,r=n?.current?.key.toString()??`root`,i=J.empty(r).add({type:q.System,image:`event: ${e.name}`,value:{name:e.name,data:e.data,blockKey:r},origin:`runtime`,timestamp:t});this.add(new ga({outputType:`event`,timeSpan:new el(t.getTime(),t.getTime()),sourceBlockKey:r,stackLevel:n?.count??0,metrics:i}))}emitCompilerBlock(e){let t=this._requireClock().currentDate,n=this._stack?.count??0,r=J.empty(e.key.toString()).add({type:q.Label,image:`Behaviors: ${e.behaviors.map(e=>e.constructor.name).join(`, `)}`,value:e.behaviors.map(e=>e.constructor.name),origin:`runtime`,timestamp:t});this.add(new ga({outputType:`compiler`,timeSpan:new el(t.getTime(),t.getTime()),sourceBlockKey:e.key.toString(),stackLevel:n,metrics:r}))}_propagateSourceLine(e){if(e.sourceStatementId===void 0||e.line!==void 0)return;let t=this._script?.getId(e.sourceStatementId);t&&(e.line=t.line,e.text??=t.text,e.dialect??=t.dialect)}},Cl=class{_stackObservers=new Set;_logger;constructor(e){this._logger=e}subscribeToStack(e){return this._stackObservers.add(e),()=>{this._stackObservers.delete(e)}}emitStack(e){if(this._stackObservers.size!==0)for(let t of this._stackObservers)try{t(e)}catch(e){this._logger?.error?.(`[RuntimeObservers] Stack observer error:`,e)}}hasStackObserver(e){return this._stackObservers.has(e)}emitSettled(e,t,n){if(this._stackObservers.size===0||e.length===0)return;let r={type:`initial`,blocks:e,depth:t,clockTime:n};this.emitStack(r)}dispose(){this._stackObservers.clear()}get stackObserverCount(){return this._stackObservers.size}},wl=class{block;options;_type=`push-block`;constructor(e,t={}){this.block=e,this.options=t}get type(){return this._type}set type(e){throw Error(`Cannot modify readonly property type`)}do(e){if(!e.stack)return[];try{let t=this.options.startTime,n=this.options.clock??e.clock;!t&&n?.isRunning&&(t=n.currentDate);let r=t?{...this.options,startTime:t}:{...this.options},i=this.block;t&&(i.executionTiming={...i.executionTiming??{},startTime:t}),e.stack.push(this.block);let a=this.block.mount(e,r),o=e.stack.blocks.length>1?e.stack.blocks[1]?.key.toString():void 0;return xl.logPush(this.block,o,e.stack.blocks.length),a}catch(t){let n=e;return typeof n.setError==`function`&&n.setError(t),[]}}},Tl=class{options;type=`pop-block`;constructor(e={}){this.options=e}do(e){let t=e.stack.current;if(!t)return[];let n=this.options.createdAt??e.clock.currentDate,r={...this.options,createdAt:n};t.executionTiming&&(t.executionTiming.createdAt=n),!t.isComplete&&typeof t.markComplete==`function`&&(t.markComplete(`forced-pop`),xl.logPop(t,`forced-pop (incomplete block popped without next)`,e.stack.blocks.length));let i=t.unmount(e,r)??[],a=e.stack.pop();return a?(a.dispose(e),a.context?.release?.(),a.completionReason!==`forced-pop`&&xl.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new il(r,e.nowProvider)]:i):[]}},El=class{script;eventBus;clock;stack;jit;errors=[];options;analyticsContext;_output=new Sl;_observers;_activeContext=null;_now;_stackSubscriptionUnsub=null;_nextHandlerUnsub=null;get nowProvider(){return this._now}_abortHandlerUnsub=null;constructor(e,t,n,r={},i=rl){this.script=e,this.options={...$c,...r},this._observers=new Cl(this.options.logger),this.stack=n.stack,this.clock=n.clock,this.eventBus=n.eventBus,this._now=i,this._nextHandlerUnsub=this.eventBus.register(`next`,new cl(`runtime-next-handler`),`runtime`,{scope:`global`}),this._abortHandlerUnsub=this.eventBus.register(`abort`,new ul(`runtime-abort-handler`),`runtime`,{scope:`global`}),this.jit=t,this._output.attach({clock:this.clock,stack:this.stack,script:this.script}),this._stackSubscriptionUnsub=this.stack.subscribe(e=>{e.type===`pop`&&this._output.emitSegmentFromResultMemory(e.block,e.depth),(e.type===`push`||e.type===`pop`)&&this._output.emitStackEvent(e);let t={type:e.type===`initial`?`initial`:e.type,blocks:(e.type,e.blocks),affectedBlock:e.type===`initial`?void 0:e.block,depth:e.type===`initial`?e.blocks.length:e.depth,clockTime:this.clock.currentDate};this._observers.emitStack(t)}),this.clock.start(),this._output.emitLoad(),xl.logBoot(`statements ${this.script.statements.length}`)}do(e){if(this._activeContext){this._activeContext.do(e);return}this._activeContext=new fl(this,this.options.maxActionDepth??20);try{this._activeContext.execute(e)}finally{this._activeContext=null,this._notifyStackSettled()}}_buildInitialSnapshot(){let e=this.stack.blocks;return{type:`initial`,blocks:e,depth:e.length,clockTime:this.clock.currentDate}}_notifyStackSettled(){this._observers.emitSettled(this.stack.blocks,this.stack.count,this.clock.currentDate)}doAll(e){if(e.length!==0){if(this._activeContext){this._activeContext.doAll(e);return}this.do({type:`composite-doAll`,do:()=>e})}}handle(e){let t=this.eventBus.dispatch(e,this);(e.name!==`tick`||t.length>0)&&this._output.emitRuntimeEvent(e),t.length!==0&&this.doAll(t)}subscribeToOutput(e){return this._output.subscribe(e)}getOutputStatements(){return this._output.getAll()}getLiveAnalytics(){return this._output.getLiveAnalytics()}addOutput(e){this._output.add(e)}setAnalyticsEngine(e){this._output.setAnalyticsEngine(e)}finalizeAnalytics(){return this._output.finalizeAnalytics()}subscribeToStack(e){let t=this._observers.subscribeToStack(e);return setTimeout(()=>{if(this._observers.hasStackObserver(e))try{e(this._buildInitialSnapshot())}catch(e){console.error(`[RT] Stack observer error (initial):`,e)}},0),t}dispose(){for(this.clock.stop();this.stack.count>0;){let e=this.stack.current;if(e){try{e.unmount(this)}catch{}this.stack.pop();try{e.dispose(this)}catch{}}else this.stack.pop()}this._nextHandlerUnsub&&=(this._nextHandlerUnsub(),null),this._abortHandlerUnsub&&=(this._abortHandlerUnsub(),null),this._output.dispose(),this._stackSubscriptionUnsub&&=(this._stackSubscriptionUnsub(),null),this._observers.dispose(),this.eventBus.dispose()}pushBlock(e,t){let n=this.stack.current;this.options.hooks?.onBeforePush?.(e,n),this._output.emitCompilerBlock(e);let r=this.options.wrapper?.wrap?.(e,n)??e;this.do(new wl(r,t)),this.options.logger?.debug?.(`runtime.pushBlock`,{blockKey:e.key.toString(),parentKey:n?.key.toString()}),this.options.hooks?.onAfterPush?.(r,n)}popBlock(e){let t=this.stack.current;t&&(this.options.hooks?.onBeforePop?.(t),this.do(new Tl(e)),this.options.wrapper?.cleanup?.(t),this.options.hooks?.unregisterByOwner?.(t.key.toString()),this.options.logger?.debug?.(`runtime.popBlock`,{blockKey:t.key.toString(),stackDepth:this.stack.count}),this.options.hooks?.onAfterPop?.(t))}},Dl=class{_memory;ownerId;type;visibility;_logger;id=b();_subscriptions=[];constructor(e,t,n,r=`private`,i){this._memory=e,this.ownerId=t,this.type=n,this.visibility=r,this._logger=i}value(){return this.get()}get subscriptions(){return this._subscriptions}get(){return this._memory.get(this)}set(e){this._memory.set(this,e)}subscribe(e,t){let n=b(),r={id:n,callback:e,memoryId:this.id,createdAt:new Date};return this._subscriptions.push(r),t?.immediate&&e(this.get(),void 0),()=>this.unsubscribe(n)}unsubscribe(e){let t=this._subscriptions.findIndex(t=>t.id===e);t>=0&&this._subscriptions.splice(t,1)}hasSubscribers(){return this._subscriptions.length>0}notifySubscribers(e,t){for(let n of this._subscriptions)try{n.callback(e,t)}catch(e){this._logger?.error?.(`Error in memory subscription callback:`,e)}}},Ol=class{_references=[];allocate(e,t,n,r=`private`){let i=new Dl(this,t,e,r);return this._references.push({ref:i,data:n}),i}get(e){return this._references.find(t=>t.ref.id===e.id)?.data??void 0}set(e,t){let n=this._references.find(t=>t.ref.id===e.id);if(!n)throw Error(`Invalid memory reference: ${e.id}`);let r=n.data;n.data=t,e.hasSubscribers()&&e.notifySubscribers(t,r)}search(e){return this._references.map(e=>e.ref).filter(t=>!(e.id!==null&&e.id!==void 0&&e.id!==t.id||e.ownerId!==null&&e.ownerId!==void 0&&e.ownerId!==t.ownerId||e.type!==null&&e.type!==void 0&&e.type!==t.type||e.visibility!==null&&e.visibility!==void 0&&e.visibility!==t.visibility))}release(e){let t=this._references.findIndex(t=>t.ref.id===e.id);if(t>=0){let e=this._references[t],n=e.data,r=e.ref;r instanceof Dl&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}},kl=function(e){return e.DISPLAY_STACK_STATE=`displaystack`,e.ACTION_STACK_STATE=`actions`,e.TIMER_PREFIX=`timer:`,e.HANDLER_PREFIX=`handler:`,e.METRIC_REPS=`metric:reps`,e.ANCHOR=`anchor`,e}({}),Al=class{timestamp;constructor(e=rl){this.timestamp=e.now()}},jl=class extends Al{name=`memory:allocate`;data;constructor(e,t,n=rl){super(n),this.data={ref:e,value:t}}},Ml=class extends Al{name=`memory:set`;data;constructor(e,t,n,r=rl){super(r),this.data={ref:e,value:t,oldValue:n}}},Nl=class extends Al{name=`memory:release`;data;constructor(e,t,n=rl){super(n),this.data={ref:e,lastValue:t}}},Pl=class{runtime;ownerId;exerciseId;_references=[];_released=!1;_memory;constructor(e,t,n=``,r=[],i){this.runtime=e,this.ownerId=t,this.exerciseId=n,this._references=[...r],this._memory=i??new Ol}get references(){return[...this._references]}allocate(e,t,n=`private`){if(this._released)throw Error(`Cannot allocate on released context (ownerId: ${this.ownerId})`);let r=e,i=this._memory.allocate(r,this.ownerId,t,n);return this._references.push(i),this.runtime.eventBus.dispatch(new jl(i,t,this.runtime.nowProvider),this.runtime),i}get(e){let t=e;return this._references.find(e=>e.type===t)}getAll(e){let t=e;return this._references.filter(e=>e.type===t)}set(e,t){if(this._released)throw Error(`Cannot set on released context (ownerId: ${this.ownerId})`);let n=e.get();this._memory.set(e,t),this.runtime.eventBus.dispatch(new Ml(e,t,n,this.runtime.nowProvider),this.runtime)}release(){if(!this._released){for(let e of this._references){let t=e.value();this._memory.release(e),this.runtime.eventBus.dispatch(new Nl(e,t,this.runtime.nowProvider),this.runtime)}this._references=[],this._released=!0}}isReleased(){return this._released}getOrCreateAnchor(e){if(this._released)throw Error(`Cannot access anchor on released context (ownerId: ${this.ownerId})`);let t;for(let n of this.runtime.stack.blocks){let r=n.context.references.find(t=>t.id===e&&t.type===kl.ANCHOR);if(r){t=r;break}}if(t)return this._references.find(e=>e.id===t.id)||this._references.push(t),t;let n=this._memory.allocate(kl.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}},Fl=class{tag;_listeners=new Set;_metrics;_isDisposed=!1;constructor(e,t=J.empty()){this.tag=e,this._metrics=J.from(t,e)}get metrics(){return this._metrics}update(e){if(this._isDisposed){console.warn(`Attempted to update disposed MemoryLocation with tag '${this.tag}'`);return}let t=this._metrics;this._metrics=J.from(e,this.tag);for(let e of this._listeners)e(this._metrics,t)}subscribe(e){return this._isDisposed?(console.warn(`Attempted to subscribe to disposed MemoryLocation with tag '${this.tag}'`),()=>{}):(this._listeners.add(e),()=>this._listeners.delete(e))}dispose(){if(this._isDisposed)return;this._isDisposed=!0;let e=this._metrics;this._metrics=J.empty(this.tag);for(let t of this._listeners)t(this._metrics,e);this._listeners.clear()}},Il=class{block;clock;stackLevel;runtime;subscriptions=[];_capabilities;constructor(e,t,n,r,i){this.block=e,this.clock=t,this.stackLevel=n,this.runtime=r,this._capabilities=i??new Set}subscribe(e,t,n){let r=this,i={id:`behavior-${this.block.key.toString()}-${e}-${Date.now()}`,name:`BehaviorHandler-${this.block.label}-${e}`,handler:(e,n)=>t(e,Object.create(r,{clock:{value:n.clock,enumerable:!0,configurable:!0}}))},a=this.runtime.eventBus.register(e,i,this.block.key.toString(),{scope:n?.scope??`active`});return this.subscriptions.push({eventType:e,unsubscribe:a}),a}emitEvent(e){this.runtime.handle(e)}emitOutput(e,t,n){let r=this.clock.currentDate,i=this.block.getMemoryByTag(`time`),a=r.getTime(),o=r.getTime(),s=[];if(i.length>0){let e=i[0].metrics;if(e.length>0){let t=e[0].value;t?.spans&&t.spans.length>0&&(s=[...t.spans],a=s[0].started)}}let c=J.from(t,this.block.key.toString());if(c.length===0){let e=this.block.getMemoryByTag(`metric:display`);e.length>0&&(c=e[0].metrics.clone(this.block.key.toString()))}let l=c.map(e=>({...e,sourceBlockKey:e.sourceBlockKey??this.block.key.toString(),timestamp:e.timestamp??r})),u=new ga({outputType:e,timeSpan:new el(a,o),spans:s.length>0?s:void 0,sourceBlockKey:this.block.key.toString(),sourceStatementId:this.block.sourceIds?.[0],stackLevel:this.stackLevel,metrics:l,completionReason:n?.completionReason});this.addOutputToRuntime(u)}addOutputToRuntime(e){this.runtime.addOutput(e)}pushMemory(e,t){let n=new Fl(e,t);return this.block.pushMemory(n),n}getMemoryByTag(e){return this.block.getMemoryByTag(e)}updateMemory(e,t){let n=this.block.getMemoryByTag(e);n.length>0&&n[0].update(t)}declareCapability(e){this._capabilities.add(e)}hasCapability(e){return this._capabilities.has(e)}getCapabilities(){return this._capabilities}markComplete(e){this.block.markComplete(e)}dispose(){for(let{unsubscribe:e}of this.subscriptions)try{e()}catch(e){this.runtime.options.logger?.error?.(`[BehaviorContext] Unsubscribe error:`,e)}this.subscriptions=[]}},Ll=new Set([`metric:display`]),Rl=new Set([`metric:result`]),zl=new Set([`metric:promote`,`metric:rep-target`]),Bl=new Set([`metric:tracked`,`metric:label`,`metric:next`]);function Vl(e){if(Ll.has(e))return`display`;if(Rl.has(e))return`result`;if(zl.has(e))return`promote`;if(Bl.has(e)||e.startsWith(`metric:`))return`private`}var Hl={display:`Display`,result:`Result`,promote:`Promote`,private:`Private`},Ul=class{behaviors=[];key;blockType;context;sourceIds;tagComposition;_memory=[];get label(){for(let e of this._memory)for(let t of e.metrics)if(t.type===q.Label)return t.image||t.value?.toString()||this.blockType||`Block`;return this.blockType||`Block`}_behaviorContext;executionTiming={};_isComplete=!1;_completionReason;_eventUnsubscribers=[];_runtime;constructor(e){let{runtime:t,sourceIds:n=[],behaviors:r=[],context:i,key:a,blockType:o,label:s,metrics:c,tagComposition:l}=e;if(this._runtime=t,this.sourceIds=n,this.behaviors=r,this.key=a??new _a,this.blockType=o,this.tagComposition=l,this.context=i??new Pl(t,this.key.toString()),s&&this._memory.push(new Fl(`metric:label`,[{type:q.Label,image:s,origin:`compiler`,value:s}])),c)for(let e of c)this._memory.push(new Fl(`metric:display`,e))}pushMemory(e){this._memory.push(e)}mergeHints(e){if(!e||Object.keys(e).length===0)return;let t=this._memory.find(e=>e.tag===`metric:hint`),n=Object.entries(e).map(([e,t])=>({type:q.Hint,value:e,image:e,origin:`compiler`,timestamp:new Date}));if(t){let e=new Set(n.map(e=>e.value)),r=t.metrics.toArray().filter(t=>!(t.type===q.Hint&&e.has(t.value)));t.update([...r,...n])}else this._memory.push(new Fl(`metric:hint`,n))}getMemoryByTag(e){return this._memory.filter(t=>t.tag===e)}getAllMemory(){return[...this._memory]}getMetricMemoryByVisibility(e){return this._memory.filter(t=>Vl(t.tag)===e)}registerDefaultHandler(){}mount(e,t){this._runtime=e;let n=t?.clock??e.clock;this.executionTiming.startTime=t?.startTime??n.currentDate,this.registerDefaultHandler();let r=Math.max(0,e.stack.count-1);this._behaviorContext=new Il(this,n,r,e);let i=[];for(let e of this.behaviors)if(e.onMount){let t=e.onMount(this._behaviorContext);t&&i.push(...t)}return i}inspectNext(e,t){if(!this._behaviorContext)return{complete:!1,actions:[]};let n=t?.clock??this._behaviorContext.clock,r=new Il(this,n,this._behaviorContext.stackLevel,e,this._behaviorContext.getCapabilities()),i=this._isComplete,a=this._completionReason;for(let e of this.behaviors){let t=e;typeof t.prepareForNextCycle==`function`&&t.prepareForNextCycle()}let o=[];for(let e of this.behaviors)if(e.onNext){let t=e.onNext(r);t&&o.push(...t)}r.dispose(),this._isComplete&&!o.some(e=>e.type===`pop-block`)&&o.push(new Tl);let s={complete:this._isComplete,reason:this._completionReason,actions:o};return this._isComplete=i,this._completionReason=a,s}next(e,t){if(!this._behaviorContext)return xl.logAlways(`warn`,`RuntimeBlock`,`next() called before mount()`),[];let n=t?.clock??this._behaviorContext.clock;this.emitNextSystemOutput(e,n);let r=this.inspectNext(e,t);return r.complete&&!this._isComplete&&this.markComplete(r.reason),xl.logNext(this,[...r.actions]),r.actions}unmount(e,t){let n=t?.clock??e.clock;this.executionTiming.endTime=t?.createdAt??n.currentDate;let r=[],i=new Il(this,n,this._behaviorContext?.stackLevel??0,e,this._behaviorContext?.getCapabilities());for(let e of this.behaviors)if(e.onUnmount){let t=e.onUnmount(i);t&&r.push(...t)}i.dispose();let a=e.eventBus.dispatch({name:`unmount`,timestamp:e.clock.currentDate,data:{blockKey:this.key.toString()}},e);a.length>0&&r.push(...a);for(let e of this._eventUnsubscribers)try{e()}catch(e){xl.logAlways(`error`,`RuntimeBlock`,`Error unsubscribing event handler`,{error:e})}return this._eventUnsubscribers=[],this._behaviorContext&&=(this._behaviorContext.dispose(),void 0),r}dispose(e){let t=this._behaviorContext??new Il(this,e.clock,0,e);for(let e of this.behaviors)e.onDispose&&e.onDispose(t);!this._behaviorContext&&t&&t.dispose();for(let e of this._memory)e.dispose();this._memory=[]}get isComplete(){return this._isComplete}get completionReason(){return this._completionReason}markComplete(e){this._isComplete=!0,this._completionReason=e}getBehavior(e){return this.behaviors.find(t=>t instanceof e)}emitNextSystemOutput(e,t){let n=t.currentDate,r={event:`next`,blockKey:this.key.toString(),blockLabel:this.label,actionType:`next`},i={type:q.System,image:`next: ${this.label??this.blockType??`Block`} [${this.key.toString().slice(0,8)}]`,value:r,origin:`runtime`,timestamp:n},a=new ga({outputType:`system`,timeSpan:new el(n.getTime(),n.getTime()),sourceBlockKey:this.key.toString(),stackLevel:e.stack.count,metrics:[i]});e.addOutput(a)}},Wl=class{_blocks=[];_listeners=new Set;get blocks(){return[...this._blocks].reverse()}get count(){return this._blocks.length}get current(){if(this._blocks.length!==0)return this._blocks[this._blocks.length-1]}get keys(){return this.blocks.map(e=>e.key)}push(e){this._blocks.push(e),this.notify({type:`push`,block:e,depth:this._blocks.length,blocks:this.blocks})}pop(){let e=this._blocks.pop();return e&&this.notify({type:`pop`,block:e,depth:this._blocks.length,blocks:this.blocks}),e}clear(){for(;this._blocks.length>0;)this.pop()}subscribe(e){return this._listeners.add(e),e({type:`initial`,blocks:this.blocks}),()=>{this._listeners.delete(e)}}notify(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`Error in stack listener:`,e)}}};function Gl(){if(typeof window<`u`){let e=window.__chromecast_senderClockTimeMs;if(typeof e==`function`)try{let t=e();if(Number.isFinite(t))return t}catch{}}return Date.now()}var Kl=class{completionTime;wasComplete=!1;onMount(e){return[]}onNext(e){if(e.block.isComplete&&!this.wasComplete&&!this.completionTime){this.completionTime=new Date(e.clock.currentDate),this.wasComplete=!0;let t={type:q.SystemTime,image:this.completionTime.toISOString(),origin:`runtime`,value:{createdAt:this.completionTime.getTime(),timestamp:this.completionTime},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};e.pushMemory(`completion`,[t])}return[]}onUnmount(e){return[]}onDispose(e){}getCompletionTime(){return this.completionTime}},ql=`time`;function Jl(e){return[new el(e)]}function Yl(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new el(n.started,t):n)}function Xl(e,t){return[...e,new el(t)]}function Zl(e){return e.getMemoryByTag(ql)[0]?.metrics[0]?.value}function Ql(e,t){let n=e.getMemoryByTag(ql)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(ql,[{...n,value:{...r,spans:i}}]),!0}var $l=class{onMount(e){let t=e.clock.currentDate.getTime(),n=e.block.label,r={type:q.Time,image:`0:00`,origin:`runtime`,value:{spans:Jl(t),direction:`up`,durationMs:void 0,label:n,role:`hidden`},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};return e.pushMemory(`time`,[r]),[]}onNext(e){return[]}onUnmount(e){let t=Zl(e);return!t||t.spans.length===0||Ql(e,Yl),[]}onDispose(e){}},eu=class{config;constructor(e={}){this.config=e}subscriptions=[];isPaused=!1;onMount(e){let t=e.clock.currentDate.getTime(),n=this.config.label??e.block.label,r=this.config.role===`hidden`?`auto`:this.config.role??`primary`;return e.pushMemory(`time`,[this.createFragment(e,{spans:Jl(t),direction:`up`,durationMs:void 0,label:n,role:r})]),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||Ql(t,Yl)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&Ql(t,Xl)&&(this.isPaused=!1),[]))),[]}onNext(e){return[]}onUnmount(e){return Ql(e,Yl),[]}onDispose(e){for(let e of this.subscriptions)try{e()}catch{}this.subscriptions.length=0}createFragment(e,t){return{type:q.Time,image:`0:00`,origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}},tu=class{targetBlockKey;type=`clear-children`;constructor(e){this.targetBlockKey=e}do(e){let t=[],n=0;for(;n<20;){let r=e.stack.current;if(!r||r.key.toString()===this.targetBlockKey)break;let i=new Tl().do(e);for(let e of i)e.type!==`next`&&t.push(e);n++}return n>=20&&e.options.logger?.error?.(`[ClearChildrenAction] Max iterations reached, possible infinite loop`,Error(`Exceeded 20 pop iterations for target ${this.targetBlockKey}`)),e.stack.current?.key.toString()===this.targetBlockKey&&t.push(new il(void 0,e.nowProvider)),t}};function nu(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function ru(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var iu=class{current;total;sourceBlockKey;timestamp;type=q.CurrentRound;origin=`tracked`;value;image;constructor(e,t,n,r,i){this.current=e,this.total=t,this.sourceBlockKey=n,this.timestamp=r,this.value=e,this.image=i??(t===void 0?`Round ${e}`:`Round ${e} of ${t}`)}},au=class{config;constructor(e){this.config=e}subscriptions=[];isPaused=!1;onMount(e){let t=e.clock.currentDate.getTime(),n=this.config.label??e.block.label,r=this.config.role===`hidden`?`auto`:this.config.role??`primary`,i=this.config.mode??`complete-block`;return e.pushMemory(`time`,[this.createFragment(e,{spans:Jl(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new tu(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>{let n=Zl(t);return!n||n.direction!==`down`||n.durationMs===void 0||i===`complete-block`&&t.block.isComplete||nu(n,t.clock.currentDate.getTime())<n.durationMs?[]:(this.handleExpiry(t,i),[new tu(t.block.key.toString())])},{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&Ql(t,(e,t)=>Jl(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||Ql(t,Yl)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&Ql(t,Xl)&&(this.isPaused=!1),[]))),[])}onNext(e){if(this.config.required&&!e.block.isComplete)return e.emitEvent({name:`timer:skip-attempt`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),[];if(e.hasCapability(`childSelection`)||!this.config.restBlockFactory)return[];let t=Zl(e);if(!t||t.direction!==`down`||!t.durationMs)return[];let n=this.getRemainingCountdownMs(e);return n>1e3?this.config.restBlockFactory(n,`Rest`):[]}onUnmount(e){return Ql(e,Yl),[]}onDispose(e){for(let e of this.subscriptions)try{e()}catch{}this.subscriptions.length=0}handleExpiry(e,t){if(e.emitEvent({name:`timer:complete`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),t===`complete-block`)e.markComplete(`timer-expired`);else{if(Ql(e,(e,t)=>Jl(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new iu(t.current+1,t.total,e.block.key.toString(),e.clock.currentDate);e.updateMemory(`round`,[n])}let n=e.getMemoryByTag(`children:status`)[0],r={childIndex:0,totalChildren:n?.metrics[0]?.value?.totalChildren??0,allExecuted:!1,allCompleted:!1};n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:r}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:r}])}}getRemainingCountdownMs(e){let t=Zl(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=nu(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:q.Time,image:ou(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function ou(e){if(!e||e===0)return`0:00`;let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`:`${r}:${i.toString().padStart(2,`0`)}`}var su=class{config;_repScheme;_lastPromotedRound;constructor(e){this.config=e,this._repScheme=[...e.repScheme??[]]}get repScheme(){return this._repScheme}getRepsForRound(e){if(this._repScheme.length===0)return;let t=(e-1)%this._repScheme.length;return this._repScheme[t]}getRepsForCurrentRound(){return this._lastPromotedRound===void 0?this._repScheme[0]:this.getRepsForRound(this._lastPromotedRound)}getPromotedFragments(e,t){let n=J.empty(t.key.toString());if(this._repScheme.length>0){let r=t.getMemoryByTag(`round`)[0]?.metrics[0]?.current??1,i=this.getRepsForRound(r);i!==void 0&&n.add({type:q.Rep,image:i.toString(),origin:`compiler`,value:i,sourceBlockKey:t.key.toString(),timestamp:e.clock.currentDate})}for(let e of this.config.promotions){let r=this.findSourceFragmentInBlock(t,e);r&&n.add({...r,origin:e.origin??`compiler`})}return n}onMount(e){if(this._repScheme.length>0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0]?.current??1;this.promoteRepScheme(e,t)}return this.promoteFragments(e,this.config.promotions),[]}onNext(e){if(this._repScheme.length>0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];t&&t.current!==this._lastPromotedRound&&this.promoteRepScheme(e,t.current)}let t=this.config.promotions.filter(e=>e.enableDynamicUpdates);return this.promoteFragments(e,t),[]}onUnmount(e){return[]}onDispose(e){}promoteFragments(e,t){for(let n of t){let t=this.findSourceFragment(e,n);if(!t)continue;let r={...t,origin:n.origin??`runtime`};this.upsertPromotedFragment(e,r)}}promoteRepScheme(e,t){let n=this.getRepsForRound(t);if(n===void 0)return;this._lastPromotedRound=t;let r={type:q.Rep,image:n.toString(),origin:`runtime`,value:n,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};e.block.getMemoryByTag(`metric:rep-target`).length>0?e.updateMemory(`metric:rep-target`,[r]):e.pushMemory(`metric:rep-target`,[r])}findSourceFragment(e,t){return this.findSourceFragmentInBlock(e.block,t)}findSourceFragmentInBlock(e,t){let n=e.getAllMemory();for(let e of n){if(e.tag===`metric:promote`||e.tag===`metric:rep-target`||t.sourceTag&&e.tag!==t.sourceTag)continue;let n=e.metrics.find(e=>e.type===t.metricType);if(n)return n}}upsertPromotedFragment(e,t){let n=e.block.getMemoryByTag(`metric:promote`);if(n.length===0){e.pushMemory(`metric:promote`,[t]);return}let r=n[0].metrics.filter(e=>e.type!==t.type);e.updateMemory(`metric:promote`,[...r,t])}},cu=class{config;unsubscribers=[];constructor(e){this.config={mode:e.mode,onNext:e.onNext??e.mode===`immediate`,onEvents:e.onEvents??[]}}onMount(e){if(this.config.mode!==`immediate`)return[];for(let t of this.config.onEvents){let n=e.subscribe(t,(e,t)=>(t.markComplete(`event:${e.name}`),[new Tl]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new Tl]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new Tl]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},lu=class{config;constructor(e={}){this.config=e}onMount(e){let t=this.createStaticLabels(e),n=this.createRoundLabel(e),r=t.clone();return n&&r.add(n),r.length>0&&e.pushMemory(`display`,r.toArray()),[]}onNext(e){let t=this.createRoundLabel(e);if(!t)return[];let n=e.block.getMemoryByTag(`display`);if(n.length===0)return e.pushMemory(`display`,[t]),[];let r=n[0].metrics.filter(e=>!this.isRoundRoleFragment(e));return e.updateMemory(`display`,[...r,t]),[]}onUnmount(e){return[]}onDispose(e){}createStaticLabels(e){let t=this.config.label??e.block.label,n=this.config.subtitle,r=this.config.actionDisplay,i=J.empty(e.block.key.toString());return t&&i.add(this.createTextMetric(e,t,`label`)),n&&i.add(this.createTextMetric(e,n,`subtitle`)),r&&i.add(this.createTextMetric(e,r,`action`)),i}createRoundLabel(e){if(this.config.showRoundDisplay===!1)return;let t=e.block.getMemoryByTag(`round`)[0];if(!t||t.metrics.length===0)return;let n=t.metrics[0];if(!n||typeof n.current!=`number`)return;let r=this.formatRound(n.current,n.total);return this.createTextMetric(e,r,`round`)}createTextMetric(e,t,n){return{type:q.Text,image:t,origin:`runtime`,value:{text:t,role:n},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}formatRound(e,t){return this.config.roundFormat?this.config.roundFormat(e,t):typeof t==`number`?`Round ${e} of ${t}`:`Round ${e}`}isRoundRoleFragment(e){return e.value?.role===`round`}},uu=class{blockKey;nextStatementIds;type=`update-next-preview`;target;payload;constructor(e,t){this.blockKey=e,this.nextStatementIds=t,this.target=e,this.payload={nextStatementIds:t}}do(e){let t=e.stack.blocks.find(e=>e.key.toString()===this.blockKey);if(!t)return[];let n=t.getMemoryByTag(`metric:next`);if(this.nextStatementIds.length===0){for(let e of n)e.update([]);return[]}let r=e.script;if(!r)return[];let i=J.empty(this.blockKey);for(let e of this.nextStatementIds){let t=r.getId(e);t&&i.merge(t.metrics)}if(i.removeByType(q.Hint),i.length===0){for(let e of n)e.update([]);return[]}return n.length>0?n[0].update(i):t.pushMemory(new Fl(`metric:next`,i)),[]}},du=`effort-data`;cc.defaultMet;function fu(e){return!!e&&typeof e==`object`&&`effort`in e&&`met`in e&&`disciplineFactor`in e}function pu(e){if(fu(e))return e;let t=e,n=t.baseAttributes.discipline,r=t.baseAttributes.disciplineFactor??wc(n);return{effort:t,definition:t,slug:t.slug,label:t.label,met:t.baseAttributes.met,baseAttributes:t.baseAttributes,discipline:n,disciplineFactor:r,intensityTier:t.baseAttributes.intensityTier,modifiers:{},registrySource:t.registrySource,resolvedFrom:t.registrySource===`user`?`user`:t.registrySource===`bundled`?`bundled`:`default`,isEstimated:t.registrySource===`synthetic-unresolved`}}function mu(e){let t;for(let n of e)if(n.type===`effort-data`&&n.value&&typeof n.value==`object`){let e=pu(n.value);t={resolved:e,effort:e.effort,origin:n.origin}}return t}var hu=e=>console.log(e);function gu(e,t){let{resolver:n,references:r,overwrite:i=!1,debug:a=!1}=t;_u(e,n,r,i,a)}function _u(e,t,n,r,i){let a=e.blockType?.toLowerCase();if(a!==`effort`&&a!==`exercise`)return;let o=e.label;if(!o){i&&hu(`[EffortEnrichment] Skipping block with no label: ${e.key}`);return}if(e.getAllMemory().find(e=>e.metrics.toArray().some(e=>e.type===`effort-data`))&&!r){i&&hu(`[EffortEnrichment] Skipping block already enriched: ${o}`);return}try{let a,s=`none`,c=[],l=[];if(n){let e=n.resolve(o);a=e.effort??void 0,s=e.matched,c=e.equipment,l=e.diagnostics}else a=t.resolveEffort(o);if(!a){l.length>0&&e.pushMemory(new Fl(`metric:tracked`,[{type:q.Hint,value:`reference.unresolved`,image:o,origin:`compiler`,metadata:{[ca]:{matched:`none`,source:o,diagnostics:l}}}])),i&&hu(`[EffortEnrichment] Unresolved effort: ${o}`);return}let u=a.effort.hints;u&&Object.keys(u).length>0&&e.mergeHints(u),i&&hu(`[EffortEnrichment] Resolved effort: ${o} → ${a.label} (MET: ${a.met})`);let d={type:du,image:a.label,value:a,origin:`compiler`,timestamp:new Date,...c.length>0||l.length>0?{metadata:{[ca]:{matched:s,source:o,refs:[{kind:`effort`,slug:a.slug,label:a.label},...c],...l.length>0?{diagnostics:l}:{}}}}:{}},f=e.getMetricMemoryByVisibility(`private`).find(e=>e.metrics.toArray().some(e=>e.type===du));if(f&&r){let e=f.metrics.toArray().filter(e=>e.type!==du);e.push(d),f.update(e)}else if(!f){let t=new Fl(`metric:tracked`,[d]);e.pushMemory(t)}c.length>0&&vu(e,q.Equipment,[new gs(c.map(e=>e.slug),{refs:c,source:o,origin:`compiler`})],q.Equipment,r)}catch(e){console.error(`[EffortEnrichment] Failed to resolve effort "${o}":`,e)}}function vu(e,t,n,r,i){let a=e.getMetricMemoryByVisibility(`private`).find(e=>e.metrics.toArray().some(e=>e.type===t));if(a&&i){let e=a.metrics.toArray().filter(e=>e.type!==r);a.update([...e,...n])}else a||e.pushMemory(new Fl(`metric:tracked`,n))}var yu=class{statementIds;options;type=`compile-and-push-block`;constructor(e,t={}){this.statementIds=e,this.options=t}do(e){if(!this.statementIds||this.statementIds.length===0)return[];let t=e.script.getIds(this.statementIds);if(t.length===0)return[];try{let n=e.jit.compile(t,e);return n?(e.analyticsContext?.effortResolver&&gu(n,{resolver:e.analyticsContext.effortResolver,references:e.analyticsContext.references}),[new wl(n,this.options)]):[]}catch(t){return e.options.logger?.error?.(`CompileAndPushBlockAction: Compilation failed`,t),[]}}},bu=class{durationMs;label;type=`push-rest-block`;constructor(e,t=`Rest`){this.durationMs=e,this.label=t}do(e){return[new wl(new Hu(e,{durationMs:this.durationMs,label:this.label}))]}},xu=class e{config;static DEFAULT_MIN_REST_MS=1e3;childIndex=0;dispatchedOnLastNext=!1;restState=`idle`;constructor(e){this.config=e}onMount(e){this.restState=`idle`,this.dispatchedOnLastNext=!1,e.declareCapability(`childSelection`);let t=[];if(this.config.startRound!==void 0){let t=e.block.key.toString();e.pushMemory(`round`,[new iu(this.config.startRound,this.config.totalRounds,t,e.clock.currentDate)])}if(this.config.injectRest&&e.subscribe(`timer:complete`,(t,n)=>{if(this.restState!==`idle`)return[];let r=this.advanceRound(e);return this.childIndex=0,this.restState=`idle`,this.writeChildrenStatus(e),r},{scope:`active`}),this.config.skipOnMount)return this.totalChildren>0&&t.push(this.createNextPreview(e,this.config.childGroups[0])),this.writeChildrenStatus(e),t;if(this.totalChildren===0)return this.writeChildrenStatus(e),t;let n=this.dispatchNext(e);return this.writeChildrenStatus(e),[...t,...n]}onNext(e){if(this.dispatchedOnLastNext=!1,e.block.isComplete){let t=[this.createNextPreview(e)];return this.writeChildrenStatus(e),t}let t=[];if(this.config.startRound!==void 0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t?.total!==void 0&&t.current>t.total)return e.markComplete(`rounds-exhausted`),this.writeChildrenStatus(e),[new Tl]}if(this.restState===`active`&&(this.restState=`idle`,this.config.injectRest&&(t.push(...this.advanceRound(e)),this.childIndex=0,e.emitEvent({name:`timer:reset`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}))),this.childIndex>=this.totalChildren){if(!this.shouldLoop(e))return this.writeChildrenStatus(e),e.markComplete(this.isLoopEnabled()?`rounds-exhausted`:`children-complete`),[this.createNextPreview(e)];if(this.shouldInjectRest(e)){this.restState=`pending`;let n=[new bu(this.getRemainingCountdownMs(e),`Rest`),this.createNextPreview(e,this.config.childGroups[0])];return this.restState=`active`,this.writeChildrenStatus(e),[...t,...n]}t.push(...this.advanceRound(e)),this.childIndex=0}let n=this.dispatchNext(e);return this.writeChildrenStatus(e),[...t,...n]}onUnmount(e){return[]}onDispose(e){this.restState=`idle`}get allChildrenExecuted(){return this.childIndex>=this.totalChildren}get allChildrenCompleted(){return this.allChildrenExecuted&&!this.dispatchedOnLastNext}get totalChildren(){return this.config.childGroups.length}dispatchNext(e){if(this.childIndex>=this.totalChildren)return[this.createNextPreview(e)];let t=this.config.childGroups[this.childIndex];this.childIndex++,this.dispatchedOnLastNext=!0;let n=this.config.childGroups[this.childIndex];return[new yu(t),this.createNextPreview(e,n)]}shouldLoop(e){if(e.block.isComplete||!this.isLoopEnabled())return!1;let t=this.getLoopCondition();if(t===`always`)return!0;if(t===`timer-active`){let t=e.getMemoryByTag(`time`)[0]?.metrics[0]?.value;return t?t.direction===`down`&&t.durationMs?this.getRemainingCountdownMs(e)>0:!0:!1}let n=e.getMemoryByTag(`round`)[0]?.metrics[0];return n?n.total===void 0||n.current<n.total:!1}shouldInjectRest(t){if(!this.config.injectRest)return!1;let n=t.getMemoryByTag(`time`)[0]?.metrics[0]?.value;if(!n||n.direction!==`down`||!n.durationMs)return!1;let r=this.getRemainingCountdownMs(t);return!(r<e.DEFAULT_MIN_REST_MS||r>=n.durationMs)}getRemainingCountdownMs(e){let t=e.getMemoryByTag(`time`)[0]?.metrics[0]?.value;if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=nu(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}writeChildrenStatus(e){let t={childIndex:this.childIndex,totalChildren:this.totalChildren,allExecuted:this.allChildrenExecuted,allCompleted:this.allChildrenCompleted},n=e.getMemoryByTag(`children:status`)[0];n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:t}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:t}])}advanceRound(e){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(!t)return[];if(t.total!==void 0&&t.current>=t.total)return e.markComplete(`rounds-exhausted`),[];let n=e.block.key.toString(),r=t.current+1,i=t.total,a=new iu(r,i,n,e.clock.currentDate);return e.updateMemory(`round`,[a]),[]}createNextPreview(e,t){return new uu(e.block.key.toString(),t??[])}isLoopEnabled(){return this.config.loop===void 0?!1:typeof this.config.loop!=`boolean`||this.config.loop}getLoopCondition(){return typeof this.config.loop==`object`&&this.config.loop.condition?this.config.loop.condition:`timer-active`}},Su=class{value;sourceBlockKey;timestamp;type=q.Elapsed;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return ru(this.value)}},Cu=class{value;sourceBlockKey;timestamp;type=q.Total;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return ru(this.value)}},wu=class e{spans;sourceBlockKey;timestamp;type=q.Spans;origin=`tracked`;constructor(e,t,n){this.spans=e,this.sourceBlockKey=t,this.timestamp=n}get value(){return this.spans}get image(){if(this.spans.length===0)return`--:--`;if(this.spans.length===1){let t=this.spans[0];return t.started===t.ended?e.formatTimestamp(t.started):`${e.formatTimestamp(t.started)} – ${e.formatTimestamp(t.ended??Date.now())}`}return`${this.spans.length} spans`}get isOpen(){return this.spans.length!==0&&this.spans[this.spans.length-1].isOpen}static formatTimestamp(e){let t=new Date(e);return`${t.getHours().toString().padStart(2,`0`)}:${t.getMinutes().toString().padStart(2,`0`)}:${t.getSeconds().toString().padStart(2,`0`)}`}},Tu=class{value;sourceBlockKey;type=q.SystemTime;origin=`tracked`;constructor(e,t){this.value=e,this.sourceBlockKey=t}get timestamp(){return this.value}get image(){return this.value.toISOString()}},Eu=class{config;_now;lastEmittedRound;constructor(e={},t=rl){this.config=e,this._now=t}onMount(e){if(this.config.emitSegmentOnMount??!1){let t=this.collectDisplayFragments(e),n=this.collectStateFragments(e),r=this.mergeFragments(t,n);e.emitOutput(`segment`,r.toArray(),{label:this.formatLabel(e)})}let t=e.getMemoryByTag(`round`)[0]?.metrics[0];return(this.config.emitMilestones??!!t)&&t&&(t.total===void 0||t.total>1)&&(this.lastEmittedRound=t.current,e.emitOutput(`milestone`,this.buildMilestoneFragments(e,t).toArray(),{label:this.formatRoundLabel(t)})),[]}onNext(e){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];return!(this.config.emitMilestones??!!t)||!t||t.total!==void 0&&t.total<=1||t.total!==void 0&&t.current>t.total||this.lastEmittedRound!==void 0&&t.current===this.lastEmittedRound?[]:(this.lastEmittedRound=t.current,e.emitOutput(`milestone`,this.buildMilestoneFragments(e,t).toArray(),{label:this.formatRoundLabel(t)}),[])}onUnmount(e){let t=Zl(e),n=e.getMemoryByTag(`round`)[0]?.metrics[0],r=this.config.computeTimeResults??!0,i=this.config.label??`Completed`;if(this.config.label||(e.block.blockType===`SessionRoot`?i=`Session Completed`:n&&n.total!==void 0&&n.total>1?i=`Completed ${n.total} Round(s)`:n&&n.current>1&&(i=`Completed ${n.current} Round(s)`)),r){let n=e.block.getMemoryByTag(`metric:display`);if(n.length>1){let r=this.computeSplitTimeResults(e,t,n.map(e=>e.metrics),i);return this.writeResultGroups(e,r),[]}}let a=r?this.computeTimeResults(e,t,i):J.from([new Tu(this._now.now(),e.block.key.toString())],e.block.key.toString());return this.writeResultMemory(e,a),[]}onDispose(e){}collectDisplayFragments(e){let t=J.empty(e.block.key.toString());for(let n of e.block.getMemoryByTag(`metric:display`))t.merge(n.metrics);return t}collectStateFragments(e){let t=J.empty(e.block.key.toString());for(let n of e.block.getMemoryByTag(`round`))t.merge(n.metrics);for(let n of e.block.getMemoryByTag(`time`))t.merge(n.metrics);return t}mergeFragments(e,t){let n=new Set(e.map(e=>`${e.type}:${e.type}`)),r=t.filter(e=>!n.has(`${e.type}:${e.type}`));return e.clone().add(...r)}buildMilestoneFragments(e,t){let n=J.empty(e.block.key.toString()).add(new iu(t.current,t.total,e.block.key.toString(),e.clock.currentDate)),r=Zl(e);if(r){let t=nu(r,e.clock.currentDate.getTime());n.add(new Su(t,e.block.key.toString(),e.clock.currentDate)),r.spans.length>0&&n.add(new wu([...r.spans],e.block.key.toString(),e.clock.currentDate))}return n}computeTimeResults(e,t,n){let r=e.clock.currentDate,i=r.getTime(),a=e.block.key.toString(),o=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t&&t.spans.length>0){let e=nu(t,i),s=t.spans[0].started,c=t.spans[t.spans.length-1].ended??i,l=Math.max(0,c-s),u=J.empty(a).add(new Su(e,a,r),new Cu(l,a,r),new wu([...t.spans],a,r),new Tu(this._now.now(),a));return o&&u.add(new iu(o.current,o.total,a,r,n)),u}let s=new el(i,i),c=J.empty(a).add(new Su(0,a,r),new Cu(0,a,r),new wu([s],a,r),new Tu(this._now.now(),a));return o&&c.add(new iu(o.current,o.total,a,r,n)),c}computeSplitTimeResults(e,t,n,r){let i=e.clock.currentDate,a=i.getTime(),o=e.block.key.toString(),s=e.getMemoryByTag(`round`)[0]?.metrics[0];if(!t||t.spans.length===0)return n.map(e=>{let t=e.clone().add(new Su(0,o,i),new Cu(0,o,i),new wu([new el(a,a)],o,i),new Tu(this._now.now(),o));return s&&t.add(new iu(s.current,s.total,o,i,r)),t});let c=nu(t,a),l=t.spans[0].started,u=(t.spans[t.spans.length-1].ended??a)-l,d=n.map(e=>{let t=e.filter(e=>e.type===q.Rep&&typeof e.value==`number`).reduce((e,t)=>e+t.value,0);return t>0?t:1}),f=d.reduce((e,t)=>e+t,0),p=0;return n.map((e,t)=>{let n=d[t]/f,a=Math.round(c*n),m=Math.round(u*n),h=l+p,g=h+m;p+=m;let _=e.clone().add(new Su(a,o,i),new Cu(m,o,i),new wu([new el(h,g)],o,i),new Tu(this._now.now(),o));return s&&_.add(new iu(s.current,s.total,o,i,r)),_})}writeResultMemory(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length>0){let r=Du(n);r.length>0&&(t=t.clone().add(...r)),e.updateMemory(`metric:result`,t.toArray());return}e.pushMemory(`metric:result`,t.toArray())}writeResultGroups(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length===0){for(let n of t)e.pushMemory(`metric:result`,n.toArray());return}let r=Math.max(n.length,t.length);for(let i=0;i<r;i++){let r=t[i]?t[i].clone():n[i].metrics.clone(),a=t[i]&&i<n.length?Du([n[i]]):[],o=r.add(...a);i<n.length?n[i].update(o):e.pushMemory(`metric:result`,o.toArray())}}formatLabel(e){return this.config.label??e.block.label}formatRoundLabel(e){return e.total===void 0?`Round ${e.current}`:`Round ${e.current} of ${e.total}`}};function Du(e){let t=[];for(let n of e)for(let e of n.metrics)e.origin===`user`&&t.push(e);return t}var Ou=class{sound;trigger;type=q.Sound;origin;value;image;constructor(e,t,n={}){this.sound=e,this.trigger=t,this.origin=n.origin??`tracked`,this.value={sound:e,trigger:t,atSecond:n.atSecond},this.image=n.atSecond===void 0?e:`${e}@${n.atSecond}s`}};function ku(e){let t=e.trim();if(t.length===0)return;let n,r;t.startsWith(`-`)?(n=`end`,r=t.slice(1)):(n=`start`,r=t),r.startsWith(`:`)&&(r=r.slice(1));let i=Au(r);if(i!==void 0)return{anchor:n,offsetMs:i}}function Au(e){let t=e.trim().replace(/^:/,``);if(t.length===0)return 0;if(!/^\d+(:\d+)*$/.test(t))return;let n=t.split(`:`).map(Number).reverse(),[r=0,i=0,a=0,o=0]=n;if(!(n.length>4)&&!(i>59||a>59))return((o*24+a)*60+i)*6e4+r*1e3}function ju(e,t){return e.rules.filter(e=>{let{anchor:n,offsetMs:r}=e.trigger;return n===`start`||r===0||t!==void 0&&r<=t})}var Mu={id:`default`,name:`Default`,rules:[{trigger:{anchor:`end`,offsetMs:3e3},sound:`countdown-beep`},{trigger:{anchor:`end`,offsetMs:2e3},sound:`countdown-beep`},{trigger:{anchor:`end`,offsetMs:1e3},sound:`countdown-beep`},{trigger:{anchor:`end`,offsetMs:0},sound:`timer-complete`}]},Nu=`sound:play`,Pu=class{config;rules=[];fired=new Set;durationMs;constructor(e){this.config=e}onMount(e){let t=Zl(e);return this.durationMs=t?.durationMs,this.rules=ju(this.config.profile,this.durationMs),this.fireDue(e,0,this.durationMs),e.subscribe(`tick`,(e,t)=>{let n=this.elapsedMs(t);return n===void 0||this.fireDue(t,n,this.durationMs),[]},{scope:`bubble`}),[]}onNext(e){return[]}onUnmount(e){return this.fireDue(e,this.elapsedMs(e)??0,this.durationMs,!0),[]}onDispose(e){this.fired.clear()}elapsedMs(e){let t=Zl(e);if(t)return nu(t,e.clock.currentDate.getTime())}fireDue(e,t,n,r=!1){let i=n===void 0?void 0:Math.max(0,n-t);this.rules.forEach((n,a)=>{if(this.fired.has(a))return;let{anchor:o,offsetMs:s}=n.trigger;(o===`start`?t>=s:s===0?r||i!==void 0&&i<=0:i!==void 0&&i<=s)&&(this.fired.add(a),this.play(e,n,o,s))})}play(e,t,n,r){let i=n===`start`?r===0?`mount`:`countdown`:r===0?`complete`:`countdown`;e.emitOutput(`system`,[new Ou(t.sound,i,{atSecond:r/1e3})],{label:`Sound: ${t.sound}`}),e.emitEvent({name:Nu,timestamp:e.clock.currentDate,data:{sound:t.sound,volume:1}})}},Fu=class{config;constructor(e){this.config=e}onMount(e){let t=J.from(this.config.buttons.map(t=>({type:q.Action,image:t.label,origin:`runtime`,value:{id:t.id,label:t.label,variant:t.variant,visible:t.visible,enabled:t.enabled,eventName:t.eventName},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate})),e.block.key.toString());return t.length>0&&e.pushMemory(`controls`,t.toArray()),[]}onNext(e){return[]}onUnmount(e){return e.updateMemory(`controls`,[]),[]}onDispose(e){}static updateButton(e,t,n){let r=e.block.getMemoryByTag(`controls`);if(r.length===0)return;let i=r[0].metrics.map(e=>{let r=e.value;return r.id===t?{...e,value:{...r,...n}}:e});e.updateMemory(`controls`,i)}},Iu=class e extends Ul{constructor(t){let n=new _a(`waiting-to-start`),r=new Pl(t,n.toString(),`WaitingToStart`),i=e.buildBehaviors();super({runtime:t,sourceIds:[],behaviors:i,context:r,key:n,blockType:`WaitingToStart`,label:`Ready to Start`})}static buildBehaviors(){let e=[];return e.push(new Eu({label:`Ready to Start`,emitSegmentOnMount:!0})),e.push(new lu({mode:`clock`,label:`Ready to Start`})),e.push(new Fu({buttons:[{id:`start`,label:`Start Workout`,variant:`primary`,visible:!0,enabled:!0,eventName:`next`}]})),e.push(new cu({mode:`immediate`,onNext:!0})),e}mount(e,t){return super.mount(e,t)}unmount(e,t){return super.unmount(e,t)}dispose(e){super.dispose(e),this.context&&this.context.release()}},Lu=class{runtime;constructor(e){this.runtime=e}onMount(e){return[new wl(new Iu(this.runtime))]}onNext(e){return[]}onUnmount(e){return[]}onDispose(e){}},Ru=q.Sound;function zu(e,t){let n=Bu(e);if(n){let e=Vu(t?.profiles,n);if(e)return e}if(t?.noteProfileId){let e=Vu(t?.profiles,t.noteProfileId);if(e)return e}return Mu}function Bu(e){for(let t of e){let e=t.metrics.find(e=>e.type===Ru);if(!e)continue;let n=e.value;if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function Vu(e,t){if(e)return e.find(e=>e.id===t)}var Hu=class e extends Ul{constructor(t,n){if(n.durationMs<0)throw RangeError(`RestBlock durationMs must be >= 0, got: ${n.durationMs}`);let r=n.label??`Rest`,i=new _a(`rest`),a=new Pl(t,i.toString(),`Rest`),o=e.buildBehaviors(n,t.options?.soundOptions);super({runtime:t,sourceIds:[],behaviors:o,context:a,key:i,blockType:`Rest`,label:r})}static buildBehaviors(e,t){let n=[],r=e.label??`Rest`;return n.push(new Eu({label:r})),n.push(new au({durationMs:e.durationMs,label:r,role:`primary`,mode:`complete-block`})),n.push(new cu({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})),n.push(new lu({mode:`timer`,label:r})),n.push(new Pu({profile:zu([],t)})),n}mount(e,t){return super.mount(e,t)}unmount(e,t){return super.unmount(e,t)}dispose(e){super.dispose(e),this.context&&this.context.release()}},Uu=class{runtime;behaviors=new Map;context;key;label=``;blockType=`Block`;metrics;sourceIds=[];tagComposition=[];pendingRoundConfig;declaredExitMode;constructor(e){this.runtime=e}addBehavior(e){return this.behaviors.set(e.constructor,e),this}addBehaviorIfMissing(e){return this.behaviors.has(e.constructor)||this.behaviors.set(e.constructor,e),this}removeBehavior(e){return this.behaviors.delete(e),this}moveBehaviorLast(e){let t=this.behaviors.get(e);return t?(this.behaviors.delete(e),this.behaviors.set(e,t),this):this}hasBehavior(e){return this.behaviors.has(e)}declareExit(e){return(e===`deferred`||this.declaredExitMode===void 0)&&(this.declaredExitMode=e),this}get exitMode(){return this.declaredExitMode}getBehavior(e){return this.behaviors.get(e)}setContext(e){return this.context=e,this}setKey(e){return this.key=e,this}setLabel(e){return this.label=e,this}setBlockType(e){return this.blockType=e,this}setFragments(e){return this.metrics=e.map(e=>{let t=J.from(e);return t.removeByType(q.Hint),t}),this}setSourceIds(e){return this.sourceIds=e,this}setTagComposition(e){return this.tagComposition=e,this}getLabel(){return this.label}getBlockType(){return this.blockType}getFragments(){return this.metrics}getSourceIds(){return this.sourceIds}getContext(){return this.context}getKey(){return this.key}asTimer(e){if(e.direction===`down`&&e.durationMs){let t=e.completionConfig?.completesBlock===!1?`reset-interval`:`complete-block`;this.addBehavior(new au({durationMs:e.durationMs,label:e.label,role:e.role,mode:t,required:e.required,restBlockFactory:e.injectRest?(e,t)=>[new wl(new Hu(this.runtime,{durationMs:e,label:t}))]:void 0}))}else this.addBehavior(new eu({label:e.label,role:e.role}));return this}hasRoundConfig(){return this.pendingRoundConfig!==void 0}hasTimerBehavior(){return this.behaviors.has(au)||this.behaviors.has(eu)||this.behaviors.has($l)}asRepeater(e){return this.pendingRoundConfig={totalRounds:e.totalRounds,startRound:e.startRound??1,addCompletion:e.addCompletion},this}asContainer(e){let t=this.pendingRoundConfig;return this.addBehavior(new xu({childGroups:e.childGroups,loop:e.addLoop?{condition:e.loopConfig?.condition??`timer-active`}:!1,injectRest:e.injectRest,skipOnMount:e.skipOnMount,startRound:t?.startRound,totalRounds:t?.totalRounds})),this}build(){if(!this.context)throw Error(`BlockContext is required`);if(!this.key)throw Error(`BlockKey is required`);this.addBehaviorIfMissing(new Kl),this.declaredExitMode&&(this.removeBehavior(cu),this.addBehavior(new cu(this.declaredExitMode===`immediate`?{mode:`immediate`,onNext:!0}:{mode:`deferred`}))),this.moveBehaviorLast(su);let e=new Ul({runtime:this.runtime,sourceIds:this.sourceIds,tagComposition:this.tagComposition,behaviors:Array.from(this.behaviors.values()),context:this.context,key:this.key,blockType:this.blockType});if(this.metrics&&this.metrics.length>0)for(let t of this.metrics)e.pushMemory(new Fl(`metric:display`,t));return this.label&&e.pushMemory(new Fl(`metric:label`,[{type:q.Label,image:this.label,origin:`compiler`,value:this.label}])),e}};function Wu(e){return typeof e==`object`&&!!e&&`getPromotedFragments`in e&&typeof e.getPromotedFragments==`function`}var Gu=class{resolvePromotions(e,t){if(!e)return{promotedFragments:[],hasPromotions:!1};let n=e.getMetricMemoryByVisibility(`promote`).flatMap(e=>e.metrics.toArray());for(let r of e.behaviors){if(!Wu(r))continue;let i=r.getPromotedFragments(t,e);for(let e of i){let t=n.findIndex(t=>t.type===e.type);t===-1?n.push(e):n[t]=e}}return{promotedFragments:n,hasPromotions:n.length>0}}},Ku=class{strategies;_promotionResolver;constructor(e=[],t){this.strategies=e,this._promotionResolver=t??new Gu}registerStrategy(e){this.strategies.push(e)}compile(e,t){if(e.length===0)return;let n=e,r=t.stack?.current,i=this._promotionResolver.resolvePromotions(r,t);if(i.hasPromotions){let e=i.promotedFragments;n=n.map(t=>{let n=Object.create(Object.getPrototypeOf(t));return Object.assign(n,t),n.metrics=t.metrics.clone(t.id).add(...e),n})}let a=this.strategies.filter(e=>e.match(n,t)).sort((e,t)=>(t.priority||0)-(e.priority||0));if(a.length===0)return;let o=new Uu(t),s=[];for(let e of n)vo(e.metrics,s);o.setTagComposition(s);for(let e of a)e.apply(o,n,t);try{return o.build()}catch{return}}},qu=class{handlersByEvent=new Map;callbacksByEvent=new Map;register(e,t,n,r={}){let{priority:i=0,scope:a=`active`}=r,o=[...this.handlersByEvent.get(e)??[],{handler:t,ownerId:n,priority:i,scope:a}];return o.sort((e,t)=>t.priority-e.priority),this.handlersByEvent.set(e,o),()=>this.unregisterById(t.id)}on(e,t,n){let r=b(),i=this.callbacksByEvent.get(e)??[];return i.push({id:r,callback:t,ownerId:n}),this.callbacksByEvent.set(e,i),()=>this.unregisterById(r)}unregisterById(e){for(let[t,n]of this.handlersByEvent.entries()){let r=n.filter(t=>t.handler.id!==e);r.length===0?this.handlersByEvent.delete(t):this.handlersByEvent.set(t,r)}for(let[t,n]of this.callbacksByEvent.entries()){let r=n.filter(t=>t.id!==e);r.length===0?this.callbacksByEvent.delete(t):this.callbacksByEvent.set(t,r)}}unregisterByOwner(e){for(let[t,n]of this.handlersByEvent.entries()){let r=n.filter(t=>t.ownerId!==e);r.length===0?this.handlersByEvent.delete(t):this.handlersByEvent.set(t,r)}for(let[t,n]of this.callbacksByEvent.entries()){let r=n.filter(t=>t.ownerId!==e);r.length===0?this.callbacksByEvent.delete(t):this.callbacksByEvent.set(t,r)}}dispatch(e,t){let n=[...this.callbacksByEvent.get(`*`)??[],...this.callbacksByEvent.get(e.name)??[]];for(let r of n)try{r.callback(e,t)}catch(t){console.error(`EventBus callback error for ${e.name}:`,t)}let r=t.stack.current?.key.toString(),i=new Set(t.stack.keys.map(e=>e.toString())),a=[...this.handlersByEvent.get(`*`)??[],...this.handlersByEvent.get(e.name)??[]].filter(e=>{switch(e.scope){case`global`:return!0;case`bubble`:return i.has(e.ownerId);default:return e.ownerId===r}}),o=[];for(let n of a)try{let r=n.handler.handler(e,t);r&&r.length>0&&o.push(...r)}catch(t){console.error(`EventBus handler error for ${e.name}:`,t)}return xl.logEvent(e,o),o}emit(e,t){t.handle(e)}dispose(){this.handlersByEvent.clear(),this.callbacksByEvent.clear()}},Ju=class e extends Ul{constructor(t,n){let r=n.label??`Session`,i=new _a(`session-root`),a=new Pl(t,i.toString(),`Session`),o=e.buildBehaviors(n,t);super({runtime:t,sourceIds:n.childGroups.flat(),behaviors:o,context:a,key:i,blockType:`SessionRoot`,label:r})}static buildBehaviors(e,t){let n=[],r=e.totalRounds??1,i=e.label??`Session`;return n.push(new eu({label:i,role:`auto`})),n.push(new xu({childGroups:e.childGroups,loop:r>1&&{condition:`rounds-remaining`},skipOnMount:!0,startRound:1,totalRounds:r})),n.push(new Lu(t)),n.push(new Eu({label:i})),n.push(new lu({mode:`clock`,label:i})),n.push(new Fu({buttons:[{id:`pause`,label:`Pause`,variant:`secondary`,visible:!0,enabled:!0,eventName:`timer:pause`},{id:`next`,label:`Next`,variant:`primary`,visible:!0,enabled:!0,eventName:`next`},{id:`stop`,label:`Stop`,variant:`danger`,visible:!0,enabled:!0,eventName:`workout:stop`}]})),n}mount(e,t){return super.mount(e,t)}unmount(e,t){return super.unmount(e,t)}dispose(e){super.dispose(e),this.context&&this.context.release()}},Yu=class{priority=100;id=`session-root`;match(e,t){return!1}apply(e,t,n){}build(e,t){return new Ju(e,t)}buildFromStatements(e,t,n){let r={childGroups:Qu(t),label:n?.label,totalRounds:n?.totalRounds};return this.build(e,r)}};function Xu(e){let t=e.metrics;return(!e.children||e.children.length===0)&&!t.some(e=>e.type===q.Effort)&&!t.some(e=>e.type===q.Duration)&&!t.some(e=>e.type===q.Rounds)&&!t.some(e=>e.type===q.Rep)&&t.some(e=>e.type===q.Resistance||e.type===q.Distance)}function Zu(e){return!!e.children&&e.children.length>0||e.metrics.some(e=>e.type===q.Rounds)||e.metrics.some(e=>e.type===q.Duration)}function Qu(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(Xu(r)&&n+1<e.length){let i=e[n+1];if(Zu(i)){t.push([i.id,r.id]),n+=2;continue}}t.push([r.id]),n++}return t}var $u=class{options;type=`start-session`;constructor(e={}){this.options=e}do(e){if(e.stack.count>0)return console.warn(`[StartSessionAction] Session already started - stack is not empty`),[];let t=e.script?.statements;if(!t||t.length===0)return console.warn(`[StartSessionAction] No statements in script to start`),[];let n=new Set;for(let e of t)if(e.children)for(let t of e.children)for(let e of t)n.add(e);let r={childGroups:Qu(t.filter(e=>!n.has(e.id))),label:this.options.label,totalRounds:this.options.totalRounds};return[new wl(new Yu().build(e,r),{startTime:e.clock.currentDate,...this.options.lifecycle})]}},ed=class{realtimeProcessors=[];summaryProcessors=[];outputHistory=[];_onLiveOutput;_lastLiveProjectionSignature;setLiveOutputEmitter(e){this._onLiveOutput=e}addRealtimeProcessor(e){this.realtimeProcessors.push(e)}addSummaryProcessor(e){this.summaryProcessors.push(e)}run(e){let t=e;for(let e of this.realtimeProcessors)try{t=e.process(t)}catch(t){console.error(`[AnalyticsEngine] realtime error in '${e.id}':`,t)}if(t.outputType===`segment`&&(this.outputHistory.push(t),this._onLiveOutput)){let e=Date.now(),t=this._runSummaries(),n=this._projectionSignature(t);if(n!==this._lastLiveProjectionSignature){this._lastLiveProjectionSignature=n;let r=this._buildProjectionOutputs(t,e);this._onLiveOutput(r)}}return t}finalize(){let e=this._runSummaries(),t=this._buildProjectionOutputs(e,Date.now()),n=this._projectionSignature(e);return this._lastLiveProjectionSignature!==void 0&&this._lastLiveProjectionSignature===n?[]:t}_projectionSignature(e){return JSON.stringify(e.map(e=>({name:e.name,value:e.value,unit:e.unit,metricType:e.metricType})))}_buildProjectionOutputs(e,t){return e.map(e=>{let n=J.empty(`projection-${e.name}`).add({type:q.Label,image:e.name,value:e.name,origin:e.origin??`analyzed`,timestamp:new Date(t)},{type:e.metricType||q.Metric,image:`${e.value} ${e.unit}`,value:e.value,unit:e.unit,origin:e.origin??`analyzed`,timestamp:new Date(t),...e.metadata?{metadata:e.metadata}:{}});return new ga({outputType:`analytics`,timeSpan:{started:t,ended:t},sourceBlockKey:`analytics-summary`,stackLevel:0,metrics:n})})}_runSummaries(){let e=[];for(let t of this.summaryProcessors)try{e.push(...t.summarize(this.outputHistory))}catch(e){console.error(`[AnalyticsEngine] summary error in '${t.id}':`,e)}return e}},td=class{resolver;id=`two-pass-effort-resolution`;fenceTypes=[`time`,`log`];constructor(e){this.resolver=e}process(e){let t=e.getMetric(q.Effort),n=e.getMetric(q.Action),r,i=`analyzed`;if(t&&typeof t.value==`string`?(r=t.value,i=t.origin===`compiler`?`compiler`:`analyzed`):n&&typeof n.value==`string`&&(r=n.value,i=`analyzed`),!r)return e;let{resolved:a,finalOrigin:o}=this.resolve(r,i),s={type:du,image:a.label,value:a,origin:o,timestamp:new Date},c=e.metrics.toArray(),l=[],u=!1;for(let e of c)l.push(e),!u&&(e.type===q.Effort||e.type===q.Action)&&(l.push(s),u=!0);u||l.push(s),e.metrics.clear();for(let t of l)e.metrics.add(t);return e}resolve(e,t){let n;if(t===`compiler`&&(n=this.resolver.resolveBySlug(e)??this.resolver.resolveByAlias(e),n))return{resolved:this.resolver.resolveDefinition(n),finalOrigin:`compiler`};let r=this.resolver.resolveEffort(e);return{resolved:r,finalOrigin:r.isEstimated?`analyzed-estimated`:`analyzed`}}},nd=[0,0,0,0,0],rd=[1,0,0,0,0],id=[0,1,0,0,0],ad=[0,0,1,0,0],od=[0,0,0,1,0],sd=[0,0,0,0,1];function cd(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2],e[3]+t[3],e[4]+t[4]]}function ld(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2],e[3]-t[3],e[4]-t[4]]}function ud(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]}function dd(e){return ud(e,nd)}var fd=[`L`,`M`,`T`,`C`,`E`];function pd(e){if(dd(e))return`dimensionless`;let t=[];for(let n=0;n<5;n++){let r=e[n];r!==0&&t.push(r===1?fd[n]:`${fd[n]}^${r}`)}return t.join(`·`)}var md={pace:{dim:[-1,0,1,0,0],preferredUnits:[`min/km`,`sec/km`,`min/mi`]},speed:{dim:[1,0,-1,0,0],preferredUnits:[`m/s`,`km/h`]},volume:{dim:[0,1,0,1,0],preferredUnits:[`kg`,`lb`]},power:{dim:[0,1,-1,1,0],preferredUnits:[`kg/s`,`lb/s`]},time:{dim:ad,preferredUnits:[`min`,`s`,`h`]},mass:{dim:id,preferredUnits:[`kg`,`lb`]},length:{dim:rd,preferredUnits:[`m`,`km`,`mi`]},count:{dim:od,preferredUnits:[`reps`]},energy:{dim:sd,preferredUnits:[`cal`,`kcal`]},dimensionless:{dim:nd,preferredUnits:[`pts`,`AU`,`MET`,`ratio`]}};function hd(e){for(let[t,n]of Object.entries(md))if(ud(n.dim,e))return t}var gd={reps:{dim:od,metricType:`rep`,unit:`reps`},elapsed:{dim:ad,metricType:`elapsed`,unit:`ms`},distance:{dim:rd,metricType:`distance`,unit:`m`},resistance:{dim:id,metricType:`resistance`,unit:`kg`},segmentVolume:{dim:[0,1,0,1,0],metricType:`segmentVolume`,unit:`kg`},metMinutes:{dim:ad,metricType:`metMinutes`,unit:`min`},effortRpe:{dim:nd,metricType:`effortRpe`},metMinutesEstimated:{dim:nd,metricType:`metMinutesEstimated`},sessionRpe:{dim:nd,metricType:`session-rpe`},climbSend:{dim:od,metricType:`climb-send-type`,unit:`count`},climbGrade:{dim:nd,metricType:`climb-grade`}},_d={effort:nd,effortLabel:nd,sessionRpe:nd,"session.duration":ad,"profile.vo2max":nd},vd={sum:!0,max:!0,min:!0,avg:!0,count:!0,last:!0},yd={AU:!0,pts:!0,"MET-min":!0,ratio:!0},bd=.45359237,xd=1609.344,Sd={ms:{dim:ad,factor:1},s:{dim:ad,factor:1e3},sec:{dim:ad,factor:1e3},min:{dim:ad,factor:6e4},h:{dim:ad,factor:36e5},hr:{dim:ad,factor:36e5},m:{dim:rd,factor:1},km:{dim:rd,factor:1e3},mi:{dim:rd,factor:xd},kg:{dim:id,factor:1},lb:{dim:id,factor:bd},lbs:{dim:id,factor:bd},rep:{dim:od,factor:1},reps:{dim:od,factor:1},cal:{dim:sd,factor:1},kcal:{dim:sd,factor:1e3},MET:{dim:nd,factor:1},"%":{dim:nd,factor:1},rating:{dim:nd,factor:1},bpm:{dim:nd,factor:1},count:{dim:od,factor:1},"m/s":{dim:[1,0,-1,0,0],factor:.001},"km/h":{dim:[1,0,-1,0,0],factor:1e3/36e5},"sec/km":{dim:[-1,0,1,0,0],factor:1},"min/km":{dim:[-1,0,1,0,0],factor:60},"min/mi":{dim:[-1,0,1,0,0],factor:6e4/xd},"reps/min":{dim:[0,0,-1,1,0],factor:1/6e4},"kg/s":{dim:[0,1,-1,1,0],factor:.001},"lb/s":{dim:[0,1,-1,1,0],factor:bd/1e3}};function Cd(e){let t=Sd[e];if(t)return t;if(yd[e])return{dim:nd,factor:1}}function wd(e,t,n){let r=Sd[n];if(!r)throw new Td(`Unknown unit: ${n}`);if(!t)return e/r.factor;let i=Sd[t];if(!i)throw new Td(`Unknown unit: ${t}`);if(!ud(i.dim,r.dim))throw new Td(`Cannot convert from ${t} to ${n}: dimension mismatch`);return e*i.factor/r.factor}var Td=class extends Error{constructor(e){super(e),this.name=`CalcUnitError`}};function Ed(e,t,n,r,i){if(ud(i,nd))return;let a=[];for(let[i,o]of[[e,t],[n,r]])!i||ud(o,nd)||a.push(i);let o=a.filter(e=>!ud(Sd[e]?.dim??nd,od)),s=o.length>0?o:a;return s.length>0?s.join(`·`):void 0}function Dd(e,t,n,r){if(!ud(r,nd)){if(!t||ud(n,nd))return e;if(e)return`${e}/${t}`}}var Od={kind:`absent`};function kd(e,t=nd,n){return{kind:`number`,value:e,dim:t,unit:n}}function Ad(e){return{kind:`string`,value:e}}function jd(e){return e.kind===`number`?e.value!==0:e.kind===`string`?e.value.length>0:e.kind===`series`?e.points.size>0:e.kind===`period`&&e.days>0}var Md=class extends Error{constructor(e){super(e),this.name=`CalcEvalError`}};function Nd(e,t){switch(e.kind){case`literal`:return kd(e.value);case`period`:return{kind:`period`,days:e.days};case`string`:return Ad(e.value);case`ref`:return t.resolveRef(e.name);case`filter`:throw new Md(`Exclusion filter is only valid as an aggregate argument`);case`wql`:if(!t.resolveWql)throw new Md(`WQL atom ${e.aggregator}:${e.metric} is store-scope only`);return t.resolveWql(e);case`unary`:{let n=Nd(e.arg,t);if(e.op===`not`)return kd(+!jd(n));if(n.kind===`absent`)return Od;if(n.kind!==`number`)throw new Md(`Unary minus requires a number`);return kd(-n.value,n.dim,n.unit)}case`binary`:return Pd(e,t);case`call`:return Rd(e,t)}}function Pd(e,t){let{op:n}=e;if(n===`and`)return jd(Nd(e.left,t))?kd(+!!jd(Nd(e.right,t))):kd(0);if(n===`or`)return jd(Nd(e.left,t))?kd(1):kd(+!!jd(Nd(e.right,t)));let r=Nd(e.left,t),i=Nd(e.right,t);if(r.kind===`series`||i.kind===`series`)return Fd(n,r,i);if(n===`==`||n===`!=`){let e=Id(r,i);return kd(n===`==`?+!!e:+!e)}if(r.kind===`absent`||i.kind===`absent`)return n===`<`||n===`<=`||n===`>`||n===`>=`?kd(0):Od;if(r.kind!==`number`||i.kind!==`number`)throw new Md(`Operator '${n}' requires numbers`);switch(n){case`+`:case`-`:if(!ud(r.dim,i.dim))throw new Md(`Dimension mismatch for '${n}': ${pd(r.dim)} vs ${pd(i.dim)}`);return kd(n===`+`?r.value+i.value:r.value-i.value,r.dim,r.unit??i.unit);case`*`:{let e=cd(r.dim,i.dim);return kd(r.value*i.value,e,Ed(r.unit,r.dim,i.unit,i.dim,e))}case`/`:{if(i.value===0)return Od;let e=ld(r.dim,i.dim);return kd(r.value/i.value,e,Dd(r.unit,i.unit,i.dim,e))}case`<`:return kd(+(Ld(r)<Ld(i)));case`<=`:return kd(+(Ld(r)<=Ld(i)));case`>`:return kd(+(Ld(r)>Ld(i)));case`>=`:return kd(+(Ld(r)>=Ld(i)))}}function Fd(e,t,n){if(e===`and`||e===`or`||e===`==`||e===`!=`||e===`<`||e===`<=`||e===`>`||e===`>=`)throw new Md(`Operator '${e}' is not defined on series`);if(t.kind===`absent`||n.kind===`absent`)return Od;let r=t.kind===`series`?t:void 0,i=n.kind===`series`?n:void 0,a=e=>e.kind===`number`?e.value:void 0;if(!r&&a(t)===void 0||!i&&a(n)===void 0)throw new Md(`Operator '${e}' requires numbers or series`);let o=a(t),s=a(n),c=t.kind===`number`||t.kind===`series`?t.dim:void 0,l=n.kind===`number`||n.kind===`series`?n.dim:void 0;if((e===`+`||e===`-`)&&c&&l&&!ud(c,l))throw new Md(`Dimension mismatch for '${e}': ${pd(c)} vs ${pd(l)}`);let u=e===`*`?cd(c??nd,l??nd):e===`/`?ld(c??nd,l??nd):c??l??nd,d=(t,n)=>{switch(e){case`+`:return t+n;case`-`:return t-n;case`*`:return t*n;case`/`:return n===0?void 0:t/n;default:return}},f=new Map,p=r??i;for(let[e,t]of p.points){let n=r?t:o,a=i?i.points.get(e):s;if(a===void 0)continue;let c=d(n,a);c!==void 0&&Number.isFinite(c)&&f.set(e,c)}return{kind:`series`,points:f,dim:u}}function Id(e,t){return e.kind===`absent`||t.kind===`absent`?e.kind===t.kind:e.kind===`string`||t.kind===`string`?e.kind===`string`&&t.kind===`string`&&e.value===t.value:e.kind!==`number`||t.kind!==`number`?e.kind===t.kind:ud(e.dim,t.dim)?Ld(e)===Ld(t):!1}function Ld(e){if(!e.unit)return e.value;let t=Sd[e.unit];return t?e.value*t.factor:e.value}function Rd(e,t){let{name:n,args:r}=e;if(n===`has`){if(r.length!==1)throw new Md(`has() takes one argument`);return kd(Nd(r[0],t).kind===`absent`?0:1)}if(n===`convert`){if(r.length!==2)throw new Md(`convert() takes (value, targetUnit)`);let e=Vd(r[1]),n=Nd(r[0],t);if(n.kind===`absent`)return Od;if(n.kind!==`number`)throw new Md(`convert() requires a number`);let i=Sd[e];if(!i)throw new Md(`Unknown unit: ${e}`);if(!ud(n.dim,i.dim))throw new Md(`convert() dimension mismatch: ${pd(n.dim)} is not ${pd(i.dim)}`);return kd(wd(n.value,n.unit,e),i.dim,e)}let i=r.map(e=>e.kind===`filter`?Od:Nd(e,t));if(zd[n]&&(r[0]?.kind===`ref`||r[0]?.kind===`filter`)){let e=t.callFunction?.(n,i,r);if(e!==void 0)return e}if(n===`windowMean`||n===`windowSum`||n===`windowSd`){let[e,t]=i;if(e?.kind===`absent`)return Od;if(e?.kind!==`series`||t?.kind!==`period`)throw new Md(`${n}() takes (series, period)`);return Bd(n,e,t.days)}if(n===`windowEwma`){let[e,t]=i;if(e?.kind===`absent`)return Od;if(e?.kind!==`series`||t?.kind!==`period`)throw new Md(`windowEwma() takes (series, period)`);let n=1/t.days,r=0,a=new Map;for(let t of[...e.points.keys()].sort((e,t)=>e-t))r+=((e.points.get(t)??0)-r)*n,a.set(t,r);return{kind:`series`,points:a,dim:e.dim,unit:e.unit}}if(i[0]?.kind===`series`&&(n===`sum`||n===`mean`||n===`min`||n===`max`||n===`last`)){let e=i[0],t=[...e.points.values()];if(t.length===0)return Od;switch(n){case`sum`:return kd(t.reduce((e,t)=>e+t,0),e.dim,e.unit);case`mean`:return kd(t.reduce((e,t)=>e+t,0)/t.length,e.dim,e.unit);case`min`:return kd(Math.min(...t),e.dim,e.unit);case`max`:return kd(Math.max(...t),e.dim,e.unit);case`last`:return kd(t[t.length-1],e.dim,e.unit)}}switch(n){case`min`:case`max`:{let e=Hd(n,i);if(e.length===0)return Od;let t=e.reduce((e,t)=>(n===`min`?Ld(t)<Ld(e):Ld(t)>Ld(e))?t:e);return kd(t.value,t.dim,t.unit)}case`abs`:{let[e]=Hd(n,i,1);return kd(Math.abs(e.value),e.dim,e.unit)}case`round`:{let[e,t]=Hd(n,i),r=10**(t?t.value:0);return kd(Math.round(e.value*r)/r,e.dim,e.unit)}case`floor`:{let[e]=Hd(n,i,1);return kd(Math.floor(e.value),e.dim,e.unit)}case`ceil`:{let[e]=Hd(n,i,1);return kd(Math.ceil(e.value),e.dim,e.unit)}case`clamp`:{let[e,t,r]=Hd(n,i,3);return kd(Math.min(Math.max(e.value,t.value),r.value),e.dim,e.unit)}}let a=t.callFunction?.(n,i,r);if(a!==void 0)return a;throw new Md(`Unknown function: ${n}`)}var zd={sum:!0,max:!0,min:!0,avg:!0,count:!0,last:!0};function Bd(e,t,n){let r=e=>t.points.get(e)??0,i=new Map;for(let a of t.points.keys()){let t=0;for(let e=0;e<n;e++)t+=r(a-e);if(e===`windowSum`){i.set(a,t);continue}let o=t/n;if(e===`windowMean`){i.set(a,o);continue}let s=0;for(let e=0;e<n;e++){let t=r(a-e)-o;s+=t*t}i.set(a,Math.sqrt(s/n))}return{kind:`series`,points:i,dim:t.dim,unit:t.unit}}function Vd(e){if(e.kind===`ref`)return e.name;if(e.kind===`string`)return e.value;throw new Md(`convert() target unit must be a unit name`)}function Hd(e,t,n){let r=[];for(let n of t)if(n.kind!==`absent`){if(n.kind!==`number`)throw new Md(`${e}() requires numeric arguments`);r.push(n)}if(n!==void 0&&(t.length!==n||r.length!==n))throw new Md(`${e}() needs ${n} numeric argument(s), got ${r.length}`);return r}var Ud=class extends Error{constructor(e){super(e),this.name=`CalcRegistrationError`}};function Wd(e,t){switch(e.kind){case`literal`:return nd;case`period`:return nd;case`string`:return nd;case`filter`:return nd;case`ref`:{let n=t.refDim(e.name);if(!n)throw new Ud(`Unknown symbol: ${e.name}`);return n}case`wql`:return t.wqlDim?.(e)??nd;case`unary`:return e.op===`not`?nd:Wd(e.arg,t);case`binary`:{let{op:n}=e;if(n===`and`||n===`or`)return Wd(e.left,t),Wd(e.right,t),nd;if(n===`*`)return cd(Wd(e.left,t),Wd(e.right,t));if(n===`/`)return ld(Wd(e.left,t),Wd(e.right,t));let r=Gd(e.left,t),i=Gd(e.right,t);if(r&&i&&!ud(r,i))throw new Ud(`Dimension mismatch for '${n}': ${pd(r)} vs ${pd(i)}`);return n===`+`||n===`-`?r??nd:nd}case`call`:return qd(e,t)}}function Gd(e,t){if(e.kind!==`literal`||e.value!==0)return Wd(e,t)}function Kd(e){return e.kind===`string`?e.value:void 0}function qd(e,t){let{name:n,args:r}=e;if(n===`has`)return nd;if(n===`convert`){if(r.length!==2)throw new Ud(`convert() takes (value, targetUnit)`);let e=r[1],n=e.kind===`ref`?e.name:e.kind===`string`?e.value:void 0,i=n===void 0?void 0:Cd(n);if(!n||!i)throw new Ud(`convert() target must be a known unit name`);let a=Wd(r[0],t);if(!ud(a,i.dim))throw new Ud(`convert(x, ${n}) dimension mismatch: ${pd(a)} is not ${pd(i.dim)}`);return i.dim}if(n===`min`||n===`max`||n===`clamp`){let e;for(let i of r){let r=Wd(i,t);if(e&&!ud(e,r))throw new Ud(`${n}() arguments have mismatched dimensions`);e=r}if(!e)throw new Ud(`${n}() requires at least one argument`);return e}if(n===`abs`||n===`round`||n===`floor`||n===`ceil`){if(r.length<1)throw new Ud(`${n}() requires an argument`);return Wd(r[0],t)}if(n===`windowMean`||n===`windowSum`||n===`windowSd`||n===`windowEwma`){if(r.length!==2)throw new Ud(`${n}() takes (series, period)`);return Wd(r[0],t)}if(n===`lookup`){if(r.length!==3)throw new Ud(`lookup() takes (table, key, field)`);let e=Kd(r[0]),n=Kd(r[2]);if(!e||!n)throw new Ud(`lookup() table and field must be string literals`);Wd(r[1],t);let i=t.lookupDim?.(e,n);if(!i)throw new Ud(`Unknown lookup field: ${e}.${n}`);return i}let i=r.map(e=>e.kind===`filter`?nd:Wd(e,t)),a=t.callDim?.(n,i);if(!a)throw new Ud(`Unknown function: ${n}`);return a}function Jd(e,t){if(!t||t===`auto`||yd[t])return;let n=Cd(t);if(!n)throw new Ud(`Unknown output unit: ${t}`);if(!ud(n.dim,e))throw new Ud(`Declared unit ${t} (${pd(n.dim)}) does not match expression dimension ${pd(e)}`)}var Yd=class extends Error{pos;constructor(e,t){super(`${e} (at ${t})`),this.pos=t,this.name=`CalcParseError`}},Xd=/[A-Za-z_]/,Zd=/[A-Za-z0-9_.]/;function Qd(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===` `||r===` `||r===`
17
+ `||r===`\r`){n++;continue}if(r>=`0`&&r<=`9`||r===`.`&&e[n+1]>=`0`&&e[n+1]<=`9`){let r=/^\d*\.?\d+/.exec(e.slice(n)),i=n+r[0].length;if(e[i]===`d`&&!(i+1<e.length&&Zd.test(e[i+1]))){t.push({t:`period`,v:parseFloat(r[0]),pos:n}),n=i+1;continue}t.push({t:`num`,v:parseFloat(r[0]),pos:n}),n=i;continue}if(r===`"`||r===`'`){let i=e.indexOf(r,n+1);if(i<0)throw new Yd(`Unterminated string literal`,n);t.push({t:`str`,v:e.slice(n+1,i),pos:n}),n=i+1;continue}if(r===`{`){let r=e.indexOf(`}`,n+1);if(r<0)throw new Yd(`Unterminated filter braces`,n);t.push({t:`brace`,v:e.slice(n+1,r),pos:n}),n=r+1;continue}if(Xd.test(r)){let r=n+1;for(;r<e.length&&Zd.test(e[r]);)r++;let i=e.slice(n,r);if(i===`without`){let i=/^\s*:\s*([^,)]+)/.exec(e.slice(r));if(i){t.push({t:`filter`,v:i[1].trim(),pos:n}),n=r+i[0].length;continue}}t.push({t:`ident`,v:i,pos:n}),n=r;continue}let i=e.slice(n,n+2);if(i===`==`||i===`!=`||i===`<=`||i===`>=`||i===`->`){t.push({t:`op`,v:i,pos:n}),n+=2;continue}if(`+-*/()<>=,:`.includes(r)){t.push({t:`op`,v:r,pos:n}),n++;continue}throw new Yd(`Unexpected character '${r}'`,n)}return t.push({t:`eof`,pos:e.length}),t}var $d={or:1,and:2,"==":3,"!=":3,"<":3,"<=":3,">":3,">=":3,"+":4,"-":4,"*":5,"/":5},ef=class{tokens;pos=0;constructor(e){this.tokens=e}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}isOp(e){let t=this.peek();return t.t===`op`&&t.v===e}isIdent(e){let t=this.peek();return t.t===`ident`&&t.v===e}parseTop(){let e=this.parseExpression(),t=this.peek();if(t.t!==`eof`)throw new Yd(`Unexpected trailing input`,t.pos);return e}expectOp(e){let t=this.next();if(t.t!==`op`||t.v!==e)throw new Yd(`Expected '${e}'`,t.pos);return t}binaryOp(){let e=this.peek(),t=e.t===`op`||e.t===`ident`&&(e.v===`and`||e.v===`or`)?e.v:void 0;if(t===void 0)return;let n=$d[t];return n===void 0?void 0:{op:t,prec:n}}parseExpression(e=1){let t=this.parseUnary();for(;;){let n=this.binaryOp();if(!n||n.prec<e)return t;this.next();let r=this.parseExpression(n.prec+1);t={kind:`binary`,op:n.op,left:t,right:r}}}parseUnary(){let e=this.peek();return e.t===`op`&&e.v===`-`?(this.next(),{kind:`unary`,op:`-`,arg:this.parseUnary()}):e.t===`ident`&&e.v===`not`?(this.next(),{kind:`unary`,op:`not`,arg:this.parseUnary()}):this.parsePrimary()}parsePrimary(){let e=this.next();if(e.t===`num`)return{kind:`literal`,value:e.v};if(e.t===`period`)return{kind:`period`,days:e.v};if(e.t===`str`)return{kind:`string`,value:e.v};if(e.t===`op`&&e.v===`(`){let e=this.parseExpression();return this.expectOp(`)`),e}if(e.t===`op`&&e.v===`:`)throw new Yd(`Unexpected ':'`,e.pos);if(e.t===`ident`){if(this.isOp(`:`)){this.next();let t=this.next();if(t.t!==`ident`)throw new Yd(`Expected metric name after aggregator`,t.pos);let n,r,i=this.peek();if(i.t===`brace`&&(n=i.v,this.next()),this.isIdent(`by`)){this.next();let e=this.next();if(e.t!==`brace`)throw new Yd(`Expected '{dims}' after 'by'`,e.pos);r=e.v.split(`,`).map(e=>e.trim()).filter(Boolean)}return{kind:`wql`,aggregator:e.v,metric:t.v,filters:n,groupBy:r}}if(this.isOp(`(`)){this.next();let t=[];if(this.isOp(`)`))this.next();else for(;;){t.push(this.parseArg());let e=this.next();if(e.t!==`op`||e.v!==`,`){if(e.t===`op`&&e.v===`)`)break;throw new Yd(`Expected ',' or ')' in argument list`,e.pos)}}return{kind:`call`,name:e.v,args:t}}return{kind:`ref`,name:e.v}}throw new Yd(`Expected expression`,e.pos)}parseArg(){let e=this.peek();return e.t===`filter`?(this.next(),{kind:`filter`,value:e.v}):this.parseExpression()}};function tf(e){return new ef(Qd(e)).parseTop()}var nf=class{lookups;defs=new Map;libraryDims=new Map;constructor(e){this.lookups=e}byScope(e){return[...this.defs.values()].filter(t=>t.scope===e)}get(e){return this.defs.get(e)}register(e){if(e.variants.length===0)throw new Ud(`Calc ${e.id}: at least one variant is required`);let t=this.staticEnv();e.when&&(e.whenAst=rf(e.when,e.id,t)),e.variants=[...e.variants].sort((e,t)=>t.priority-e.priority);for(let n of e.variants)this.compileVariant(e,n,t);if(e.kind===`output`&&e.output?.unit&&e.output.unit!==`auto`)for(let t of e.variants)for(let n of sf(e)){let r=t.nodeDims?.[n];r&&Jd(r,e.output.unit)}if(e.kind===`library`)for(let t of e.variants)for(let[n,r]of Object.entries(t.nodeDims??{}))this.libraryDims.set(`${e.id}.${n}`,r);this.defs.set(e.id,e)}compileVariant(e,t,n){t.when&&(t.whenAst=rf(t.when,`${e.id}:${t.id}`,n));let r={},i=new Set,a=n=>{if(r[n])return r[n];let a=t.nodes[n];if(!a)throw new Ud(`Unknown symbol: ${n}`);if(i.has(n))throw new Ud(`Calc ${e.id}:${t.id}.${n}: cyclic node reference`);i.add(n);try{let i=a.ast??tf(af(e,t,n,a.expression));a.ast=i;let s=Wd(i,this.staticEnv(o));return a.unit&&(Jd(s,a.unit),yd[a.unit]&&(s=nd)),r[n]=s,s}catch(r){throw of(e,t,n,r)}finally{i.delete(n)}},o=e=>{if(e in t.nodes)return a(e)};for(let e of Object.keys(t.nodes))a(e);t.nodeDims=r}staticEnv(e=()=>void 0){return{refDim:t=>e(t)??this.libraryDims.get(t)??gd[t]?.dim??_d[t],callDim:(e,t)=>{if(e===`count`)return nd;if(vd[e])return t[0]},lookupDim:(e,t)=>this.lookups.fieldDim(e,t)}}};function rf(e,t,n){try{let t=tf(e);return Wd(t,n),t}catch(e){throw e instanceof Error?new Ud(`Calc ${t} predicate: ${e.message}`):e}}function af(e,t,n,r){if(!r)throw new Ud(`Calc ${e.id}:${t.id}.${n}: node needs an expression or AST`);return r}function of(e,t,n,r){return r instanceof Error?new Ud(`Calc ${e.id}:${t.id}.${n}: ${r.message}`):r}function sf(e){let t=e.output?.nodeId;return t?Array.isArray(t)?t:[t]:[]}var cf=class{registry;deps;id=`composed-calculations`;fenceTypes=[`time`,`log`];segmentCalcs;workoutCalcs;lastSegmentEffort;tagCarriedFunctions=new Map;activatedTags=new Set;runTags;constructor(e,t){this.registry=e,this.deps=t;let n=e=>!e.fences||e.fences.includes(t.dialect);this.segmentCalcs=e.byScope(`segment`).filter(n),this.workoutCalcs=e.byScope(`workout`).filter(n);for(let e of t.tags?.list()??[]){let n=xo(t.tags,e.slug);for(let t of n.functions){let n=this.tagCarriedFunctions.get(t);n?n.add(e.slug):this.tagCarriedFunctions.set(t,new Set([e.slug]))}}this.runTags=[...t.activeTags??[]];for(let e of this.runTags)this.activatedTags.add(e)}isActive(e,t){let n=this.tagCarriedFunctions.get(e.id);if(!n)return!0;for(let e of n)if(t.includes(e))return!0;return!1}appliedTags(e){let t=Eo(e.metrics.rawMetrics);for(let e of t)this.activatedTags.add(e);return this.runTags.length===0?t:[...t,...this.runTags.filter(e=>!t.includes(e))]}process(e){if(e.outputType!==`segment`||!e.isLeaf)return e;let t=mu(e.metrics.rawMetrics);t&&(this.lastSegmentEffort=t.resolved.slug);let n=lf(e,this.lastSegmentEffort),r=pf(e).slug??this.lastSegmentEffort,i={};if(r){i.effortSlug=r;let e=this.lookupString(r,`discipline`),t=this.lookupString(r,`intensityTier`);e&&(i.effortDiscipline=e),t&&(i.effortIntensityTier=t)}let a=e.metrics.rawMetrics.find(e=>e.type===`climb-grade`)?.value;a&&typeof a==`object`&&`raw`in a&&(i.grade=String(a.raw));let o=this.appliedTags(e);for(let t of this.segmentCalcs){if(!this.isActive(t,o))continue;let r=this.makeContext(n);if(!this.applicable(t.whenAst,r))continue;let a=this.selectVariant(t,r);if(!a)continue;let s=this.evaluateVariant(a,n);if(t.kind===`library`)for(let[t,n]of s)n.kind===`number`&&(this.hasFrozen(e,t)||this.appendAnnotation(e,t,n,a.origin,void 0,i));else for(let n of sf(t)){let r=s.get(n);r?.kind===`number`&&(this.hasFrozen(e,t.output?.emitType??t.id)||this.appendAnnotation(e,t.output?.emitType??t.id,r,a.origin,t.output?.unit,i))}}return e}appendAnnotation(e,t,n,r,i,a){let o=!i||i===`auto`?n.unit:i;e.metrics.add({type:t,image:o?`${_f(n.value)} ${o}`:_f(n.value),value:n.value,unit:o,origin:r,timestamp:new Date,...a&&Object.keys(a).length>0?{metadata:a}:{}})}hasFrozen(e,t){return e.metrics.rawMetrics.some(e=>e.type===t&&e.origin===`analyzed-estimated`)}summarize(e){let t=[];for(let t of e)if(t.outputType===`segment`)for(let e of Eo(t.metrics.rawMetrics))this.activatedTags.add(e);let n=[...this.activatedTags];for(let r of this.workoutCalcs)this.isActive(r,n)&&(r.output?.isGrouped?t.push(...this.summarizeGrouped(r,e)):t.push(...this.summarizeUngrouped(r,e)));return t}summarizeUngrouped(e,t){let n=this.buildWorkoutAtoms(t),r=this.makeContext(n);if(!this.applicable(e.whenAst,r))return[];let i=this.selectVariant(e,r);if(!i)return[];let a=this.evaluateVariant(i,n),o=this.toProjection(e,i,a,void 0);return o?[o]:[]}summarizeGrouped(e,t){let n=new Map;for(let e of t){if(e.outputType!==`segment`)continue;let t=pf(e);if(!t.slug)continue;let r=n.get(t.slug);r||(r={label:t.label,segments:[]},n.set(t.slug,r)),r.segments.push(e)}let r=[];for(let[t,i]of n){let n=this.buildWorkoutAtoms(i.segments),a=this.makeContext(n);if(!this.applicable(e.whenAst,a))continue;let o=this.selectVariant(e,a);if(!o)continue;let s=this.evaluateVariant(o,n),c=this.toProjection(e,o,s,{effortSlug:t,exerciseName:i.label,groupTags:{effort:t},effortDiscipline:this.lookupString(t,`discipline`),effortIntensityTier:this.lookupString(t,`intensityTier`)});c&&r.push(c)}return r}lookupString(e,t){let n=this.deps.lookups.lookup(`effort`,e,t);return n.kind===`string`&&n.value?n.value:void 0}toProjection(e,t,n,r){let i=sf(e)[0],a=n.get(i);if(a?.kind!==`number`)return;let o={canonicalKey:e.output?.key??e.id,...r};for(let t of e.output?.publishMetadataNodes??[]){let e=n.get(t);e?.kind===`number`&&(o[t]=e.value),e?.kind===`string`&&(o[t]=e.value)}return{name:e.output?.key??e.id,value:a.value,unit:!e.output?.unit||e.output.unit===`auto`?a.unit??``:e.output.unit,metricType:e.output?.emitType,timeSpan:{started:Date.now(),ended:Date.now()},origin:t.origin,metadata:o}}applicable(e,t){return!e||jd(Nd(e,t))}selectVariant(e,t){for(let n of e.variants)if(this.applicable(n.whenAst,t))return n}evaluateVariant(e,t){let n=new Map,r=new Set,i=i=>{let o=n.get(i);if(o)return o;let s=e.nodes[i];if(!s?.ast||r.has(i))return Od;r.add(i);let c=Nd(s.ast,this.makeContext(t,a));return r.delete(i),c.kind===`number`&&s.unit&&yd[s.unit]&&(c=kd(c.value,nd,s.unit)),n.set(i,c),c},a=t=>t in e.nodes?i(t):void 0;for(let t of Object.keys(e.nodes))i(t);return n}makeContext(e,t){return{resolveRef:n=>t?.(n)??e.resolveRef(n),callFunction:(t,n,r)=>t===`lookup`?this.deps.lookups.callFunction(t,n,r):e.callFunction?.(t,n,r)}}buildWorkoutAtoms(e){let t=new Map,n=e=>{let n=t.get(e);return n||(n=pf(e),t.set(e,n)),n},r=(t,r)=>{let i=gd[t],a=i?.metricType??t,o=[],s=i?.unit;for(let t of e)if(t.outputType===`segment`&&!(r&&mf(n(t).slug,r)))for(let e of t.getDisplayMetrics({types:[a]})){let t=uf(e);t!==void 0&&(o.push(t),s=df(e)??e.unit??s)}return{values:o,unit:s}},i=(e,t)=>{let n=t[0];if(n?.kind!==`ref`)return Od;let i=t[1]?.kind===`filter`?t[1].value:void 0,{values:a,unit:o}=r(n.name,i);if(a.length===0)return Od;let s=gd[n.name]?.dim;switch(e){case`sum`:return kd(a.reduce((e,t)=>e+t,0),s,o);case`max`:return kd(Math.max(...a),s,o);case`min`:return kd(Math.min(...a),s,o);case`avg`:return kd(a.reduce((e,t)=>e+t,0)/a.length,s,o);case`last`:return kd(a[a.length-1],s,o);case`count`:return kd(a.length);default:return Od}},a=new Map,o=(e,t)=>{let n=t.indexOf(`.`);if(n<0)return Od;let r=a.get(t);if(r)return r;let i=this.registry.get(t.slice(0,n));if(!i||i.kind!==`library`)return Od;let o=this.makeContext(e);if(!this.applicable(i.whenAst,o))return Od;let s=this.selectVariant(i,o);if(!s)return Od;let c=this.evaluateVariant(s,e);for(let[e,t]of c)a.set(`${i.id}.${e}`,t);return a.get(t)??Od},s={resolveRef:t=>{if(t===`session.duration`){let t=hf(e);return t===void 0?Od:kd(t,gd.elapsed.dim,`ms`)}if(t===`sessionRpe`){let t=gf(e,q.SessionRPE);return t===void 0?Od:kd(t)}if(t===`profile.vo2max`){let e=this.deps.userProfile?.vo2max;return e===void 0?Od:kd(e)}if(t===`effort`){for(let t=e.length-1;t>=0;t--){let n=mu(e[t].metrics.rawMetrics);if(n)return Ad(n.resolved.slug)}return Ad(``)}return t.includes(`.`)?o(s,t):Od},callFunction:(e,t,n)=>{if([`sum`,`max`,`min`,`avg`,`count`,`last`].includes(e))return i(e,n)}};return s}};function lf(e,t){let n=e.metrics.rawMetrics,r=t=>{let n=0,r=!1;for(let i of e.getDisplayMetrics({types:[t]}))typeof i.value==`number`&&(n+=i.value,r=!0);return r?n:void 0},i=t=>{let n=e.getMetric(t);if(!n)return;let r=uf(n);if(r!==void 0)return{value:r,unit:df(n)??n.unit}},a=r(q.Rep),o=typeof e.getMetric(q.Elapsed)?.value==`number`?e.getMetric(q.Elapsed).value:void 0,s=i(q.Distance),c=i(q.Resistance),l=mu(n),u=[...n].reverse().find(e=>e.type===q.Effort&&typeof e.value==`string`),d=[...n].some(e=>e.type===`climb-send-type`),f=[...n].find(e=>e.type===`climb-grade`)?.value,p=f&&typeof f==`object`&&`raw`in f?String(f.raw):void 0;return{resolveRef:e=>{switch(e){case`reps`:return a===void 0?Od:kd(a,gd.reps.dim,`reps`);case`elapsed`:return o===void 0?Od:kd(o,gd.elapsed.dim,`ms`);case`distance`:return s===void 0?Od:kd(s.value,gd.distance.dim,s.unit??`m`);case`resistance`:return c===void 0?Od:kd(c.value,gd.resistance.dim,c.unit??`kg`);case`climbSend`:return d?kd(1,gd.reps.dim,`count`):Od;case`climbGrade`:return p?Ad(p):Od;case`effort`:return Ad(l?.resolved.slug??t??``);case`effortLabel`:return u?Ad(u.value):Od;default:return Od}}}}function uf(e){if(typeof e.value==`number`)return e.value;let t=e.value;if(t&&typeof t==`object`&&`amount`in t&&typeof t.amount==`number`)return t.amount}function df(e){let t=e.value;if(t&&typeof t==`object`&&`units`in t&&typeof t.units==`string`&&t.units)return t.units}function ff(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``)}function pf(e){let t=mu(e.metrics.rawMetrics);if(t)return{slug:t.resolved.slug,label:t.resolved.label};let n=[...e.metrics.rawMetrics].reverse().find(e=>e.type===q.Effort&&typeof e.value==`string`);return n?{slug:ff(n.value),label:n.value}:{slug:``,label:``}}function mf(e,t){for(let n of t.split(`|`)){let t=n.trim();if(t){if(t.endsWith(`*`)){if(e.startsWith(t.slice(0,-1)))return!0}else if(e===t)return!0}}return!1}function hf(e){let t=e.filter(e=>e.outputType===`segment`);if(t.length===0)return;let n=t.find(e=>e.stackLevel===0||e.sourceBlockKey===`root`),r=e=>{let t=e.getMetric(q.Elapsed)?.value;return typeof t==`number`?t:0};if(n&&r(n)>0)return r(n);let i=t.filter(e=>e.stackLevel>0),a=(i.length>0?i:t).reduce((e,t)=>e+r(t),0);return a>0?a:void 0}function gf(e,t){let n;for(let r of e)for(let e of r.metrics.rawMetrics){if(e.type!==t)continue;let r=uf(e);r!==void 0&&(n=r)}return n}function _f(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/\.?0+$/,``)}var vf={bundled:0,dialect:1,user:2},yf=class{tables=new Map;register(e,t=`bundled`){let n=this.tables.get(e.id);n&&vf[n.layer]>vf[t]||this.tables.set(e.id,{table:e,layer:t})}get(e){return this.tables.get(e)?.table}fieldDim(e,t){return this.tables.get(e)?.table.fields[t]?.dimension}lookup(e,t,n){let r=this.tables.get(e)?.table;return r?r.get(t,n)??Od:Od}callFunction=(e,t)=>{if(e!==`lookup`)return;let[n,r,i]=t;if(n?.kind!==`string`||i?.kind!==`string`)throw new Md(`lookup() table and field must be strings`);if(r.kind===`absent`||r.kind===`series`||r.kind===`period`)return Od;let a=r.kind===`string`?r.value:String(r.value);return this.lookup(n.value,a,i.value)}},bf=`rest|pause|rest-*`,Y=(e,t,n)=>({id:e,kind:`expr`,expression:t,unit:n}),xf=[{id:`pace-reps`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(reps)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`reps / convert(elapsed, min)`)}}],output:{nodeId:`value`,emitType:`pace`,unit:`reps/min`}},{id:`pace-speed`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(distance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`distance / convert(elapsed, s)`)}}],output:{nodeId:`value`,emitType:`pace`,unit:`m/s`}},{id:`pace-runner`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(distance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`convert(elapsed, min) / convert(distance, km)`)}}],output:{nodeId:`value`,emitType:`pace`,unit:`min/km`}},{id:`power`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(reps) and has(resistance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`reps * resistance / convert(elapsed, s)`)}}],output:{nodeId:`value`,emitType:`power`,unit:`auto`}},{id:`segment-volume`,kind:`library`,scope:`segment`,when:`has(reps) and has(resistance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{segmentVolume:Y(`segmentVolume`,`reps * resistance`)}}]},{id:`e1rm`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`has(reps) and has(resistance) and reps > 0 and resistance > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{repFactor:Y(`repFactor`,`reps / 30`,`ratio`),value:Y(`value`,`round(resistance * (1 + repFactor), 1)`)}}],output:{nodeId:`value`,emitType:`calc.e1rm`,key:`calc.e1rm`,unit:`auto`,label:`Estimated 1RM`}},{id:`pct1rm`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`has(reps) and has(resistance) and reps > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{repFactor:Y(`repFactor`,`reps / 30`,`ratio`),value:Y(`value`,`100 / (1 + repFactor)`)}}],output:{nodeId:`value`,emitType:`calc.pct1rm`,key:`calc.pct1rm`,unit:`%`,label:`%1RM Intensity`}},{id:`climb-sends`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`has(climbSend)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`climbSend`)}}],output:{nodeId:`value`,emitType:`calc.sends`,key:`calc.sends`,unit:`count`,label:`Sends`}},{id:`effort-rpe`,kind:`library`,scope:`segment`,when:`has(effortLabel)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{effortRpe:Y(`effortRpe`,`lookup("rpe-labels", effortLabel, "rpe")`)}}]},{id:`met-minutes-segment`,kind:`library`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0`,variants:[{id:`resolved`,priority:100,when:`lookup("effort", effort, "resolvedFrom") != "default"`,origin:`analyzed`,nodes:{metMinutes:Y(`metMinutes`,`lookup("effort", effort, "met") * convert(elapsed, min)`)}},{id:`unresolved`,priority:10,origin:`analyzed-estimated`,nodes:{metMinutes:Y(`metMinutes`,`lookup("effort", effort, "met") * convert(elapsed, min)`),metMinutesEstimated:Y(`metMinutesEstimated`,`1`)}}]},{id:`total-reps`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(reps)) and sum(reps) > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(reps)`)}}],output:{nodeId:`total`,key:`reps`,emitType:`rep`,unit:`reps`}},{id:`total-reps-by-effort`,kind:`output`,scope:`workout`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(reps, without: ${bf})`)}}],output:{nodeId:`total`,key:`reps`,emitType:`rep`,unit:`reps`,isGrouped:!0,groupBy:[`effort`]}},{id:`total-distance`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(distance)) and sum(distance) > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(distance)`)}}],output:{nodeId:`total`,key:`distance`,emitType:`distance`,unit:`auto`}},{id:`total-volume`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(segmentVolume)) and sum(segmentVolume) > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(segmentVolume)`)}}],output:{nodeId:`total`,key:`totalVolume`,emitType:`volume`,unit:`auto`}},{id:`total-volume-by-effort`,kind:`output`,scope:`workout`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(segmentVolume)`),totalSets:Y(`totalSets`,`count(segmentVolume)`)}}],output:{nodeId:`total`,key:`totalVolume`,emitType:`volume`,unit:`auto`,isGrouped:!0,groupBy:[`effort`],publishMetadataNodes:[`totalSets`]}},{id:`met-minutes`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(metMinutes))`,variants:[{id:`estimated`,priority:100,when:`sum(metMinutesEstimated) > 0`,origin:`analyzed-estimated`,nodes:{total:Y(`total`,`round(sum(metMinutes))`)}},{id:`resolved`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`round(sum(metMinutes))`)}}],output:{nodeId:`total`,key:`calc.metMinutes`,emitType:`work`,unit:`MET-min`}},{id:`rpeSource`,kind:`library`,scope:`workout`,variants:[{id:`captured`,priority:100,when:`has(sessionRpe)`,origin:`analyzed`,nodes:{rpe:Y(`rpe`,`sessionRpe`)}},{id:`label`,priority:50,when:`has(max(effortRpe))`,origin:`analyzed`,nodes:{rpe:Y(`rpe`,`max(effortRpe)`)}},{id:`default`,priority:10,origin:`analyzed-estimated`,nodes:{rpe:Y(`rpe`,`5`)}}]},{id:`session-load`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(session.duration)`,variants:[{id:`captured-rpe`,priority:100,when:`has(sessionRpe)`,origin:`analyzed`,nodes:Sf()},{id:`label-rpe`,priority:50,when:`has(max(effortRpe))`,origin:`analyzed`,nodes:Sf()},{id:`default-rpe`,priority:10,origin:`analyzed-estimated`,nodes:Sf()}],output:{nodeId:`load`,key:`sessionLoad`,emitType:`load`,unit:`AU`,publishMetadataNodes:[`sRPE`,`durationMinutes`]}},{id:`sharedMet`,kind:`library`,scope:`workout`,variants:[{id:`personalized`,priority:100,when:`has(profile.vo2max)`,origin:`analyzed`,nodes:{metMax:Y(`metMax`,`profile.vo2max / 3.5`)}},{id:`population`,priority:10,origin:`analyzed`,nodes:{metMax:Y(`metMax`,`11.4`)}}]},{id:`tis`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(metMinutes)) and has(sum(elapsed))`,variants:[{id:`resolved`,priority:100,when:`not (sum(metMinutesEstimated) > 0)`,origin:`analyzed`,nodes:Cf()},{id:`estimated`,priority:10,origin:`analyzed-estimated`,nodes:Cf()}],output:{nodeId:`tis`,key:`tis`,emitType:`tis`,unit:`pts`,publishMetadataNodes:[`metScore`,`rpeScore`,`durationScore`,`disciplineFactor`,`metMax`]}}];function Sf(){return{sRPE:Y(`sRPE`,`rpeSource.rpe`),durationMinutes:Y(`durationMinutes`,`convert(session.duration, min)`),load:Y(`load`,`round(rpeSource.rpe * convert(session.duration, min))`)}}function Cf(){return{elapsedMin:Y(`elapsedMin`,`convert(sum(elapsed), min)`),avgMets:Y(`avgMets`,`sum(metMinutes) / elapsedMin`),metMax:Y(`metMax`,`sharedMet.metMax`),metScore:Y(`metScore`,`min(100, avgMets / metMax * 100)`),rpeScore:Y(`rpeScore`,`rpeSource.rpe * 10`),durationScore:Y(`durationScore`,`elapsedMin / 60 * metScore`,`pts`),disciplineFactor:Y(`disciplineFactor`,`lookup("effort", effort, "disciplineFactor")`),tis:Y(`tis`,`round(0.30 * metScore + 0.35 * rpeScore + 0.20 * durationScore + 0.15 * disciplineFactor, 1)`)}}var wf=()=>({id:`daily`,kind:`wql`,expression:`sum:sessionLoad{} by {day}`}),Tf=[{id:`acwr`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:wf(),acute:Y(`acute`,`windowMean(daily, 7d)`),chronic:Y(`chronic`,`windowMean(daily, 28d)`),value:Y(`value`,`acute / chronic`)}}],output:{nodeId:`value`,key:`calc.acwr`,unit:`ratio`,label:`Acute:Chronic Workload Ratio`}},{id:`monotony`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:wf(),mean7:Y(`mean7`,`windowMean(daily, 7d)`),sd7:Y(`sd7`,`windowSd(daily, 7d)`),value:Y(`value`,`mean7 / sd7`)}}],output:{nodeId:`value`,key:`calc.monotony`,unit:`ratio`,label:`Training Monotony`}},{id:`strain`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:wf(),monotony:Y(`monotony`,`windowMean(daily, 7d) / windowSd(daily, 7d)`,`ratio`),weekly:Y(`weekly`,`windowSum(daily, 7d)`),value:Y(`value`,`monotony * weekly`)}}],output:{nodeId:`value`,key:`calc.strain`,unit:`AU`,label:`Training Strain`}},{id:`ctl`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:wf(),value:Y(`value`,`windowEwma(daily, 42d)`)}}],output:{nodeId:`value`,key:`calc.ctl`,unit:`AU`,label:`Chronic Training Load (CTL)`}},{id:`atl`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:wf(),value:Y(`value`,`windowEwma(daily, 7d)`)}}],output:{nodeId:`value`,key:`calc.atl`,unit:`AU`,label:`Acute Training Load (ATL)`}},{id:`tsb`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:wf(),ctl:Y(`ctl`,`windowEwma(daily, 42d)`),atl:Y(`atl`,`windowEwma(daily, 7d)`),value:Y(`value`,`ctl - atl`)}}],output:{nodeId:`value`,key:`calc.tsb`,unit:`AU`,label:`Training Stress Balance (TSB)`}},{id:`soreness`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`user`,nodes:{daily:{id:`daily`,kind:`wql`,expression:`avg:soreness{} by {day}`},value:Y(`value`,`daily * (daily / daily)`)}}],output:{nodeId:`value`,key:`calc.soreness`,unit:`rating`,label:`Soreness`}},{id:`sleep`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`user`,nodes:{daily:{id:`daily`,kind:`wql`,expression:`avg:sleep{} by {day}`},value:Y(`value`,`daily * (daily / daily)`)}}],output:{nodeId:`value`,key:`calc.sleep`,unit:`pts`,label:`Sleep (h)`}},{id:`hrv`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`user`,nodes:{daily:{id:`daily`,kind:`wql`,expression:`avg:hrv{} by {day}`},value:Y(`value`,`daily * (daily / daily)`)}}],output:{nodeId:`value`,key:`calc.hrv`,unit:`pts`,label:`HRV (ms)`}},{id:`readiness`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{soreness:{id:`soreness`,kind:`wql`,expression:`avg:soreness{} by {day}`},sleep:{id:`sleep`,kind:`wql`,expression:`avg:sleep{} by {day}`},hrv:{id:`hrv`,kind:`wql`,expression:`avg:hrv{} by {day}`},value:Y(`value`,`((10 - soreness) / 10 * 40 + sleep / 8 * 30 + hrv / 90 * 30) * (soreness / soreness) * (sleep / sleep) * (hrv / hrv)`)}}],output:{nodeId:`value`,key:`calc.readiness`,unit:`pts`,label:`Readiness`}},{id:`mvcBw`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{hang:{id:`hang`,kind:`wql`,expression:`max:hang{} by {day}`},weight:{id:`weight`,kind:`wql`,expression:`avg:weight{} by {day}`},value:Y(`value`,`hang / weight * 100`)}}],output:{nodeId:`value`,key:`calc.mvcBw`,unit:`%`,label:`Max Hang %BW`}},{id:`ef`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{dist:{id:`dist`,kind:`wql`,expression:`sum:totalDistance{discipline:running} by {day}`},elapsed:{id:`elapsed`,kind:`wql`,expression:`sum:elapsed{discipline:running} by {day}`},hr:{id:`hr`,kind:`wql`,expression:`avg:hr{} by {day}`},pace:Y(`pace`,`dist / (elapsed / 1000)`,`pts`),value:Y(`value`,`pace / hr * 100000`,`pts`)}}],output:{nodeId:`value`,key:`calc.ef`,unit:`pts`,label:`Efficiency Factor`}},{id:`adherence`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{sessions:{id:`sessions`,kind:`wql`,expression:`count:sessionLoad{} by {day}`},planned:{id:`planned`,kind:`wql`,expression:`avg:planned{} by {day}`},value:Y(`value`,`sessions / planned`)}}],output:{nodeId:`value`,key:`calc.adherence`,unit:`ratio`,label:`Plan Adherence`}}],Ef={easy:3,moderate:5,hard:7,"all-out":10,max:10};function Df(e){return{id:`effort`,missPolicy:`default-row`,fields:{met:{dimension:nd,type:`number`},disciplineFactor:{dimension:nd,type:`number`},discipline:{dimension:nd,type:`string`},intensityTier:{dimension:nd,type:`string`},resolvedFrom:{dimension:nd,type:`string`},isEstimated:{dimension:nd,type:`number`}},get(t,n){if(!t)switch(n){case`met`:return kd(cc.defaultMet);case`disciplineFactor`:return kd(1);case`resolvedFrom`:return Ad(`default`);case`isEstimated`:return kd(1);default:return}let r=e.resolveEffort(t);switch(n){case`met`:return kd(r.met);case`disciplineFactor`:return kd(r.disciplineFactor);case`discipline`:return r.discipline?Ad(r.discipline):void 0;case`intensityTier`:return r.intensityTier?Ad(r.intensityTier):void 0;case`resolvedFrom`:return Ad(r.resolvedFrom);case`isEstimated`:return kd(+!!r.isEstimated);default:return}}}}function Of(){return{id:`rpe-labels`,missPolicy:`absent`,fields:{rpe:{dimension:nd,type:`number`}},get(e,t){if(t!==`rpe`)return;let n=Ef[e.toLowerCase()];return n===void 0?void 0:kd(n)}}}function kf(e){return{id:`profile`,missPolicy:`absent`,fields:{vo2max:{dimension:nd,type:`number`}},get(t,n){if(n===`vo2max`)return e?.vo2max===void 0?void 0:kd(e.vo2max)}}}function Af(){return{id:`disciplines`,missPolicy:`default-row`,fields:{disciplineFactor:{dimension:nd,type:`number`}},get(e,t){if(t===`disciplineFactor`)return kd(Sc(e)?wc(e):1)}}}function jf(e){let t=new yf;t.register(Df(e.effortResolver)),t.register(Of()),t.register(kf(e.userProfile)),t.register(Af());let n=new nf(t);for(let e of xf)n.register(e);for(let t of e.calcs??[])n.register(t);return{lookups:t,registry:n}}function Mf(e,t){let n=jf(t);return new cf(n.registry,{dialect:e,lookups:n.lookups,userProfile:t.userProfile,tags:t.tags,activeTags:t.activeTags})}var Nf=new Ja([]),Pf=new Ja([]),Ff=class{build(e){let t=[],n=[];if(e.analyticsContext?.effortResolver){t.push(new td(e.analyticsContext.effortResolver));let r=Mf(e.dialect,{effortResolver:e.analyticsContext.effortResolver,userProfile:e.userProfile,calcs:e.calcs,tags:e.tags,activeTags:e.activeTags});t.push(r),n.push(r)}return t.push(...Nf.list().filter(t=>this.isApplicable(t,e))),n.push(...Pf.list().filter(t=>this.isApplicable(t,e))),{realtime:t,summary:n}}isApplicable(e,t){if(e.fenceTypes&&e.fenceTypes.length>0&&!e.fenceTypes.includes(t.dialect))return!1;if(e.requiredMetrics&&e.requiredMetrics.length>0){for(let n of e.requiredMetrics)if(!t.scriptMetricTypes.has(n))return!1}return!0}};function If(e,t){let n=e.dialect||`time`,r=new Set;if(e.statements)for(let t of e.statements)for(let e of t.metrics)r.add(e.type);let i=t?.effortResolver;if(!i){let e=new Xc;e.seed(Yc),i=new qc(e)}let a={effortResolver:i,...t?.references?{references:t.references}:{}},o={dialect:n,scriptMetricTypes:r,analyticsContext:a,userProfile:t?.userProfile,calcs:t?.calcs,tags:t?.tags,activeTags:t?.activeTags},{realtime:s,summary:c}=new Ff().build(o),l=new ed;for(let e of s)l.addRealtimeProcessor(e);for(let e of c)l.addSummaryProcessor(e);return{engine:l,analyticsContext:a}}function Lf(e,t){return!e.metrics.some(e=>e===t)}function Rf(e){let t=[];return e.forEach((e,n)=>{for(let r of e.metrics)if(r.type===q.Choice){let i=r;Lf(e,i)||t.push({statementIndex:n,statementId:e.id,choice:i})}}),t}function zf(e,t,n){let r=t[n]??t[0];r&&(e.metrics.remove(e=>e.type===r.type&&e.origin===`user-plan`),e.metrics.remove(e=>e.type===q.Choice&&e.alternatives===t),e.metrics.add({...r,origin:`user-plan`}))}function Bf(e){let t=Rf(e);for(let n of t){let t=e[n.statementIndex],r=n.choice.alternatives[0]?.type;r&&t.metrics.some(e=>e.type===r&&e.origin===`user-plan`)?t.metrics.remove(e=>e===n.choice):zf(t,n.choice.alternatives,0)}return t.length}var Vf=class{compiler;nowProvider;constructor(e,t=rl){this.compiler=e,this.nowProvider=t}createRuntime(e,t){if(!e.statements||e.statements.length===0)return null;let n=new tc(e.content,e.statements);Bf(n.statements);let r={stack:new Wl,clock:new nl,eventBus:new qu},i=new El(n,this.compiler,r,t,this.nowProvider),{engine:a,analyticsContext:o}=If(e,t?.analyticsOptions);return i.analyticsContext=o,i.setAnalyticsEngine(a),i.do(new $u),i}disposeRuntime(e){e.dispose()}},Hf=class{static build(e,t={}){let{includeMetric:n=!0,includeLogic:r=!0,includeIdentity:i=!0,includeAttributes:a=!0,defaultLabel:o=`Block`,format:s=`logic-first`}=t,c=J.from(e.flatMap(e=>J.from(e.metrics).toArray()).filter(e=>e.origin!==`runtime`&&e.type!==q.Hint));if(c.length===0)return o;let l=c.find(e=>e.type===q.Label);if(l)return l.image||l.value?.toString()||o;let u=n?this.getPrimaryMetric(c):void 0,d=r?this.getLogicKeyword(e,c):void 0,f=i?this.getIdentityText(c):void 0,p=a?this.getAttributesText(c):void 0,m=[];return s===`logic-first`?(d&&m.push(d),u&&m.push(u),f&&m.push(f),p&&m.push(p)):s===`metric-first`?(u&&m.push(u),d&&m.push(d),f&&m.push(f),p&&m.push(p)):(f&&m.push(f),u&&m.push(u),d&&m.push(d),p&&m.push(p)),m.length===0?c.filter(e=>!!e.image&&!jo.isStructural(e)).map(e=>e.image).join(` `)||o:m.join(` `).trim().replace(/\s+/g,` `)}static getPrimaryMetric(e){let t=e.find(e=>e.type===q.Rounds);if(t&&t.image)return t.image;let n=e.find(e=>e.type===q.Duration);if(n&&n.image)return n.image}static getLogicKeyword(e,t){if(e.some(e=>eo(e,Ya.LABEL_AMRAP)))return`AMRAP`;if(e.some(e=>eo(e,Ya.LABEL_EMOM)))return`EMOM`;if(e.some(e=>eo(e,Ya.LABEL_TABATA)))return`TABATA`;if(e.some(e=>eo(e,Ya.LABEL_FOR_TIME)))return`FOR TIME`;let n=[`AMRAP`,`EMOM`,`TABATA`,`FOR TIME`];for(let e of t){let t=(e.image||e.value?.toString()||``).toUpperCase();if(n.includes(t))return t}}static getIdentityText(e){let t=[`AMRAP`,`EMOM`,`TABATA`,`FOR TIME`],n=e.filter(e=>{if(e.type===q.Duration||e.type===q.Rounds||e.type===q.Resistance||e.type===q.Distance||e.type===q.Lap||e.type===q.Group)return!1;let n=(e.image||e.value?.toString()||``).toUpperCase();return!t.includes(n)});if(n.length!==0)return n.map(e=>e.image).join(` `).trim()}static getAttributesText(e){let t=e.filter(e=>e.type===q.Resistance||e.type===q.Distance);if(t.length!==0)return t.map(e=>e.image).join(` `).trim()}},Uf=class{distribute(e,t){return[e.clone()]}},Wf=e=>e[0];function Gf(e,t){let{statements:n,runtime:r,blockType:i,defaultLabel:a}=t,o=(t.pickStatement??Wf)(n),s=t.key??new _a,c=t.context??new Pl(r,s.toString(),o.exerciseId||``),l=Hf.build(n,{defaultLabel:a});e.setContext(c).setKey(s).setBlockType(i).setLabel(l).setSourceIds(n.map(e=>e.id));let u=t.metricDistributorType??i,d=new Uf,f=t.filterMetrics,p=n.flatMap(e=>{let t=f?J.from(e.metrics.filter(f)):J.from(e.metrics);return d.distribute(t,u)}).filter(e=>e.length>0);if(e.setFragments(p),t.timer){let n=t.timer,r=n.mode===`reset-interval`?{completesBlock:!1}:void 0;e.asTimer({direction:n.direction,durationMs:n.durationMs,label:n.label,role:n.role??`primary`,addCompletion:n.mode!==`reset-interval`,completionConfig:r,injectRest:n.injectRest,required:n.required,...t.countdownTimerConfig??{}})}if(t.repeater){let n=t.repeater;e.asRepeater({totalRounds:n.totalRounds,startRound:n.startRound??1,addCompletion:n.addCompletion})}return l}var Kf=class{priority=90;id=`amrap-logic`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.hasMetric(q.Duration)),r=e.some(e=>e.hasMetric(q.Rounds)),i=e.some(e=>e.metrics.some(e=>(e.type===q.Effort||e.type===q.Action)&&typeof e.value==`string`&&(e.value.toLowerCase()===`rounds`||e.value.toLowerCase()===`amrap`)));return n&&(r||i)}apply(e,t,n){let r=(t.find(e=>e.hasMetric(q.Duration))||t[0]).metrics.find(e=>e.type===q.Duration)?.value||0,i=Gf(e,{blockType:`AMRAP`,defaultLabel:`AMRAP ${Math.round(r/6e4)} min`,statements:t,runtime:n,timer:{direction:`down`,durationMs:r,label:`AMRAP`,role:`primary`,mode:`complete-block`,injectRest:!1},repeater:{totalRounds:void 0,startRound:1,addCompletion:!1},pickStatement:e=>e.find(e=>e.hasMetric(q.Duration))||e[0]});e.addBehavior(new lu({mode:`countdown`,label:i}))}},qf=class{priority=90;id=`interval-logic`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.metrics.some(e=>e.type===q.Duration)),r=e.some(e=>eo(e,Ya.REPEATING_INTERVAL)),i=e.some(e=>e.metrics.some(e=>(e.type===q.Action||e.type===q.Effort)&&typeof e.value==`string`&&e.value.toLowerCase()===`emom`));return n&&(r||i)}apply(e,t,n){let r=(t.find(e=>e.metrics.some(e=>e.type===q.Duration))||t[0]).metrics.find(e=>e.type===q.Duration),i=t.flatMap(e=>J.from(e.metrics).toArray()).find(e=>e.type===q.Rounds),a=r?.value||6e4,o=typeof i?.value==`number`?i.value:10,s=Gf(e,{blockType:`EMOM`,defaultLabel:`EMOM ${o}`,statements:t,runtime:n,timer:{direction:`down`,durationMs:a,label:`Interval`,role:`primary`,mode:`reset-interval`,injectRest:!0},repeater:{totalRounds:o,startRound:1,addCompletion:!0},pickStatement:e=>e.find(e=>e.hasMetric(q.Duration))||e[0],metricDistributorType:`EMOM`});e.addBehavior(new lu({mode:`countdown`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===q.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===q.Distance)),u=[...c?[{metricType:q.Resistance,origin:`compiler`}]:[],...l?[{metricType:q.Distance,origin:`compiler`}]:[]];u.length>0&&e.addBehavior(new su({promotions:u}))}},Jf=class{priority=0;id=`effort-fallback`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`)),r=e.some(e=>e.metrics.some(e=>e.type===q.Rounds&&e.origin!==`runtime`)),i=e.some(e=>e.children&&e.children.length>0);return!n&&!r&&!i}apply(e,t,n){Gf(e,{blockType:`effort`,defaultLabel:`Effort`,statements:t,runtime:n,timer:{direction:`up`,role:`secondary`,mode:`reset-interval`},filterMetrics:e=>e.origin!==`runtime`}),e.addBehavior(new cu({mode:`immediate`,onNext:!0}))}},Yf=class{priority=50;id=`generic-group`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.children&&e.children.length>0),r=e.some(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`)),i=e.some(e=>e.metrics.some(e=>e.type===q.Rounds&&e.origin!==`runtime`));return n&&!r&&!i}apply(e,t,n){if(e.hasTimerBehavior()||e.hasRoundConfig())return;let r=Gf(e,{blockType:`Group`,defaultLabel:`Group`,statements:t,runtime:n});e.addBehavior(new lu({mode:`clock`,label:r}));let i=t.some(e=>e.metrics.some(e=>e.type===q.Resistance)),a=t.some(e=>e.metrics.some(e=>e.type===q.Distance)),o=[...i?[{metricType:q.Resistance,origin:`compiler`}]:[],...a?[{metricType:q.Distance,origin:`compiler`}]:[]];o.length>0&&e.addBehavior(new su({promotions:o}))}},Xf=class{priority=50;id=`generic-loop`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===q.Rounds))}apply(e,t,n){if(e.hasRoundConfig())return;let r=(t.find(e=>e.metrics.some(e=>e.type===q.Rounds))||t[0]).metrics.find(e=>e.type===q.Rounds);if(!r)return;let i=1,a;typeof r.value==`number`&&(i=r.value);let o=t.flatMap(e=>e.metrics.filter(e=>e.type===q.Rep&&typeof e.value==`number`)).map(e=>e.value);o.length>0&&(a=o,i<=1&&(i=a.length));let s=Gf(e,{blockType:`Rounds`,defaultLabel:a?a.join(`-`):`${i} Rounds`,statements:t,runtime:n,repeater:{totalRounds:i,startRound:1,addCompletion:!0},pickStatement:e=>e.find(e=>e.metrics.some(e=>e.type===q.Rounds))||e[0],filterMetrics:e=>e.type!==q.Rep});e.addBehavior(new lu({mode:`clock`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===q.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===q.Distance)),u=[...c?[{metricType:q.Resistance,origin:`compiler`}]:[],...l?[{metricType:q.Distance,origin:`compiler`}]:[]];e.addBehavior(new su({repScheme:a,promotions:u})),e.declareExit(`immediate`)}},Zf=class{priority=50;id=`generic-timer`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`))}apply(e,t,n){if(e.hasTimerBehavior())return;let r=(t.find(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`))||t[0]).metrics.find(e=>e.type===q.Duration&&e.origin!==`runtime`),i=r?.direction||`up`,a=r?.value||void 0,o=t.some(e=>eo(e,Ya.REQUIRED_TIMER)),s=t.some(e=>eo(e,Ya.INJECT_REST)),c=!!(a&&i===`down`),l=Gf(e,{blockType:`Timer`,defaultLabel:i===`down`?`Countdown`:`For Time`,statements:t,runtime:n,timer:{direction:i,durationMs:a,label:a?`Countdown`:`For Time`,role:`primary`,mode:`complete-block`,injectRest:s,required:o},pickStatement:e=>e.find(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`))||e[0]});o&&c?e.addBehavior(new cu({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})):e.addBehavior(new cu({mode:`immediate`,onNext:!0})),e.addBehavior(new lu({mode:a?`countdown`:`clock`,label:l}))}},Qf=class{priority=50;id=`children`;match(e,t){return e&&e.length>0&&e[0].children&&e[0].children.length>0}apply(e,t,n){let r=t[0].children.filter(e=>e.length>0),i=e.hasRoundConfig(),a=e.getBehavior(au),o=!!a;i||(o?e.asRepeater({totalRounds:void 0,startRound:1,addCompletion:!1}):e.asRepeater({totalRounds:1,startRound:1,addCompletion:!0}));let s=o||i,c=i?`rounds-remaining`:`timer-active`,l=o&&a?.config.mode===`reset-interval`;e.asContainer({childGroups:r,addLoop:s,loopConfig:s?{condition:c}:void 0,injectRest:l}),e.declareExit(`deferred`)}},$f=class{priority=15;id=`report-output`;match(e,t){return e&&e.length>0}apply(e,t,n){e.hasBehavior(Eu)||e.addBehavior(new Eu)}},ep=class{priority=20;id=`sound`;match(e,t){return e.length>0}apply(e,t,n){if(e.hasBehavior(Pu)||!e.hasTimerBehavior())return;let r=zu(t,n.options?.soundOptions);e.addBehavior(new Pu({profile:r}))}},tp=class e{now;name=`next`;timestamp;_data;static _counter=0;constructor(t,n=rl){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this._data=t}get data(){return this._data}set data(e){this._data=e}toJSON(){return{name:this.name,timestamp:this.timestamp,data:this._data}}},np=new Ja([new Kf,new qf,new Zf,new Xf,new Yf,new ep,new $f,new Qf,new Jf]);np.list();function rp(e){let t=new Ku;for(let n of e??np.list())t.registerStrategy(n);return t}var ip=class{id;onStackSnapshotCallback;onOutputCallback;constructor(e){this.id=e?.id??`local`,this.onStackSnapshotCallback=e?.onStackSnapshot,this.onOutputCallback=e?.onOutput}onStackSnapshot(e){this.onStackSnapshotCallback?.(e)}onOutput(e){this.onOutputCallback?.(e)}dispose(){this.onStackSnapshotCallback=void 0,this.onOutputCallback=void 0}},ap=class{runtime;subscriptions=new Map;stackUnsub=null;outputUnsub=null;disposed=!1;constructor(e){this.runtime=e,this.stackUnsub=this.runtime.subscribeToStack(e=>{for(let t of this.subscriptions.values())try{t.onStackSnapshot(e)}catch(e){console.error(`[SubscriptionManager] Error in subscription '${t.id}' onStackSnapshot:`,e)}}),this.outputUnsub=this.runtime.subscribeToOutput(e=>{for(let t of this.subscriptions.values())try{t.onOutput(e)}catch(e){console.error(`[SubscriptionManager] Error in subscription '${t.id}' onOutput:`,e)}})}add(e){if(this.disposed){console.warn(`[SubscriptionManager] Cannot add subscription after dispose`);return}let t=this.subscriptions.get(e.id);t&&t.dispose(),this.subscriptions.set(e.id,e);try{e.onStackSnapshot({type:`initial`,blocks:[...this.runtime.stack.blocks],depth:this.runtime.stack.count,clockTime:this.runtime.clock.currentDate});let t=this.runtime.getOutputStatements();for(let n of t)e.onOutput(n)}catch(t){console.error(`[SubscriptionManager] Error catching up subscription '${e.id}':`,t)}}remove(e){let t=this.subscriptions.get(e);return t?(t.dispose(),this.subscriptions.delete(e),!0):!1}has(e){return this.subscriptions.has(e)}get count(){return this.subscriptions.size}dispose(){if(!this.disposed){this.disposed=!0,this.stackUnsub?.(),this.stackUnsub=null,this.outputUnsub?.(),this.outputUnsub=null;for(let e of this.subscriptions.values())try{e.dispose()}catch(t){console.error(`[SubscriptionManager] Error disposing subscription '${e.id}':`,t)}this.subscriptions.clear()}}},op=/^(segment|workout|store)\b/;function sp(e,t){let n=[],r=[],i=t?.scope,a=t?.fences,o;for(let s of e.split(/\r?\n/)){let e=s.trim();if(!e||e.startsWith(`#`))continue;let c=op.exec(e);if(c&&/^(on\s|when\s|:)/.test(e.slice(c[0].length).trim())){i=c[1];let t=cp(e.slice(c[0].length).trim());a=t.fences,o=t.when;continue}n.push(yp(e,i??t?.scope??`segment`,a,o,r))}return{defs:n,warnings:r}}function cp(e){let t=e.replace(/^\s*:/,``).trim(),n,r=/^on\s*\[([^\]]*)\]/.exec(t);r&&(n=r[1].split(`,`).map(e=>e.trim()).filter(Boolean),t=t.slice(r[0].length).trim());let i,a=/^when\s+([\s\S]+)$/.exec(t);return a&&(i=a[1].replace(/:\s*$/,``).trim()),{fences:n,when:i}}function lp(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===` `||r===` `){n++;continue}if(r===`"`){let r=n+1;for(;r<e.length&&e[r]!==`"`;)r++;t.push({pos:n,word:e.slice(n+1,r),isStr:!0}),n=r<e.length?r+1:r;continue}let i=e.slice(n,n+2);if(i===`->`||i===`==`||i===`!=`||i===`<=`||i===`>=`){t.push({pos:n,op:i}),n+=2;continue}if(`(),[]{}|=<:`.includes(r)){t.push({pos:n,op:r}),n++;continue}if(/[0-9A-Za-z_.]/.test(r)){let r=n+1;for(;r<e.length&&/[0-9A-Za-z_.]/.test(e[r]);)r++;t.push({pos:n,word:e.slice(n,r)}),n=r;continue}n++}return t}function up(e,t){let n=[],r=0,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===`"`){i=!i;continue}i||(o===`(`||o===`[`||o===`{`?r++:o===`)`||o===`]`||o===`}`?r--:r===0&&e.startsWith(t,a)&&(n.push(a),a+=t.length-1))}return n}function dp(e,t){let n=lp(e),r=[],i=0;for(let e of n)e.op===`(`?i++:e.op===`)`?i--:i===0&&e.word&&t.includes(e.word)&&r.push(e.pos);return r}function fp(e){let t=up(e,`|`),n=dp(e,[`where`]).find(e=>!t.length||e>t[t.length-1]),r=n??e.length,i=e.slice(0,t.length?t[0]:r).trim(),a=[];for(let n=0;n<t.length;n++){let i=t[n]+1,o=n+1<t.length?t[n+1]:r;a.push(e.slice(i,o).trim())}return{primary:i,variants:a,where:n===void 0?void 0:e.slice(n+5).trim()}}var pp=[`when`,`key`,`label`,`emit`,`meta`,`estimated`];function mp(e){let t=up(e,`->`),n=dp(e,pp),r=e.length;t.length&&t[0]<r&&(r=t[0]);for(let e of n)e<r&&(r=e);let i=e.slice(0,r).trim(),a=e.slice(r).trim(),o,s={};if(a.startsWith(`->`)){let e=a.slice(2).trim(),t=/(?:^|\s)(when|key|label|emit|meta|estimated)\b/.exec(e),n=t?t.index+ +(t[0][0]===` `):e.length;o=e.slice(0,n).trim()||void 0,a=e.slice(n).trim()}for(;a=a.trim(),a;){let e=/^(when|key|label|emit|meta|estimated)\b([\s\S]*)$/.exec(a);if(!e)break;let t=e[1],n=e[2].trim(),r=/^(when|key|label|emit|meta|estimated)\b/.exec(n);s[t]=(r?n.slice(0,r.index):n).trim(),a=n.slice(r?r.index:n.length)}return{expr:i,unit:o,clauses:s}}function hp(e){let t=[],n=0,r=0,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===`"`){i=!i;continue}if(!i){if(o===`(`||o===`[`||o===`{`)r++;else if(o===`)`||o===`]`||o===`}`)r--;else if(r===0&&o===`,`){t.push(e.slice(n,a)),n=a+1;continue}r===0&&e.startsWith(`where`,a)&&!/[A-Za-z0-9_.]/.test(e[a-1]??``)&&!/[A-Za-z0-9_.]/.test(e[a+5]??``)&&(t.push(e.slice(n,a)),n=a+5,a+=4)}}return t.push(e.slice(n)),t.map(e=>e.trim()).filter(Boolean)}function gp(e){let t=[];for(let n of hp(e)){let e=up(n,`->`),r=n,i;e.length&&(r=n.slice(0,e[0]).trim(),i=n.slice(e[0]+2).trim()||void 0);let a=lp(r).find(e=>e.op===`=`);if(!a)throw new Yd(`Invalid where binding: ${n}`,0);t.push({name:r.slice(0,a.pos).trim(),expr:r.slice(a.pos+1).trim(),unit:i})}return t}function _p(e,t){let n=dp(e,[`when`])[0],r=e,i;n!==void 0&&(i=e.slice(n+4).trim(),r=e.slice(0,n).trim());let a=/\bestimated\b/.test(r),o=r.replace(/\bestimated\b/g,``).trim();if(!o)return{when:i,estimated:a,expr:t};let{expr:s,unit:c}=mp(o);return{expr:s,unit:c,when:i,estimated:a}}function vp(e,t,n,r,i,a,o){let s={};s.value={id:`value`,kind:`expr`,expression:r,...i?{unit:i}:{}};for(let e of a)s[e.name]={id:e.name,kind:`expr`,expression:e.expr,...e.unit?{unit:e.unit}:{}};let c={id:e,priority:t,origin:n,nodes:s};return o&&(c.when=o),c}function yp(e,t,n,r,i){let a=/\(library\)/.exec(e),o=!!a,s=o?e.slice(0,a.index)+` `+e.slice(a.index+a[0].length):e,c=lp(s).find(e=>e.op===`=`);if(!c)throw new Yd(`Missing '=' in calc line: ${e}`,0);let l=s.slice(0,c.pos).trim();if(!l)throw new Yd(`Missing calc name`,0);let{primary:u,variants:d,where:f}=fp(s.slice(c.pos+1).trim()),{expr:p,unit:m,clauses:h}=mp(u),g=f?gp(f):[];tf(p);for(let e of g)tf(e.expr);h.when&&tf(h.when);let _=h.when,v=d.length>0,y=[],b=h.estimated===void 0?`analyzed`:`analyzed-estimated`,x=b===`analyzed-estimated`?10:100,S=v?_:void 0;y.push(vp(`default`,x,b,p,m,g,S??void 0)),d.forEach((e,t)=>{let n=_p(e,p),r=n.estimated?`est-${t+1}`:`alt-${t+1}`,i=t===0?50:10;y.push(vp(r,i,n.estimated?`analyzed-estimated`:`analyzed`,n.expr??p,n.unit??(t===0?m:void 0),g,n.when))});let C;if(!o){if(C={nodeId:`value`,...m?{unit:m}:{}},h.key){let e=bp(h.key);C.key=e.key,e.grouped&&(C.isGrouped=!0,C.groupBy=e.groupBy)}h.label&&(C.label=h.label.replace(/^"|"$/g,``)),h.emit&&(C.emitType=h.emit),h.meta&&(C.publishMetadataNodes=h.meta.split(`,`).map(e=>e.trim()).filter(Boolean))}let w=v?r:_??r,T={id:l,kind:o?`library`:`output`,scope:t,variants:y,...n&&n.length?{fences:n}:{},...w?{when:w}:{}};return C&&(T.output=C),T}function bp(e){let t=/by\s*\{([^}]*)\}/.exec(e),n=e.includes(`grouped`)||!!t,r=t?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):void 0;return{key:e.split(/\s+/).find(e=>e!==`grouped`&&!/^by$/.test(e)&&!e.startsWith(`{`)&&!e.startsWith(`by`))??e,grouped:n,groupBy:r}}function xp(e){let t=e.output?.nodeId;return Array.isArray(t)?t[0]:t}function Sp(e){let t=e.metrics instanceof J?e.metrics.toArray():Array.isArray(e.metrics)?e.metrics:typeof e.metrics.toArray==`function`?e.metrics.toArray():[],n=$a(e);return{id:e.id,line:e.line??e.statement?.line,text:e.text??e.statement?.text,dialect:e.dialect??e.statement?.dialect,outputType:e.outputType,timeSpan:e.timeSpan?{started:e.timeSpan.started,ended:e.timeSpan.ended}:void 0,metrics:t,hints:n.length>0?n:void 0,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,parent:e.parent,sourceStatementId:e.sourceStatementId,completionReason:e.completionReason}}var Cp=[`reps`,`distance`,`resistance`,`elapsed`,`power`,`pace`],wp=[`totalVolume`,`totalDistance`,`tis`,`sessionLoad`],Tp=[`sum`,`avg`,`min`,`max`,`count`,`last`,`delta`],Ep=[`domain`,`format`,`equipment`,`quality`,`intent`],Dp=[...Ep,`effort`,`discipline`,`intensity`,`grade`,`note`,`page`,`origin`,`grain`,`metric`,`block`,`result`,`tags`],Op=[`type`,`text`,`has`,`source`,`catalog`,`notebook`],kp=[`effort`,`discipline`,`intensity`,`origin`,`text`],Ap=[`day`,`week`,`session`,`round`],jp=[`calc.metMinutes`,`calc.acwr`,`calc.monotony`,`calc.strain`,`calc.e1rm`,`calc.ctl`,`calc.atl`,`calc.tsb`,`calc.soreness`,`calc.sleep`,`calc.hrv`,`calc.readiness`,`calc.mvcBw`,`calc.ef`,`calc.adherence`,`calc.pct1rm`,`calc.sends`],Mp=[`low`,`moderate`,`high`],Np=[`summary`,`event`],Pp=[`note`,`block`,`effort`,`session`,`segment`,`event`],Fp=[`journal`,`feeds`,`guides`,`playground`,`dashboards`,`efforts`,`equipment`],Ip=[`note`,`notes`,`block`,`effort`,`session`,`segment`,`event`,`journal`,`notebook`,`notebooks`,`feed`,`feeds`,`catalog`,`catalogs`,`playground`,`dashboard`],Lp={journal:`journal`,notebook:`feeds`,notebooks:`feeds`,feed:`feeds`,feeds:`feeds`,catalog:`feeds`,catalogs:`feeds`,playground:`playground`},Rp={dashboard:`dashboard`},zp=[],Bp=Tp,Vp=[`timeseries`,`bar`,`table`,`donut`,`toplist`,`value`],Hp=[`@session`,`@today`],Up=Sa;[...Dp];var Wp=[`2w`,`4w`],Gp=[`kg`,`lb`],Kp=[`date`,`day`,`week`,`month`,`year`,`discipline`,`origin`,`source`,`notebook`,`kind`,`type`,`tag`],qp={time:!0,groupby:!0,rollup:!0,unit:!0,where:!0,agg:!0},Jp=Dp.filter(e=>e!==`metric`),Yp=Dp.filter(e=>e!==`tags`),Xp=new Set([...Jp.map(e=>e===`tags`?`tag`:e),`time`,`groupby`,`rollup`,`unit`,`where`,`agg`,`metric`]),Zp={note:new Set([`text`,`catalog`,`notebook`,`tag`,`effort`,...Ep,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`]),block:new Set([`text`,`catalog`,`notebook`,`tag`,`effort`,`type`,`source`,`note`,`time`,`groupby`,`where`]),effort:new Set([...kp,`groupby`]),session:new Set([`result`,`block`,`note`,`plane`,`time`,`groupby`]),segment:new Set([...Yp,`time`,`groupby`,`unit`]),event:new Set([...Yp,`time`,`groupby`,`unit`])},Qp=new Set,$p=Dp,em=Object.fromEntries(Object.entries(Zp).map(([e,t])=>[e,[...t].filter(e=>!qp[e]).map(e=>e===`tag`?`tags`:e)])),tm=[`day`,`week`,`session`,`round`,...Dp],nm=[`date`,`effort`,`discipline`,...Cp,...wp,...jp];function rm(e,t){return t===`aggregate`?Xp:Zp[e]??Qp}function im(e,t){return t===`aggregate`?$p:em[e]??[]}function am(e,t){return t===`aggregate`?tm:e===`segment`||e===`event`?nm:Kp}function om(e,t,n){let r=n===`tag`?`tags`:n;return t===`aggregate`||e===`segment`||e===`event`?!Op.includes(r)&&r!==`plane`&&(t!==`find`||r!==`tags`):im(e,t).includes(r)}var sm=Si.deserialize({version:14,states:"+^OVQPOOOOQO'#Cb'#CbObQPO'#C`OgQPO'#C`OlQPO'#ClOqQQO'#C_OOQO'#C_'#C_O!SQQO'#CnQOQPOOOOQO,58z,58zO!bQPO,58zOOQO,59W,59WO!gQPO'#CdOOQO,58y,58yOVQPO,58xO!rQPO'#CoO!wQPO'#CrOOQO,59Y,59YO!|QPO,59YO#UQQO'#CcOOQO1G.f1G.fOOQO'#Cg'#CgO#jQPO'#CeO#oQPO'#CeOOQO,59O,59OO#tQPO,59OO#|QPO'#C_O$XQPO1G.dO$aQPO,59ZO$iQQO,59^OOQO1G.t1G.tO$nQPO'#CuO$sQQO,58}O%XQPO,59PO%aQPO,59PO%fQPO'#CxO%nQPO1G.jOOQO1G.j1G.jOVQPO'#CyO%vQPO7+$OOOQO'#Cq'#CqOOQO1G.u1G.uO&OQPO1G.uO&WQPO1G.xOOQO,59a,59aOOQO-E6s-E6sO&]QPO'#CiO&qQPO'#CiO'PQPO'#ChOOQO1G.k1G.kO%XQPO1G.kOOQO,59d,59dOOQO-E6v-E6vOOQO7+$U7+$UO'[QPO'#CcOOQO,59e,59eOOQO-E6w-E6wO'jQPO'#CzO'oQPO7+$aOOQO7+$a7+$aO'wQPO7+$dO'|QPO'#CvO(RQPO,59TOOQO,59T,59TO%XQPO'#CwO(gQPO,59SOOQO7+$V7+$VO(rQPO,58}OOQO,59f,59fOOQO-E6x-E6xOOQO<<G{<<G{OOQO<<HO<<HOOOQO,59b,59bOOQO-E6t-E6tOOQO1G.o1G.oOOQO,59c,59cOOQO-E6u-E6uO)QQPO,58zO)VQPO'#C`",stateData:")[~OqOS~OTPOaSOrQO~OTXO~OrYO~OTZO~Ot[OdRXgRXoRXuRX~Od_Og`Ou^OobX~OTcO~OTeOYgOwhO~OtlO~OxmO~Og`Ooba~OsoOdVXgVXoVXtVXuVX~OrqO~OTeO~OvsOwuO~Ot[OoRXuRX~OuvOoQi~OTxOwyO~Oh{O~OT|O~OsoOdVagVaoVatVauVa~OT!OO_!PO~Or!SO~OTeOYgO~OvsOw!VO~OuvOoQq~Ov!ZOw!]O~OT!^O~O^!aOr!_Os!_Ou]Xv]Xw]X~O^!aOu]Xv]Xw]X~Ou!bOv[Xw[X~OsoOoVXtVXuVX~OTxO~Ov!ZOw!hO~Oy!iO~OT!jO~O^!lOr!_Os!_Ou]av]aw]a~Ou!bOv[aw[a~OsoOoVatVauVa~OT!WO~Or!oO~O",goto:"$^oPPps|P!T![!`!dP!j!q!wPP#OPp#TP#W#^PP#d#n#t#z$Q$WRWOQVOQk^R!XvQTOTj^vQROT!p^vTdY!oT]TjQi[R!TsSf[sRrgQ!RqR!d!SS!Qq!SR!m!bVUO^vRbVQzlR!f!ZQaVRnbQpcS}p!eR!e!WQ!`!OR!k!`Q!c!QR!n!cQtiR!UtQwkR!YwQ![zR!g![",nodeNames:`⚠ Query Pipeline Stage Head Word Aggregator Metric Filters Filter Negate TagKey TagValue Value Star Quoted DatasetReference At Single GroupBy By Dimension Rollup RollupDot Int`,maxTerm:41,skippedNodes:[0],repeatNodeCount:6,tokenData:"'i~RgXY!jYZ!j]^!jpq!jqr!{rs#Qxy#oyz#tz{#y|}$O}!O$T!O!P$i!Q![%f![!]%|!b!c&R!c!}$T#R#S$T#T#U$T#U#V&W#V#o$T#o#p'Y#p#q'_#q#r'd~!oSq~XY!jYZ!j]^!jpq!j~#QOY~~#TTOr#Qrs#ds;'S#Q;'S;=`#i<%lO#Q~#iO_~~#lP;=`<%l#Q~#tOx~~#yOy~~$OO^~~$TOv~P$YTTP}!O$T!Q![$T!c!}$T#R#S$T#T#o$T~$nPs~#f#g$q~$tP#c#d$w~$zP#`#a$}~%QP#`#a%T~%WP#i#j%Z~%^P#d#e%a~%fOg~R%mThQTP}!O$T!Q![%f!c!}$T#R#S$T#T#o$T~&ROr~~&WOa~R&]VTP}!O$T!Q![$T!c!}$T#R#S$T#T#m$T#m#n&r#n#o$TR&yTdQTP}!O$T!Q![$T!c!}$T#R#S$T#T#o$T~'_Ot~~'dOu~~'iOw~",tokenizers:[0,1],topRules:{Query:[0,1]},tokenPrec:0});function cm(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`{`)t++;else if(r===`}`)t=Math.max(0,t-1);else if(t===0&&r===`w`&&e.slice(n,n+5)===`where`&&(n===0||/\s/.test(e[n-1]))&&(n+5>=e.length||/\s/.test(e[n+5])))return{primary:e.slice(0,n).trim(),where:e.slice(n+5).trim()}}return{primary:e.trim()}}var lm=/\s*=>\s*@?([a-zA-Z0-9_-]+)\s*$/,um=/^@([a-zA-Z0-9_-]+)\s*(?:\||=>)\s*/,dm=/\s+(?:in|from)\s+@([a-zA-Z0-9_-]+)\s*$/i,fm=/\s+in\s+([a-zA-Z0-9_-]+)\s*$/,pm=/\.rollup\((\d+)?([a-zA-Z]*)\)\s*$/,mm=/\s+by\s+\{([^}]*)\}\s*$/,hm=/\s+last\s+(\d+)([dw])\s*$/i,gm=/\s+from\s+(\d{4}-\d{2}-\d{2})(?:\s+to\s+(\d{4}-\d{2}-\d{2}))?\s*$/i;function _m(e){let{primary:t,where:n}=cm(e),r=t.trim(),i,a,o,s,c,l,u,d=[],f=r.match(um);f&&(a=`@`+f[1],r=r.slice(f[0].length).trim());let p=r.startsWith(`find:`),m=/^rows(?=[:{]|\s|$)/.test(r),h=e=>{let t=[];for(let n=e.exec(r);n;n=e.exec(r))t.unshift(n),r=r.slice(0,n.index).trim();return t},g=(e,t)=>{t.length>1&&d.push(`Duplicate '${e}' clause: '${t[0][0].trim()}' conflicts with '${t[t.length-1][0].trim()}'`)},_=h(lm);g(`=>`,_),_.length&&(i=`@`+_[_.length-1][1]);let v=h(gm),y=h(hm);{let e=[...v.map(e=>({kind:`range`,start:e[1],end:e[2],raw:e[0].trim(),at:e.index})),...y.map(e=>({kind:`relative`,size:parseInt(e[1],10),unit:e[2].toLowerCase(),raw:e[0].trim(),at:e.index}))].sort((e,t)=>e.at-t.at);if(e.length>1&&d.push(`Duplicate 'window' clause: '${e[0].raw}' conflicts with '${e[e.length-1].raw}'`),e.length===1){let t=e[0];l=t.kind===`range`?{kind:`range`,start:t.start,end:t.end,raw:t.raw}:{kind:`relative`,size:t.size,unit:t.unit,raw:t.raw}}}let b=h(fm);if(g(p||m?`scope`:`display-unit`,b),b.length){let e=b[b.length-1][1];e===`kg`||e===`lb`?o=e:p||m?u=e:o=e}let x=h(pm);if(g(`.rollup`,x),x.length){let e=x[x.length-1];s={size:e[1]?parseInt(e[1],10):1,unit:e[2]||``,raw:e[1]+e[2]}}let S=h(mm);g(`by`,S),S.length&&(c=S[S.length-1][1].split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean));let C=h(dm);return C.length&&(a=`@`+C[C.length-1][1]),{where:n,storedAs:i,sourceRef:a,displayUnit:o,rollup:s,groupBy:c,window:l,legacyScope:u,conflicts:d.length?d:void 0,primaryText:vm(r)}}function vm(e){let t=e.indexOf(`{`),n=t===-1?-1:e.lastIndexOf(`}`);if(t===-1||n<=t)return e;let r=e.slice(t+1,n);if(!r.includes(`,`))return e;let i=[],a=``,o=!1;for(let e of r)e===`"`&&(o=!o),e===`,`&&!o?(i.push(a),a=``):a+=e;i.push(a);let s=[];for(let e=0;e<i.length;e++){let t=i[e];for(;e+1<i.length;){let n=i[e+1].trim();if(n&&!n.includes(`:`)&&!n.includes(`"`))t=`${t}|${n}`,e++;else break}s.push(t)}return`${e.slice(0,t+1)}${s.join(`,`)}${e.slice(n)}`}function ym(e){let t={},n=e.split(`|`).map(e=>e.trim()).filter(Boolean);for(let e of n){let n=e.toLowerCase();if(n.startsWith(`select`))t.select=e.slice(6).trim().split(`,`).map(e=>{let t=/^([\w-]+)(?:\s+in\s+([\w/%]+))?$/i.exec(e.trim());return t?{col:t[1],...t[2]?{unit:t[2]}:{}}:{col:e.trim()}});else if(n.startsWith(`order by`))t.order=e.slice(8).trim().split(`,`).map(e=>{let t=/^(\S+)(?:\s+(asc|desc))?$/i.exec(e.trim());return{col:t?.[1]??e.trim(),dir:t?.[2]?.toLowerCase()??`asc`}});else if(n.startsWith(`limit`)){let n=/^limit\s+(\d+)(?:\s+offset\s+(\d+))?$/i.exec(e);if(!n)return t.error=`Cannot parse pipe "${e}". Expected limit <n> [offset <m>]`,t;t.limit=Number(n[1]),n[2]&&(t.offset=Number(n[2]))}else if(n.startsWith(`offset`)){let n=/^offset\s+(\d+)$/i.exec(e);if(!n)return t.error=`Cannot parse pipe "${e}". Expected offset <n>`,t;t.offset=Number(n[1])}else return t.error=`Unknown pipe "${e}". Try: select, order by, limit`,t}return t}function bm(e){return e.family===`find`}function xm(e){return e.family===`aggregate`}function Sm(e){return e.family===`pipeline`}var Cm=Tp;function wm(e){return`Cannot parse "${e}". Expected agg:metric{filters} by {dims} .rollup(period)`}var Tm=/^(.+?)\s*(>=|<=|!=|==|>|<)\s*(-?\d+(?:\.\d+)?)\s*$/;function Em(e){return`Cannot parse join "${e}". Expected :source{filters} or find:target{filters}, or agg:metric{filters} <op> <number>`}function Dm(e){let t=e.trimStart(),n=/^:?([a-zA-Z0-9_-]+)/.exec(t)?.[1]?.toLowerCase()??``;if(t.startsWith(`find:`)||t.startsWith(`:`)&&Ip.includes(n)){let n=qm(e,{colon:t.startsWith(`:`)});return n.error?{error:n.error}:n.window?.kind===`range`?{error:`Range windows are not supported on join halves — use last <n>d|w`}:{find:{target:n.target,filters:n.filters,last:n.window?.kind===`relative`?{size:n.window.size,unit:n.window.unit}:void 0},advisories:n.advisories}}let r=Tm.exec(e.trim());if(!r)return{error:Em(e)};let i=Gm(r[1].trim(),{colon:r[1].trimStart().startsWith(`:`)});return i.error?{error:i.error}:{metric:{agg:i.agg,metric:i.metric,filters:i.filters,operator:r[2],threshold:parseFloat(r[3])}}}function Om(e){let t=/^rows(?::(\w+))?\{([^}]*)\}/.exec(e);if(!t)return`The "rows:" query family is retired — use :session, :segment, or :event instead.`;let n=t[1]??`all`,r=t[2].trim();return n===`all`||[`note`,`block`,`effort`,`page`].includes(n)?`rows:${n}{…} is retired — use :session{${r}} instead.`:n===`segment`&&!r.includes(`result:`)&&!r.includes(`block:`)&&!r.includes(`note:`)?`rows:segment{…} is retired — use :segment{${r}} instead.`:n===`event`?`rows:event{…} is retired — use :event{${r}} instead.`:`rows:${n}{…} is retired — use :session{${r?`${r}, plane:${n}`:`plane:${n}`}} instead.`}var km=/^\s*(?:select|order\s+by|limit|offset)\b/i;function Am(e){let t=[],n=0,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(r){o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}o===`{`?n++:o===`}`?n=Math.max(0,n-1):o===`|`&&n===0&&(t.push(e.slice(i,a)),i=a+1)}return t.push(e.slice(i)),t}function jm(e){let t=/^\s*([:@])([a-zA-Z0-9_-]+)/.exec(e);return t?{name:t[2].toLowerCase(),dataset:t[1]===`@`}:void 0}function Mm(e){return`Cannot parse pipeline "${e}". Expected :source{filters} | :function{metric:key} | :chart{params} or @dataset | :function{…}`}function Nm(e){return{family:`find`,raw:e,target:``,filters:[],error:`The "find:" query family is retired — use the :${(/^find:([a-zA-Z0-9_-]*)/.exec(e.trim())?.[1]??``)||`note`}{…} colon head instead.`}}function Pm(e){let t=Im(e),n=jm(t.query),r;return r=n&&!n.dataset?Bp.includes(n.name)?Gm(t.query,{colon:!0}):(Ip.includes(n.name),qm(t.query,{colon:!0})):Gm(t.query,{colon:!1}),t.advisories.length&&(r.advisories=[...new Set([...r.advisories??[],...t.advisories])]),r.raw=e,r}function X(e){let t=e.trimStart();if(/^rows(?=[:{]|\s|$)/.test(t))return{family:`find`,raw:e,target:``,filters:[],error:Om(e.trim())};if(/^find:/.test(t))return Nm(e);let n=Am(e),r=n[0];if(n.length>1&&!km.test(r)&&n.slice(1).every(e=>km.test(e.trim())))return Pm(e);let i=jm(r);return n.length>1||i&&(i.dataset||Vp.includes(i.name))?Ym(e,n):Pm(e)}function Fm(e){return e.replace(/\bnotebook:notebook\/([a-zA-Z0-9_-]+)/g,`notebook:"notebook/$1"`)}function Im(e){let t=[],n=Fm(e.trim()),{primary:r,where:i}=cm(n);if(r.startsWith(`find:`)){let e=_m(r);if(e.legacyScope&&!e.conflicts?.length){t.push(`Legacy 'in <scope>' syntax is deprecated; use 'source:<scope>' filter instead.`);let r=e.legacyScope,a=e.primaryText.trim();if(r!==`all`){let e=a.indexOf(`{`),t=a.lastIndexOf(`}`);if(e!==-1&&t!==-1&&t>e){let n=a.slice(0,e+1),i=a.slice(e+1,t).trim(),o=a.slice(t);a=`${n}${i?`${i},source:${r}`:`source:${r}`}${o}`}else a=`${a}{source:${r}}`}let o=[a];e.groupBy&&o.push(`by {${e.groupBy.join(`, `)}}`),e.rollup&&o.push(`.rollup(${e.rollup.raw})`),e.window&&o.push(e.window.raw),i&&o.push(`where ${i}`),n=o.join(` `)}}return{query:n,advisories:t}}function Lm(e){for(let t of e)if(t.key===`source`)for(let e of t.values){let t=e.value;if(t===`page`||t===`pages`)return`source:${t} is retired — page-ness is handled by type: (e.g. type:feed or source:guides).`;if(t===`all`)return`source:all is retired — omit the source: filter to query all sources.`;if(t===`collection`||t===`collections`)return`source:${t} is retired — collections were renamed to feeds; use source:feeds or :feed{}.`;if(!(Fp.includes(t)||t===`feed`||t===`notebook`||t===`notebooks`||t.startsWith(`collection:`)||t.startsWith(`feed:`)||t.startsWith(`notebook:`)||t.startsWith(`notebook/`)))return`Unknown source "${t}". Try: ${Fp.join(`, `)} (or collection:<id>, feed:<id>)`}}function Rm(e){let t=-1,n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){a===`"`&&(r=!1);continue}if(a===`"`){r=!0;continue}if(a===`{`)n++;else if(a===`}`)n=Math.max(0,n-1);else if(a===`|`&&n===0){t=i;break}}if(t!==-1){let n=e.slice(t+1);return{text:e.slice(0,t).trimEnd(),pipes:ym(n)}}return{text:e}}function zm(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(n,r-1,i);return a.getFullYear()===n&&a.getMonth()===r-1&&a.getDate()===i}function Bm(e){if(!e)return{};if(e.kind===`relative`)return{window:{kind:`relative`,size:e.size,unit:e.unit}};for(let t of[e.start,e.end])if(t!==void 0&&!zm(t))return{error:`Invalid window date "${t}" — expected a real calendar date YYYY-MM-DD`};return{window:{kind:`range`,start:e.start,end:e.end}}}function Vm(e){if(e.some(e=>e.key===`grain`&&e.values.some(e=>e.value===`rollup`)))return`grain:rollup is retired — rollup grains are never stored; compute them with the .rollup suffix`}function Hm(e,t){let n=[],r=e.getChild(8);if(!r)return n;for(let e of r.getChildren(9)){let r=e.getChild(11),i=e.getChild(12);if(!r||!i)continue;let a=[];for(let e of i.getChildren(13)){let n=t.slice(e.from,e.to),r=e.getChild(15)!==null,i=r?n.slice(1,-1):n,o=!r&&i.endsWith(`*`);o&&(i=i.slice(0,-1)),i&&a.push({value:i,wildcard:o})}a.length!==0&&n.push({key:t.slice(r.from,r.to),negate:e.getChild(10)!==null,values:a})}return n}function Um(e){return e.getChild(18)?.getChild(3)??e.getChild(3)??void 0}function Wm(e){return`Cannot parse "${e}". Expected :function{metric:<key>, filters} by {dims} .rollup(period) — e.g. :sum{metric:tis}`}function Gm(e,t){let n=_m(e),{where:r,displayUnit:i,groupBy:a,rollup:o,window:s,primaryText:c}=n,l=Bm(s),u={family:`aggregate`,raw:e,agg:`sum`,metric:``,filters:[],groupBy:a??[],displayUnit:i,rollup:o?{size:o.size,unit:o.unit}:void 0,window:l.window};if(l.error)return u.error=l.error,u;if(n.conflicts?.length)return u.error=n.conflicts.join(`; `),u;if(o){if(o.unit!==`d`&&o.unit!==`w`)return u.error=wm(c),u;if((o.unit===`d`||o.unit===`w`)&&o.size===1)return u.error=`.rollup(1${o.unit}) is retired — use by {${o.unit===`d`?`day`:`week`}} instead.`,u}let d=sm.parse(c),f=!1;if(d.iterate({enter(e){e.type.isError&&(f=!0)}}),f)return u.error=wm(c),u;let p=d.topNode,m=Um(p),h=m?.getChild(4),g=h?.getChild(6),_=h?.getChild(7);if(u.filters=m?Hm(m,c):[],t.colon){let e=h?.getChild(5);if(!h||!e)return u.error=Wm(c),u;let n=c.slice(e.from,e.to).toLowerCase();if(!Bp.includes(n))return u.error=`Unknown function ":${n}". Try: ${Bp.join(`, `)}`,u;u.agg=n;let r=u.filters.filter(e=>e.key===`metric`);u.filters=u.filters.filter(e=>e.key!==`metric`);let i=r[0];if(!i){if(n!==`count`&&t.inheritedMetric===void 0)return u.error=`:${n} requires 'metric:<key>' — e.g. :${n}{metric:tis}`,u;u.metric=n===`count`?``:t.inheritedMetric}else if(i.negate||r.length>1||i.values.length!==1||i.values[0].wildcard)return u.error=`:${n} takes a single 'metric:<key>' clause — no negation, OR values, or wildcards`,u;else u.metric=i.values[0].value}else{if(!m||!h||!g||!_)return u.error=wm(c),u;let e=c.slice(g.from,g.to);if(!Cm.includes(e))return u.error=`Unknown aggregator "${e}". Try: ${Cm.join(`, `)}`,u;u.agg=e,u.metric=c.slice(_.from,_.to)}let v=u.filters.map(e=>e.key).filter(e=>Op.includes(e));if(v.length>0)return u.error=`Content filter key(s) ${v.map(e=>`"${e}"`).join(`, `)} cannot narrow an aggregate — facts carry effort/dimension data, not note text. Aggregate dims: ${Dp.join(`, `)}, plus any custom dimension.`,u;let y=Vm(u.filters);if(y)return u.error=y,u;if(r){let e=Dm(r);if(e.error)return u.error=e.error,u;if(e.advisories?.length&&(u.advisories=[...u.advisories??[],...e.advisories]),!e.find)return u.error=`Cross-store join on an analytics query must be find:…, got "${r}"`,u;u.join=e.find}return u}function Km(e){return`Cannot parse "${e}". Expected :source{key:value, !key:value}; filters are optional. Optional suffixes include by {dimension}, last <n>d or last <n>w, from YYYY-MM-DD [to YYYY-MM-DD], where <aggregator>:<metric>{filters} <operator> <number>, and | order by <column> | limit <n>. Support depends on the target.`}function qm(e,t){let{text:n,pipes:r}=Rm(Fm(e)),i=_m(n),{where:a,window:o,legacyScope:s,groupBy:c,displayUnit:l,primaryText:u}=i,d=Bm(o),f=[];s&&f.push(`Legacy 'in <scope>' syntax is deprecated; use 'source:<scope>' filter instead.`);let p={family:`find`,raw:e,target:``,filters:[],window:d.window,...r?{pipes:r}:{},...c?{groupBy:c}:{},...l?{displayUnit:l}:{},...f.length?{advisories:f}:{}};if(d.error)return p.error=d.error,p;if(r?.error)return p.error=r.error,p;if(i.conflicts?.length)return p.error=i.conflicts.join(`; `),p;let m=sm.parse(u),h=!1;if(m.iterate({enter(e){e.type.isError&&(h=!0)}}),h)return p.error=Km(u),p;let g=Um(m.topNode),_=g?.getChild(4),v=_?.getChild(6),y=_?.getChild(7),b;if(t?.colon){let e=_?.getChild(5);if(!g||!_||!e)return p.error=Km(u),p;b=u.slice(e.from,e.to).toLowerCase()}else{if(!g||!_||!v||!y)return p.error=Km(u),p;let e=u.slice(v.from,v.to);if(e!==`find`)return p.error=`Expected "find:" but got "${e}:"`,p;b=u.slice(y.from,y.to)}let x=Lp[b],S=Rp[b];if(x||S)p.target=`note`;else{if(p.target=b===`notes`?`note`:b,p.target===`page`)return p.error=`find:page is retired — page-ness is handled by type: (e.g. :note{source:guides} or type:feed).`,p;if(!Pp.includes(p.target))return p.error=`Unknown find target "${p.target}". Try: ${Pp.join(`, `)}`,p}p.filters=Hm(g,u),S&&p.filters.unshift({key:`type`,negate:!1,values:[{value:S,wildcard:!1}]}),x&&(p.filters.push({key:`source`,negate:!1,values:[{value:x,wildcard:!1}]}),(b===`catalog`||b===`catalogs`||b===`notebook`||b===`notebooks`)&&p.filters.push({key:`type`,negate:!1,values:[{value:`feed`,wildcard:!1}]}));let C=t?.colon&&p.displayUnit&&p.displayUnit!==`kg`&&p.displayUnit!==`lb`?p.displayUnit:s;t?.colon&&C&&(delete p.displayUnit,f.push(`Legacy 'in <scope>' syntax is deprecated; use 'source:<scope>' filter instead.`)),C&&C!==`all`&&p.filters.push({key:`source`,negate:!1,values:[{value:C,wildcard:!1}]});let w=Lm(p.filters);if(w)return p.error=w,p;let T=Vm(p.filters);if(T)return p.error=T,p;let E=p.target;if(i.rollup&&f.push(`:${E} ignores '.rollup(...)'; rollup is supported by aggregate queries.`),a){let e=Dm(a);if(e.error)return p.error=e.error,p;if(!e.metric)return p.error=`Cross-store join on a find query must be agg:metric{} <op> <number>, got "${a}"`,p;p.join=e.metric}let D=Xm(p);return(f.length||D.length)&&(p.advisories=[...new Set([...f,...D])]),p}function Jm(e){return e?e.dataset?`dataset`:Bp.includes(e.name)?`function`:Ip.includes(e.name)?`source`:Vp.includes(e.name)?`chart`:`unknown`:`unknown`}function Ym(e,t){let n=[],r=t=>({family:`pipeline`,raw:e,source:{kind:`dataset`,name:``},transforms:[],error:t}),i=t.map(jm),a=i.map(Jm),o;if(!i[0]){if(km.test(t[0]))return r(`Presentation pipes (| select / order by / limit) apply to a single source query — they cannot sit between pipeline stages.`);let e=Gm(t[0],{colon:!1});if(e.error)return r(e.error);o=e,a[0]=`function`}for(let e=0;e<t.length;e++){if(e===0&&o)continue;let n=i[e]?`:${i[e].name}`:`"${t[e].trim()}"`;if(!i[e])return r(`Empty or unparseable pipeline stage ${n} — check for doubled or trailing "|".`);if(a[e]===`unknown`)return r(`Unknown pipeline head ${n}. Sources: ${Ip.join(`, `)}; functions: ${Bp.join(`, `)}; charts: ${Vp.join(`, `)}.`);if(e>0&&(a[e]===`source`||a[e]===`dataset`))return r(`Pipeline stage ${n} must come first — a pipeline starts at its source, transforms follow.`);if(a[e]===`chart`&&e<t.length-1)return r(`Chart head ${n} must be the final pipeline stage — nothing may follow a chart.`)}let s=t.map(e=>_m(e).primaryText.trim()).join(` | `),c=sm.parse(s),l=!1;c.iterate({enter(e){e.type.isError&&(l=!0)}});let u=l?void 0:c.topNode.getChild(2),d=l?void 0:c.topNode.getChild(18),f=u?u.getChildren(3):d?[d.getChild(3)].filter(e=>e!==null):[];if(!u&&t.length>1||f.length!==t.length)return r(Mm(e));let p=t.length-1,m;if(a[0]===`dataset`)m={kind:`dataset`,name:`@`+i[0].name};else if(a[0]===`chart`)m={kind:`query`,query:{family:`find`,raw:`:segment{}`,target:`segment`,filters:[]}};else{let e=a[0]===`function`?Gm(t[0],{colon:t[0].trimStart().startsWith(`:`)}):qm(t[0],{colon:!0});if(e.error)return r(e.error);m={kind:`query`,query:e}}let h=[],g=m.kind===`query`&&m.query.family===`aggregate`?m.query.metric:void 0,_=a[p]===`chart`?p-1:p;for(let e=1;e<=_;e++){let n=Gm(t[e],{colon:!0,inheritedMetric:g});if(n.error)return r(n.error);h.push(n),g=n.metric||g}let v;if(a[p]===`chart`){let i=f[p],a=i.getChild(4)?.getChild(5);if(!a)return r(Mm(e));let o=s.slice(a.from,a.to).toLowerCase();if(!Vp.includes(o))return r(`Unknown chart head ":${o}". Try: ${Vp.join(`, `)}`);let c=_m(t[p]);(c.window||c.rollup||c.groupBy||c.displayUnit||c.where||c.legacyScope)&&n.push(`:${o} ignores query suffixes — apply windows and grouping to the source or function stages.`),v={head:o,filters:Hm(i,s)}}return{family:`pipeline`,raw:e,source:m,transforms:h,...v?{sink:v}:{},...n.length?{advisories:n}:{}}}function Xm(e){let t=[],n=e.target,r=rm(n,`find`),i=[...new Set(e.filters.filter(e=>!om(n,`find`,e.key)).map(e=>e.key))];if(i.length){let e=n===`segment`||n===`event`?`, custom fact dimensions`:``,r=i.find(e=>kp.includes(e)),a=r&&n!==`effort`?` To filter by ${r}, use :effort{${r}:…}.`:``;t.push(`:${n} ignores ${i.map(e=>`'${e}:'`).join(`, `)} — the filter is not applied.${a} Supported keys: ${im(n,`find`).join(`, `)}${e}.`)}for(let r of e.filters){if(i.includes(r.key))continue;let e=[`result`,`block`,`note`].includes(r.key),a=n===`note`?[`effort`,`text`,`type`,`domain`,`format`,`equipment`,`quality`,`intent`].includes(r.key):n===`block`?[`text`,`type`,`tags`,`effort`].includes(r.key):(n===`session`||n===`segment`||n===`event`)&&e;r.negate&&a&&t.push(`:${n} does not support '!${r.key}:' negation; this clause is not applied as a negated filter.`);let o=n===`effort`?[`effort`,`text`].includes(r.key):(n===`segment`||n===`event`)&&!e;r.values.some(e=>e.wildcard)&&!o&&t.push(`:${n} does not support '${r.key}:…*' wildcards; values are matched without wildcard expansion.`)}if(e.window&&!r.has(`time`)&&t.push(`:${n} ignores the window because its registry has no time dimension.`),e.groupBy?.length){let r=am(n,`find`),i=e.groupBy.filter(e=>!r.some(t=>t.toLowerCase()===e.toLowerCase()));if(n!==`note`&&n!==`block`){if(n===`segment`||n===`event`){let i=e.pipes?.select?.map(e=>e.col),a=e.groupBy.filter(e=>i?!i.includes(e):!r.includes(e));a.length&&t.push(`:${n} groups only emitted table columns; ${a.join(`, `)} may be unassigned. Select each grouping column explicitly.`)}else i.length&&t.push(`:${n} cannot group by ${i.join(`, `)}; the view groups by content dimensions. Valid alternatives: ${r.join(`, `)}.`)}}return e.displayUnit&&!r.has(`unit`)&&t.push(`:${n} ignores the display unit 'in ${e.displayUnit}'.`),e.join&&!r.has(`where`)&&t.push(`:${n} ignores the 'where' join; joins are supported by :note and :block.`),e.pipes?.select&&n!==`segment`&&n!==`event`&&t.push(`:${n} ignores '| select'; the result keeps its original fields.`),e.pipes?.order&&n===`session`&&t.push(`:session ignores '| order by'; sessions remain ordered by completion time.`),[...new Set(t)]}function Zm(e){let t=e.filters[0];return e.target===`note`&&e.sourceScope===void 0&&!!t&&t.key===`type`&&!t.negate&&t.values.length===1&&!t.values[0].wildcard&&t.values[0].value===Rp.dashboard}function Qm(e,t=[]){if(Zm(e)){let n=[...e.filters.slice(1),...t];return`:dashboard${n.length?`{${ah(n)}}`:``}`}let n=[...e.filters,...t];return`:${e.target}${n.length?`{${ah(n)}}`:``}`}function $m(e){return e.target!==`note`||e.filters.some(e=>e.key===`source`)||Zm(e)||!e.sourceScope?.length?{clause:``,scopeFilters:[]}:{clause:``,scopeFilters:[{key:`source`,negate:!1,values:e.sourceScope.map(e=>({value:e,wildcard:!1}))}]}}function eh(e){let t=$m(e),n=[Qm(e,t.scopeFilters)];return e.groupBy?.length&&n.push(`by {${e.groupBy.join(`, `)}}`),e.displayUnit&&n.push(`in ${e.displayUnit}`),n.push(t.clause),n.push(uh(e.window)),e.join&&n.push(`where ${lh(e.join)}`),n.filter(Boolean).join(` `)}function th(e){let t=e.metric?[{key:`metric`,negate:!1,values:[{value:e.metric,wildcard:!1}]},...e.filters]:e.filters,n=`:${e.agg}{${ah(t)}}`;e.groupBy.length&&(n+=` by {${e.groupBy.join(`, `)}}`),e.rollup&&(n+=`.rollup(${e.rollup.size}${e.rollup.unit})`),e.displayUnit&&(n+=` in ${e.displayUnit}`);let r=uh(e.window);return r&&(n+=` ${r}`),e.join&&(n+=` where ${ch(e.join.target,e.join.filters,e.join.last)}`),n}function nh(e){return e.kind===`dataset`?e.name:e.query.family===`find`?eh(e.query):th(e.query)}function rh(e){let t=[nh(e.source),...e.transforms.map(th)];return e.sink&&t.push(`:${e.sink.head}${e.sink.filters.length?`{${ah(e.sink.filters)}}`:``}`),t.join(` | `)}function ih(e){return/^[a-zA-Z0-9_-]+((:|\.)[a-zA-Z0-9_-]+)*$/.test(e)?e:`"${e}"`}function ah(e){return e.map(e=>`${e.negate?`!`:``}${e.key}:${e.values.map(e=>ih(e.value)+(e.wildcard?`*`:``)).join(`|`)}`).join(`,`)}function oh(e,t,n){return`${e}:${t}{${ah(n)}}`}function sh(e){return oh(e.agg,e.metric,e.filters)}function ch(e,t,n){let r=`find:${e}${t.length?`{${ah(t)}}`:``}`;return n?`${r} last ${n.size}${n.unit}`:r}function lh(e){return`${oh(e.agg,e.metric,e.filters)} ${e.operator} ${e.threshold}`}function uh(e){return e?e.kind===`relative`?`last ${e.size}${e.unit}`:e.end?`from ${e.start} to ${e.end}`:`from ${e.start}`:``}function dh(e){if(e.error)return e.raw;if(e.family===`aggregate`){let t=e,n=sh(t);t.groupBy.length&&(n+=` by {${t.groupBy.join(`, `)}}`),t.rollup&&(n+=`.rollup(${t.rollup.size}${t.rollup.unit})`),t.displayUnit&&(n+=` in ${t.displayUnit}`);let r=uh(t.window);return r&&(n+=` ${r}`),t.join&&(n+=` where ${ch(t.join.target,t.join.filters,t.join.last)}`),n}if(e.family===`find`){let t=$m(e),n=[Qm(e,t.scopeFilters)];e.groupBy?.length&&n.push(`by {${e.groupBy.join(`, `)}}`),e.displayUnit&&n.push(`in ${e.displayUnit}`),n.push(t.clause),n.push(uh(e.window)),e.join&&n.push(`where ${lh(e.join)}`);let r=n.filter(Boolean).join(` `);if(e.pipes){let t=[];e.pipes.select&&t.push(`select ${e.pipes.select.map(e=>e.col+(e.unit?` in ${e.unit}`:``)).join(`, `)}`),e.pipes.order&&t.push(`order by ${e.pipes.order.map(e=>e.dir===`desc`?`${e.col} desc`:e.col).join(`, `)}`),e.pipes.limit===void 0?e.pipes.offset!==void 0&&t.push(`offset ${e.pipes.offset}`):t.push(`limit ${e.pipes.limit}${e.pipes.offset===void 0?``:` offset ${e.pipes.offset}`}`),t.length>0&&(r+=` | ${t.join(` | `)}`)}return r}return e.family===`pipeline`?rh(e):e.raw??``}var fh=[`bodyweight`,`cycling`,`gymnastics`,`kettlebell`,`recovery`,`rowing`,`running`,`strength`,`swimming`,`walking`],ph=Mr.define({parser:sm.configure({props:[Di({"Aggregator/Word":H.keyword,"Metric/Word":H.variableName,"Head/Word":H.keyword,DatasetReference:H.keyword,"DatasetReference/Word":H.keyword,At:H.punctuation,TagKey:H.propertyName,"TagKey/Word":H.propertyName,TagValue:H.string,"TagValue/Value/Word":H.string,"TagValue/Word":H.string,Negate:H.operator,Star:H.operator,Dimension:H.attributeName,"Dimension/Word":H.attributeName,By:H.keyword,RollupDot:H.keyword,Int:H.number,"Rollup/Word":H.unit,braceOpen:H.bracket,braceClose:H.bracket,parenOpen:H.bracket,parenClose:H.bracket,colon:H.punctuation,comma:H.punctuation,pipe:H.punctuation,dot:H.punctuation})]}),languageData:{closeBrackets:{brackets:[`{`,`(`]}}});function mh(e){return e.map(e=>typeof e==`string`?{label:e}:e)}function hh(e,t){let n=0,r=!1,i=-1,a=-1,o=0;for(let s=0;s<t;s++){let t=e[s];if(r){t===`"`&&(r=!1);continue}if(t===`"`){r=!0;continue}t===`{`?(n++,a=s,o=s+1):t===`}`?(n=Math.max(0,n-1),o=s+1):t===`,`&&n>0?o=s+1:t===`|`&&n===0&&(i=s+1,o=s+1)}return{depth:n,quoted:r,pipeFrom:i,lastBrace:a,fragStart:o}}function gh(e){let t=``,n=!1;for(let r of e)r===`"`?(n=!n,t+=` `):t+=n?` `:r;return t}function _h(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(r===`"`)t=!t;else if(r===`:`&&!t)return n}return-1}function vh(e,t,n){let r=gh(e.slice(t+1,n)),i=new Set;for(let e of r.split(`,`)){let t=/!?\s*([A-Za-z][\w-]*)/.exec(e);t&&i.add(t[1])}return i}function yh(e){return typeof e.apply==`string`?e.apply:e.label}function bh(e){let t=yh(e);return/\s/.test(t)?{...e,apply:(e,n,r,i)=>{let a=e.state.sliceDoc(Math.max(0,r-1),r)===`"`?t:`"${t}"`;e.dispatch({changes:{from:r,to:i,insert:a},selection:{anchor:r+a.length},userEvent:`input.complete`})}}:e}function xh(e,t){let n=new Set,r=[];e.forEach((e,t)=>{let i=yh(e).toLowerCase();!i||n.has(i)||(n.add(i),r.push(bh({...e,boost:Math.max(-99,Math.min(99,80-t))})))});for(let e of t){let t=yh(e).toLowerCase();!t||n.has(t)||(n.add(t),r.push(bh(e)))}return r}function Sh(e,t){let n=t.toLowerCase();if(!n)return[...e];let r=[],i=[];for(let t of e){let e=t.label.toLowerCase();e.startsWith(n)?r.push(t):e.includes(n)&&i.push(t)}return[...r,...i]}function Ch(e,t,n,r){let i=Sh(n,r);return i.length?{from:t,options:i.map((e,t)=>e.boost===void 0?{...e,boost:Math.max(-99,50-t)}:e),filter:!1}:null}function wh(e,t){return e.map(e=>({...e,apply:(n,r,i,a)=>{let o=typeof e.apply==`string`?e.apply:e.label,s=n.state.sliceDoc(a,a+t.length)===t;n.dispatch({changes:{from:i,to:a,insert:s?o:o+t},selection:{anchor:i+o.length+t.length},userEvent:`input.complete`}),ii(n)}}))}var Th=[...Bp.map(e=>({label:e,detail:`function head`,type:`keyword`})),...Ip.map(e=>({label:e,detail:`source head`,type:`keyword`})),...Vp.map(e=>({label:e,detail:`chart head`,type:`class`})),...Hp.map(e=>({label:e,detail:`page dataset`,type:`class`}))];function Eh(e,t){return e.label.startsWith(`@`)?{...e,apply:e.label}:{...e,apply:`${t?``:`:`}${e.label}{`}}var Dh=Tp.map(e=>({label:e,type:`keyword`})),Oh=[`title`,`date`,`createdAt`,`type`,`sourceId`,`catalog`,`notebookId`],kh=[`noteTitle`,`dataType`,`position`,`createdAt`,`noteId`,`sourceId`],Ah=[`slug`,`label`,`registrySource`],jh=[`duration`,`startTime`,`origin`],Mh=[`date`,`effort`,`discipline`,`note`,`grade`,`intensity`,...Cp,...wp],Nh=new Set([`distance`,`resistance`,`totalVolume`,`totalDistance`]),Ph=[{label:`asc`,detail:`sort ascending`,type:`keyword`},{label:`desc`,detail:`sort descending`,type:`keyword`}],Fh=Gp.map(e=>({label:e,detail:`display unit`,type:`constant`}));function Ih(e,t){return{family:`aggregate`}}function Lh(e){let t=e.toLowerCase();if(Bp.includes(t))return{family:`aggregate`};if(Vp.includes(t))return{family:`find`};let n=e=>e===`notes`||Lp[e]||Rp[e]?`note`:e;if(Ip.includes(t))return{family:`find`,target:n(t)};let r=t?Ip.filter(e=>e.startsWith(t)):[],i=[...new Set(r.map(n))];return i.length===1?{family:`find`,target:i[0]}:{family:`find`}}var Rh=[...new Set(Pp.flatMap(e=>[...im(e,`find`)]))];function zh(e){return e.family===`find`?e.target?im(e.target,`find`):Rh:im(``,`aggregate`)}function Bh(e){switch(e){case`note`:return Oh;case`block`:return kh;case`effort`:return Ah;case`session`:return jh;default:return Mh}}var Vh=new Set([`note`,`block`,`effort`,`session`]);function Hh(e={}){let{effortNames:t,tagTypeValues:n,catalog:r,values:i}=e,a=async e=>r?(await r.listByPrefix(e,20)).map(e=>({label:e.path,detail:[e.kind,...e.units].filter(Boolean).join(` · `),type:`variable`,apply:e.path})):[],o=async(e,t)=>r?(await r.listValues(e,t,20)).map(e=>({label:e.value,type:`constant`})):[],s=()=>{let e=t?.()??[];return[...mh(wp).map(e=>({...e,type:`constant`})),...mh(Cp).map(e=>({...e,type:`variable`})),...mh(e.flatMap(e=>Cp.map(t=>`${e}.${t}`))).map(e=>({...e,type:`variable`})),...mh(jp).map(e=>({...e,type:`namespace`})),br("calc.${target}",{label:`calc.`,detail:`calculated target`,type:`namespace`})]},c=e=>{switch(e){case`effort`:return mh(t?.()??[]);case`discipline`:return mh(fh);case`intensity`:return mh(Mp);case`grain`:return mh(Np);case`metric`:return s();case`source`:return mh(Fp);case`domain`:case`format`:case`equipment`:case`quality`:case`intent`:return n?Promise.resolve(n(e)).then(e=>mh(e)):null;default:return null}},l=(e,t,n,a)=>{let s=(i,s)=>{let c=xh(i,s??[]);return c.length?Ch(t,n,c,a):r?o(e,a).then(e=>Ch(t,n,e,a)):Ch(t,n,[],a)},l=c(e);if(!i)return l instanceof Promise?l.then(e=>s([],e)):s([],l);let u=i(e);return l instanceof Promise?Promise.all([Promise.resolve(u),l]).then(([e,t])=>s(e,t)):Promise.resolve(u).then(e=>s(e,l))},u=(e,t,n)=>r?a(n).then(r=>Ch(e,t,[...s(),...r],n)):Ch(e,t,s(),n),d=(e,t,n,r,i,a)=>{if(/\bby\s*$/.test(gh(t.slice(0,n.lastBrace)))){let o=am(a.target??``,a.family),s=vh(t,n.lastBrace,n.fragStart),c=[...o].filter(e=>!s.has(e));return c.length?Ch(e,r,wh(c.map(e=>({label:e,type:`atom`,detail:`grouping dimension`})),`, `),i):Ch(e,r,[],i)}let o=t.slice(n.fragStart,e.pos),s=_h(o);if(s>=0){let t=o.slice(0,s).replace(/^!/,``).trim();return l(t,e,r,i)}let c=e.matchBefore(/[\w-]*/),u=o.trimStart().startsWith(`!`),d=vh(t,n.lastBrace,n.fragStart),f=wh(zh(a).filter(e=>!d.has(e)).map(e=>({label:e,type:`property`,...u?{detail:`exclude ${e} values`}:{}})),`:`);return Ch(e,c.from,f,i)},f=(e,t,n,r,i,a,o)=>{let s=t.slice(o,e.pos);if(/\.rollup\([^)]*$/.test(s))return a.family===`aggregate`?Ch(e,r,mh(Wp).map(e=>({...e,type:`constant`})),i):Ch(e,r,[],i);if(/\bby\s*\{[^}]*$/.test(s))return d(e,t,n,r,i,a);if(/\s+last\s+$/i.test(s))return Ch(e,e.pos,[{label:`4w`,detail:`relative window`,type:`constant`},{label:`8w`,detail:`relative window`,type:`constant`},{label:`7d`,detail:`relative window`,type:`constant`},{label:`30d`,detail:`relative window`,type:`constant`}],``);let c=/\s+last\s+(\d+)([dw]?)$/i.exec(s);return c?c[2]?null:Ch(e,e.pos,[{label:`d`,detail:`days`,type:`constant`},{label:`w`,detail:`weeks`,type:`constant`}],``):/\s+from\s+$/i.test(s)?Ch(e,e.pos,[{label:`2026-01-01`,apply:`2026-01-01 `,detail:`start date (YYYY-MM-DD)`,type:`constant`}],``):/\s+from\s+\d{4}-\d{2}-\d{2}\s+$/i.test(s)?Ch(e,e.pos,[{label:`to`,apply:`to `,detail:`end date`,type:`keyword`}],``):/\s+to\s+$/i.test(s)?Ch(e,e.pos,[{label:`2026-03-31`,detail:`end date (YYYY-MM-DD)`,type:`constant`}],``):Ch(e,r,wh([{label:`by {}`,apply:`by `,detail:am(a.target??``,a.family).length?`group by dimensions`:`advisory: no grouping dimensions for find:${a.target}`,type:`keyword`},...a.family===`aggregate`?[{label:`.rollup()`,apply:`.rollup(`,detail:`bucket period`,type:`keyword`}]:[],{label:`last`,apply:`last `,detail:`relative window: last <n>d|w`,type:`keyword`},{label:`from`,apply:`from `,detail:`date range: from YYYY-MM-DD [to YYYY-MM-DD]`,type:`keyword`},...a.family===`find`?[{label:`|`,apply:`| `,detail:`presentation pipes: order by / select / limit`,type:`keyword`}]:[]],` `),i)},p=(e,t,n,r,i,a)=>{let o=t.slice(n.pipeFrom,e.pos),s=/^\s*order\b/i.exec(o);if(s){let t=o.slice(s[0].length),n=/^\s*by\b/i.exec(t);if(!n)return Ch(e,r,[{label:`by`,apply:`by `,type:`keyword`}],i);let c=t.slice(n[0].length).split(`,`).pop()??``,l=c.trim().split(/\s+/).filter(Boolean),u=Bh(a.target).map(e=>({label:e,type:`property`}));return l.length?/\s$/.test(c)?Ch(e,e.pos,Ph,``):l.length>=2?/^(asc|desc)$/i.test(l[1])?null:Ch(e,r,Ph,i):Ch(e,r,u,c.trim()):Ch(e,r,u,``)}let c=/^\s*select\b/i.exec(o);if(c){let t=o.slice(c[0].length).split(`,`).pop()??``,n=t.trim().split(/\s+/).filter(Boolean);if(!n.length)return Ch(e,r,Bh(a.target).map(e=>({label:e,type:`property`})),``);if(/\s$/.test(t))return Nh.has(n[0].toLowerCase())?Ch(e,e.pos,Fh,``):Ch(e,r,[],i);if(n.length>=2){let t=n[1].toLowerCase();return t===`in`?n[2]?Ch(e,r,Fh,n[2]):Ch(e,e.pos,Fh,``):`in`.startsWith(t)?Ch(e,e.pos,Fh,``):null}return Ch(e,r,Bh(a.target).map(e=>({label:e,type:`property`})),n[0])}if(/^\s*(limit|offset)\b/i.test(o))return null;let l=br("limit ${10}",{label:`limit`,detail:`cap result rows`,type:`keyword`});return Ch(e,r,[...wh([{label:`order by`,apply:`order by `,detail:a.target===`session`?`advisory: order ignored for sessions`:`sort rows`,type:`keyword`},{label:`select`,apply:`select `,detail:Vh.has(a.target??``)?`advisory: select ignored for find:${a.target}`:`choose columns`,type:`keyword`}],` `),l],i)};function m(e,t=!1){let n=e.state.doc.toString(),r=e.pos,i=e.matchBefore(/[\w.*-]*/)??{from:r,to:r,text:``},a=i.from===i.to&&r>0&&/[{,:|(!"@]/.test(n[r-1]);if(i.from===i.to&&!e.explicit&&!a)return null;let o=hh(n,r);if(o.quoted&&o.depth===0)return null;let s=t?``:i.text,c=/^[ \t]*:[ \t]*([A-Za-z][\w-]*)/.exec(n),l=c??/^[ \t]*([A-Za-z]+)[ \t]*:[ \t]*([A-Za-z0-9_.-]*)/.exec(n),m=c?Lh(c[1]):l?Ih(l[1],l[2]):{family:`aggregate`};if(o.pipeFrom>=0&&o.depth===0)return p(e,n,o,i.from,s,m);if(o.depth>0)return d(e,n,o,i.from,s,m);let h=i.from>0&&n[i.from-1]===`@`,g=h?Th.filter(e=>e.label.startsWith(`@`)):Th,_=h?`@`+s:s,v=h?i.from-1:i.from;return l?c?r<=c[0].length?Ch(e,v,g.map(e=>Eh(e,!0)),_):f(e,n,o,i.from,s,m,c[0].length):r<=l[0].indexOf(`:`)?Ch(e,i.from,wh(Dh,`:`),s):r<=l[0].length?u(e,i.from,s):f(e,n,o,i.from,s,m,l[0].length):Ch(e,v,g.map(e=>Eh(e,!1)),_)}function h(e){let t=e.state.selection.main;if(t.empty)return m(e);let n=m(new Ci(e.state,t.to,!0),!0),r=e=>e&&{...e,from:t.from,to:t.to,filter:!1,validFor:void 0};return n instanceof Promise?n.then(r):r(n)}return h}var Uh=jr.define([{tag:H.keyword,color:`hsl(var(--primary))`},{tag:H.variableName,color:`hsl(var(--accent-foreground))`,fontWeight:`600`},{tag:H.propertyName,color:`hsl(var(--secondary-foreground))`},{tag:H.string,color:`hsl(var(--success))`},{tag:H.attributeName,color:`hsl(var(--warning))`},{tag:H.number,color:`hsl(var(--primary))`},{tag:H.unit,color:`hsl(var(--muted-foreground))`},{tag:H.operator,color:`hsl(var(--destructive))`},{tag:[H.bracket,H.punctuation],color:`hsl(var(--muted-foreground))`}]);function Wh(e,t,n){if(t===void 0||n===void 0||t===n)return e;let r=ia(t);if(!r||r!==ia(n))return e;try{return sa(e,t,n)}catch{return e}}function Gh(e){return e?ia(e):void 0}function Kh(e,{directive:t,preferred:n}){let r=new Set;for(let t of e){let e=t.unit??t.metricUnit;e&&r.add(e)}let i;for(let e of r){let t=ia(e);if(!t)return{error:`Unknown unit "${e}"`,convert:!1};if(i&&t!==i)return{error:`Incompatible units in one calculation (${[...r].join(`, `)})`,convert:!1};i=t}if(t){let e=ia(t);return e?i&&e!==i?{error:`Output unit "${t}" is not compatible with this result's dimension`,convert:!1}:i?{unit:t,convert:!0}:{unit:t,convert:!1}:{error:`Unknown unit "${t}"`,convert:!1}}if(i){let e=oa(i);return{unit:e,convert:e!==void 0}}return{unit:void 0,convert:!1}}function qh(e=Date.now(),t=Jh()){return{instant:e,timeZone:t}}function Jh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`}catch{return`UTC`}}var Yh=/^(\d{4})-(\d{2})-(\d{2})$/;function Xh(e){let t=Yh.exec(e);if(!t)throw Error(`Invalid civil date: ${e}`);return{y:Number(t[1]),m:Number(t[2]),d:Number(t[3])}}var Zh=new Map;function Qh(e,t){let n=`${e}|${JSON.stringify(t)}`,r=Zh.get(n);return r||(r=new Intl.DateTimeFormat(`en-CA`,{timeZone:e,...t}),Zh.set(n,r)),r}function $h(e,t){let n=Qh(t,{year:`numeric`,month:`2-digit`,day:`2-digit`}).formatToParts(e),r=e=>n.find(t=>t.type===e)?.value??``;return`${r(`year`)}-${r(`month`)}-${r(`day`)}`}function eg(e,t){let{y:n,m:r,d:i}=Xh(e),a=new Date(Date.UTC(n,r-1,i+t)),o=e=>String(e).padStart(2,`0`);return`${a.getUTCFullYear()}-${o(a.getUTCMonth()+1)}-${o(a.getUTCDate())}`}function tg(e,t){let n=Xh(e),r=Xh(t);return Math.round((Date.UTC(r.y,r.m-1,r.d)-Date.UTC(n.y,n.m-1,n.d))/864e5)}function ng(e){let{y:t,m:n,d:r}=Xh(e);return eg(e,-((new Date(Date.UTC(t,n-1,r)).getUTCDay()+6)%7))}function rg(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hour12:!1,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}).formatToParts(e),r=e=>Number(n.find(t=>t.type===e)?.value??`0`);return Date.UTC(r(`year`),r(`month`)-1,r(`day`),r(`hour`)%24,r(`minute`),r(`second`))-e}function ig(e,t){let{y:n,m:r,d:i}=Xh(e),a=Date.UTC(n,r-1,i);return a-rg(a-rg(a,t),t)}function ag(e,t){return ig(e,t)+432e5}function og(e,t){if(!e)return;if(e.kind===`relative`){let n=$h(t.instant,t.timeZone);return{start:ig(e.unit===`d`?eg(n,-(e.size-1)):eg(ng(n),-7*(e.size-1)),t.timeZone),end:t.instant+1,endExclusive:!0}}let n=ig(e.start,t.timeZone);return e.end===void 0?{start:n,end:2**53-1,endExclusive:!1}:{start:n,end:ig(eg(e.end,1),t.timeZone),endExclusive:!0}}function sg(e,t){return t?e<t.start?!1:t.endExclusive?e<t.end:e<=t.end:!0}var cg=/^[\w\s.+\-*/(),]+$/;function lg(e,t){let n=[];for(let r of e.matchAll(/[A-Za-z_][\w-]*/g)){let e=r[0];t.has(e)&&!n.includes(e)&&n.push(e)}return n}function ug(e){let t=[],n=e.split(`
18
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`//`)),r={},i=!1,a=[],o,s=!1,c=new Set;for(let e of n){if(e.startsWith(`defaults `)){i=!0;let t=e.slice(9).trim(),n=/by\s*\{([^}]*)\}/.exec(t);n&&(r.groupBy=n[1].split(`,`).map(e=>e.trim()).filter(Boolean));let a=/last\s+(\d+)\s*(d|w)/.exec(t);a&&(r.window={kind:`relative`,size:Number(a[1]),unit:a[2]});let o=/from\s+(\d{4}-\d{2}-\d{2})(?:\s+to\s+(\d{4}-\d{2}-\d{2}))?/.exec(t);o&&(r.window={kind:`range`,start:o[1],end:o[2]});continue}if(e.startsWith(`show `)){o=e.slice(5).split(`,`).map(e=>e.trim()).filter(Boolean);continue}let n=/^([A-Za-z_][\w-]*)\s*=\s*(.+)$/.exec(e);if(n){let r=n[1],i=n[2].trim();c.add(r);let o=/->\s*([\w/%.]+)\s*$/.exec(i),s=/\(normalize\s+([^)]+)\)/.exec(i),l=i.replace(/->\s*[\w/%.]+\s*$/,``).replace(/\(normalize\s+[^)]+\)/,``).trim();if(/^(sum|avg|min|max|count|last|delta|find|rows)\b|^[:@|]/.test(l)){let n=X(l);n.error?t.push(`Assignment "${r}" is not a valid query`):a.push({name:r,kind:`query`,queryText:l,parsed:n,raw:e});continue}if(!cg.test(l)){t.push(`Assignment "${r}" has characters a formula cannot parse`);continue}let u={expression:l,references:[],...s?{normalize:s[1].trim()}:{},...o?{unit:o[1]}:{}};a.push({name:r,kind:`formula`,formula:u,raw:e});continue}s=!0}if(!i&&o===void 0&&!s&&a.length===1&&a[0].kind,!i&&o===void 0&&a.length===0){let e=X(n.join(` `));e.error?t.push(`Body is neither a valid query nor a valid document`):(c.add(`query`),a.push({name:`query`,kind:`query`,queryText:n.join(` `),parsed:e,raw:n.join(` `)}),o=[`query`],s=!0)}for(let e of a)if(!(e.kind!==`formula`||!e.formula)){e.formula.references=lg(e.formula.expression,c);for(let n of e.formula.expression.matchAll(/[A-Za-z_][\w-]*/g)){let r=n[0];c.has(r)||t.push(`Formula "${e.name}" references unknown name "${r}"`)}e.formula.references.length===0&&t.push(`Formula "${e.name}" references no named query or formula`)}let l=dg(a);if(l&&t.push(`Reference cycle detected: ${l.join(` -> `)}`),o===void 0)o=a.filter(e=>e.kind===`query`).map(e=>e.name),a.length>0&&o.length===0&&(o=[a[0].name]);else for(let e of o)c.has(e)||t.push(`show references unknown name "${e}"`);return{doc:{...Object.keys(r).length>0?{defaults:r}:{},assignments:a,show:o,degenerate:s},diagnostics:t}}function dg(e){let t=new Map(e.filter(e=>e.kind===`formula`).map(e=>[e.name,e.formula.references])),n=new Map,r=[],i=e=>{let a=n.get(e);if(a!==2){if(a===1){let t=r.indexOf(e);return[...r.slice(t===-1?0:t),e]}n.set(e,1),r.push(e);for(let n of t.get(e)??[]){let e=i(n);if(e)return e}r.pop(),n.set(e,2)}};for(let e of t.keys()){let t=i(e);if(t)return t}}function fg(){let e=(t,n,r)=>{let i=t.trim();if(i.startsWith(`(`)&&i.endsWith(`)`))return e(i.slice(1,-1),n,r);let a=e=>{let t=0;for(let n=i.length-1;n>=0;n--){let r=i[n];if(r===`)`)t++;else if(r===`(`)t--;else if(t===0&&e.includes(r)&&n>0){let e=r,t=i.slice(0,n),a=i.slice(n+1);if(t.trim()&&a.trim())return{op:e,left:t,right:a}}}},o=a([`+`]);if(o&&o.op===`+`){let t=e(o.left,n,r),i=e(o.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:{value:t.value+i.value,missingDerived:t.missingDerived||i.missingDerived}}let s=a([`-`]);if(s&&s.op===`-`){let t=e(s.left,n,r),i=e(s.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:{value:t.value-i.value,missingDerived:t.missingDerived||i.missingDerived}}let c=a([`*`]);if(c&&c.op===`*`){let t=e(c.left,n,r),i=e(c.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:{value:t.value*i.value,missingDerived:t.missingDerived||i.missingDerived}}let l=a([`/`]);if(l&&l.op===`/`){let t=e(l.left,n,r),i=e(l.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:i.value===0?{value:0,missingDerived:!1,error:`Division by zero`}:{value:t.value/i.value,missingDerived:t.missingDerived||i.missingDerived}}if(/^-?\d+(\.\d+)?$/.test(i))return{value:Number(i),missingDerived:!1};let u=n[i];if(u){let e=u(r);return e===void 0?{value:0,missingDerived:!0}:e}return{value:0,missingDerived:!0,error:`Unknown reference "${i}"`}};return{evaluate(t,n,r){try{return e(t,n,r)}catch(e){return{value:0,missingDerived:!0,error:e instanceof Error?e.message:String(e)}}}}}function pg(e,t,n){let r=e;return n&&n.length>0&&!/by\s*\{/.test(r)&&(r+=` by {${n.join(`, `)}}`),t.kind===`relative`&&!/\blast\b/.test(r)?r+=` last ${t.size}${t.unit}`:t.kind===`range`&&!/\bfrom\b/.test(r)&&(r+=` from ${t.start}${t.end?` to ${t.end}`:``}`),r}var mg=class{runAggregate;evaluator;constructor(e,t={}){this.runAggregate=e,this.options=t,this.evaluator=t.formulaEvaluator??fg()}options;async run(e){let t=ug(e),n=[...t.diagnostics],r=t.doc,i=[],a=new Map,o=async e=>{if(e.kind===`query`){let t=this.mergeDefaults(e,r),n=e.parsed?.family;if(n===`find`){let n=t.window?pg(t.queryText,t.window,t.groupBy):t.queryText,r=await this.options?.runFind?.(n)??{error:`find queries are not supported by this host`};i.push({name:e.name,kind:`find`,...r.notes?{notes:r.notes}:{},...r.blocks?{blocks:r.blocks}:{},...r.efforts?{efforts:r.efforts}:{},...r.containers?{containers:r.containers}:{},...r.runs?{runs:r.runs}:{},...r.table?{table:r.table}:{},...r.unit?{unit:r.unit}:{},...r.error?{error:r.error}:{}});return}if(n===`pipeline`){let n=t.window?pg(t.queryText,t.window,t.groupBy):t.queryText,r=await this.options?.runPipeline?.(n)??{error:`pipeline queries are not supported by this host`},o=new Map;for(let e of r.series??[])for(let t of e.points)t.missing||o.set(t.ts,{value:t.value,missingDerived:!1});o.size>0&&a.set(e.name,{byPosition:o,unit:r.unit,groupKeys:(r.series??[]).map(e=>e.key)}),i.push({name:e.name,kind:`pipeline`,...r.series?{series:r.series}:{},...r.table?{table:r.table}:{},...r.notes?{notes:r.notes}:{},...r.blocks?{blocks:r.blocks}:{},...r.efforts?{efforts:r.efforts}:{},...r.containers?{containers:r.containers}:{},...r.runs?{runs:r.runs}:{},...r.unit?{unit:r.unit}:{},...r.chart?{chart:r.chart}:{},...r.error?{error:r.error}:{}});return}let o=await this.runAggregate(t.queryText,{groupBy:t.groupBy,window:t.window}),s=o.series??[],c=new Map;for(let e of s)for(let t of e.points)t.missing||c.set(t.ts,{value:t.value,missingDerived:!1});a.set(e.name,{byPosition:c,unit:o.unit,groupKeys:s.map(e=>e.key)}),i.push({name:e.name,kind:`aggregate`,unit:o.unit,...r.defaults?.groupBy?{groupBy:r.defaults.groupBy}:{},...t.window?{window:t.window}:{},series:s,...o.error?{error:o.error}:{}});return}let t=e.formula,o={},s=new Set;for(let r of t.references){let t=a.get(r);if(!t){n.push(`Formula "${e.name}" references unavailable input "${r}"`);return}for(let e of t.byPosition.keys())s.add(e);o[r]=e=>t.byPosition.get(e)}let c=new Map,l,u;if(t.expression.startsWith(`corr(`)&&t.expression.endsWith(`)`)){let[r,o]=t.expression.slice(5,-1).split(`,`).map(e=>e.trim()),s=a.get(r)?.byPosition,l=a.get(o)?.byPosition;if(!s||!l){n.push(`corr("${r}", "${o}") references unavailable inputs`);return}let d=[];for(let[e,t]of s){let n=l.get(e);n&&!t.missingDerived&&!n.missingDerived&&d.push([t.value,n.value])}if(u=d.length,d.length<2){i.push({name:e.name,kind:`formula`,pairs:u,error:`corr needs at least two paired positions`}),a.set(e.name,{byPosition:new Map,groupKeys:[]});return}let f=e=>e.reduce((e,t)=>e+t,0)/e.length,p=f(d.map(([e])=>e)),m=f(d.map(([,e])=>e)),h=0,g=0,_=0;for(let[e,t]of d)h+=(e-p)*(t-m),g+=(e-p)**2,_+=(t-m)**2;if(g===0||_===0){i.push({name:e.name,kind:`formula`,pairs:u,error:`corr is undefined for zero-variance inputs`}),a.set(e.name,{byPosition:new Map,groupKeys:[]});return}let v=h/Math.sqrt(g*_);c.set(0,{value:v,missingDerived:!1}),i.push({name:e.name,kind:`formula`,pairs:u,series:[{key:`corr`,label:`corr`,points:[{ts:0,value:v}]}]}),a.set(e.name,{byPosition:c,groupKeys:[`corr`]});return}for(let e of[...s].sort((e,t)=>e-t)){let n=this.evaluator.evaluate(t.expression,o,e);if(n.error){l=n.error;continue}c.set(e,{value:n.value,missingDerived:n.missingDerived})}let d=[{key:e.name,label:e.name,points:[...c.entries()].map(([e,t])=>({ts:e,value:t.value,...t.missingDerived?{missingDerived:!0}:{}}))}];a.set(e.name,{byPosition:c,unit:t.unit,groupKeys:[e.name]}),i.push({name:e.name,kind:`formula`,...t.unit?{unit:t.unit}:{},series:d,...l?{error:l}:{}})},s=[...r.assignments],c=!0,l=new Set;for(;s.length>0&&c;){c=!1;for(let e=s.length-1;e>=0;e--){let t=s[e];(t.formula?.references??[]).every(e=>l.has(e))&&(await o(t),l.add(t.name),s.splice(e,1),c=!0)}}let u=new Set(r.show);return{outputs:i.filter(e=>u.has(e.name)),diagnostics:n}}mergeDefaults(e,t){let n=e.parsed,r=n?.family===`aggregate`?n.groupBy:void 0,i=r?.length?r:t.defaults?.groupBy,a=(n&&n.family!==`pipeline`?n.window:void 0)??t.defaults?.window;return{queryText:e.queryText??``,...i?{groupBy:i}:{},...a?{window:a}:{}}}},hg=class extends Map{getDataset(e){return this.get(e)}},gg=[`calc.acwr`,`calc.monotony`,`calc.strain`],_g=class{host;initialOptions;constructor(e,t={}){this.host=e,this.initialOptions=t}async run(e,t={}){let n={...this.initialOptions,...t,tokens:{...this.initialOptions.tokens,...t.tokens},context:t.context??this.initialOptions.context??qh()},r=vg(e,n.tokens??{});return ug(r).doc.assignments.some(e=>yg(e.parsed))&&await this.host.rollupEnsure?.(),new mg(async(e,t)=>(t.window&&(e=pg(e,t.window,t.groupBy)),this.host.runAggregate(e,{context:n.context,window:t.window})),{formulaEvaluator:n.formulaEvaluator??this.host.formulaEvaluator,runFind:async e=>await this.host.runFind?.(e,n.context)??{error:`find queries are not supported by this host`},runPipeline:async e=>await this.host.runPipeline?.(e,n.context)??{error:`pipeline queries are not supported by this host`}}).run(r)}};function vg(e,t){return e.replace(/\$([A-Za-z_][\w-]*)/g,(e,n)=>{let r=t[n];return r===void 0?e:r})}function yg(e){return e?e.family===`aggregate`?gg.includes(e.metric):e.family===`pipeline`?e.source.kind===`query`&&e.source.query.family===`aggregate`&&gg.includes(e.source.query.metric)?!0:e.transforms.some(e=>gg.includes(e.metric)):!1:!1}function bg(e){return e.trim().split(/[^a-zA-Z0-9]+/).filter(Boolean).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function xg(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}function Sg(e){let t=e?.fieldRef;if(!t||typeof t!=`object`)return;let{path:n,kind:r,dimension:i}=t;if(typeof n==`string`&&n.length!==0&&typeof r==`string`)return{path:n,kind:r,...typeof i==`string`?{dimension:i}:{}}}function Cg(e){let t=e?.groupTags;if(!t||typeof t!=`object`)return;let n=Object.entries(t).filter(e=>typeof e[1]==`string`&&e[1].length>0).sort(([e],[t])=>e<t?-1:1);return n.length>0?Object.fromEntries(n):void 0}function wg(e){let t=new Map;for(let n of e){if(n.outputType!==`analytics`)continue;let e=n.metrics.find(e=>e.type===q.Label),r=n.metrics.find(e=>e.type!==q.Label&&typeof e.value==`number`);if(!e||!r)continue;let i=String(e.value??e.image??``);if(!i)continue;let a=Sg(r.metadata),o=xg(r.metadata,`canonicalKey`)??a?.path??bg(i),s=xg(r.metadata,`effortSlug`),c=xg(r.metadata,`effortDiscipline`),l=xg(r.metadata,`effortIntensityTier`),u=xg(r.metadata,`grade`),d=Cg(r.metadata)??(s?{effort:s}:void 0),f=a?`${$i(a)}${d?`:`+Object.entries(d).map(([e,t])=>`${e}=${t}`).join(`:`):``}`:d?`${o}:${Object.entries(d).map(([e,t])=>`${e}=${t}`).join(`:`)}`:o;t.set(f,{projectionName:i,metricKey:o,value:r.value,unit:r.unit,effortSlug:s,discipline:c,intensityTier:l,grade:u,groupTags:d,rowKey:f,...a?{fieldRef:a}:{},started:n.timeSpan?.started})}return t}function Tg(e){let t=e;for(let e of t){let t=xg(e.metadata,`effortSlug`);if(t)return t;if((e.type===`effort`||e.type===q.Effort)&&typeof e.value==`string`&&e.value)return e.value}}function Eg(e,t){return e.map((e,n)=>({id:`${t.resultId}:${n}`,resultId:t.resultId,noteId:t.noteId,blockContentId:t.blockContentId,pageId:t.pageId,origin:t.origin,timestamp:e.timeSpan?.started??t.workoutTimestamp??Date.now(),grain:`event`,outputType:e.outputType??`segment`,effortSlug:Tg(e.metrics),metrics:e.metrics,timeSpan:e.timeSpan?.started===void 0?void 0:{started:e.timeSpan.started,ended:e.timeSpan.ended},metricTemporal:e.timeSpan?.started===void 0?void 0:e.metrics.map(()=>({temporalKind:`instant`,instant:e.timeSpan.started})),sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,line:e.line,sourceStatementId:e.sourceStatementId,text:e.text,dialect:e.dialect,completionReason:e.completionReason,blockId:t.blockId,blockVersion:t.blockVersion}))}function Dg(e,t){let n=Date.now();return Array.from(wg(e).values(),e=>({id:`${t.resultId}:summary:${e.rowKey}`,resultId:t.resultId,noteId:t.noteId,blockContentId:t.blockContentId,pageId:t.pageId,origin:t.origin,timestamp:t.workoutTimestamp??e.started??n,grain:`summary`,outputType:`analytics`,representationKind:`calculated`,summaryCoverage:{scope:e.effortSlug?`effort`:e.groupTags?`partition`:`workout`,...e.effortSlug?{effortSlug:e.effortSlug}:{},...e.groupTags?{groupTags:e.groupTags}:{}},effortSlug:e.effortSlug,metrics:[{type:e.metricKey,value:e.value,...e.unit?{unit:e.unit}:{},metadata:{canonicalKey:e.metricKey,...e.fieldRef?{fieldRef:e.fieldRef,originalKey:e.projectionName}:{},...e.effortSlug?{effortSlug:e.effortSlug}:{},...e.discipline?{effortDiscipline:e.discipline}:{},...e.intensityTier?{effortIntensityTier:e.intensityTier}:{},...e.groupTags?{groupTags:e.groupTags}:{},...e.grade?{grade:e.grade}:{}}}],blockId:t.blockId,blockVersion:t.blockVersion}))}function Og(e){let t=Ki(e.metrics).visible();if(e.grain===`summary`){let n=t[0];if(!n||typeof n.value!=`number`)return[];let r=Sg(n.metadata),i=xg(n.metadata,`canonicalKey`)??r?.path??n.type??``,a=e.metricTemporal?.[0],o=Cg(n.metadata);return[{id:`${e.id}:0`,noteId:e.noteId,blockContentId:e.blockContentId,origin:e.origin,pageId:e.pageId,grain:`summary`,blockId:e.blockId??``,blockVersion:e.blockVersion??0,resultId:e.resultId,type:i,value:n.value,unit:n.unit,label:i,metricKey:i,metricLabel:i,metricUnit:n.unit,...r?{fieldRef:r}:{},...a?.temporalKind===`civil-date`&&a.civilDate?{metricDate:a.civilDate,temporalKind:`civil-date`}:{},representationKind:e.representationKind??(e.outputType===`wellness`?`direct`:void 0),...e.summaryCoverage?{summaryCoverage:e.summaryCoverage}:{},...e.reducerStats?{reducerStats:e.reducerStats}:{},effortSlug:xg(n.metadata,`effortSlug`)??e.effortSlug,discipline:xg(n.metadata,`effortDiscipline`),intensityTier:xg(n.metadata,`effortIntensityTier`),grade:xg(n.metadata,`grade`),...o?{dimensions:o}:{},timestamp:e.timestamp,createdAt:e.timestamp}]}let n=t.find(e=>e.type===q.Label),r=n?String(n.value??n.image??``):``,i=t.find(e=>e.type===q.Effort||e.type===`effort`),a=xg(t[0]?.metadata,`effortSlug`)??e.effortSlug??(i&&typeof i.value==`string`?i.value:void 0),o=t.find(e=>e.type===q.Grade||e.type===`grade`),s=xg(t[0]?.metadata,`grade`)??(o&&typeof o.value==`string`?o.value:void 0),c=[],l={};for(let e of t){if(e.type===q.Label||e.type===`label`||e.type===q.Hint||e.type===`hint`)continue;let t=Qi(e.value);if(t!==`string`&&t!==`boolean`)continue;let n=Sg(e.metadata)?.path??Zi(e.type??``);n&&(l[n]=String(e.value))}let u=Object.keys(l).length>0?l:void 0;return t.forEach(t=>{if(t.type===q.Label||t.type===`label`||typeof t.value!=`number`)return;let n=Sg(t.metadata),i=t.type===q.Rep||t.type===`rep`?`reps`:t.type??`metric`;if(!n&&i===`custom`)return;let o=xg(t.metadata,`canonicalKey`)??n?.path??(r?bg(r):i),l=c.length,d=e.metricTemporal?.[l],f=d?.temporalKind===`instant`&&d.instant!==void 0?d.instant:e.timestamp;c.push({id:`${e.id}:${l}`,noteId:e.noteId,blockContentId:e.blockContentId,origin:e.origin,pageId:e.pageId,grain:`event`,blockId:e.blockId??``,blockVersion:e.blockVersion??0,resultId:e.resultId,type:o,value:t.value,unit:t.unit,label:r||o,metricKey:o,metricLabel:r||o,metricUnit:t.unit,...n?{fieldRef:n}:{},...d?.temporalKind===`civil-date`&&d.civilDate?{metricDate:d.civilDate,temporalKind:`civil-date`}:{},effortSlug:xg(t.metadata,`effortSlug`)??a,discipline:xg(t.metadata,`effortDiscipline`),intensityTier:xg(t.metadata,`effortIntensityTier`),grade:xg(t.metadata,`grade`)??s,...u?{dimensions:u}:{},timestamp:f,createdAt:e.timestamp})}),c}function kg(e){return[...e].sort((e,t)=>e.timestamp===t.timestamp?e.id.localeCompare(t.id):e.timestamp-t.timestamp).map((e,t)=>({id:t,outputType:e.outputType,timeSpan:e.timeSpan??{started:e.timestamp},metrics:e.metrics,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,line:e.line,sourceStatementId:e.sourceStatementId,text:e.text,dialect:e.dialect,completionReason:e.completionReason}))}function Ag(e,t){let n=e?.groupTags?Object.entries(e.groupTags).sort(([e],[t])=>e<t?-1:1).map(([e,t])=>`${e}=${t}`).join(`,`):``;return`${e?.effortSlug??t??``}|${n}`}function jg(e,t){if(!e)return t===`sum`||t===`min`||t===`max`||t===`last`||t===`delta`;switch(t){case`sum`:case`min`:case`max`:case`last`:return!0;case`avg`:case`count`:return typeof e.observedCount==`number`;case`delta`:return!0}}function Mg(e,t){let n={detailPopulations:0,selectedSummaries:[],ignoredDuplicates:[],insufficientScopes:[]},r=[],i=new Map;for(let t of e){let e=`${t.resultId}\u0000${t.metricKey??t.type}`,n=i.get(e);n?n.push(t):i.set(e,[t])}for(let[e,a]of i){let[i,o]=e.split(`\0`),s=a.filter(e=>e.grain!==`summary`||e.representationKind===`direct`),c=a.filter(e=>e.grain===`summary`);if(s.length>0){n.detailPopulations+=1,r.push(...s);let e=new Set(s.map(e=>Ag(void 0,e.effortSlug)));for(let a of c){let s=Ag(a.summaryCoverage,a.effortSlug);s!==`|`&&a.summaryCoverage!==void 0&&!e.has(s)&&jg(a.reducerStats,t)?(n.selectedSummaries.push({resultId:i,metricKey:o,coverage:a.summaryCoverage}),r.push(a)):n.ignoredDuplicates.push({resultId:i,metricKey:o,id:a.id})}continue}let l=!1;for(let e of c)jg(e.reducerStats,t)&&(n.selectedSummaries.push({resultId:i,metricKey:o,coverage:e.summaryCoverage}),r.push(e),l=!0);l||n.insufficientScopes.push({resultId:i,metricKey:o,reason:t===`avg`||t===`count`||t===`delta`?`summary lacks the retained observation count this operation requires`:`no detail rows and no sufficient summary for this population`})}return{selected:r,report:n}}function Ng(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}var Pg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fg(e){if(e.catalog)return e.catalog;let t=!!e.sourceId&&/^(collection|feed):/.test(e.sourceId),n=t?e.sourceId.replace(/^(collection|feed):/,``):e.noteId||e.id||``;if(!n||Pg.test(n))return;let r=n.startsWith(`feeds/`)?n.slice(6):n;if(!(!t&&!r.includes(`/`)))return r.split(`/`)[0]}function Ig(e){if(e.notebookId&&e.notebookId.trim())return Ta(e.notebookId);if(e.tags){for(let t of e.tags)if(t.startsWith(`notebook:`)||t.startsWith(`notebook/`)){let e=wa(t);if(e)return Ta(e)}}if(Lg(e,`playground`))return`notebook/playground`;if(Lg(e,`guides`))return`notebook/guides`;let t=Fg(e);if(t)return Ta(t);if(Lg(e,`journal`))return`notebook/journal`}function Lg(e,t){let n=e.sourceId;if(t===`all`)return!n||Fp.some(t=>Lg(e,t));if(t===`journal`)return e.type===`playground`||e.id?.startsWith(`playground/`)||e.noteId?.startsWith(`playground/`)||n&&n!==`journal`&&!Pg.test(n)&&!/^journal\/\d{4}-\d{2}-\d{2}$/.test(n)?!1:e.type!==`dashboard`&&e.type!==`effort`&&e.type!==`equipment`&&e.seedOrigin!==`seed`&&e.seedChunkId===void 0&&!e.catalog&&!(e.sourcePath&&e.sourcePath.startsWith(`markdown/`));if(t===`feed`||t===`feeds`||t===`notebook`||t===`notebooks`)return!!n&&(n.startsWith(`collection:`)||n.startsWith(`page:collection:`));if(t===`page`||t===`pages`)return!!n&&(n===`page`||n.startsWith(`page:`)||n.startsWith(`guides:`));if(t===`guide`||t===`guides`)return!!n&&n.startsWith(`guides:`);if(t===`playground`)return n===`playground`||e.type===`playground`;if(t.startsWith(`feed:`)){let e=t.slice(5).replace(/^feeds\//,``);if(!e||!n?.startsWith(`feed:`))return!1;let r=n.slice(5).replace(/^feeds\//,``);return r===e||r.startsWith(`${e}/`)}return t.startsWith(`notebook:`)||t.startsWith(`notebook/`)?Ig(e)===Ta(t):n===t}function Rg(e,t){for(let n of t){if(n.key!==`source`)continue;let t=n.values.map(e=>e.value);e=e.filter(e=>{let r=t.some(t=>Lg(e,t));return n.negate?!r:r})}return e}function zg(e,t){for(let n of t){if(n.key!==`notebook`)continue;let t=new Set(n.values.map(e=>Ta(e.value)));e=e.filter(e=>{let r=Ig(e);if(!r)return n.negate;let i=t.has(r);return n.negate?!i:i})}return e}var Bg={feed:!0,feeds:!0,page:!0,pages:!0,guide:!0,guides:!0,playground:!0};function Vg(e,t,n){let r=[],i=[],a=!1;for(let n of e){let e=!n.negate&&n.values.every(e=>!e.wildcard),o=e?n.values.map(e=>e.value):[];if(n.key===`source`&&e&&n.values.every(e=>Bg[e.value]===!0)){r.push({field:`source`,values:o});continue}if(n.key===`type`&&e){i.push({field:`type`,values:o});continue}if(n.key===`page`){a=!0;continue}if(n.key===`text`&&e){i.push({field:`text`,value:o.join(` `)});continue}if(n.key===`note`&&e){i.push({field:t===`block`?`noteId`:`id`,values:o});continue}a=!0}return t===`note`&&n?.length&&r.push({field:`source`,values:n}),t===`block`&&r.push({field:`sourceFence`}),{selection:r,filters:i,residual:a}}function Hg(e,t){let n=Rg(e,t.filters);if(t.sourceScope?.length){let e=t.sourceScope;n=n.filter(t=>e.some(e=>Lg(t,e)))}return n}function Ug(e,t,n){let r=e.pipes,i=r?.limit!==void 0||(r?.offset??0)>0;return n||e.join||e.window||t.range||r?.order||!i?{order:[{field:`id`,direction:`asc`}],paged:!1}:{order:[{field:`id`,direction:`asc`}],...r?.offset?{offset:r.offset}:{},...r?.limit===void 0?{}:{limit:r.limit},paged:!0}}function Wg(e){return e.context?e.context:qh(e.anchorNow)}function Gg(e,t,n,r){return sg(e,t?og(t,r):n)}function Kg(e){let t=e.find(e=>e.outputType===`completion`);return t?.timestamp?t.timestamp:e[0]?.timestamp??0}function qg(e,t,n){if(e.window)return og(e.window,n);if(t.rangeStart!==void 0||t.rangeEnd!==void 0)return{start:t.rangeStart??0,end:t.rangeEnd??2**53-1,endExclusive:!1}}var Jg={getEventsByTimeRange:async()=>[],getEventsByResult:async()=>[],getEventsForNote:async()=>[],getEventsByContent:async()=>[],scanAll:async()=>[],appendEvents:async()=>{},finalizeSummaries:async()=>{},deleteEvents:async()=>{}},Yg={getAllNotes:async()=>[],getNoteIdsForTag:async()=>new Set,getNoteTagLabels:async()=>[]},Xg={getAllBlocks:async()=>[]},Zg={getAllEfforts:async()=>[]};function Qg(e,t,n){let r=[],i=e;for(;i<t;){let e=$h(i,n);r[r.length-1]!==e&&r.push(e);let t=ig(eg(e,1),n);if(t<=i)break;i=t}return r}function $g(e,t,n){switch(t){case`effort`:return e.effortSlug;case`discipline`:return e.discipline;case`intensity`:return e.intensityTier;case`grade`:return e.grade;case`note`:return e.noteId;case`page`:return e.pageId;case`origin`:return e.origin;case`grain`:return e.grain;case`metric`:return e.metricKey;case`block`:return e.blockContentId;case`result`:return e.resultId;case`tags`:return n.get(e.noteId)??[];default:{let n=e.dimensions;return n?n[t]??n[Xi(t)]:void 0}}}function e_(e,t,n){let r=new Map;for(let e of t){let t=`${e.negate?`!`:``}${e.key}`,n=r.get(t);n?n.push(e):r.set(t,[e])}return[...r.values()].every(t=>{let r=t[0].key,i=t[0].negate,a=$g(e,r,n),o=(Array.isArray(a)?a:a===void 0?[]:[a]).some(e=>t.some(t=>t.values.some(t=>t.wildcard?e.startsWith(t.value):e===t.value)));return i?!o:o})}function t_(e,t,n,r){if(t===`day`)return e.metricDate??$h(e.timestamp,r.timeZone);if(t===`week`)return ng(e.metricDate??$h(e.timestamp,r.timeZone));if(t===`session`)return e.resultId;let i=$g(e,t,n);return i===void 0?n_:typeof i==`string`?i:i.length?i.join(`,`):n_}var n_=`\0unassigned`;function r_(e,t,n){if(t===`count`)return{state:`observed`,value:n.length};if(e.length===0)return{state:`absent`,value:0};switch(t){case`sum`:return{state:`observed`,value:e.reduce((e,t)=>e+t,0)};case`avg`:return{state:`observed`,value:e.reduce((e,t)=>e+t,0)/e.length};case`min`:return{state:`observed`,value:Math.min(...e)};case`max`:return{state:`observed`,value:Math.max(...e)};case`last`:{let t=0;for(let e=0;e<n.length;e++)n[e].timestamp>n[t].timestamp&&(t=e);return{state:`observed`,value:e[t]}}case`delta`:{if(n.length<2)return{state:`absent`,value:0};let t=n.map((t,n)=>({point:t,value:e[n]})).sort((e,t)=>e.point.timestamp-t.point.timestamp),r=t[0],i=t[t.length-1],a=t.filter(e=>e.point.timestamp===r.point.timestamp),o=t.filter(e=>e.point.timestamp===i.point.timestamp),s=new Set(a.map(e=>e.point.value)),c=new Set(o.map(e=>e.point.value));return s.size>1||c.size>1?{state:`error`,message:`Ambiguous delta order: tied endpoint observations differ in value without recorded order`}:{state:`observed`,value:i.value-r.value}}}}function i_(e,t,n){switch(t){case`>`:return e>n;case`>=`:return e>=n;case`<`:return e<n;case`<=`:return e<=n;case`==`:return e===n;case`!=`:return e!==n}}function a_(e,t,n,r){let i={selected:0,buckets:0,aggregated:0,groups:0},a=[t.join&&`where <content> join`,t.filters.length>0&&`tag filters`,t.groupBy.length>0&&`by {…} grouping`,t.rollup&&`.rollup(…)`].filter(Boolean);if(a.length>0)return{parsed:t,series:[],stages:{...i},matched:[],error:`:${t.agg}{…} on a carried stage cannot apply ${a.join(`, `)} — carried values carry no fact dimensions; author them in the source stage.`};if(e.error)return e;let o=qg(t,n,r),s=[],c=[],l=0;for(let t of e.series)for(let e of t.points)e.missing||o&&!sg(e.ts,o)||(s.push(e.value),c.push({timestamp:e.ts,value:e.value,noteId:``,resultId:``}),e.ts>l&&(l=e.ts));if(t.metric&&!(e.parsed.metric&&((e,t)=>e===t||e===`rep`&&t===`reps`||e===`reps`&&t===`rep`)(t.metric,e.parsed.metric)))return{parsed:t,series:[],stages:{...i},matched:[],error:`:${t.agg}{metric:${t.metric}} on a carried stage reduces the preceding "${e.parsed.metric||`metricless`}" values — metric:${t.metric} does not exist on them.`};let u=t.agg===`count`?`count`:e.unit;if(t.displayUnit){if(!u||u===`count`)return{parsed:t,series:[],stages:{...i},matched:[],error:`Cannot apply in ${t.displayUnit} — the preceding stage carries no convertible unit.`};try{for(let e=0;e<s.length;e++){let n=sa(s[e],u,t.displayUnit);s[e]=n,c[e]={...c[e],value:n}}u=t.displayUnit}catch(e){return{parsed:t,series:[],stages:{...i},matched:[],error:e instanceof Error?e.message:String(e)}}}let d=r_(s,t.agg,c);return d.state===`error`?{parsed:t,series:[],stages:{...i},matched:[],error:d.message}:{parsed:t,series:[{key:t.agg,label:t.agg,points:[{ts:l||r.instant,value:d.value,...d.state===`absent`?{missing:!0}:{}}],unit:u}],stages:{selected:s.length,buckets:1,aggregated:1,groups:1},matched:[],...u?{unit:u}:{}}}var o_=class{store;noteStore;blockStore;effortStore;pageStore;relationStore;datasetStore;blockEffortsStore={getAllFromIndex:async()=>[]};tagsStore={getAllFromIndex:async()=>[]};noteTagsStore={getAllFromIndex:async()=>[]};constructor(e,t,n,r){if(e&&typeof e==`object`&&(`eventStore`in e||`noteStore`in e||`blockStore`in e||`effortStore`in e||`pageStore`in e||`relationStore`in e||`datasetStore`in e)){let t=e;this.store=t.eventStore??Jg,this.noteStore=t.noteStore??Yg,this.blockStore=t.blockStore??Xg,this.effortStore=t.effortStore??Zg,this.pageStore=t.pageStore,this.relationStore=t.relationStore,this.datasetStore=t.datasetStore,t.blockEffortsStore&&(this.blockEffortsStore=t.blockEffortsStore),t.tagsStore&&(this.tagsStore=t.tagsStore),t.noteTagsStore&&(this.noteTagsStore=t.noteTagsStore)}else this.store=e??Jg,this.noteStore=t??Yg,this.blockStore=n??Xg,this.effortStore=r??Zg}async getFactsByTimeRange(e,t){return(await this.store.getEventsByTimeRange(e,t)).flatMap(Og)}async runQuery(e,t={}){let n=X(e);return Sm(n)?this.pipelineResultToQueryResult(await this.runPipelineParsed(n,t)):this.run(n,t)}async runRows(e,t={}){let n=e.filters.some(e=>[`result`,`block`,`note`].includes(e.key)),r=e.outputType??(e.target===`all`?void 0:e.target),i,a=e.filters;r?r===`segment`&&!n?i=`segment`:(i=`session`,a=[...e.filters,{key:`plane`,negate:!1,values:[{value:r,wildcard:!1}]}]):i=`session`;let o={family:`find`,raw:e.raw,target:i,filters:a,...e.window?{window:e.window}:{},...e.pipes?{pipes:e.pipes}:{},...e.error?{error:e.error}:{}},s=await this.runFind(o,t);return{parsed:e,runs:s.runs??[],...s.table?{table:s.table}:{}}}async runFindSession(e,t={}){let n=Wg(t),r=t=>e.filters.filter(e=>e.key===t).flatMap(e=>e.values.map(e=>e.value)),i=r(`result`),a=r(`block`),o=r(`note`),s=new Map,c=new Set,l=e=>{for(let t of e){if(c.has(t.id))continue;c.add(t.id);let e=s.get(t.resultId);e?e.push(t):s.set(t.resultId,[t])}};if(i.length+a.length+o.length===0){let r=e.window?og(e.window,n):t.range?t.range:void 0;l(r?await this.store.getEventsByTimeRange(r.start,r.end):await this.store.scanAll())}else{for(let e of i)l(await this.store.getEventsByResult(e));for(let e of a)l(await this.store.getEventsByContent(e));for(let e of o)l(await this.store.getEventsForNote(e))}let u=[...s.entries()].filter(([,e])=>e.length>0);(e.window||t.range)&&(u=u.filter(([,r])=>Gg(Kg(r),e.window,t.range,n))),u.sort((e,t)=>Kg(t[1])-Kg(e[1]));let d=e.filters.filter(e=>e.key===`plane`),f=u.map(([e,t])=>{let n=t;return d.length>0&&(n=n.filter(e=>d.every(t=>{let n=t.values.some(t=>t.value===e.outputType);return t.negate?!n:n}))),{resultId:e,noteId:t[0].noteId,timestamp:Kg(t),events:n}}).filter(e=>e.events.length>0),p=f,m=e.pipes;if(m&&(m.limit!==void 0||(m.offset??0)>0)){let e=m.offset??0;f=m.limit===void 0?f.slice(e):f.slice(e,e+m.limit)}return{parsed:e,notes:[],blocks:[],runs:f,events:p.flatMap(e=>e.events),stages:{selected:u.length,matched:f.length}}}async runFindTable(e,t={}){let n=Wg(t),r=t=>e.filters.filter(e=>e.key===t).flatMap(e=>e.values.map(e=>e.value)),i=r(`result`),a=r(`block`),o=r(`note`),s=[];if(i.length+a.length+o.length===0){let r=e.window?og(e.window,n):t.range?t.range:void 0,i=r&&r.start>0&&r.end<2**53-1?r:void 0;if(i){if(s=await this.store.getEventsByTimeRange(i.start,i.end),this.store.getEventsByMetricDates){let e=Qg(i.start,i.end,n.timeZone);if(e.length>0){let t=await this.store.getEventsByMetricDates(e);if(t.length>0){let e=new Set(s.map(e=>e.id));s=[...s,...t.filter(t=>!e.has(t.id))]}}}}else s=await this.store.scanAll()}else{let e=new Set,t=t=>{for(let n of t)e.has(n.id)||(e.add(n.id),s.push(n))};for(let e of i)t(await this.store.getEventsByResult(e));for(let e of a)t(await this.store.getEventsByContent(e));for(let e of o)t(await this.store.getEventsForNote(e))}let c=new Set,l=[];for(let t of s)t.grain===`event`&&(e.target!==`segment`||t.outputType===`segment`)&&(c.has(t.id)||(c.add(t.id),l.push(t)));let u=new Map,d=e=>{let t=e.metricTemporal?.[0];if(t?.temporalKind===`civil-date`&&t.civilDate)return t.civilDate;let r=u.get(e.timestamp);if(r)return r;let i=$h(e.timestamp,n.timeZone);return u.set(e.timestamp,i),i},f=e=>{let t=e.metricTemporal?.[0];return t?.temporalKind===`civil-date`&&t.civilDate?ag(t.civilDate,n.timeZone):e.timestamp},p=new Map,m=e.filters.filter(e=>![`result`,`block`,`note`,`plane`].includes(e.key)),h=!!(e.window||t.range),g=l.filter(r=>!h||Gg(f(r),e.window,t.range,n)).filter(e=>{if(m.length===0)return!0;let t=Og(e);return t.length!==0&&t.some(e=>e_(e,m,p))}),_=g.length,v=new Map,y=new Set;for(let e of g)for(let t of e.metrics)if(t.type&&t.type!==`label`&&typeof t.value==`number`){y.add(t.type);let e=typeof t.metadata?.canonicalKey==`string`?t.metadata.canonicalKey:void 0;t.unit&&(v.set(t.type,t.unit),e&&v.set(e,t.unit))}let b=e.pipes,x=b?.select?.map(e=>e.col)??[`date`,`effort`,`discipline`,...y],S=t=>b?.select?.find(e=>e.col===t)?.unit??(e.displayUnit?e.displayUnit:v.get(t)),C=x.map(e=>e===`date`?{name:`date`,type:`date`}:e===`effort`||e===`discipline`||e===`note`||e===`grade`||e===`intensity`?{name:e,type:`string`}:{name:e,type:`number`,...S(e)?{unit:S(e)}:{}}),w=new Map(C.map(e=>[e.name,e.type])),T=g.map(t=>{let n={};for(let r of x)if(w.get(r)===`date`)n.date=d(t);else if(r===`effort`)n.effort=t.effortSlug;else if(r===`discipline`)n.discipline=t.metrics.find(e=>e.metadata?.effortDiscipline)?.metadata?.effortDiscipline;else{let i=t.metrics.find(e=>e.type===r||e.metadata?.canonicalKey===r);if(i&&typeof i.value==`number`){let t=i.value;if(e.displayUnit&&i.unit&&i.unit!==e.displayUnit)try{t=sa(t,i.unit,e.displayUnit)}catch{}n[r]=t}else n[r]=i?i.value:void 0}return n.__id=t.id,n.__resultId=t.resultId,n});for(let e of[...b?.order??[]].reverse()){let t=e.dir===`desc`?-1:1;T=[...T].sort((n,r)=>{let i=n[e.col]??n.__id,a=r[e.col]??r.__id;return i===a?0:(i>a?1:-1)*t})}let E;if(e.groupBy&&e.groupBy.length>0){let t=new Map;for(let n of T){let r=e.groupBy.map(e=>String(n[e]??`unassigned`)).join(` · `),i=t.get(r);i?i.push(n):t.set(r,[n])}E=[...t.entries()].map(([e,t])=>({key:e,label:e,rows:t}))}let D=b?.offset??0,O=b?.limit;return{parsed:e,notes:[],blocks:[],runs:[],events:g,table:{columns:C,rows:O===void 0?T.slice(D):T.slice(D,D+O),...E?{groups:E}:{},totalCount:_,...O===void 0?{}:{limit:O},...D>0?{offset:D}:{}},stages:{selected:g.length,matched:_}}}async runFind(e,t={}){if(e.error)return{parsed:e,notes:[],blocks:[],stages:{selected:0,matched:0}};let n=Xm(e);if(n.length){let t=[...new Set([...e.advisories??[],...n])];t.length!==(e.advisories?.length??0)&&(e={...e,advisories:t})}if(e.target===`block`)return this.runFindBlock(e,t);if(e.target===`effort`)return this.runFindEffort(e);if(e.target===`session`)return this.runFindSession(e,t);if(e.target===`segment`||e.target===`event`)return this.runFindTable(e,t);if(e.target===`note`&&e.filters.some(e=>e.key===`type`&&!e.negate&&e.values.some(e=>e.value===`feed`))&&(e.filters.some(e=>e.key===`source`&&!e.negate&&e.values.some(e=>e.value===`feed`||e.value===`feeds`||e.value===`notebook`||e.value===`notebooks`))||e.sourceScope?.includes(`feeds`)||e.sourceScope?.includes(`notebooks`)))return this.runFindCatalog(e,t,await this.noteStore.getAllNotes());let r=Vg(e.filters,`note`,e.sourceScope),i=Ug(e,t,r.residual),a=(r.filters.length>0||r.selection.length>0||i.paged)&&this.noteStore.queryDomain?await this.noteStore.queryDomain({plan:`notes`,selection:r.selection,...r.filters.length?{filters:r.filters}:{},...i.order?{order:i.order}:{},...i.offset===void 0?{}:{offset:i.offset},...i.limit===void 0?{}:{limit:i.limit}}):void 0,o=a&&a.plan===`notes`?a:void 0,s=o?o.rows:await this.noteStore.getAllNotes(),c=o?o.selectedCount:void 0,l=!!o&&i.paged;s=Hg(s,e);let u=c??s.length,d=Wg(t);for(let t of e.filters)if(t.key===`tags`&&!t.negate){let e=new Set;for(let n of t.values)(await this.noteStore.getNoteIdsForTag(n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.id))}else if(t.key===`tags`&&t.negate)for(let e of t.values){let t=await this.noteStore.getNoteIdsForTag(e.value);s=s.filter(e=>!t.has(e.id))}else if(t.key===`effort`&&!t.negate){let e=new Set;for(let n of t.values)(await this.getNoteIdsForEffort(n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.id))}else if(Ep.includes(t.key)&&!t.negate){let e=new Set;for(let n of t.values)(await this.getNoteIdsForTypedTag(t.key,n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.id))}for(let t of e.filters)if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();s=s.filter(n=>{let r=n.title.toLowerCase().includes(e)||n.rawContent.toLowerCase().includes(e);return t.negate?!r:r})}for(let t of e.filters)if(t.key===`type`&&!t.negate){let e=new Set(t.values.map(e=>e.value));s=s.filter(t=>t.type&&e.has(t.type))}for(let t of e.filters)if(t.key===`page`){let e=t.values.some(e=>e.value===`true`||e.value===`1`),n=t.negate?!e:e;s=s.filter(e=>n?e.type===`page`:e.type!==`page`)}for(let t of e.filters)if(t.key===`catalog`){let e=new Set(t.values.map(e=>e.value));s=s.filter(n=>{let r=Fg(n);if(!r)return t.negate;let i=e.has(r);return t.negate?!i:i})}s=zg(s,e.filters);for(let t of e.filters)if(t.key===`note`){let e=new Set(t.values.map(e=>e.value));s=s.filter(n=>t.negate?!e.has(n.id):e.has(n.id))}if((e.window||t.range)&&(s=s.filter(n=>Gg(n.date??n.createdAt,e.window,t.range,d))),e.join&&(s=(await this.applyMetricJoin(e,s,[])).notes),e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;s=[...s].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}let f=e.pipes;if(!l&&f&&(f.limit!==void 0||(f.offset??0)>0)){let e=f.offset??0;s=f.limit===void 0?s.slice(e):s.slice(e,e+f.limit)}return{parsed:e,notes:s,blocks:[],...s.length&&(this.pageStore||this.relationStore)?{containers:await this.containersForNotes(s)}:{},stages:{selected:u,matched:s.length}}}async containersForNotes(e){let t={},n=this.relationStore?await this.relationStore.getBatches([...new Set(e.map(e=>e.id))]):void 0,r=new Map;for(let i of e){let e,a;if(n){a=n.get(i.id);let[t]=[...a?.links??[]].sort((e,t)=>(e.position??0)-(t.position??0));e=t?a.pages.find(e=>e.id===t.pageId):void 0,a&&a.tags.length>0&&(!i.tags||i.tags.length===0)&&(i.tags=a.tags.map(e=>e.label))}else{let t=await this.pageStore.getNotePages(i.id);if(t.length>0){let[n]=[...t].sort((e,t)=>(e.position??0)-(t.position??0));r.has(n.pageId)||r.set(n.pageId,await this.pageStore.getPage(n.pageId)),e=r.get(n.pageId)}}t[i.id]=e?{kind:`page`,id:e.id,...e.slug?{slug:e.slug}:{},...e.date?{date:e.date}:{}}:{kind:`note`,id:i.id}}return t}async hydrateBlocks(e){let t=[...new Set(e.map(e=>e.noteId))];if(t.length===0)return[];let n=this.noteStore.getNotesByIds?await this.noteStore.getNotesByIds(t):await this.noteStore.getAllNotes(),r=new Map;for(let e of n)if(!(!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1))try{Pa(e.rawContent,e.blocks,e.sourceRevision),r.set(e.id,e)}catch{}return e.flatMap(e=>{let t=r.get(e.noteId),n=t?.blocks[e.blockId];return!t||!n||e.id!==`${t.id}:${n.id}`||n.id!==e.blockId||n.kind!==e.dataType||n.version!==e.blockVersion||n.sourceRevision!==e.sourceRevision||t.sourceRevision!==e.sourceRevision||n.from!==e.from||n.to!==e.to?[]:[{...e,rawContent:t.rawContent.slice(n.from,n.to)}]})}async runFindBlock(e,t={}){let n=Vg(e.filters,`block`),r=Ug(e,t,n.residual),i=(n.filters.length>0||n.selection.length>1||r.paged)&&this.blockStore.queryDomain?await this.blockStore.queryDomain({plan:`blocks`,selection:n.selection,...n.filters.length?{filters:n.filters}:{},...r.order?{order:r.order}:{},...r.offset===void 0?{}:{offset:r.offset},...r.limit===void 0?{}:{limit:r.limit}}):void 0,a=i&&i.plan===`blocks`?i:void 0,o=a?a.rows:await this.blockStore.getAllBlocks(),s=await this.hydrateBlocks(o),c=s.length!==o.length,l=a&&!c?a.selectedCount:void 0,u=!!a&&r.paged&&!c;a&&c&&(s=await this.hydrateBlocks(await this.blockStore.getAllBlocks())),s=Rg(s,e.filters),s=s.filter(e=>!e.sourceId||Fp.some(t=>Lg(e,t)));let d=l??s.length,f=Wg(t);for(let t of e.filters)if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();s=s.filter(n=>t.negate!==n.rawContent.toLowerCase().includes(e))}for(let t of e.filters)if(t.key===`type`&&!t.negate){let e=new Set(t.values.map(e=>e.value));s=s.filter(t=>e.has(t.dataType))}for(let t of e.filters)if(t.key===`catalog`){let e=new Set(t.values.map(e=>e.value));s=s.filter(n=>{let r=Fg(n);if(!r)return t.negate;let i=e.has(r);return t.negate?!i:i})}s=zg(s,e.filters);for(let t of e.filters)if(t.key===`tags`&&!t.negate){let e=new Set;for(let n of t.values)(await this.noteStore.getNoteIdsForTag(n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.noteId))}else if(t.key===`effort`&&!t.negate){let e=new Set;for(let n of t.values){let t=await this.blockEffortsStore.getAllFromIndex(`by-effort`,n.value);for(let n of t)e.add(`${n.noteId}:${n.blockId}`)}s=s.filter(t=>e.has(`${t.noteId}:${t.blockId}`))}for(let t of e.filters)if(t.key===`note`){let e=new Set(t.values.map(e=>e.value));s=s.filter(n=>t.negate?!e.has(n.noteId):e.has(n.noteId))}if(e.window||t.range){let n=await this.noteStore.getAllNotes(),r=new Map(n.map(e=>[e.id,e.date??e.createdAt]));s=s.filter(n=>Gg(r.get(n.noteId)??n.createdAt,e.window,t.range,f))}if(e.join&&(s=(await this.applyMetricJoin(e,[],s)).blocks),e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;s=[...s].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}let p=e.pipes;if(!u&&p&&(p.limit!==void 0||(p.offset??0)>0)){let e=p.offset??0;s=p.limit===void 0?s.slice(e):s.slice(e,e+p.limit)}return{parsed:e,notes:[],blocks:s,stages:{selected:d,matched:s.length}}}async runFindEffort(e){let t=await this.effortStore.getAllEfforts(),n=t.length,r=(e,t,n,r)=>{let i=n.toLowerCase();switch(t){case`effort`:return r?e.slug.includes(i)||e.label.toLowerCase().includes(i)||e.aliases.some(e=>e.toLowerCase().includes(i)):e.slug===n||e.label.toLowerCase()===i||e.aliases.some(e=>e.toLowerCase()===i);case`discipline`:return e.baseAttributes.discipline===n;case`intensity`:return e.baseAttributes.intensityTier===n;case`origin`:return e.registrySource===n;case`text`:return e.label.toLowerCase().includes(i)||e.slug.includes(i)||e.aliases.some(e=>e.toLowerCase().includes(i));default:return!0}},i=t;for(let t of e.filters)[`effort`,`discipline`,`intensity`,`origin`,`text`].includes(t.key)&&(i=i.filter(e=>{let n=t.values.some(n=>r(e,t.key,n.value,n.wildcard));return t.negate?!n:n}));if(e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;i=[...i].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}let a=e.pipes;if(a&&(a.limit!==void 0||(a.offset??0)>0)){let e=a.offset??0;i=a.limit===void 0?i.slice(e):i.slice(e,e+a.limit)}return{parsed:e,notes:[],blocks:[],efforts:i,stages:{selected:n,matched:i.length}}}async run(e,t={}){if(Sm(e))throw Error(`Pipeline queries do not aggregate directly — execute them with runPipeline().`);if(bm(e))return{parsed:{family:`aggregate`,raw:e.raw,agg:`count`,metric:e.target,filters:[],groupBy:[]},series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],...e.error?{error:e.error}:{}};let n={parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[]};if(e.error)return n;if(e.join)return this.runJoined(e,t);let r=Wg(t),i=qg(e,t,r),a=i?{start:i.start,end:i.end}:void 0,o=a&&a.start>0&&a.end<2**53-1?a:void 0,s=o?await this.store.getEventsByTimeRange(o.start,o.end):await this.store.scanAll();if(o&&this.store.getEventsByMetricDates){let e=Qg(o.start,o.end,r.timeZone);if(e.length>0){let t=await this.store.getEventsByMetricDates(e);if(t.length>0){let e=new Set(s.map(e=>e.id));s=[...s,...t.filter(t=>!e.has(t.id))]}}}return this.aggregateEventRows(e,s,t,i)}async runAggregateEvents(e,t,n={}){let r={parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[]};if(e.error)return r;if(e.join)return{...r,error:`where <content> joins re-read the store and cannot run on carried pipeline data — author the join in the source stage.`};let i=qg(e,n,Wg(n));return this.aggregateEventRows(e,t,n,i)}async runPipeline(e,t={}){return this.runPipelineParsed(X(e),t)}async runPipelineParsed(e,t={}){if(!Sm(e)){let t=e.error??`Not a pipeline: "${e.raw}". Pipelines look like :source{filters} | :sum{metric:x} | :table.`;return{parsed:{family:`pipeline`,raw:e.raw,source:{kind:`dataset`,name:``},transforms:[],error:t},error:t}}let n=t=>({parsed:e,error:t});if(e.error)return n(e.error);let r,i,a,o=[];if(e.source.kind===`dataset`){let r=e.source.name,i=t.pageSources?.get(r)??this.datasetStore?.getDataset(r);if(!i)return n(`Unknown dataset "${r}" — the host must register it before the query runs.`);a=i.events,o=i.notes}else if(bm(e.source.query)){let i=e.source.query;if(r=await this.runFind(i,{context:t.context,...t.rangeStart!==void 0||t.rangeEnd!==void 0?{range:{start:t.rangeStart??0,end:t.rangeEnd??2**53-1,endExclusive:!1}}:{}}),i.error)return n(i.error)}else if(i=await this.run(e.source.query,t),e.source.query.error)return n(e.source.query.error);if(e.transforms.length===0)return r?{parsed:e,...r.notes.length?{notes:r.notes}:{},...r.blocks.length?{blocks:r.blocks}:{},...r.efforts?.length?{efforts:r.efforts}:{},...r.runs?.length?{runs:r.runs}:{},...r.table?{table:r.table}:{},...r.containers?{containers:r.containers}:{},...e.sink?{chart:e.sink}:{}}:e.source.kind===`dataset`?{parsed:e,notes:o,...e.sink?{chart:e.sink}:{}}:{parsed:e,...i?{series:i.series,...i.unit?{unit:i.unit}:{},...i.error?{error:i.error}:{}}:{},...e.sink?{chart:e.sink}:{}};if(i)for(let n of e.transforms){if(i.error)break;i=a_(i,n,t,Wg(t))}else{!a&&r&&(a=await this.sourceEventsFromFind(r)),i=await this.runAggregateEvents(e.transforms[0],a??[],t);for(let n of e.transforms.slice(1)){if(i.error)break;i=a_(i,n,t,Wg(t))}}return{parsed:e,series:i.series,...i.unit?{unit:i.unit}:{},...i.error?{error:i.error}:{},...e.sink?{chart:e.sink}:{}}}async sourceEventsFromFind(e){if(e.events)return e.events;let t=[];for(let n of e.notes)t.push(...await this.store.getEventsForNote(n.id));for(let n of e.blocks)n.dataType===`wod`&&n.blockContentId&&t.push(...await this.store.getEventsByContent(n.blockContentId));return t}pipelineResultToQueryResult(e){let t={family:`aggregate`,raw:e.parsed.raw,agg:`count`,metric:``,filters:[],groupBy:[]};if(e.series){let n=e.series.reduce((e,t)=>e+t.points.length,0);return{parsed:t,series:e.series,stages:{selected:0,buckets:e.series[0]?.points.length??0,aggregated:n,groups:e.series.length},matched:[],...e.unit?{unit:e.unit}:{},...e.error?{error:e.error}:{}}}return{parsed:t,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],...e.error?{error:e.error}:{}}}async aggregateEventRows(e,t,n,r){let i=Wg(n);if(!e.metric&&e.agg!==`count`)return{parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],error:`Aggregate "${e.agg}" requires a metric — use ${e.agg}{metric:<key>}`};let a=(e,t)=>!t||e===t||t===`rep`&&e===`reps`||t===`reps`&&e===`rep`,o=e=>e.metricDate?ag(e.metricDate,i.timeZone):e.timestamp,s=t.flatMap(Og).filter(t=>a(t.metricKey,e.metric)).filter(e=>!r||sg(o(e),r)),c=e.filters.some(e=>e.key===`tags`)||e.groupBy.includes(`tags`),l=await this.loadNoteTags(s,c),{selected:u,report:d}=Mg(s.filter(t=>e_(t,e.filters,l)),e.agg);return this.buildResult(u,e,n,l,r,d)}buildResult(e,t,n,r,i,a){let o=Wg(n),s=t.groupBy.find(e=>e===`day`||e===`week`),c=t.groupBy.filter(e=>e!==`day`&&e!==`week`),l=t.rollup,u=e=>e.metricDate??$h(e.timestamp,o.timeZone),d=e=>{if(s===`day`)return`d:${u(e)}`;if(s===`week`)return`w:${ng(u(e))}`;if(l){let t=u(e);if(l.unit===`w`){let e=ng(t),n=Math.floor(tg(`1970-01-05`,e)/7);return`w:${eg(`1970-01-05`,Math.floor(n/l.size)*l.size*7)}`}if(l.unit===`d`){let e=tg(`1970-01-01`,t);return`d:${eg(`1970-01-01`,Math.floor(e/l.size)*l.size)}`}}return``},f=e=>e.startsWith(`d:`)||e.startsWith(`w:`)?ag(e.slice(2),o.timeZone):2**53-1,p=e=>e.startsWith(`d:`)||e.startsWith(`w:`)?e.slice(2):e,m=e=>{let t=s??(l?.unit===`w`?`week`:l?.unit===`d`?`day`:void 0);if(!t||e.length===0)return e;let n=i&&i.end!==2**53-1?{startIso:$h(i.start,o.timeZone),endIso:i.endExclusive?$h(i.end-1,o.timeZone):$h(i.end,o.timeZone)}:{startIso:p(e[0]),endIso:p(e[e.length-1])},r=t===`week`?ng(n.startIso):n.startIso,a=t===`week`?ng(n.endIso):n.endIso,c=t===`week`?7*(l?.size??1):l?.size??1,u=tg(r,a);if(u<0||u/c>1e4)return e;let d=[];for(let e=r;d.push(t===`week`?`w:${e}`:`d:${e}`),!(e>=a);e=eg(e,c));return d},h=Kh(e,{directive:t.displayUnit,preferred:n.preferredUnit}),g=h.unit,_=h.convert===!0,v=h.error,y=new Map;for(let n of e){let e=c.map(e=>t_(n,e,r,o)),i=c.length?JSON.stringify(e):t.metric,a=c.length?e.map(e=>e===`\0unassigned`?`unassigned`:e).join(` · `):t.metric,s=y.get(i);s?s.rows.push(n):y.set(i,{label:a,rows:[n]})}let b=[...y.entries()].map(([e,n])=>{let r=n.rows;if(v)return{key:e,label:n.label,points:[],unit:void 0,error:v};let i=new Map;for(let e of r){let t=d(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=[...i.keys()].sort(),o=s?m(a):a,c,u=o.map(e=>{let n=i.get(e);if(!n)return{ts:f(e),value:0,missing:!0};let r;try{r=n.map(e=>_&&g&&(e.unit??e.metricUnit)!==void 0?sa(e.value,e.unit??e.metricUnit,g):e.value)}catch(t){return c=t instanceof Error?t.message:String(t),{ts:f(e),value:0,missing:!0}}let a=r_(r,t.agg,n);return a.state===`error`?(c=a.message,{ts:f(e),value:0,missing:!0}):{ts:s||l?f(e):Math.min(...n.map(e=>e.timestamp)),value:a.value,...a.state===`absent`?{missing:!0}:{}}}),p=t.agg===`count`?`count`:g;return{key:e,label:n.label,points:u,unit:p,...c?{error:c}:{}}}),x=b.reduce((e,t)=>e+t.points.length,0),S=b.length===1&&b[0].points.length===1?b[0].points[0].value:void 0,C=b.length>0?b[0].unit:void 0,w=s||l?b[0]?.points.length??0:+!!e.length,T=a?.insufficientScopes??[],E=b.find(e=>e.error)?.error??(T.length>0?`Insufficient evidence: ${T.map(e=>`${e.resultId}/${e.metricKey} (${e.reason})`).join(`; `)}`:void 0);return{parsed:t,series:b,stages:{selected:e.length,buckets:w,aggregated:x,groups:b.length},matched:e,scalar:S,unit:C,...E?{error:E}:{},...a?{coverage:a}:{}}}async runJoined(e,t){let n={parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[]},r=e.join,i=await this.runFind({family:`find`,raw:``,target:r.target,filters:r.filters,window:r.last?{kind:`relative`,size:r.last.size,unit:r.last.unit}:void 0}),a=await this.contentIdsFromFindResult(i);if(a.size===0)return n;let o=Ng(await this.deriveMetricFacts(a,e.metric)),s=qg(e,t,Wg(t));s&&(o=o.filter(e=>sg(e.timestamp,s)));let c=e.filters.some(e=>e.key===`tags`)||e.groupBy.includes(`tags`),l=await this.loadNoteTags(o,c),{selected:u,report:d}=Mg(o.filter(t=>e_(t,e.filters,l)),e.agg);return this.buildResult(u,e,t,l,s,d)}async applyMetricJoin(e,t,n){let r=e.join,i=await this.noteContentMap(new Set(t.map(e=>e.id))),a=new Set;for(let e of i.values())for(let t of e)a.add(t);for(let e of n)e.dataType===`wod`&&e.blockContentId&&a.add(e.blockContentId);let o=await this.contentIdsSatisfying(a,r);return n=n.filter(e=>e.dataType===`wod`&&!!e.blockContentId&&o.has(e.blockContentId)),t=t.filter(e=>{let t=i.get(e.id);return!!t&&[...t].some(e=>o.has(e))}),{notes:t,blocks:n}}async contentIdsSatisfying(e,t){let n=Ng(await this.deriveMetricFacts(e,t.metric)),r=await this.loadNoteTags(n,t.filters.some(e=>e.key===`tags`)),i=Mg(n.filter(e=>e_(e,t.filters,r)),t.agg).selected,a=new Map;for(let e of i){let t=e.blockContentId??``,n=a.get(t);n?n.push(e):a.set(t,[e])}let o=new Set;for(let[e,n]of a){let r=r_(n.map(e=>e.value),t.agg,n);r.state===`observed`&&i_(r.value,t.operator,t.threshold)&&o.add(e)}return o}async deriveMetricFacts(e,t){let n=[...new Set(e)];return(await Promise.all(n.map(e=>this.store.getEventsByContent(e)))).flat().flatMap(Og).filter(e=>e.metricKey===t)}async allContentBlocks(){return this.hydrateBlocks(await this.blockStore.getAllBlocks())}async noteContentMap(e){let t=new Map;if(!e.size)return t;let n=await this.allContentBlocks();for(let r of n){if(r.dataType!==`wod`||!r.blockContentId||!e.has(r.noteId))continue;let n=t.get(r.noteId);n||(n=new Set,t.set(r.noteId,n)),n.add(r.blockContentId)}return t}async contentIdsFromFindResult(e){let t=new Set;for(let n of e.blocks)n.dataType===`wod`&&n.blockContentId&&t.add(n.blockContentId);if(e.notes.length){let n=new Set(e.notes.map(e=>e.id)),r=await this.noteContentMap(n);for(let e of r.values())for(let n of e)t.add(n)}return t}async loadNoteTags(e,t){let n=new Map;if(!t)return n;let r=[...new Set(e.map(e=>e.noteId))];if(this.relationStore){let e=await this.relationStore.getBatches(r);for(let t of r)n.set(t,(e.get(t)?.tags??[]).map(e=>e.label));return n}return await Promise.all(r.map(async e=>n.set(e,await this.noteStore.getNoteTagLabels(e)))),n}async getNoteIdsForEffort(e){let t=await this.blockEffortsStore.getAllFromIndex(`by-effort`,e);return new Set(t.map(e=>e.noteId))}async getNoteIdsForTypedTag(e,t){let n=(await this.tagsStore.getAllFromIndex(`by-label`,t)).find(t=>t.type===e);if(!n)return new Set;let r=await this.noteTagsStore.getAllFromIndex(`by-tag`,n.id);return new Set(r.map(e=>e.noteId))}async runFindCatalog(e,t,n){let r=Wg(t),i=n.filter(e=>Lg(e,`feeds`)||e.catalog&&!e.sourceId),a=i.filter(e=>e.type===`feed`||e.sourceId?.startsWith(`page:collection:`)),o=new Set(a.map(e=>Fg(e)??e.id));for(let e of i){let t=Fg(e);t&&!o.has(t)&&(a.push({id:t,title:t,type:`feed`,sourceId:`page:collection:${t}`,catalog:t,createdAt:e.createdAt??0,rawContent:``,sourceRevision:1,blocks:{}}),o.add(t))}let s=new Map;for(let e of a){let t=Fg(e)??e.id;s.set(t,[e])}for(let e of i){let t=Fg(e);if(t){let n=s.get(t);n?n.includes(e)||n.push(e):s.set(t,[e])}}let c=e.filters.filter(e=>!(e.key===`source`&&!e.negate&&e.values.some(e=>e.value===`feeds`||e.value===`feed`||e.value===`notebooks`||e.value===`notebook`))&&!(e.key===`type`&&!e.negate&&e.values.some(e=>e.value===`feed`))),l=[...a];for(let e of c)if(e.key===`catalog`||e.key===`notebook`){let t=new Set(e.values.map(e=>wa(e.value)));l=l.filter(n=>{let r=wa(Fg(n)??n.id),i=t.has(r);return e.negate?!i:i})}else if(e.key===`effort`){let t=new Set;for(let n of e.values)(await this.getNoteIdsForEffort(n.value)).forEach(e=>t.add(e));l=l.filter(n=>{let r=Fg(n)??n.id,i=(s.get(r)??[]).some(e=>t.has(e.id));return e.negate?!i:i})}else if(e.key===`tags`){let t=new Set;for(let n of e.values)(await this.noteStore.getNoteIdsForTag(n.value)).forEach(e=>t.add(e));l=l.filter(n=>{let r=Fg(n)??n.id,i=(s.get(r)??[]).some(n=>t.has(n.id)||n.tags&&e.values.some(e=>n.tags.includes(e.value)));return e.negate?!i:i})}else if(Ep.includes(e.key)){let t=new Set;for(let n of e.values)(await this.getNoteIdsForTypedTag(e.key,n.value)).forEach(e=>t.add(e));l=l.filter(n=>{let r=Fg(n)??n.id,i=(s.get(r)??[]).some(e=>t.has(e.id));return e.negate?!i:i})}else if(e.key===`text`){let t=e.values.map(e=>e.value).join(` `).toLowerCase();l=l.filter(n=>{let r=Fg(n)??n.id,i=(s.get(r)??[]).some(e=>e.title.toLowerCase().includes(t)||e.rawContent.toLowerCase().includes(t));return e.negate?!i:i})}else if(e.key===`note`){let t=new Set(e.values.map(e=>e.value));l=l.filter(n=>{let r=Fg(n)??n.id,i=(s.get(r)??[]).some(e=>t.has(e.id));return e.negate?!i:i})}if((e.window||t.range)&&(l=l.filter(n=>{let i=Fg(n)??n.id;return(s.get(i)??[]).some(n=>Gg(n.date??n.createdAt,e.window,t.range,r))})),e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;l=[...l].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}return{parsed:e,notes:l,blocks:[],stages:{selected:a.length,matched:l.length}}}},s_=[`table`,`list`,`value`,`timeseries`,`bar`,`donut`,`toplist`,`stacked-bar`,`goal-rings`,`zone-distribution`];function c_(e){return s_.includes(e)}function l_(e){return e==null||e===``?`table`:e}function u_(e){return`unknown widget type "${e}"`}function d_(e){return`unknown token${e.length>1?`s`:``}: ${e.map(e=>`$${e}`).join(`, `)}`}var f_=[];new Set(jp);function p_(e){if(e===``)return{type:``,attributes:{},attributeOrder:[],error:`missing widget type after "query:"`};let t={},n=[],r=e.trim(),i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i),s=/([a-zA-Z][a-zA-Z0-9_-]*)=("([^"]*)"|\S+)/g,c=0;for(let e of o.matchAll(s)){c+=e[0].length;let r=e[1].toLowerCase(),i=e[3]===void 0?e[2]:e[3];if(r in t)return{type:a,attributes:t,attributeOrder:n,error:`duplicate attribute "${r}"`};t[r]=i,n.push(r)}let l=o.replace(s,``).trim();if(l!==``)return{type:a,attributes:t,attributeOrder:n,error:`malformed attribute "${l.split(/\s+/)[0]}"`};let u=a.toLowerCase(),d,f;if(u.endsWith(`-full`))f=!0,u=u.slice(0,-5);else{let e=u.match(/-(\d+)$/);e&&(d=Number(e[1]),u=u.slice(0,-e[0].length))}return u===``||!/^[a-z][a-z0-9-]*$/.test(u)?{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n,error:`malformed widget type "${e}"`}:/-(\d+|full)$/.test(u)?{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n,error:`malformed widget suffix "${e}"`}:d!=null&&(d<1||d>4)?{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n,error:`span ${d} outside 1..4`}:{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n}}var m_=`dashboard.`;function h_(e){return e.dashboard===`true`||e.dashboard===!0}function g_(e){let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith(m_)||n===m_)continue;let e=n.slice(10);e!==``&&(Array.isArray(r)?r.length>0&&t.push({name:e,values:r.map(String),isList:!0}):t.push({name:e,values:[String(r)],isList:!1}))}return t}function __(e){let t={};for(let n of e)t[n.name]=n.values[0];return t}function v_(e,t,n){let r=`${m_}${t}`,i=e[r],a={...e};if(Array.isArray(i)){if(!i.includes(n))return e;a[r]=[n,...i.filter(e=>e!==n)]}else a[r]=i==null?n:typeof i==`number`&&!isNaN(Number(n))?Number(n):n;return a}var y_=/\$([A-Za-z][\w-]*)/g;function b_(e,t){let n=new Set;return{query:e.replace(y_,(e,r)=>t[r]??(n.add(r),e)),missing:[...n]}}function x_(e){let t=e.split(`
19
+ `,1)[0].replace(/^#{1,6}\s*/,``).trim();return t===``?void 0:t}function S_(e){let t=e.replace(/\s*\n\s*/g,` `).trim();return t===``?void 0:t}function C_(e,t){let n=[];e.forEach((t,r)=>{if(t.type!==`query`)return;let i=t.content.split(`
20
+ `).filter(e=>{let t=e.trim();return t!==``&&!t.startsWith(`#`)}).map(e=>e.trim()).join(`
21
+ `),a,o,s=e[r-1];if(s?.type===`markdown`&&s.subtype===`paragraph`){o=S_(s.content);let t=e[r-2];t?.type===`markdown`&&t.subtype===`heading`&&(a=x_(t.content))}else s?.type===`markdown`&&s.subtype===`heading`&&(a=x_(s.content));n.push({key:`w${n.length}`,type:t.widgetType??``,spanCols:t.spanCols,spanFull:t.spanFull,widgetError:t.widgetError,body:i,attributes:t.attributes??{},attributeOrder:t.attributeOrder??[],title:a,question:o})});let r=t.title;return{isDashboard:h_(t),title:typeof r==`string`&&r!==``?r:void 0,tokens:g_(t),widgets:n}}var w_=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function T_(e){return e.replace(/^(['"])(.*)\1$/,(e,t,n)=>t===`"`?n.replace(/\\(["\\])/g,`$1`):n)}function E_(e){let t=e.match(w_);return t?{meta:D_(t[1].split(/\r?\n/)),body:e.slice(t[0].length)}:{meta:{},body:e}}function D_(e){let t={};for(let n=0;n<e.length;n++){let r=e[n].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!r)continue;let i=r[1],a=r[2].trim();if(a===``){let r=[];for(;n+1<e.length;){let t=e[n+1].match(/^\s+-\s+(.+)$/);if(!t)break;r.push(t[1].trim()),n++}t[i]=r.length>0?r:``}else{let e=/^(['"])(.*)\1$/.test(a),n=T_(a),r=Number(n);t[i]=!e&&n!==``&&!isNaN(r)?r:n}}return t}function O_(e){return D_(e.split(/\r?\n/))}function k_(e){let{meta:t}=E_(e),n=e.split(/\r?\n/),r=[],i=0;if(n.length>0&&n[0].trim()===`---`){for(i=1;i<n.length&&n[i].trim()!==`---`;)i++;i++}for(;i<n.length;){let e=n[i].trim();if(/^```query/.test(e)){let t=e.slice(3),a,o,s,c,l,u;if(t.startsWith(`query:`)){let e=p_(t.slice(6));a=e.type||void 0,o=e.spanCols,s=e.spanFull,c=e.error,l=e.attributes,u=e.attributeOrder}let d=i;i++;let f=[];for(;i<n.length&&!/^```[\w\d_:-]*$/.test(n[i].trim());)f.push(n[i]),i++;let p=i;r.push({type:`query`,content:f.join(`
22
+ `),widgetType:a,spanCols:o,spanFull:s,widgetError:c,attributes:l,attributeOrder:u,startLine:d,endLine:p}),i++;continue}if(/^```[\w\d_:-]*$/.test(e)){let e=i,t=[n[i]];for(i++;i<n.length&&!/^```[\w\d_:-]*$/.test(n[i].trim());)t.push(n[i]),i++;i<n.length&&(t.push(n[i]),i++),r.push({type:`markdown`,subtype:`paragraph`,content:t.join(`
23
+ `),startLine:e,endLine:i-1});continue}if(e.startsWith(`#`)){r.push({type:`markdown`,subtype:`heading`,content:e,startLine:i,endLine:i}),i++;continue}if(e!==``){let e=i,t=[];for(;i<n.length&&n[i].trim()!==``&&!n[i].trim().startsWith(`#`)&&!/^```[\w\d_:-]*$/.test(n[i].trim());)t.push(n[i]),i++;r.push({type:`markdown`,subtype:`paragraph`,content:t.join(`
24
+ `),startLine:e,endLine:i-1});continue}i++}return{meta:t,sections:r}}var A_=`New Dashboard`;function j_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``)||`dashboard`}function M_(e=A_){return`---
25
+ dashboard: true
26
+ dashboard.active: true
27
+ title: ${e}
28
+ slug: ${j_(e)}
29
+ dashboard.metric:
30
+ - totalVolume
31
+ ---
32
+
33
+ ## Weekly Trend
34
+ How does $metric trend week over week?
35
+
36
+ \`\`\`query:timeseries
37
+ sum:$metric{} by {week}
38
+ \`\`\`
39
+ `}function N_(e){let t=e.type.trim(),n=t===``?``:`:${t}`;e.spanFull?n+=`-full`:e.spanCols!=null&&e.spanCols>1&&(n+=`-${e.spanCols}`);let r=e.attributes??{};for(let t of e.attributeOrder??Object.keys(r)){if(!(t in r))continue;let e=r[t],i=/^[a-zA-Z0-9_.-]+$/.test(e)?e:`"${e.replace(/"/g,``)}"`;n+=` ${t}=${i}`}return`\`\`\`query${n}`}function P_(e){return e.wql.trim()}function F_(e){let t=[],n=e.title?.trim(),r=e.question?.trim();return n&&t.push(`## ${n}`),r&&t.push(r),t.length>0&&t.push(``),t.push(N_(e)),t.push(P_(e)),t.push("```"),t}function I_(e,t,n){let r=e.filter(e=>e.type===`query`),i=r.findIndex((e,n)=>`w${n}`===t);if(i===-1)return{ok:!1,reason:`not-found`};let a=r[i];return a.content.split(`
40
+ `).filter(e=>{let t=e.trim();return t!==``&&!t.startsWith(`#`)}).map(e=>e.trim()).join(`
41
+ `)===n.trim()?{ok:!0,group:{widgetIndex:i,startLine:L_(e,a),endLine:a.endLine}}:{ok:!1,reason:`stale-body`}}function L_(e,t){let n=e.indexOf(t),r=e[n-1];if(r?.type===`markdown`&&r.subtype===`paragraph`){let t=e[n-2];return t?.type===`markdown`&&t.subtype===`heading`?t.startLine:r.startLine}return r?.type===`markdown`&&r.subtype===`heading`?r.startLine:t.startLine}function R_(e){return e.filter(e=>e.type===`query`).map((t,n)=>({widgetIndex:n,startLine:L_(e,t),endLine:t.endLine}))}function z_(e,t){let n=e.split(`
42
+ `),r=F_(t);for(;n.length>0&&n[n.length-1]===``;)n.pop();return[...n,``,...r,``].join(`
43
+ `)}function B_(e,t,n){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)i--,a--;let o=k_(e).sections.filter(e=>e.type===`query`),s=k_(t).sections.filter(e=>e.type===`query`),c=V_(e),l=V_(t),u=e.split(`
44
+ `),d=t.split(`
45
+ `),f=[];for(let[e,t]of(n??o.map((e,t)=>t)).entries()){if(t===null)continue;let n=o[t],r=s[e];if(!n||!r)throw Error(`Widget mutation lost its source lineage`);f.push({from:c[n.startLine],to:c[n.endLine]+u[n.endLine].replace(/\r$/,``).length,nextFrom:l[r.startLine],nextTo:l[r.endLine]+d[r.endLine].replace(/\r$/,``).length})}return{ok:!0,note:t,changes:e===t?[]:[{from:r,to:i,insert:t.slice(r,a)}],retainedBlocks:f}}function V_(e){let t=0;return e.split(`
46
+ `).map(e=>{let n=t;return t+=e.length+1,n})}function H_(e,t,n,r){let{sections:i}=k_(e),a=I_(i,t,n);if(!a.ok)return a;let{group:o}=a,s=e.split(`
47
+ `);return s.splice(o.startLine,o.endLine-o.startLine+1,...F_(r)),B_(e,s.join(`
48
+ `))}function U_(e,t,n){let{sections:r}=k_(e),i=I_(r,t,n);if(!i.ok)return i;let{group:a}=i,o=e.split(`
49
+ `),s=o.slice(a.startLine,a.endLine+1);o.splice(a.endLine+1,0,``,...s);let c=r.filter(e=>e.type===`query`).map((e,t)=>t);return c.splice(a.widgetIndex+1,0,null),B_(e,o.join(`
50
+ `),c)}function W_(e,t,n){let{sections:r}=k_(e),i=I_(r,t,n);if(!i.ok)return i;let{group:a}=i,o=e.split(`
51
+ `);o.splice(a.startLine,a.endLine-a.startLine+1),a.startLine>0&&a.startLine<o.length&&o[a.startLine-1]===``&&o[a.startLine]===``&&o.splice(a.startLine,1);let s=r.filter(e=>e.type===`query`).map((e,t)=>t);return s.splice(a.widgetIndex,1),B_(e,o.join(`
52
+ `),s)}function G_(e,t,n,r){let{sections:i}=k_(e),a=I_(i,t,n);if(!a.ok)return a;let{group:o}=a,s=R_(i),c=s[o.widgetIndex+r];if(!c)return B_(e,e);let l=e.split(`
53
+ `),u=l.slice(o.startLine,o.endLine+1);if(r===-1)l.splice(o.startLine,o.endLine-o.startLine+1),l.splice(c.startLine,0,...u);else{l.splice(o.startLine,o.endLine-o.startLine+1);let e=o.startLine<c.startLine?o.endLine-o.startLine+1:0,t=c.endLine-e+1;l.splice(t,0,...u)}let d=s.map((e,t)=>t);return d.splice(o.widgetIndex,1),d.splice(o.widgetIndex+r,0,o.widgetIndex),B_(e,l.join(`
54
+ `),d)}function K_(e,t,n,r){if(r.spanCols!=null&&(r.spanCols<1||r.spanCols>4))return{ok:!1,reason:`stale-body`};let{sections:i}=k_(e),a=I_(i,t,n);if(!a.ok)return a;let{group:o}=a,s=i.find(e=>e.type===`query`&&e.startLine>=o.startLine&&e.endLine<=o.endLine),c=e.split(`
55
+ `),l=c[s.startLine].match(/^\s*/)[0];return c[s.startLine]=l+N_({type:s.widgetType??``,spanCols:r.spanCols,spanFull:r.spanFull,attributes:s.attributes,attributeOrder:s.attributeOrder}),B_(e,c.join(`
56
+ `))}function q_(e){let t=[...e];return{getEventsByTimeRange:async(e,n)=>t.filter(t=>t.timestamp>=e&&t.timestamp<=n),getEventsByResult:async e=>t.filter(t=>t.resultId===e),getEventsForNote:async e=>t.filter(t=>t.noteId===e),getEventsByContent:async e=>t.filter(t=>t.blockContentId===e),scanAll:async()=>t,appendEvents:async e=>{t.push(...e)},finalizeSummaries:async(e,n)=>{for(let n=t.length-1;n>=0;n--){let r=t[n];r.resultId===e&&r.grain===`summary`&&r.origin!==`user`&&t.splice(n,1)}t.push(...n)},deleteEvents:async e=>{let n=new Set(e);for(let e=t.length-1;e>=0;e--)n.has(t[e].id)&&t.splice(e,1)}}}var J_=/^---\r?\n([\s\S]*?)\r?\n---/;function Y_(e){let t=J_.exec(e);if(!t)return{};let n={},r=t[1].split(/\r?\n/),i;for(let e of r){let t=e.trimEnd(),r=t.match(/^\s+-\s+(.*)$/);if(r&&i){n[i].push(r[1].trim());continue}let a=t.match(/^([^:]+):\s*(.*)$/);if(!a)continue;let o=a[1].trim().toLowerCase(),s=a[2].trim();s===``?(n[o]=[],i=o):s.startsWith(`[`)&&s.endsWith(`]`)?(n[o]=s.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/g,``)).filter(e=>e.length>0),i=void 0):(n[o]=s,i=void 0)}return n}var X_=e=>Array.isArray(e)?e:typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];function Z_(e,t=Ep){let n=Y_(e),r=X_(n.tags).map(e=>({label:e})),i=Object.keys(n);for(let e of t){if(e===`tags`)continue;let t=i.find(t=>t===e.toLowerCase());if(t)for(let i of X_(n[t]))r.push({label:i,type:e})}return r.filter(e=>e.label.length>0)}var Q_=[`sessionId`,`noteId`,`blockId`,`blockVersion`,`blockContentId`,`origin`,`status`,`startTime`,`endTime`,`duration`,`completed`,`sessionCreatedAt`,`sessionExtraJson`],$_=`eventId.grain.outputType.timestamp.pageId.effortSlug.eventBlockId.eventBlockVersion.eventBlockContentId.eventOrigin.timeSpan.sourceBlockKey.sourceStatementId.line.text.dialect.stackLevel.completionReason.representationKind.metricType.metricValue.metricUnit.metricImage.metricOrigin.metricMetadata.metricTemporal.metricJson.eventExtraJson`.split(`.`);[...Q_,...$_];var ev=Da,tv=`1b671a64-40d5-491e-99b0-da01ff1f3341`,nv={core:0,community:1,imported:2,user:3};function rv(e,t){if(t)return t;if(!e)return`core`;if(e===`user`)return`user`;let n=e.startsWith(`seed:`)?e.slice(5):e;return n===`core`||n===`efforts`||n===`equipment`?`core`:n===`community`||n.startsWith(`community-`)||n===`common`?`community`:`imported`}function iv(e,t){return nv[rv(e,t)]}var av=`wodwiki.seed`,ov=`canvas`;function sv(e){return`seed:${e}`}function cv(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function lv(e){let t=/^(?:collection|feed)\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function uv(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);return t?.[1]&&!/^template:\s*canvas\s*$/m.test(t[1])?null:t?.[1]?.match(/^route:\s*(\S+)\s*$/m)?.[1]?.replace(/^\//,``)||null}function dv(e,t,n){let r=e.split(`/`),i=(r.at(-1)??``).replace(/\.md$/i,``),a=r.slice(2).map(e=>e.replace(/\.md$/i,``)).join(`/`);if(n===`canvas`)return`guides:${uv(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n===`template`)return`playground`;if(n.startsWith(`collection.`)){let e=lv(n);return e?i.toLowerCase()===`readme`?`collection:${e}`:`collection:${e}/${i}`:`collection:_root`}if(n.startsWith(`feed.`))return`feed:feeds/${a}`}var fv=[{name:`notes`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-created`,keyPath:[`createdAt`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`page`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`],unique:!0},{name:`by-slug`,keyPath:[`slug`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`page_notes`,keyPath:[`id`],indexes:[{name:`by-page`,keyPath:[`pageId`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-page-note`,keyPath:[`pageId`,`noteId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`tags`,keyPath:[`id`],indexes:[{name:`by-label`,keyPath:[`label`],unique:!0},{name:`by-type`,keyPath:[`type`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`tag_types`,keyPath:[`id`],indexes:[{name:`by-name`,keyPath:[`name`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`note_tags`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-tag`,keyPath:[`tagId`]},{name:`by-note-tag`,keyPath:[`noteId`,`tagId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_revisions`,keyPath:[`noteId`,`blockId`,`version`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-block`,keyPath:[`noteId`,`blockId`]}]},{name:`sessions`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-completed`,keyPath:[`createdAt`]},{name:`by-content`,keyPath:[`blockContentId`]},{name:`by-block`,keyPath:[`blockId`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-origin`,keyPath:[`origin`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`attachments`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-time`,keyPath:[`createdAt`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-result`,keyPath:[`resultId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`events`,keyPath:[`id`],indexes:[{name:`by-timestamp`,keyPath:[`timestamp`]},{name:`by-result-grain`,keyPath:[`resultId`,`grain`]},{name:`by-content-grain`,keyPath:[`blockContentId`,`grain`]},{name:`by-effort`,keyPath:[`effortSlug`]},{name:`by-outputType`,keyPath:[`outputType`]},{name:`by-grain`,keyPath:[`grain`]},{name:`by-metric-date`,keyPath:[`metricDateKeys`],multiEntry:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`field_catalog`,keyPath:[`id`],indexes:[{name:`by-path`,keyPath:[`path`]}]},{name:`field_sources`,keyPath:[`id`],indexes:[]},{name:`field_values`,keyPath:[`key`],indexes:[{name:`by-field`,keyPath:[`fieldId`]}]},{name:`field_catalog_meta`,keyPath:[`id`],indexes:[]},{name:`efforts`,keyPath:[`slug`],indexes:[{name:`by-discipline`,keyPath:[`baseAttributes.discipline`]},{name:`by-source`,keyPath:[`registrySource`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`equipment`,keyPath:[`slug`],indexes:[{name:`by-source`,keyPath:[`registrySource`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_index`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-content`,keyPath:[`blockContentId`]},{name:`by-type`,keyPath:[`dataType`]},{name:`by-source`,keyPath:[`sourceId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_efforts`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-effort`,keyPath:[`effortSlug`]},{name:`by-block`,keyPath:[`blockContentId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_equipment`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-equipment`,keyPath:[`equipmentSlug`]},{name:`by-block`,keyPath:[`blockContentId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`meta`,keyPath:[`key`],indexes:[]},{name:`memberships`,keyPath:[`id`],indexes:[],system:!0}],pv=`default`;function mv(e=Date.now()){return{id:pv,displayName:`Anonymous`,createdAt:e}}var hv=[`notes`,`page`,`page_notes`,`tags`,`tag_types`,`note_tags`,`sessions`,`attachments`,`events`,`efforts`,`block_index`,`block_efforts`,`equipment`,`block_equipment`],gv=Object.fromEntries(hv.map(e=>[e,!0]));function _v(e,t,n){if(!gv[e]||typeof t!=`object`||!t||Array.isArray(t))return t;let r=t;return r.seedOrigin===`seed`||r.userId===n?t:{...r,userId:n}}function vv(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;let t=n;if(!(e in t))return;n=t[e]}if(n!==null&&typeof n!=`object`&&n!==void 0)return n}function yv(e,t){let n=e.keyPath.map(e=>vv(t,e));for(let[t,r]of n.entries())if(r===void 0)throw Error(`keyFromValue(${e.name}): keyPath part '${e.keyPath[t]}' missing on value`);let r=n;return r.length===1?r[0]:r}var bv=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function xv(e,t){if(Object.is(e,t))return!0;if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer){let n=new Uint8Array(e),r=new Uint8Array(t);return n.length===r.length&&n.every((e,t)=>e===r[t])}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>xv(e,t[n]));let n=Object.keys(e).filter(t=>Reflect.get(e,t)!==void 0),r=Object.keys(t).filter(e=>Reflect.get(t,e)!==void 0);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&xv(Reflect.get(e,n),Reflect.get(t,n)))}function Sv(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new bv(400,`storage row must be an object`);return e}function Cv(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`sessions`&&e!==`block_index`)return;let n=Sv(t),r=e=>typeof n[e]==`number`&&Number.isSafeInteger(n[e])&&n[e]>0,i=e=>typeof n[e]==`string`&&n[e].length>0;if(e===`notes`){if(!i(`id`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||!r(`sourceRevision`)||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||`segments`in n||`segmentIds`in n||n.date!==void 0&&(typeof n.date!=`number`||!Number.isFinite(n.date))||n.seedOrigin!==void 0&&n.seedOrigin!==`seed`&&n.seedOrigin!==`user`||n.seedVersion!==void 0&&!(typeof n.seedVersion==`number`&&Number.isSafeInteger(n.seedVersion)&&n.seedVersion>=0)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||[`type`,`sourceId`,`sourcePath`,`catalog`,`notebookId`,`seedChunkId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new bv(400,`invalid whole Note`,`invalid_note_blocks`);try{Pa(n.rawContent,Sv(n.blocks),n.sourceRevision)}catch(e){throw new bv(400,e instanceof Error?e.message:`invalid block map`,`invalid_note_blocks`)}}else if(e===`block_revisions`){if(!i(`noteId`)||!i(`blockId`)||!r(`version`)||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||![`wod`,`query`,`widget`,`embed`].includes(String(n.kind))||(n.kind===`wod`?n.dialect!==`time`&&n.dialect!==`log`:n.dialect!==void 0||n.sport!==void 0)||n.sport!==void 0&&typeof n.sport!=`string`)throw new bv(400,`invalid block revision`,`invalid_note_blocks`);try{Pa(n.rawContent,{[String(n.blockId)]:{id:String(n.blockId),kind:n.kind,version:n.version,sourceRevision:1,from:0,to:n.rawContent.length,...n.dialect===void 0?{}:{dialect:n.dialect},...n.sport===void 0?{}:{sport:n.sport}}},1)}catch(e){throw new bv(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new bv(400,`Session requires immutable block pin`,`invalid_session_pin`)}else if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||!r(`sourceRevision`)||n.id!==`${n.noteId}:${n.blockId}`||!Number.isSafeInteger(n.from)||!Number.isSafeInteger(n.to)||`segmentId`in n||`segmentVersion`in n||![`wod`,`query`,`widget`,`embed`].includes(String(n.dataType))||typeof n.rawContent!=`string`||typeof n.noteTitle!=`string`||typeof n.from!=`number`||typeof n.to!=`number`||n.from<0||n.to<=n.from)throw new bv(400,`invalid actionable block projection`,`invalid_note_blocks`)}function wv(e,t){if(e===void 0||xv(e,t))return;let n=Sv(e),r=Sv(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!xv(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new bv(409,`stale Note source revision`,`transaction_conflict`)}function Tv(e,t){if(e===void 0)return;let n=Sv(e),r=Sv(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new bv(409,`Session pin is immutable`,`invalid_session_pin`)}async function Ev(e,t,n){let r=[];for(let t of e)for(let e of Object.values(t.blocks))r.push([t.id,e.id,e.version]);for(let e of t)r.push([e.noteId,e.blockId,e.blockVersion]);let i=await n(r),a=0;for(let t of e)for(let e of Object.values(t.blocks)){let n=i[a++];if(!n||n.kind!==e.kind||n.rawContent!==t.rawContent.slice(e.from,e.to)||n.dialect!==e.dialect||n.sport!==e.sport)throw new bv(409,`Note block has no matching immutable revision`,`invalid_note_blocks`)}for(let e=0;e<t.length;e++){let e=i[a++];if(!e||e.kind!==`wod`)throw new bv(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}var Dv=`user-deleted-seed:`;function Ov(e){return`${Dv}${e}`}function kv(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function Av(e){return typeof e==`string`&&e.startsWith(`seed:`)}function jv(e){let t=new Set;for(let n of e)typeof n==`object`&&n&&`seedOrigin`in n&&n.seedOrigin===`seed`&&`id`in n&&typeof n.id==`string`&&t.add(n.id);return{seedNoteIds:t}}function Mv(e,t,n){if(typeof t!=`object`||!t)return!0;switch(e){case`notes`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`block_index`:case`block_efforts`:case`block_equipment`:return!(`isStatic`in t&&t.isStatic===!0&&`noteId`in t&&typeof t.noteId==`string`&&n.seedNoteIds.has(t.noteId));case`efforts`:case`equipment`:return!(`registrySource`in t&&t.registrySource===`bundled`);case`meta`:return!Av(`key`in t?t.key:void 0);default:return!0}}function Nv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pv(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function Fv(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Iv(e){if(!Nv(e)||e.schema!==9)throw Error(`Incompatible seed schema; rebuild seed artifacts`);if(!Fv(e.version)||typeof e.builtAt!=`string`||!Number.isFinite(Date.parse(e.builtAt))||!Array.isArray(e.chunks))throw Error(`seed manifest failed shape validation`);for(let t of[`versionLabel`,`commit`,`name`,`description`])if(e[t]!==void 0&&typeof e[t]!=`string`)throw Error(`invalid seed manifest metadata`);if(e.repositoryUrl!==void 0&&(typeof e.repositoryUrl!=`string`||!/^https:\/\//.test(e.repositoryUrl)||new URL(e.repositoryUrl).username||new URL(e.repositoryUrl).password))throw Error(`invalid seed repository URL`);if(e.dirty!==void 0&&typeof e.dirty!=`boolean`)throw Error(`invalid seed manifest metadata`);let t=new Set,n=new Set;for(let r of e.chunks){if(!Nv(r)||typeof r.id!=`string`||!r.id||typeof r.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(r.path)||typeof r.sha256!=`string`||!/^[0-9a-f]{64}$/.test(r.sha256)||!Fv(r.bytes)||!Fv(r.count)||r.kind!==void 0&&r.kind!==`notes`||t.has(r.id)||n.has(r.path))throw Error(`seed manifest failed shape validation`);t.add(r.id),n.add(r.path)}if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);for(let t of e.notebooks)if(!Nv(t)||typeof t.notebookId!=`string`||typeof t.label!=`string`||!Fv(t.count)||!Array.isArray(t.records))throw Error(`seed manifest failed shape validation`)}return e}function Lv(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!Nv(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!Nv(n.blocks)||!Array.isArray(n.blockIndex)||!Array.isArray(n.blockEfforts)||!Array.isArray(n.blockEquipment))throw Error(`seed chunk row failed shape validation`);t.add(n.path);for(let[e,t]of Object.entries(n.blocks))if(!Nv(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!Fv(t.from)||!Pv(t.to)||t.from>=t.to||t.to>n.content.length||![`wod`,`query`,`widget`,`embed`].includes(String(t.kind))||(t.kind===`wod`?![`time`,`log`].includes(String(t.dialect)):t.dialect!==void 0)||t.sport!==void 0&&typeof t.sport!=`string`)throw Error(`invalid seed block range or revision`);Pa(n.content,n.blocks,1,{registeredWidgets:ev});let e=new Set,r=ja(n.content,{registeredWidgets:ev});for(let t of n.blockIndex){if(!Nv(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!Nv(i)||e.has(t.blockId)||typeof t.id!=`string`||typeof t.noteId!=`string`||t.id!==`${t.noteId}:${t.blockId}`||t.blockVersion!==1||t.sourceRevision!==1||t.from!==i.from||t.to!==i.to||t.dataType!==i.kind||t.rawContent!==n.content.slice(Number(i.from),Number(i.to))||typeof t.noteTitle!=`string`||typeof t.createdAt!=`number`||!Number.isFinite(t.createdAt)||t.sourcePath!==n.path||t.isStatic!==!0)throw Error(`orphan or incompatible seed projection`);if(`segmentId`in t||`segmentVersion`in t)throw Error(`incompatible seed projection`);for(let e of[`sourceId`,`routeId`,`blockContentId`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw Error(`invalid seed projection metadata`);if(t.position!==void 0&&!Fv(t.position))throw Error(`invalid seed projection position`);if(i.kind===`wod`){let e=r.find(e=>e.from===i.from&&e.to===i.to);if(t.blockContentId!==xa(e?.scriptBlock?.content??n.content.slice(Number(i.from),Number(i.to))))throw Error(`invalid seed workout fingerprint`)}else if(t.blockContentId!==void 0)throw Error(`non-workout seed fingerprint`);e.add(t.blockId)}if(e.size!==Object.keys(n.blocks).length)throw Error(`missing actionable seed projection`);let i=new Set;for(let t of n.blockEfforts){if(!Nv(t)||typeof t.blockId!=`string`||typeof t.noteId!=`string`||typeof t.effortSlug!=`string`||!t.effortSlug)throw Error(`invalid seed effort identity`);let r=n.blocks[t.blockId];if(t.id!==`${t.noteId}:${t.blockId}:${t.effortSlug}`||i.has(String(t.id))||!Nv(r)||r.kind!==`wod`||!e.has(t.blockId)||t.sourcePath!==n.path||t.isStatic!==!0||typeof t.createdAt!=`number`)throw Error(`orphan or incompatible seed effort link`);let a=n.blockIndex.find(e=>Nv(e)&&e.blockId===t.blockId);if(!Nv(a)||t.noteId!==a.noteId||t.blockContentId!==a.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed effort metadata`);i.add(String(t.id))}let a=new Set;for(let t of n.blockEquipment){if(!Nv(t)||typeof t.blockId!=`string`||typeof t.noteId!=`string`||typeof t.equipmentSlug!=`string`||!t.equipmentSlug)throw Error(`invalid seed equipment identity`);let r=n.blocks[t.blockId];if(t.id!==`${t.noteId}:${t.blockId}:${t.equipmentSlug}`||a.has(String(t.id))||!Nv(r)||r.kind!==`wod`||!e.has(t.blockId)||t.sourcePath!==n.path||t.isStatic!==!0||typeof t.createdAt!=`number`)throw Error(`orphan or incompatible seed equipment link`);let i=n.blockIndex.find(e=>Nv(e)&&e.blockId===t.blockId);if(!Nv(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}}return e}function Rv(e){return Lv([e])[0]}async function zv(e){let t=await crypto.subtle.digest(`SHA-1`,new TextEncoder().encode(`${tv}:${e}`)),n=new Uint8Array(t.slice(0,16));n[6]=n[6]&15|80,n[8]=n[8]&63|128;let r=Array.from(n,e=>e.toString(16).padStart(2,`0`)).join(``);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function Bv(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e).filter(t=>Reflect.get(e,t)!==void 0),r=Object.keys(t).filter(e=>Reflect.get(t,e)!==void 0);return n.length===r.length&&n.every(n=>n in t&&Bv(Reflect.get(e,n),Reflect.get(t,n)))}function Vv(e){return(e.split(`/`).at(-1)??e).replace(/\.md$/,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function Hv(e,t,n){let r=e.rawContent,i=0,a=r.length,o=t.length;for(;i<a&&i<o&&r[i]===t[i];)i++;for(;a>i&&o>i&&r[a-1]===t[o-1];)a--,o--;let s=Object.values(e.blocks).filter(e=>i<e.to&&a>e.from),c=Fa(s.length<=1?e.blocks:Object.fromEntries(Object.entries(e.blocks).filter(([,e])=>!s.includes(e))),[{from:i,to:a,insert:t.slice(i,o)}]),l=0;return Na(t,{sourceRevision:n,blocks:c,registeredWidgets:ev,createId:()=>`seed:${e.id}:r${n}:${l++}`})}async function Uv(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=new Set(s),m=e=>{let t=-1;for(let n of o)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},h=[];for(let[e,t]of c.entries()){if(!u.has(l[e]))continue;let r=n(t.content);r&&h.push({...r,registrySource:`bundled`,ownerNoteId:l[e],sourceId:i,sourcePath:t.path})}let g=await e.getMany(h.map(e=>e.slug)),_=h.filter((e,t)=>{let n=g[t];if(!n)return!0;if(n.registrySource!==`bundled`)return!1;let r;if(n.ownerNoteId===e.ownerNoteId||n.ownerNoteId&&p.has(n.ownerNoteId)&&m(n.ownerNoteId)<a)r=a;else{let e=n.ownerNoteId?m(n.ownerNoteId):-1;r=e>=0?e:iv(n.sourceId)}return a>=r&&!Bv(e,n)});_.length&&await e.putMany(_);let v=new Set(h.map(e=>e.slug)),y=new Map;for(let e of f){let t=d.get(e);if(!t||t.seedOrigin!==`seed`)continue;let r=n(t.rawContent)?.slug;r&&!v.has(r)&&y.set(r,e)}let b=[...y.keys()];if(b.length){let a=await e.getMany(b);for(let[s,c]of a.entries()){let a=b[s];if(!c||c.registrySource!==`bundled`)continue;let l=y.get(a);if(!(c.ownerNoteId===l&&(!c.sourceId||c.sourceId===i||c.sourceId===r)))continue;let u=!1;for(let i of o){let o=i.meta.chunks?.[r]?.noteIds??[];if(!o.length)continue;let s=await t.getMany(o);for(let t of s){if(!t||t.seedOrigin!==`seed`)continue;let r=n(t.rawContent);if(r&&r.slug===a){await e.put({...r,registrySource:`bundled`,ownerNoteId:t.id,sourceId:i.sourceId,sourcePath:t.sourcePath??``}),u=!0;break}}if(u)break}u||await e.delete(a)}}return _.length}async function Wv(e,t,n){if(!t.length)return;let r=await e.getMany(n),i=t.filter((e,t)=>!Bv(e,r[t]));i.length&&await e.putMany(i)}async function Gv(e,t){Iv(t.manifest),Lv(t.rows);let n={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0},r=await Promise.all(t.rows.map(e=>zv(e.path))),i=new Map,a=new Map,o=new Map;for(let[e,n]of t.rows.entries()){let t=Y_(n.content).slug;typeof t==`string`&&t.trim()&&(i.set(t,await zv(`page:${t}`)),a.set(r[e],await zv(`pagenote:${t}:${n.path}`)));for(let{label:e}of Z_(n.content))o.has(e)||o.set(e,await zv(`tag:${e}`))}return e.transaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`tags`,`note_tags`,`efforts`,`equipment`,`meta`],`readwrite`,async e=>{let s=e.readwrite(`meta`),c=new Set;for(let e of await s.getAll()){let t=kv(e?.key);t!==void 0&&c.add(t)}if(!Bv(await s.get(t.meta.key),t.expectedMeta))throw Error(`Seed checkpoint changed during import`);if(t.meta.schema!==9||t.manifest.schema!==9)throw Error(`Incompatible seed schema; recreate artifacts`);let l=e.readwrite(`notes`),u=t.chunkId?t.expectedMeta?.chunks[t.chunkId]?.noteIds??[]:[],d=new Set(r),f=u.filter(e=>!d.has(e)),p=[...new Set([...r,...f])],m=await l.getMany(p),h=new Map(p.map((e,t)=>[e,m[t]])),g=t.meta.key.startsWith(`seed:`)?t.meta.key.slice(5):t.meta.key,_=iv(t.meta.key,t.meta.tier),v=[];for(let e of await s.getAll()){let n=e;if(!n||typeof n.key!=`string`||!n.key.startsWith(`seed:`)||n.key===t.meta.key)continue;let r=new Set;for(let e of Object.values(n.chunks??{}))for(let t of e.noteIds??[])r.add(t);v.push({key:n.key,sourceId:n.key.slice(5),rank:iv(n.key,n.tier),meta:n,noteIds:r})}v.sort((e,t)=>t.rank-e.rank);let y=e=>{let t=-1;for(let n of v)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},b=p.filter(e=>{if(c.has(e))return!1;let n=h.get(e);if(!n)return d.has(e);if(n.seedOrigin!==`seed`)return!1;let r=y(e);return d.has(e)?_>=r:r<0&&n.seedChunkId===t.chunkId}),x=new Set(b),S=e.readwrite(`block_revisions`),C=r.filter((e,n)=>x.has(e)&&h.get(e)?.rawContent!==t.rows[n].content),w=await S.getAllFromIndexMany(`by-note`,C),T=new Map(C.map((e,t)=>[e,w[t]])),E=e.readwrite(`block_index`),D=e.readwrite(`block_efforts`),O=e.readwrite(`block_equipment`),k=e.readwrite(`note_tags`),A=e.readwrite(`page_notes`),j=await E.getAllFromIndexMany(`by-note`,b),M=await D.getAllFromIndexMany(`by-note`,b),N=await O.getAllFromIndexMany(`by-note`,b),P=await k.getAllFromIndexMany(`by-note`,b),F=await A.getAllFromIndexMany(`by-note`,b),I=new Map(b.map((e,t)=>[e,t])),L=e.readwrite(`tags`),R=[...o.keys()],ee=await L.getAllFromIndexMany(`by-label`,R),te=new Map(R.map((e,t)=>[e,ee[t][0]])),ne=[],re=[],ie=[],ae=[],oe=[],se=[],ce=[],le=[],z=[];for(let[e,s]of t.rows.entries()){let c=r[e],l=h.get(c);if(!x.has(c)){l&&l.seedOrigin!==`seed`&&n.skippedUserOwned++;continue}l?l.rawContent!==s.content&&n.updatedNotes++:n.addedNotes++,Pa(s.content,s.blocks,1,{registeredWidgets:ev});let u=l?l.sourceRevision+(l.rawContent===s.content?0:1):1,d=0,f=T.get(c)??[],p=l?l.rawContent===s.content?structuredClone(l.blocks):Hv(l,s.content,u):f.length?Na(s.content,{sourceRevision:u,registeredWidgets:ev,createId:()=>`seed:${c}:new${f.length}:${d++}`}):structuredClone(s.blocks);for(let e of Object.values(p)){let n=(T.get(c)??[]).filter(t=>t.blockId===e.id).sort((e,t)=>t.version-e.version)[0],r=s.content.slice(e.from,e.to);if(l?.rawContent===s.content)continue;let i=n&&n.kind===e.kind&&n.rawContent===r&&n.dialect===e.dialect&&n.sport===e.sport;e.version=l?i?n.version:(n?.version??0)+1:1,(!l||!i)&&ie.push({noteId:c,blockId:e.id,version:e.version,kind:e.kind,rawContent:r,savedAt:t.meta.importedAt,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}Pa(s.content,p,u,{registeredWidgets:ev});let m=Y_(s.content),g=typeof m.title==`string`&&m.title.trim()?m.title.trim():Vv(s.path),_=t.chunkId?dv(s.path,s.content,t.chunkId):void 0;if(!_)throw Error(`Unknown seed source family ${t.chunkId}`);let v=typeof m.date==`string`?m.date.match(/^(\d{4})-(\d{2})-(\d{2})$/):null,y;if(v){let e=Date.parse(`${m.date}T12:00:00Z`);if(!(Number.isFinite(e)&&new Date(e).getUTCMonth()===Number(v[2])-1&&new Date(e).getUTCDate()===Number(v[3])))throw Error(`invalid frontmatter date '${m.date}' in '${s.path}' — expected a real calendar day (YYYY-MM-DD)`);y=e}let b=s.commit??t.manifest.commit,S={...l,id:c,title:g,rawContent:s.content,sourceRevision:u,blocks:p,createdAt:t.manifest.version,...y===void 0?{}:{date:y},type:t.chunkId===`dashboards`?`dashboard`:`note`,sourceId:_,catalog:lv(t.chunkId??``),seedOrigin:`seed`,seedVersion:t.manifest.version,seedChunkId:t.chunkId??void 0,sourcePath:s.path,...b?{seedCommit:b}:{}};y===void 0&&delete S.date,Bv(S,l)||re.push(S);let C=new Map(Object.values(p).map(e=>[`${e.from}:${e.to}`,e])),w=new Map(s.blockIndex.map(e=>[e.blockId,e])),E=new Map;for(let e of s.blockIndex){let t=C.get(`${e.from}:${e.to}`);if(!t||t.kind!==e.dataType)throw Error(`Orphan seed projection`);E.set(e.blockId,t.id);let n={...e,id:`${c}:${t.id}`,noteId:c,blockId:t.id,blockVersion:t.version,sourceRevision:u,noteTitle:g,sourceId:_,sourcePath:s.path,rawContent:s.content.slice(t.from,t.to)},r=j[I.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&ce.push(n)}for(let e of s.blockEfforts){let t=E.get(e.blockId);if(!t||w.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed effort link`);let n={...e,id:`${c}:${t}:${e.effortSlug}`,noteId:c,blockId:t,sourcePath:s.path},r=M[I.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&le.push(r?{...n,createdAt:r.createdAt}:n)}for(let e of s.blockEquipment){let t=E.get(e.blockId);if(!t||w.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed equipment link`);let n={...e,id:`${c}:${t}:${e.equipmentSlug}`,noteId:c,blockId:t,sourcePath:s.path},r=N[I.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&z.push(r?{...n,createdAt:r.createdAt}:n)}let D=I.get(c),O=new Set;for(let e of Z_(s.content)){let n=te.get(e.label);n?e.type&&!n.type&&(n={...n,type:e.type},ne.push(n),te.set(e.label,n)):(n={id:o.get(e.label),label:e.label,type:e.type,createdAt:t.meta.importedAt},ne.push(n),te.set(e.label,n)),!O.has(n.id)&&(O.add(n.id),P[D].find(e=>e.tagId===n.id)||se.push({id:`${c}:${n.id}`,noteId:c,tagId:n.id}))}for(let e of P[D])O.has(e.tagId)||await k.delete(e.id);let A=m.slug;if(typeof A==`string`&&i.has(A)){let e=i.get(A);ae.push({id:e,slug:A,title:Vv(s.path),createdAt:t.manifest.version}),oe.push({id:a.get(c),pageId:e,noteId:c,createdAt:t.manifest.version})}n.totalNotes++,n.totalBlocks+=Object.keys(p).length}let ue=new Set(ce.map(e=>e.id)),de=new Set(le.map(e=>e.id)),fe=new Set(z.map(e=>e.id));for(let e of j)for(let t of e)t.isStatic===!0&&!ue.has(t.id)&&await E.delete(t.id);for(let e of M)for(let t of e)t.isStatic===!0&&!de.has(t.id)&&await D.delete(t.id);for(let e of N)for(let t of e)t.isStatic===!0&&!fe.has(t.id)&&await O.delete(t.id);for(let e of f){if(!x.has(e)||!h.get(e))continue;let t=I.get(e);await l.delete(e);for(let e of P[t])await k.delete(e.id);for(let e of F[t])await A.delete(e.id);n.deleted++}return t.chunkId===`efforts`&&(n.totalEfforts=await Uv(e.readwrite(`efforts`),l,Rc,`efforts`,g,_,v,u,t.rows,r,x,h,p)),t.chunkId===`equipment`&&(n.totalEquipment=await Uv(e.readwrite(`equipment`),l,zc,`equipment`,g,_,v,u,t.rows,r,x,h,p)),re.length&&await l.putMany(re),ie.length&&await S.putMany(ie),await Wv(E,ce,ce.map(e=>e.id)),await Wv(D,le,le.map(e=>e.id)),await Wv(O,z,z.map(e=>e.id)),ne.length&&await L.putMany([...new Map(ne.map(e=>[e.id,e])).values()]),se.length&&await k.putMany(se),await Wv(e.readwrite(`page`),ae,ae.map(e=>e.id)),await Wv(A,oe,oe.map(e=>e.id)),await s.put(t.meta),n})}var Kv=(0,U.createContext)({isDebugMode:!1,toggleDebugMode:()=>{}}),qv=({children:e})=>{let[t,n]=(0,U.useState)(()=>typeof window<`u`&&localStorage.getItem(`wod-wiki-debug-mode`)===`true`),r=(0,U.useCallback)(()=>{n(e=>{let t=!e;return typeof window<`u`&&localStorage.setItem(`wod-wiki-debug-mode`,String(t)),t?xl.enable():xl.disable(),t})},[]);return(0,U.useEffect)(()=>{t?xl.enable():xl.disable()},[t]),(0,W.jsx)(Kv.Provider,{value:{isDebugMode:t,toggleDebugMode:r},children:e})};function Jv(){return(0,U.useContext)(Kv)}var Yv=new class{name=`Default`;async canProcess(e){return!0}async process(e){let t=await e.arrayBuffer();return{label:e.name,mimeType:e.type||`application/octet-stream`,data:t}}},Xv=new class{name=`GPX`;async canProcess(e){return e.name.split(`.`).pop()?.toLowerCase()===`gpx`||e.type===`application/gpx+xml`}async process(e){let t=await e.text(),n;try{let e=new DOMParser().parseFromString(t,`application/xml`),r=Array.from(e.querySelectorAll(`time`)).map(e=>new Date(e.textContent||``).getTime()).filter(e=>!isNaN(e)).sort((e,t)=>e-t);r.length>0&&(n={start:r[0],end:r[r.length-1]})}catch{console.warn(`[GpxAttachmentStrategy] Failed to parse GPX content for metadata`)}return{label:e.name,mimeType:`application/gpx+xml`,timeSpan:n,data:t}}},Zv=new class{name=`JSON`;async canProcess(e){return e.name.split(`.`).pop()?.toLowerCase()===`json`||e.type===`application/json`}async process(e){let t=await e.text(),n=e.name,r;try{let e=JSON.parse(t);if((e.label||e.name||e.title)&&(n=e.label||e.name||e.title),e.startTime&&e.endTime)r={start:new Date(e.startTime).getTime(),end:new Date(e.endTime).getTime()};else if(e.timestamp){let t=new Date(e.timestamp).getTime();r={start:t,end:t}}}catch{console.warn(`[JsonAttachmentStrategy] Failed to parse JSON content for metadata`)}return{label:n,mimeType:`application/json`,timeSpan:r,data:t}}},Qv=new class{strategies;constructor(e=[Xv,Zv,Yv]){this.strategies=e}async process(e){for(let t of this.strategies)if(await t.canProcess(e)){console.log(`[FileProcessor] Using strategy: ${t.name}`);try{return await t.process(e)}catch(e){console.error(`[FileProcessor] Strategy ${t.name} failed:`,e)}}return Yv.process(e)}},$v=/^(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})(?:-(\d{2})(?:-(\d{3}))?)?(?:-\d+)?$/,ey=/^(\d{4})-(\d{2})-(\d{2}) (\d{2})-(\d{2})(?:-(\d{2})\.(\d{3}))?$/,ty=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ny(e){let t=new Date(e),n=(e,t=2)=>String(e).padStart(t,`0`);return[t.getFullYear(),n(t.getMonth()+1),n(t.getDate()),n(t.getHours()),n(t.getMinutes()),n(t.getSeconds()),n(t.getMilliseconds(),3)].join(`-`)}function ry(e){let t=new Date(e);return`Playground – ${t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`})} ${t.toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`})}`}function iy(e){return new Date(Number(e[1]),Number(e[2])-1,Number(e[3]),Number(e[4]),Number(e[5]),Number(e[6]??0),Number(e[7]??0)).getTime()}function ay(e){let t=e;try{t=decodeURIComponent(e)}catch{}let n=t.match($v)??t.match(ey);return n?ry(iy(n)):ty.test(t)?`Playground`:t||`Playground`}var oy=`wodwiki-db`,sy=`$binary`,cy=`$bytes`;function ly(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function uy(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function dy(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=Object.keys(e);if(t.length!==2||!t.includes(sy)||!t.includes(cy))return e;let n=e;if(typeof n[sy]!=`string`||typeof n[cy]!=`number`)return e;let r=uy(n[sy]);if(r.length!==n[cy])throw Error(`corrupt binary cell: declared ${n[cy]} bytes, decoded ${r.length}`);return r.buffer}var fy=(e,t)=>typeof t!=`object`||!t||Array.isArray(t)?t:Object.fromEntries(Object.keys(t).sort().map(e=>[e,Reflect.get(t,e)]));function py(e,t){if(t&&typeof e==`object`&&e&&!Array.isArray(e)){let n=e,r=n[t];if(r instanceof ArrayBuffer){let e=new Uint8Array(r);return JSON.stringify({...n,[t]:{[sy]:ly(e),[cy]:e.length}},fy)}}return JSON.stringify(e,fy)}function my(e,t){let n=JSON.parse(e);if(t&&typeof n==`object`&&n&&!Array.isArray(n)){let e=n,r=dy(e[t]);r!==e[t]&&(e[t]=r)}return n}var hy=`_wodwiki_schema`,gy=`_wodwiki_sync_ops`,_y=`_wodwiki_sync_state`,vy={attachments:`data`},yy=Object.fromEntries(fv.map(e=>[e.name,!0])),by=`meta`;function xy(e){return typeof e==`number`&&Number.isSafeInteger(e)}function Sy(e){return typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Cy(e,t){if(!Sy(e)&&!(Array.isArray(e)&&e.length>0&&e.every(Sy)))throw new bv(400,`${t} must be a string, finite number, or non-empty scalar tuple`,`bad_sync_key`)}function wy(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new bv(400,`sync mutation must be an object`,`bad_sync_mutation`);let t=e;if(t.op===`wipe`)return{op:`wipe`};if(typeof t.store!=`string`||!yy[t.store])throw new bv(400,`sync mutation has unknown store ${String(t.store)}`,`bad_sync_mutation`);let n=t.store;if(t.op===`clear`)return{op:`clear`,store:n};if(t.op===`delete`)return Cy(t.key,`sync delete key`),{op:`delete`,store:n,key:t.key};if(t.op===`put`){if(Cy(t.key,`sync put key`),t.value===null||typeof t.value!=`object`||Array.isArray(t.value))throw new bv(400,`sync put value must be an object row`,`bad_sync_mutation`);let e=yv(fv.find(e=>e.name===n),t.value);if(Cy(e,`sync row key`),!xv(t.key,e))throw new bv(400,`sync put key differs from row key`,`bad_sync_key`);return{op:`put`,store:n,key:t.key,value:t.value}}throw new bv(400,`sync mutation has unknown op ${String(t.op)}`,`bad_sync_mutation`)}function Ty(e){if(typeof e.id!=`string`||e.id.length===0||e.id.length>200)throw new bv(400,`sync entry id must be a non-empty string`,`bad_sync_entry`);if(!xy(e.at)||e.at<0)throw new bv(400,`sync entry at must be a non-negative safe integer`,`bad_sync_entry`);if(!Array.isArray(e.ops)||e.ops.length===0)throw new bv(400,`sync entry ops must be a non-empty array`,`bad_sync_entry`);for(let t of e.ops)wy(t)}async function Ey(e,t){if(t.length===0)return[];if(e.batch)return e.batch(t);let n=[];for(let r of t)n.push(await e.query(r.sql,r.params??[]));return n}async function Dy(e,t,n){let r=t===`postgres`?`SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1`:`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`;return(await e.query(r,[n])).length>0}async function Oy(e){let t=await e.query(`SELECT "value" FROM "${_y}" WHERE "key" = ?`,[by]);if(!t[0])throw new bv(409,`sync target is not initialized`,`sync_not_initialized`);let n;try{n=JSON.parse(String(t[0].value))}catch{throw new bv(400,`malformed sync state row`,`bad_sync_state`)}if(typeof n!=`object`||!n||Array.isArray(n))throw new bv(400,`malformed sync state row`,`bad_sync_state`);let r=n;if(!xy(r.schema)||r.schema<0||!xy(r.rev)||r.rev<0)throw new bv(400,`sync state schema/rev must be non-negative safe integers`,`bad_sync_state`);return{schema:r.schema,rev:r.rev}}async function ky(e){if(await Dy(e,e.dialect,`_wodwiki_sync_state`)){let t=await Oy(e);return{kind:`current`,schemaVersion:t.schema,rev:t.rev}}if(await Dy(e,e.dialect,`_wodwiki_schema`)){let t=await e.query(`SELECT "value" FROM "${hy}" WHERE "key" = 'schema'`);if(t[0]){let e=JSON.parse(String(t[0].value));if(typeof e.version==`number`&&Number.isSafeInteger(e.version)&&e.version>=0)return{kind:`legacy`,schemaVersion:e.version}}return{kind:`legacy`,schemaVersion:0}}let t=await e.query(e.dialect===`postgres`?`SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'`:`SELECT name FROM sqlite_master WHERE type = 'table'`),n=e=>e.startsWith(`_wodwiki_`)||e.startsWith(`sqlite_`);return t.some(e=>!n(String(Object.values(e)[0])))?{kind:`unknown`}:`empty`}async function Ay(e,t){await e.transaction(async e=>{await e.exec(`CREATE TABLE IF NOT EXISTS "${_y}" ("key" TEXT PRIMARY KEY, "value" TEXT NOT NULL)`),await e.exec(`CREATE TABLE IF NOT EXISTS "${gy}" ("op_id" TEXT PRIMARY KEY, "rev" INTEGER NOT NULL, "idx" INTEGER NOT NULL, "at" INTEGER NOT NULL, "data" TEXT NOT NULL)`),await e.exec(`CREATE INDEX IF NOT EXISTS "${gy}_rev" ON "${gy}" ("rev", "idx")`),await e.exec(`INSERT INTO "${_y}" ("key", "value") VALUES (?, ?) ON CONFLICT ("key") DO NOTHING`,[by,JSON.stringify({schema:t,rev:0})])})}function jy(e){if(e.op!==`put`)return JSON.stringify(e);let t=py(e.value,vy[e.store]);return`{"key":${JSON.stringify(e.key)},"op":"put","store":${JSON.stringify(e.store)},"value":${t}}`}function My(e){if(typeof e!=`string`)throw new bv(400,`sync op data must be a string`,`bad_sync_mutation`);let t;try{t=JSON.parse(e)}catch{throw new bv(400,`sync op data is not valid JSON`,`bad_sync_mutation`)}let n=wy(t);return n.op===`put`?{op:`put`,store:n.store,key:n.key,value:my(JSON.stringify(n.value),vy[n.store])}:n}async function Ny(e,t,n={}){if(t.length===0)return 0;for(let e of t)Ty(e);return e.transaction(async e=>{let r=await Oy(e);if(n.expectSchema!==void 0&&r.schema!==n.expectSchema)throw new bv(409,`sync target schema changed from v${n.expectSchema} to v${r.schema} between probe and write — retry the cycle`,`sync_schema_conflict`);let i=t.map(e=>`${e.id}:0`),a=new Set;for(let t=0;t<i.length;t+=100){let n=i.slice(t,t+100),r=await e.query(`SELECT "op_id" FROM "${gy}" WHERE "op_id" IN (${n.map(()=>`?`).join(`, `)})`,n);for(let e of r)a.add(String(e.op_id))}let o=[],s=r.rev,c=0;for(let e of t)a.has(`${e.id}:0`)||(s+=1,c+=1,e.ops.forEach((t,n)=>{o.push({sql:`INSERT INTO "${gy}" ("op_id", "rev", "idx", "at", "data") VALUES (?, ?, ?, ?, ?) ON CONFLICT ("op_id") DO NOTHING`,params:[`${e.id}:${n}`,s,n,e.at,jy(t)]})}));return o.push({sql:`UPDATE "${_y}" SET "value" = ? WHERE "key" = ?`,params:[JSON.stringify({schema:r.schema,rev:s}),by]}),await Ey(e,o),c})}async function Py(e,t,n){if(!xy(t)||t<0)throw new bv(400,`fetchSyncOps cursor must be a non-negative safe integer`,`bad_sync_cursor`);let r=Math.min(Math.max(1,Math.floor(n)),4294967295),i=(await e.query(`SELECT DISTINCT "rev" FROM (SELECT "rev" FROM "${gy}" WHERE "rev" > ? ORDER BY "rev" ASC LIMIT ?)`,[t,r])).map(e=>{let t=Number(e.rev);if(!Number.isSafeInteger(t)||t<0)throw new bv(400,`sync op rev must be a non-negative safe integer`,`bad_sync_row`);return t});return i.length===0?[]:(await e.query(`SELECT "op_id", "rev", "idx", "at", "data" FROM "${gy}" WHERE "rev" IN (${i.map(()=>`?`).join(`, `)}) ORDER BY "rev", "idx"`,i)).map((e,t)=>{let n=e.op_id,r=Number(e.rev),i=Number(e.idx),a=Number(e.at);if(typeof n!=`string`||n.length===0||!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<0)throw new bv(400,`sync op row ${t} has malformed shape`,`bad_sync_row`);return{opId:n,rev:r,idx:i,at:a,mutation:My(e.data)}})}var Fy=oy,Iy=`sync_outbox`,Ly=`sync_state`,Ry=[{name:Iy,keyPath:`seq`,autoIncrement:!0},{name:Ly,keyPath:`key`}],zy=`bootstrap-run:`,By=fv.filter(e=>!e.system).map(e=>e.name),Vy=500,Hy=1e6,Uy={attachments:`data`},Wy=[{name:`segments`,keyPath:[`id`,`version`]},{name:`results`,keyPath:`id`}],Gy=class{ops=[];ctx},Ky=new Set;function qy(e){return Ky.add(e),()=>{Ky.delete(e)}}function Jy(){for(let e of Ky)e()}function Yy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(`lower`in e||`upper`in e||`lowerOpen`in e||`upperOpen`in e)}function Xy(e){if(e.op!==`put`)return 32;let t=32,n=Uy[e.store],r=e.value,i=n&&typeof r==`object`&&r&&!Array.isArray(r)&&n in r?Reflect.get(r,n):void 0;return t+=typeof i==`string`?i.length:i instanceof ArrayBuffer?Math.ceil(i.byteLength/3)*4+64:JSON.stringify(e.value)?.length??0,t}var Zy=[`block_revisions`,`notes`,`sessions`,...By.filter(e=>e!==`block_revisions`&&e!==`notes`&&e!==`sessions`)];async function Qy(e){let t=jv(await e(`notes`)),n=[];for(let r of Zy){let i=fv.find(e=>e.name===r);for(let a of await e(r))Mv(r,a,t)&&n.push({op:`put`,store:r,key:yv(i,a),value:a})}return n}var $y=class e{owner;name;tx;mutable;touched;journal;constructor(e,t,n,r=!1,i,a){this.owner=e,this.name=t,this.tx=n,this.mutable=r,this.touched=i,this.journal=a}async get(e){return this.tx?this.tx.objectStore(this.name).get(e):(await this.owner.open()).get(this.name,e)}async getMany(e){return this.tx?Promise.all(e.map(e=>this.tx.objectStore(this.name).get(e))):this.owner.transaction([this.name],`readonly`,t=>t.readonly(this.name).getMany(e))}async getAll(e,t){return this.tx?this.tx.objectStore(this.name).getAll(e,t):(await this.owner.open()).getAll(this.name,e,t)}async getAllFromIndex(e,t,n){return this.tx?this.tx.objectStore(this.name).index(e).getAll(t,n):(await this.owner.open()).getAllFromIndex(this.name,e,t,n)}async getAllFromIndexMany(e,t){return this.tx?Promise.all(t.map(t=>this.tx.objectStore(this.name).index(e).getAll(t))):this.owner.transaction([this.name],`readonly`,n=>n.readonly(this.name).getAllFromIndexMany(e,t))}async count(e){return this.tx?this.tx.objectStore(this.name).count(e):(await this.owner.open()).count(this.name,e)}async countFromIndex(e,t){return this.tx?this.tx.objectStore(this.name).index(e).count(t):(await this.owner.open()).countFromIndex(this.name,e,t)}async put(e,t){if(!this.mutable)throw Error(`read-only store`);if(!this.tx){let t=this.name===`notes`?[this.name,`block_revisions`]:[this.name,`block_revisions`,`notes`];return this.owner.transaction([...t],`readwrite`,t=>t.readwrite(this.name).put(e))}let n=this.owner.stamp(this.name,e);Cv(this.name,n);let r=fv.find(e=>e.name===this.name),i=yv(r,n),a=this.tx.objectStore(this.name),o=await a.get(i);if(this.name===`block_revisions`&&o!==void 0&&!xv(o,n))throw Error(`immutable block revision collision`);if(this.name===`notes`&&wv(o,n),this.name===`sessions`&&Tv(o,n),xv(o,n))return i;let s=await a.put(n);if(!r.system&&this.journal){let e=this.name===`notes`?void 0:await(this.journal.ctx??=this.owner.policyContext(this.tx)),t=o!==void 0&&Mv(this.name,o,e??jv([]));if(Mv(this.name,n,e??jv([]))){if(this.name===`notes`&&typeof n==`object`&&n&&`id`in n)for(let e of await this.tx.objectStore(`block_revisions`).index(`by-note`).getAll(String(n.id)))this.journal.ops.push({op:`put`,store:`block_revisions`,key:[e.noteId,e.blockId,e.version],value:e});else if(this.name===`sessions`&&typeof n==`object`&&n&&`noteId`in n&&`blockId`in n&&`blockVersion`in n){let e=[n.noteId,n.blockId,n.blockVersion],t=await this.tx.objectStore(`block_revisions`).get(e);t&&this.journal.ops.push({op:`put`,store:`block_revisions`,key:e,value:t})}this.journal.ops.push({op:`put`,store:this.name,key:i,value:n})}else t&&this.journal.ops.push({op:`delete`,store:this.name,key:i});this.name===`notes`&&(this.journal.ctx=void 0)}return this.name===`notes`&&this.touched?.notes.add(String(i)),this.name===`sessions`&&this.touched?.sessions.add(String(i)),s}async putMany(e,t){if(t&&t.length!==e.length)throw Error(`putMany key count mismatch`);if(!this.tx){let n=this.name===`notes`?[this.name,`block_revisions`]:[this.name,`block_revisions`,`notes`];return this.owner.transaction([...n],`readwrite`,n=>n.readwrite(this.name).putMany(e,t))}let n=[];for(let r=0;r<e.length;r++)n.push(await this.put(e[r],t?.[r]));return n}async delete(t){if(!this.mutable)throw Error(`read-only store`);if(this.name===`block_revisions`)throw Error(`block history requires explicit wipe`);if(!this.tx){let e=this.name===`notes`?[this.name]:[this.name,`notes`];return this.owner.transaction([...e],`readwrite`,e=>e.readwrite(this.name).delete(t))}if(this.name===`notes`)for(let n of await this.tx.objectStore(`notes`).getAll(t))for(let t of[`block_index`,`block_efforts`,`block_equipment`]){let r=this.tx.objectStore(t);for(let i of await r.index(`by-note`).getAllKeys(n.id))await new e(this.owner,t,this.tx,!0,this.touched,this.journal).delete(i)}await this.recordDelete(t),await this.tx.objectStore(this.name).delete(t)}async recordDelete(e){if(!this.journal)return;let t=this.tx.objectStore(this.name),n=Yy(e)?await t.getAllKeys(e):[e],r=this.name===`notes`?void 0:await(this.journal.ctx??=this.owner.policyContext(this.tx));for(let e of n){let n=await t.get(e);n!==void 0&&!Mv(this.name,n,r??jv([]))||this.journal.ops.push({op:`delete`,store:this.name,key:e})}}async clear(){if(!this.mutable)throw Error(`read-only store`);if(this.name===`block_revisions`)throw Error(`block history requires explicit wipe`);if(!this.tx){let e=this.name===`notes`?[`notes`,`block_index`,`block_efforts`]:[this.name,`notes`];return this.owner.transaction([...e],`readwrite`,e=>e.readwrite(this.name).clear())}let e=this.tx.objectStore(this.name),t=await e.getAll(),n=jv(this.name===`notes`?t:await this.tx.objectStore(`notes`).getAll());for(let r of t){let t=yv(fv.find(e=>e.name===this.name),r);if(Mv(this.name,r,n)&&!(this.name===`meta`&&typeof t==`string`&&t.startsWith(`user-deleted-seed:`))){if(this.name===`notes`&&typeof t==`string`)for(let e of[`block_index`,`block_efforts`,`block_equipment`]){let n=this.tx.objectStore(e);for(let r of await n.index(`by-note`).getAllKeys(t))this.journal?.ops.push({op:`delete`,store:e,key:r}),await n.delete(r)}await this.recordDelete(t),await e.delete(t)}}}},eb={script:`wod`,wod:`wod`};function tb(e){return Oa(e.slice(0,e.indexOf(`
57
+ `)).trim())??{}}var nb=class{options;opening;constructor(e={}){this.options=e}open(){if(typeof indexedDB>`u`)return Promise.reject(Error(`IndexedDB is unavailable in this environment`));if(!this.opening){let e=!1,t=0,n;this.opening=or(this.options.dbName??Fy,32,{upgrade:async(r,i,a,o)=>{if(o.done.catch(()=>{}),i>32){e=!0,o.abort();return}if(i!==0&&i<20){t=i,o.abort();return}try{ib(r,o),i!==0&&i<32&&this.options.onUpgradeStart?.(i),await ab(r,i,o)}catch(e){n=e instanceof Error?e:Error(String(e));try{o.abort()}catch{}}},blocking:()=>{this.close()}}).catch(r=>{throw this.opening=void 0,n||(t===0?e||r instanceof DOMException&&r.name===`VersionError`?Error(`database schema is newer than this client supports (v32); refusing to downgrade`):r:Error(`local database schema v${t} predates the supported migration chain (v20+). Open this browser profile in an intermediate app version to export your data, or clear site data to start fresh — the old database was left untouched.`))})}return this.opening}stamp(e,t){let n=this.options.getUserId?.();return n?_v(e,t,n):t}async policyContext(e){return jv(e?await e.objectStore(`notes`).getAll():await(await this.open()).getAll(`notes`))}readonly(e){return new $y(this,e)}readwrite(e){return new $y(this,e,void 0,!0)}async transaction(e,t,n){let r=await this.open(),i=t===`readwrite`?new Gy:void 0,a=new Set(e);t===`readwrite`&&(a.add(`block_revisions`),a.add(Iy),a.add(`notes`),a.has(`notes`)&&(a.add(`block_index`),a.add(`block_efforts`),a.add(`block_equipment`)));let o=r.transaction([...a],t),s=o.done;s.catch(()=>{});let c={notes:new Set,sessions:new Set},l={readonly:e=>{if(!a.has(e))throw Error(`store outside transaction scope`);return new $y(this,e,o)},readwrite:e=>{if(t!==`readwrite`)throw Error(`read-only transaction`);if(!a.has(e))throw Error(`store outside transaction scope`);return new $y(this,e,o,!0,c,i)}};try{let e=await n(l);return await Ev((await Promise.all([...c.notes].map(e=>o.objectStore(`notes`).get(e)))).filter(Boolean),(await Promise.all([...c.sessions].map(e=>o.objectStore(`sessions`).get(e)))).filter(Boolean),e=>Promise.all(e.map(e=>o.objectStore(`block_revisions`).get(e)))),i&&i.ops.length>0&&await o.objectStore(Iy).put({id:crypto.randomUUID(),at:Date.now(),ops:i.ops}),await s,i&&i.ops.length>0&&Jy(),e}catch(e){try{o.abort()}catch{}throw await s.catch(()=>{}),e}}async wipeUserData(){let e=fv.filter(e=>!e.system&&e.name!==`block_revisions`).map(e=>e.name);await this.transaction(e,`readwrite`,async t=>{for(let n of e)await t.readwrite(n).clear()})}async wipe(){let e=await this.open(),t=fv.filter(e=>!e.system).map(e=>e.name),n=e.transaction([...t,Iy],`readwrite`);await Promise.all(t.map(e=>n.objectStore(e).clear())),await n.objectStore(Iy).put({id:crypto.randomUUID(),at:Date.now(),ops:[{op:`wipe`}]}),await n.done,Jy()}async readOutbox(e,t){let n=await this.open(),r=IDBKeyRange.lowerBound(e,!0);return await n.getAll(Iy,r,Math.min(t,4294967295))}async ackOutbox(e){let t=await this.open(),n=await t.getAllKeys(Iy,IDBKeyRange.upperBound(e)),r=t.transaction(Iy,`readwrite`);await Promise.all(n.map(e=>r.store.delete(e))),await r.done}async getSyncState(e){return(await(await this.open()).get(Ly,e))?.value}async setSyncState(e,t){await(await this.open()).put(Ly,{key:e,value:t})}async captureSyncBootstrap(e){let t=(await this.open()).transaction([...By,Iy,Ly],`readwrite`),n=t.objectStore(Ly),r=await n.get(e);if(r!==void 0&&Array.isArray(r.value))return await t.done,r.value;let i=new Set,a=new Set,o=!1;for(let e of await t.objectStore(Iy).getAll())for(let t of e.ops)t.op===`put`||t.op===`delete`?i.add(`${t.store}:${JSON.stringify(t.key)}`):t.op===`clear`?a.add(t.store):o=!0;let s=crypto.randomUUID(),c=[];if(!o){let e=[],n=0,r=()=>{e.length!==0&&(c.push({id:`bootstrap:${s}:${c.length}`,at:Date.now(),ops:e}),e=[],n=0)};for(let o of await Qy(e=>t.objectStore(e).getAll())){if(a.has(o.store)||o.store!==`block_revisions`&&i.has(`${o.store}:${JSON.stringify(o.key)}`))continue;let t=Xy(o);e.length>0&&(e.length>=Vy||n+t>Hy)&&r(),e.push(o),n+=t}r()}return await n.put({key:e,value:c}),await t.done,c}async validateSyncState(){let e=(await this.open()).transaction([`notes`,`sessions`,`block_revisions`],`readonly`),t=await e.objectStore(`notes`).getAll(),n=await e.objectStore(`sessions`).getAll(),r=e.objectStore(`block_revisions`);await Ev(t,n,e=>Promise.all(e.map(e=>r.get(e)))),await e.done}async applySyncMutations(e,t,n=`cursor`){let r=new Map(fv.map(e=>[e.name,e]));for(let t of e){if(t.op===`clear`||t.op===`wipe`)continue;let e=r.get(t.store);if(!e)throw Error(`unknown store in sync mutation: ${String(t.store)}`);if(t.op===`put`||t.op===`delete`){let n=Array.isArray(t.key)?t.key:[t.key];if(n.length!==e.keyPath.length||!n.every(e=>typeof e==`string`||typeof e==`number`))throw Error(`sync ${t.op} key arity/shape mismatch for ${t.store}`)}t.op===`put`&&Cv(t.store,t.value)}let i=await this.open(),a=By,o=i.transaction([...a,Iy,Ly],`readwrite`),s=e=>e===`notes`||e===`efforts`,c=new Map;for(let t of e){if(t.op===`clear`||t.op===`wipe`||!s(t.store))continue;let e=`${t.store}:${JSON.stringify(t.key)}`;if(c.has(e))continue;let n=t.key,r=await o.objectStore(t.store).get(n);c.set(e,{store:t.store,key:n,before:r,beforeExists:r!==void 0})}let l=async(e,t)=>{if(e.op===`wipe`){for(let e of a)await o.objectStore(e).clear();return}if(e.store===`memberships`)return;if(e.op===`clear`){if(e.store===`block_revisions`)return;let n=o.objectStore(e.store),i=jv(await o.objectStore(`notes`).getAll());for(let a of await n.getAll()){if(!Mv(e.store,a,i))continue;let n=yv(r.get(e.store),a);e.store===`meta`&&typeof n==`string`&&n.startsWith(`user-deleted-seed:`)||await l({op:`delete`,store:e.store,key:n},t)}return}if(e.op===`delete`){if(e.store===`notes`){let t=String(Array.isArray(e.key)?e.key[0]:e.key);for(let e of[`block_index`,`block_efforts`,`block_equipment`]){let n=o.objectStore(e);for(let e of await n.index(`by-note`).getAllKeys(t))await n.delete(e)}}e.store!==`block_revisions`&&await o.objectStore(e.store).delete(e.key);return}let n=o.objectStore(e.store);if(e.store===`block_revisions`){let r=await n.get(e.key);if(r!==void 0&&!xv(r,e.value)&&!t){let t=e.value,i=r.version+1;for(;await n.get([t.noteId,t.blockId,i])!==void 0;)i+=1;await n.put({...t,version:i});return}(r===void 0||!xv(r,e.value))&&await n.put(e.value);return}if(e.store===`notes`&&!t){let t=await n.get(e.key);if(t!==void 0){let n=t,r=e.value;if(n.sourceRevision>r.sourceRevision)return}}await n.put(e.value)};for(let t of e)await l(t,!1);let u=(await o.objectStore(Iy).getAll()).sort((e,t)=>e.seq-t.seq);for(let e of u)for(let t of e.ops)await l(t,!0);let d=0,f=0;for(let e of c.values()){let t=await o.objectStore(e.store).get(e.key);t!==void 0&&(e.beforeExists?xv(e.before,t)||(f+=1):d+=1)}return t!==null&&await o.objectStore(Ly).put({key:n,value:{rev:t}}),await o.done,{added:d,updated:f}}async snapshotRows(){let e=await this.open(),t=fv.filter(e=>!e.system),n=e.transaction(t.map(e=>e.name),`readonly`),r=jv(await n.objectStore(`notes`).getAll()),i=await Promise.all(t.map(async e=>({store:e.name,rows:(await n.objectStore(e.name).getAll()).filter(t=>Mv(e.name,t,r))})));return await n.done,i}async snapshotAllRows(){let e=await this.open(),t=fv.filter(e=>!e.system),n=e.transaction(t.map(e=>e.name),`readonly`),r=await Promise.all(t.map(async e=>({store:e.name,rows:await n.objectStore(e.name).getAll()})));return await n.done,r}async close(){let e=this.opening;this.opening=void 0,(await e?.catch(()=>void 0))?.close()}},rb=[...fv.map(e=>({name:e.name,keyPath:e.keyPath})),...Wy.map(e=>({name:e.name,keyPath:Array.isArray(e.keyPath)?e.keyPath:[e.keyPath]}))];Object.fromEntries(rb.map(e=>[e.name,e.keyPath]));function ib(e,t){for(let n of fv){if(e.objectStoreNames.contains(n.name)){let e=t.objectStore(n.name);for(let t of n.indexes)e.indexNames.contains(t.name)||e.createIndex(t.name,t.keyPath.length===1?t.keyPath[0]:t.keyPath,{unique:t.unique,multiEntry:t.multiEntry});continue}let r=e.createObjectStore(n.name,{keyPath:n.keyPath.length===1?n.keyPath[0]:n.keyPath});for(let e of n.indexes)r.createIndex(e.name,e.keyPath.length===1?e.keyPath[0]:e.keyPath,{unique:e.unique,multiEntry:e.multiEntry})}for(let t of Ry)e.objectStoreNames.contains(t.name)||e.createObjectStore(t.name,{keyPath:t.keyPath,autoIncrement:`autoIncrement`in t&&t.autoIncrement})}async function ab(e,t,n){let r=e=>n.objectStore(e);if(t===20&&e.objectStoreNames.contains(`sessions`)){let e=r(`sessions`),t=r(`events`);for await(let n of e){let e=n.value,r=e.data?.logs??[],i=!1;for await(let n of t.index(`by-result-grain`).iterate(IDBKeyRange.bound([e.id,``],[e.id,[]]))){i=!0;break}if(!i&&r.length>0){let n={noteId:e.noteId,resultId:e.id,segmentId:e.segmentId,segmentVersion:e.segmentVersion,blockContentId:e.blockContentId,origin:e.origin,pageId:e.pageId,workoutTimestamp:e.data?.endTime??e.createdAt};for(let e of Eg(r,n))await t.put(e);for(let e of Dg(r,n))await t.put(e)}let a={...e,startTime:e.data?.startTime??e.createdAt,endTime:e.data?.endTime??e.createdAt,duration:e.data?.duration??0,completed:e.data?.completed??!0,roundsCompleted:e.data?.roundsCompleted,totalRounds:e.data?.totalRounds,repsCompleted:e.data?.repsCompleted};delete a.data,await n.update(a)}}if(t===21&&e.objectStoreNames.contains(`meta`)&&await r(`meta`).delete(`seed`),t<25)for(let t of hv){if(!e.objectStoreNames.contains(t))continue;let n=r(t);n.indexNames.contains(`by-user`)||n.createIndex(`by-user`,`userId`)}if(e.objectStoreNames.contains(`results`)){let t=r(`sessions`),n=r(`results`),i=r(`events`);for await(let e of n){let{data:n,...r}=e.value,a=n?.logs??[];if(a.length>0){let e={noteId:r.noteId,resultId:r.id,segmentId:r.segmentId,segmentVersion:r.segmentVersion,blockContentId:r.blockContentId,origin:r.origin,pageId:r.pageId,workoutTimestamp:n?.endTime??r.createdAt};for(let t of Eg(a,e))await i.get(t.id)===void 0&&await i.put(t);for(let t of Dg(a,e))await i.get(t.id)===void 0&&await i.put(t)}await t.getKey(r.id)===void 0&&await t.put({...r,startTime:n?.startTime??r.startTime??r.createdAt,endTime:n?.endTime??r.endTime??r.createdAt,duration:n?.duration??r.duration??0,completed:n?.completed??r.completed??!0,roundsCompleted:n?.roundsCompleted??r.roundsCompleted,totalRounds:n?.totalRounds??r.totalRounds,repsCompleted:n?.repsCompleted??r.repsCompleted})}e.deleteObjectStore(`results`)}if(e.objectStoreNames.contains(`block_index`)&&!r(`block_index`).indexNames.contains(`by-source`)&&r(`block_index`).createIndex(`by-source`,`sourceId`),e.objectStoreNames.contains(`notes`)&&!r(`notes`).indexNames.contains(`by-created`)&&r(`notes`).createIndex(`by-created`,`createdAt`),e.objectStoreNames.contains(`efforts`)&&!r(`efforts`).indexNames.contains(`by-source`)&&r(`efforts`).createIndex(`by-source`,`registrySource`),e.objectStoreNames.contains(`note_tags`)&&!r(`note_tags`).indexNames.contains(`by-note-tag`)){let e=r(`note_tags`),t=new Map,n=[];for await(let r of e){let e=r.value,i=`${e.noteId}${e.tagId}`,a=t.get(i);a===void 0||e.id<a?(t.set(i,e.id),a!==void 0&&n.push(a)):n.push(e.id)}for(let t of n)await e.delete(t);e.createIndex(`by-note-tag`,[`noteId`,`tagId`],{unique:!0})}if(e.objectStoreNames.contains(`notes`)&&e.objectStoreNames.contains(`segments`)){let e=r(`segments`),t=r(`notes`),n=new Set;for await(let r of e){let e=r.value;if(e.dataType!==`frontmatter`||n.has(e.noteId)||!/(^|\n)dashboard:\s*["']?true["']?\s*(\n|$)/.test(e.rawContent))continue;n.add(e.noteId);let i=await t.get(e.noteId);!i||i.type===`dashboard`&&i.sourceId===`dashboards`||await t.put({...i,type:`dashboard`,sourceId:i.sourceId??`dashboards`})}}if(e.objectStoreNames.contains(`segments`)&&await ob(e,n),t>=30&&t<32&&e.objectStoreNames.contains(Iy)){let t=r(Iy),n=[];for(let e of await t.getAll())for(let t of e.ops)if(t.op===`wipe`)for(let e of By)e!==`block_revisions`&&n.push({op:`clear`,store:e});else t.op!==`put`&&t.store!==`memberships`&&t.store!==`block_revisions`&&n.push(t);if(n.push(...await Qy(e=>r(e).getAll())),await t.clear(),n.length>0&&await t.put({id:crypto.randomUUID(),at:Date.now(),ops:n}),e.objectStoreNames.contains(Ly)){let e=r(Ly);for(let t of await e.getAllKeys())typeof t==`string`&&t.startsWith(zy)&&await e.delete(t)}}}async function ob(e,t){let n=e=>t.objectStore(e),r=await n(`segments`).getAll(),i=n(`notes`),a=n(`block_revisions`),o=new Map;for(let e of r){let t=o.get(e.noteId);t?t.push(e):o.set(e.noteId,[e])}let s=new Map,c=new Map;for(let[e,t]of o){let n=new Map;for(let e of t){let t=n.get(e.id);(!t||e.version>t.version)&&n.set(e.id,e)}let r=[...n.values()].sort((e,t)=>(e.position??2**53-1)-(t.position??2**53-1)||e.id.localeCompare(t.id)),o=r.map(e=>e.sourceContent??`${e.rawContent}\n`).join(``),l=await i.get(e);if(!l)continue;let u=ja(o,{registeredWidgets:Da}).filter(e=>Ma(e)!==null),d=r.filter(e=>e.dataType in eb),f={};u.forEach((t,n)=>{let r=Ma(t),i=d[n],a=i?.id??`migrated-${n}`;for(;Object.hasOwn(f,a);)a=`${a}-${n}`;let o=r===`wod`&&(t.type===`time`||t.type===`log`)?{dialect:t.type,...t.sport?{sport:t.sport}:{}}:{};f[a]={id:a,kind:r,version:i?.version??1,sourceRevision:1,from:t.from,to:t.to,...o},i&&s.set(`${e}${i.id}`,a),c.set(`${e}${a}`,{noteId:e,from:t.from,to:t.to,version:f[a].version})});let p=l;delete p.segments,delete p.segmentIds,await i.put({...p,rawContent:o,sourceRevision:1,blocks:f});let m=new Set(d.map(e=>e.id));for(let n of t){if(!m.has(n.id))continue;let t=tb(n.rawContent);await a.put({noteId:e,blockId:n.id,version:n.version,kind:`wod`,rawContent:n.rawContent,savedAt:n.createdAt,...t})}}let l=n(`sessions`);for(let e of await l.getAll()){if(e.segmentId===void 0&&e.segmentVersion===void 0&&e.version===void 0)continue;let{segmentId:t,segmentVersion:n,version:r,...i}=e;await l.put({...i,blockId:i.blockId??t??``,blockVersion:i.blockVersion??n??r??1})}let u=n(`events`);for(let e of await u.getAll()){if(e.segmentVersion===void 0&&e.segmentId===void 0)continue;let{segmentVersion:t,segmentId:n,...r}=e;await u.put({...r,...r.blockId===void 0&&n!==void 0?{blockId:n}:{},...r.blockVersion===void 0&&t!==void 0?{blockVersion:t}:{}})}let d=n(`block_index`);for(let e of await d.getAll()){let t=s.get(`${e.noteId}${e.segmentId}`)??e.segmentId,n=c.get(`${e.noteId}${t}`),r={...e,id:`${e.noteId}:${t}`,blockId:t,blockVersion:n?.version??e.segmentVersion??1,sourceRevision:1,...n?{from:n.from,to:n.to}:{},dataType:e.dataType===`script`?`wod`:e.dataType};delete r.segmentId,delete r.segmentVersion,r.id!==e.id&&await d.delete(e.id),await d.put(r)}e.deleteObjectStore(`segments`)}var sb=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`NotePersistenceError`}},cb={registeredWidgets:Da},lb=class{tx;constructor(e){this.tx=e}readonly(e){return this.tx.readonly(e)}readwrite(e){return this.tx.readwrite(e)}transaction(e,t,n){return n(this.tx)}wipe(){return Promise.reject(Error(`wipe() is not available inside a transaction scope`))}close(){return Promise.reject(Error(`close() is not available inside a transaction scope`))}};function ub(e){return typeof IDBKeyRange<`u`?IDBKeyRange.bound([e,``],[e,`￿`]):{lower:[e,``],upper:[e,`￿`]}}function db(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function fb(e){let t=Y_(e),n=typeof t[`metrics.effort`]==`string`?t[`metrics.effort`].trim():``,r=t[`metrics.equipment`],i=(Array.isArray(r)?r:typeof r==`string`?[r]:[]).map(e=>e.trim()).filter(Boolean);return{...n?{effort:n}:{},...i.length>0?{equipment:i}:{}}}var pb=64,mb=[{id:`type-domain`,name:`domain`,label:`Domain`,color:`#10b981`},{id:`type-format`,name:`format`,label:`Format`,color:`#8b5cf6`},{id:`type-equipment`,name:`equipment`,label:`Equipment`,color:`#3b82f6`},{id:`type-quality`,name:`quality`,label:`Quality`,color:`#f59e0b`},{id:`type-intent`,name:`intent`,label:`Intent`,color:`#ec4899`},{id:`type-category`,name:`category`,label:`Category`,color:`#6366f1`},{id:`type-type`,name:`type`,label:`Type`,color:`#a855f7`},{id:`type-discipline`,name:`discipline`,label:`Discipline`,color:`#14b8a6`}],hb=class e{storage;scopedTx;constructor(e,t=!1){this.storage=e,this.scopedTx=t}async withTransaction(t,n){return this.storage.transaction(t,`readwrite`,t=>n(new e(new lb(t),!0)))}async queryDomain(e){if(!this.scopedTx)return this.storage.queryDomain?.(e)}async getNote(e){return this.storage.readonly(`notes`).get(e)}async getNoteBySlug(e){let t=[e];e.startsWith(`playground/`)?t.push(e.slice(11)):t.push(`playground/${e}`);for(let e of t){let t=await this.storage.readonly(`page`).getAllFromIndex(`by-slug`,e);for(let e of t){let t=await this.getPageNotes(e.id);for(let e of t){let t=await this.getNote(e.noteId);if(t)return t}}}}async getAllNotes(){return this.storage.readonly(`notes`).getAll()}async getNotesByDateRange(e,t,n){let r=n?.endExclusive===!0?IDBKeyRange.bound(e,t,!1,!0):IDBKeyRange.bound(e,t),i=this.storage.readonly(`notes`),[a,o]=await Promise.all([i.getAllFromIndex(`by-date`,r),i.getAllFromIndex(`by-created`,r)]),s=new Map;for(let e of a)s.set(e.id,e);for(let e of o)e.date===void 0&&s.set(e.id,e);return Array.from(s.values()).sort((e,t)=>e.id<t.id?-1:+(e.id>t.id))}async getNotesByIds(e){return e.length===0?[]:this.storage.transaction([`notes`],`readonly`,async t=>{let n=t.readonly(`notes`),r=[];for(let t of e){let e=await n.get(t);e&&r.push(e)}return r})}async getEntryBatches(e){let t=new Map;if(e.length===0)return t;if(this.storage.queryDomain){let n=[...new Set(e)],r=[],i=!0;for(let e=0;e<n.length&&i;e+=pb){let t=await this.storage.queryDomain({plan:`entries`,selection:[{field:`id`,values:n.slice(e,e+pb)}]});t&&t.plan===`entries`?r.push(...t.rows):i=!1}if(i){for(let e of r)t.set(e.note.id,e);return t}}return this.storage.transaction([`notes`,`note_tags`,`tags`,`page_notes`,`page`],`readonly`,async n=>{for(let r of e){let e=await n.readonly(`notes`).get(r),i=await n.readonly(`page_notes`).getAllFromIndex(`by-note`,r),a=n.readonly(`tags`),o=[];for(let e of await n.readonly(`note_tags`).getAllFromIndex(`by-note`,r)){let t=await a.get(e.tagId);t&&o.push(t)}let s=n.readonly(`page`),c=[];for(let e of i){let t=await s.get(e.pageId);t&&c.push(t)}e&&t.set(r,{note:e,tags:o,links:i,pages:c})}return t})}async saveNote(e){return await this.storage.readwrite(`notes`).put(e),e.id}async deleteNote(e){await this.storage.transaction([`notes`,`attachments`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`meta`],`readwrite`,async t=>{let n=await t.readonly(`notes`).get(e);await t.readwrite(`notes`).delete(e);let r=t.readwrite(`attachments`);for(let t of await r.getAllFromIndex(`by-note`,e))await r.delete(t.id);let i=t.readwrite(`note_tags`);for(let t of await i.getAllFromIndex(`by-note`,e))await i.delete(t.id);let a=t.readwrite(`block_index`);for(let t of await a.getAllFromIndex(`by-note`,e))await a.delete(t.id);let o=t.readwrite(`block_efforts`);for(let t of await o.getAllFromIndex(`by-note`,e))await o.delete(t.id);let s=t.readwrite(`block_equipment`);for(let t of await s.getAllFromIndex(`by-note`,e))await s.delete(t.id);let c=t.readwrite(`page_notes`);for(let t of await c.getAllFromIndex(`by-note`,e))await c.delete(t.id);n&&(n.seedOrigin===`seed`||n.seedChunkId!==void 0||n.sourcePath!==void 0)&&await t.readwrite(`meta`).put({key:Ov(e),value:Date.now()})})}async getPage(e){return this.storage.readonly(`page`).get(e)}async getAllPages(){return this.storage.readonly(`page`).getAll()}async getPageByDate(e){return(await this.storage.readonly(`page`).getAllFromIndex(`by-date`,e))[0]}async getPageBySlug(e){return(await this.storage.readonly(`page`).getAllFromIndex(`by-slug`,e))[0]}async savePage(e){return await this.storage.readwrite(`page`).put(e),e.id}async getAllPageNotes(){return this.storage.readonly(`page_notes`).getAll()}async getPageNotes(e){return this.storage.readonly(`page_notes`).getAllFromIndex(`by-page`,e)}async getNotePages(e){return this.storage.readonly(`page_notes`).getAllFromIndex(`by-note`,e)}async addNoteToPage(e,t,n){let r=await this.storage.readonly(`page_notes`).getAllFromIndex(`by-page-note`,[t,e]);if(r.length>0)return r[0].id;let i=db();return await this.storage.readwrite(`page_notes`).put({id:i,pageId:t,noteId:e,position:n,createdAt:Date.now()}),i}async removeNoteFromPage(e,t){let n=await this.storage.readonly(`page_notes`).getAllFromIndex(`by-page-note`,[t,e]);for(let e of n)await this.storage.readwrite(`page_notes`).delete(e.id)}async getOrCreatePageForDate(e){let t=await this.getPageByDate(e);if(t)return t;let n={id:db(),date:e,title:e,createdAt:Date.now()};try{return await this.savePage(n),n}catch(t){let n=await this.getPageByDate(e);if(n)return n;throw t}}async getAllTags(){return this.storage.readonly(`tags`).getAll()}async getTags(e){let t=await this.storage.readonly(`tags`).getAll();if(e){let n=e.toLowerCase();return t.filter(e=>e.type?.toLowerCase()===n)}return t}async putTag(e){await this.storage.readwrite(`tags`).put(e)}async updateTagType(e,t){let n=await this.storage.readonly(`tags`).get(e);n&&await this.storage.readwrite(`tags`).put({...n,type:t})}async getAllTagTypes(){return this.storage.readonly(`tag_types`).getAll()}async ensureDefaultTagTypes(){if((await this.storage.readonly(`tag_types`).getAll()).length===0){let e=Date.now();for(let t of mb)try{await this.storage.readwrite(`tag_types`).put({...t,createdAt:e})}catch{}}}async getTagType(e){return await this.storage.readonly(`tag_types`).get(e)||(await this.storage.readonly(`tag_types`).getAllFromIndex(`by-name`,e))[0]}async putTagType(e){await this.storage.readwrite(`tag_types`).put(e)}async deleteTagType(e){await this.storage.readwrite(`tag_types`).delete(e)}async getTagsForNote(e){let t=await this.storage.readonly(`note_tags`).getAllFromIndex(`by-note`,e),n=this.storage.readonly(`tags`),r=[];for(let e of t){let t=await n.get(e.tagId);t&&r.push(t)}return r}async getAllFromIndex(e,t,n){return this.storage.readonly(e).getAllFromIndex(t,n)}async getNoteTagLabelsBatch(){let[e,t]=await Promise.all([this.storage.readonly(`note_tags`).getAll(),this.storage.readonly(`tags`).getAll()]),n=new Map(t.map(e=>[e.id,e])),r=new Map;for(let t of e){let e=n.get(t.tagId);if(!e)continue;let i=r.get(t.noteId);i?i.push({label:e.label,type:e.type}):r.set(t.noteId,[{label:e.label,type:e.type}])}return r}async getEffortSlugsByNoteBatch(){let e=await this.storage.readonly(`block_efforts`).getAll(),t=new Map;for(let n of e){let e=t.get(n.noteId);e?e.includes(n.effortSlug)||e.push(n.effortSlug):t.set(n.noteId,[n.effortSlug]);let r=(n.noteId.startsWith(`feeds/`)?n.noteId.slice(6):n.noteId).split(`/`)[0];if(r&&r!==n.noteId){let e=t.get(r);e?e.includes(n.effortSlug)||e.push(n.effortSlug):t.set(r,[n.effortSlug])}}return t}async getTagByLabel(e){return(await this.storage.readonly(`tags`).getAllFromIndex(`by-label`,e))[0]}async deleteTag(e){await this.storage.readwrite(`tags`).delete(e)}async getNotesForTag(e){let t=await this.storage.readonly(`tags`).getAllFromIndex(`by-label`,e);if(!t[0])return[];let n=t[0].id,r=await this.storage.readonly(`note_tags`).getAllFromIndex(`by-tag`,n),i=this.storage.readonly(`notes`),a=[];for(let e of r){let t=await i.get(e.noteId);t&&a.push(t)}return a}async setNoteTags(e,t){await this.storage.transaction([`tags`,`note_tags`],`readwrite`,async n=>{let r=n.readwrite(`note_tags`),i=n.readwrite(`tags`),a=await r.getAllFromIndex(`by-note`,e),o=Date.now(),s=new Map;for(let e of t){if(!e)continue;let t=typeof e==`string`?e:e?.label;if(typeof t!=`string`)continue;let n=t.trim();if(!n)continue;let r=typeof e==`string`?void 0:e.type,i=s.get(n);(!i||!i.type&&r)&&s.set(n,{label:n,type:r})}let c=new Set;for(let{label:t,type:n}of s.values()){let s=(await i.getAllFromIndex(`by-label`,t))[0];s?n&&!s.type&&(s={...s,type:n},await i.put(s)):(s={id:db(),label:t,type:n,createdAt:o},await i.put(s));let l=a.find(e=>e.tagId===s.id);l?c.add(l.id):await r.put({id:db(),noteId:e,tagId:s.id})}for(let e of a)c.has(e.id)||await r.delete(e.id)})}async getBlockRevision(e,t,n){return this.storage.readonly(`block_revisions`).get([e,t,n])}async getBlockHistory(e,t){return(await this.storage.readonly(`block_revisions`).getAllFromIndex(`by-block`,[e,t])).sort((e,t)=>e.version-t.version)}async getNoteBlockHistory(e){return(await this.storage.readonly(`block_revisions`).getAllFromIndex(`by-note`,e)).sort((e,t)=>e.savedAt-t.savedAt||e.blockId.localeCompare(t.blockId)||e.version-t.version)}async saveNoteSource(e){return this.withTransaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`],async t=>{let n=await t.getNote(e.noteId);if((n?.sourceRevision??0)!==e.expectedSourceRevision)throw new sb(`STALE_SOURCE`,`Note ${e.noteId} changed since it was loaded`);if(!n&&!e.metadata?.title)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${e.noteId}`);let r=e.blocks??Na(e.rawContent,{...cb,sourceRevision:e.expectedSourceRevision||1,blocks:n?.blocks}),i=Object.fromEntries(Object.entries(r).map(([t,n])=>[t,{...n,version:1,sourceRevision:e.expectedSourceRevision||1}]));Pa(e.rawContent,i,e.expectedSourceRevision||1,cb);let a=await t.storage.readonly(`block_revisions`).getAllFromIndexMany(`by-block`,Object.keys(i).map(t=>[e.noteId,t])),o=new Map;for(let e of a)for(let t of e)t.version>(o.get(t.blockId)?.version??0)&&o.set(t.blockId,t);let s={},c=[],l=Date.now();for(let t of Object.values(i)){let r=o.get(t.id),i=e.rawContent.slice(t.from,t.to),a=r&&r.rawContent===i&&r.kind===t.kind&&r.dialect===t.dialect&&r.sport===t.sport,u=a?r.version:(r?.version??0)+1;s[t.id]={...t,version:u,sourceRevision:n?.sourceRevision??1},a||c.push({noteId:e.noteId,blockId:t.id,version:u,kind:t.kind,rawContent:i,dialect:t.dialect,sport:t.sport,savedAt:l})}let u=!n||n.rawContent!==e.rawContent||Object.keys(n.blocks).length!==Object.keys(s).length||Object.values(s).some(e=>{let t=n.blocks[e.id];return!t||t.kind!==e.kind||t.from!==e.from||t.to!==e.to||t.version!==e.version||t.dialect!==e.dialect||t.sport!==e.sport}),d=(n?.sourceRevision??0)+ +!!u;for(let e of Object.values(s))e.sourceRevision=d;let f={...n,id:e.noteId,title:e.metadata?.title??n?.title??``,createdAt:n?.createdAt??e.createdAt??l,rawContent:e.rawContent,sourceRevision:d,blocks:s,type:e.metadata?.type??n?.type??e.noteType??`note`,date:e.metadata?.targetDate??n?.date,tags:e.metadata?.tags??n?.tags,sourceId:e.metadata?.sourceId===void 0?n?.sourceId:e.metadata.sourceId??void 0};return n&&xv(n,f)?n:(c.length&&await t.storage.readwrite(`block_revisions`).putMany(c),await t.saveNote(f),await t.rebuildBlockIndexForNote(f.id),f)})}async saveSession(e){return await this.storage.readwrite(`sessions`).put(e),e.id}async getSessionById(e){return this.storage.readonly(`sessions`).get(e)}async getSessionsForNote(e){return this.storage.readonly(`sessions`).getAllFromIndex(`by-note`,e)}async getSessionsByContentId(e){return this.storage.readonly(`sessions`).getAllFromIndex(`by-content`,e)}async getSessionsForSection(e,t){return(await this.getSessionsForNote(e)).filter(e=>e.blockId===t)}async getRecentSessions(e=20){return(await this.storage.readonly(`sessions`).getAll()).sort((e,t)=>t.createdAt-e.createdAt).slice(0,e)}async saveAttachment(e){return await this.storage.readwrite(`attachments`).put(e),e.id}async getAttachmentsForNote(e){return this.storage.readonly(`attachments`).getAllFromIndex(`by-note`,e)}async deleteAttachment(e){await this.storage.readwrite(`attachments`).delete(e)}async appendEvents(e){e.length!==0&&await this.storage.transaction([`events`],`readwrite`,async t=>{let n=t.readwrite(`events`);for(let t of e)await n.put(t)})}async finalizeSummaries(e,t){await this.storage.transaction([`events`],`readwrite`,async n=>{let r=n.readwrite(`events`),i=await r.getAllFromIndex(`by-result-grain`,[e,`summary`]);for(let e of i)await r.delete(e.id);for(let e of t)await r.put(e)})}async deleteEvents(e){e.length!==0&&await this.storage.transaction([`events`],`readwrite`,async t=>{let n=t.readwrite(`events`);for(let t of e)await n.delete(t)})}async getEventsForNote(e){let t=await this.getSessionsForNote(e),n=new Set(t.map(e=>e.id));n.add(`wellness:${e}`);let r=this.storage.readonly(`events`),i=[];for(let e of n)i.push(...await r.getAllFromIndex(`by-result-grain`,ub(e)));return i}async getEventsByResult(e){return this.storage.readonly(`events`).getAllFromIndex(`by-result-grain`,ub(e))}async getEventsByTimeRange(e,t){return this.storage.readonly(`events`).getAllFromIndex(`by-timestamp`,IDBKeyRange.bound(e,t))}async getEventsByMetricDates(e){let t=this.storage.readonly(`events`),n=new Map;for(let r of e)for(let e of await t.getAllFromIndex(`by-metric-date`,r))n.set(e.id,e);return Array.from(n.values())}async getEventsByContent(e){return this.storage.readonly(`events`).getAllFromIndex(`by-content-grain`,ub(e))}async scanAll(){return this.storage.readonly(`events`).getAll()}async countEvents(){return this.storage.readonly(`events`).count()}async getAllBlockIndex(){return this.storage.readonly(`block_index`).getAll()}async getBlockIndexByType(e){return this.storage.readonly(`block_index`).getAllFromIndex(`by-type`,e)}async getBlockIndexByNote(e){return this.storage.readonly(`block_index`).getAllFromIndex(`by-note`,e)}async countBlockIndex(){return this.storage.readonly(`block_index`).count()}async countBlockIndexInDomain(){let e=this.storage.readonly(`block_index`),[t,n,r,i,a,o,s,c]=await Promise.all([e.count(),e.countFromIndex(`by-source`),e.countFromIndex(`by-source`,``),e.countFromIndex(`by-source`,IDBKeyRange.bound(`collection:`,`collection;`,!1,!0)),e.countFromIndex(`by-source`,IDBKeyRange.bound(`page:collection:`,`page:collection;`,!1,!0)),e.countFromIndex(`by-source`,IDBKeyRange.bound(`guides:`,`guides;`,!1,!0)),e.countFromIndex(`by-source`,`playground`),e.getAllFromIndex(`by-source`,`journal`)]);return t-n+r+i+a+o+s+c.filter(e=>!e.id.startsWith(`pg-`)&&!e.noteId.startsWith(`pg-`)).length}async rebuildBlockIndexForNote(e){let t=await this.getNote(e);if(!t)return;let n=ja(t.rawContent,cb),r=hc({efforts:await this.getAllEfforts(),equipment:await this.getAllEquipment()}),i=fb(t.rawContent);await this.storage.transaction([`block_index`,`block_efforts`,`block_equipment`,`block_revisions`],`readwrite`,async a=>{let o=a.readwrite(`block_index`),s=a.readwrite(`block_efforts`),c=a.readwrite(`block_equipment`),l=new Map((await o.getAllFromIndex(`by-note`,e)).map(e=>[e.id,e])),u=new Map((await s.getAllFromIndex(`by-note`,e)).map(e=>[e.id,e])),d=new Map((await c.getAllFromIndex(`by-note`,e)).map(e=>[e.id,e])),f=0;for(let p of Object.values(t.blocks).sort((e,t)=>e.from-t.from)){let m=`${e}:${p.id}`,h=l.get(m);l.delete(m);let g=n.find(e=>e.from===p.from&&e.to===p.to),_=await a.readonly(`block_revisions`).get([e,p.id,p.version]);if(!_)throw Error(`Missing saved revision ${m}:${p.version}`);let v={id:m,noteId:e,blockId:p.id,blockVersion:p.version,sourceRevision:t.sourceRevision,from:p.from,to:p.to,position:f++,dataType:p.kind,blockContentId:g?.scriptBlock?.contentId,rawContent:t.rawContent.slice(p.from,p.to),noteTitle:t.title,createdAt:_.savedAt,isStatic:t.seedOrigin===`seed`||void 0,sourceId:t.sourceId,sourcePath:t.sourcePath,routeId:h?.routeId};if((!h||!xv(h,v))&&await o.put(v),p.kind!==`wod`||!g?.scriptBlock)continue;let y=_c(g.scriptBlock.content,{sport:p.sport,references:r,defaults:i}).statements,b=gc(y),x=new Set(b.efforts);if(x.size===0)for(let e of y){let t=e.metrics?.getMetric?.(q.Effort),n=(typeof t?.value==`string`?t.value:t&&`effort`in t?String(t.effort):``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``);n&&![`rest`,`amrap`,`emom`,`tabata`,`for-time`].includes(n)&&x.add(n)}for(let n of x){let r=`${e}:${p.id}:${n}`,i=u.get(r);u.delete(r);let a={id:r,noteId:e,blockId:p.id,blockContentId:v.blockContentId,effortSlug:n,createdAt:i?.createdAt??_.savedAt,isStatic:v.isStatic,sourcePath:t.sourcePath};(!i||!xv(i,a))&&await s.put(a)}for(let n of b.equipment){let r=`${e}:${p.id}:${n}`,i=d.get(r);d.delete(r);let a={id:r,noteId:e,blockId:p.id,blockContentId:v.blockContentId,equipmentSlug:n,createdAt:i?.createdAt??_.savedAt,isStatic:v.isStatic,sourcePath:t.sourcePath};(!i||!xv(i,a))&&await c.put(a)}}for(let e of l.values())await o.delete(e.id);for(let e of u.values())await s.delete(e.id);for(let e of d.values())await c.delete(e.id)})}async getEffort(e){return this.storage.readonly(`efforts`).get(e)}async getAllEfforts(){return this.storage.readonly(`efforts`).getAll()}async saveEffort(e){return await this.withTransaction([`efforts`,`page`],async t=>{await t.storage.readwrite(`efforts`).put(e);let n=t.storage.readwrite(`page`);for(let r of e.aliases){let i=r.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``);if(!i)continue;let a=`e/${i}`;(await t.storage.readonly(`page`).getAllFromIndex(`by-slug`,a)).length===0&&await n.put({id:db(),slug:a,title:`${e.label} (Alias)`,createdAt:Date.now()})}}),e.slug}async deleteEffort(e){await this.withTransaction([`efforts`,`page`],async t=>{let n=await t.storage.readonly(`efforts`).get(e);if(!n)return;await t.storage.readwrite(`efforts`).delete(e);let r=t.storage.readwrite(`page`);for(let e of n.aliases){let i=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``);if(i)for(let e of await t.storage.readonly(`page`).getAllFromIndex(`by-slug`,`e/${i}`))e.title===`${n.label} (Alias)`&&await r.delete(e.id)}})}async getEquipment(e){return this.storage.readonly(`equipment`).get(e)}async getAllEquipment(){return this.storage.readonly(`equipment`).getAll()}async saveEquipment(e){return await this.storage.readwrite(`equipment`).put(e),e.slug}async deleteEquipment(e){await this.storage.readwrite(`equipment`).delete(e)}async getEquipmentUsage(e){let t=await this.storage.readonly(`block_equipment`).getAllFromIndex(`by-equipment`,e),n=this.storage.readonly(`notes`),r=new Map;for(let e of t){if(r.has(e.noteId))continue;let t=await n.get(e.noteId);t&&r.set(e.noteId,t.title)}return Array.from(r,([e,t])=>({noteId:e,title:t}))}async getSeedContent(){return(await this.storage.readonly(`notes`).getAll()).filter(e=>e.seedOrigin===`seed`&&e.sourcePath).map(e=>({path:e.sourcePath,raw:e.rawContent}))}async wipe(){await this.storage.wipe()}},gb={getItem(e){try{return typeof window<`u`&&window.localStorage?window.localStorage.getItem(e):null}catch{return null}},setItem(e,t){try{typeof window<`u`&&window.localStorage&&window.localStorage.setItem(e,t)}catch{}},removeItem(e){try{typeof window<`u`&&window.localStorage&&window.localStorage.removeItem(e)}catch{}}},_b=class{prefix;backend;constructor(e=``,t=gb){this.prefix=e,this.backend=t}qualify(e){return this.prefix?`${this.prefix}${e}`:e}get(e,t){let n=this.getRaw(e,t?.alias);if(n==null)return t?.fallback??null;try{return JSON.parse(n)}catch{return t?.fallback??null}}set(e,t){try{this.backend.setItem(this.qualify(e),JSON.stringify(t))}catch{}}getRaw(e,t){let n=this.backend.getItem(this.qualify(e));return n==null&&t&&(n=this.backend.getItem(this.qualify(t))),n}setRaw(e,t){t==null?this.remove(e):this.backend.setItem(this.qualify(e),t)}remove(e,t){this.backend.removeItem(this.qualify(e)),t&&this.backend.removeItem(this.qualify(t))}},vb=`wodwiki.membership`;function yb(){try{let e=typeof window<`u`&&window.localStorage?window.localStorage.getItem(vb):null;if(e){let t=JSON.parse(e);if(typeof t?.displayName==`string`&&t.displayName.trim())return t.displayName.trim()}}catch{}return`Anonymous`}var bb=class{store;cache;updates=Promise.resolve();constructor(e=new _b){this.store=e}currentSync(){return this.cache??this.store.get(vb)??void 0}async current(){return this.cache||(this.cache=this.store.get(vb)??mv(),this.store.set(vb,this.cache)),this.cache}update(e){let t=this.updates.then(()=>this.applyUpdate(e),()=>this.applyUpdate(e));return this.updates=t.then(()=>{},()=>{}),t}async applyUpdate(e){let t={...this.cache??this.store.get(vb)??mv(),...e,updatedAt:Date.now()};return this.cache=t,this.store.set(vb,t),t}},xb;function Sb(){return xb??=wt(()=>Promise.resolve().then(()=>SO).then(e=>e.storage),void 0)}var Cb=class{cache;updates=Promise.resolve();currentSync(){return this.cache}async current(){if(this.cache)return this.cache;let e=await Sb(),t=await e.readonly(`memberships`).get(pv);return t||(t=mv(),await e.readwrite(`memberships`).put(t)),this.cache=t,t}update(e){let t=this.updates.then(()=>this.applyUpdate(e),()=>this.applyUpdate(e));return this.updates=t.then(()=>{},()=>{}),t}async applyUpdate(e){let t={...await this.current(),...e,updatedAt:Date.now()};return await(await Sb()).readwrite(`memberships`).put(t),this.cache=t,t}};function wb(e){return e===`indexed-db`?new bb:new Cb}function Tb(e,t=256){let{promise:n,resolve:r,reject:i}=Promise.withResolvers();if(!e.type.startsWith(`image/`))return i(Error(`Not an image file: ${e.type||e.name||`unknown`}`)),n;let a=URL.createObjectURL(e),o=new Image;return o.onload=()=>{URL.revokeObjectURL(a);let e=Math.min(o.naturalWidth,o.naturalHeight),n=Math.min(t,e),s=document.createElement(`canvas`);s.width=n,s.height=n;let c=s.getContext(`2d`);if(!c){i(Error(`Canvas 2D context unavailable`));return}c.drawImage(o,(o.naturalWidth-e)/2,(o.naturalHeight-e)/2,e,e,0,0,n,n),r(s.toDataURL(`image/jpeg`,.85))},o.onerror=()=>{URL.revokeObjectURL(a),i(Error(`Failed to decode image: ${e.name}`))},o.src=a,n}var Eb=0,Db=0,Ob=null,kb=null,Ab=null,jb=1,Mb=[],Nb=new Set,Pb={uploading:0,downloading:0,label:null,result:null,error:null};function Fb(){Pb={uploading:Eb,downloading:Db,label:Mb.length?Mb[Mb.length-1].label:null,result:Ob,error:kb,activeProgress:Ab};for(let e of Nb)e()}function Ib(e,t){let n={direction:e,label:t};Mb.push(n),e===`upload`?Eb+=1:Db+=1,Fb();let r=!1;return()=>{if(r)return;r=!0;let t=Mb.indexOf(n);t>=0&&Mb.splice(t,1),e===`upload`?Eb=Math.max(0,Eb-1):Db=Math.max(0,Db-1),Fb()}}function Lb(e){Ob={id:jb++,source:e.source,added:e.added,updated:e.updated},kb=null,Fb()}function Rb(e){Ab=e,Fb()}function zb(e){kb=e,Fb()}function Bb(){return Pb}function Vb(e){return Nb.add(e),()=>{Nb.delete(e)}}function Hb(e){return e.rows}function Ub(e){let t=Promise.resolve(),n=e=>{let n=t.then(e,e);return t=n.then(()=>void 0,()=>void 0),n};return{dialect:`sqlite`,query:(t,r=[])=>n(()=>e.execute({sql:t,args:r}).then(Hb)),exec:async(t,r=[])=>{await n(()=>e.execute({sql:t,args:r}))},transaction(t){return n(async()=>{let n=await e.transaction(`write`);try{let e=await t({query:(e,t=[])=>n.execute({sql:e,args:t}).then(Hb),exec:async(e,t=[])=>{await n.execute({sql:e,args:t})},batch:async e=>(await n.batch(e.map(({sql:e,params:t=[]})=>({sql:e,args:t})))).map(Hb)});return await n.commit(),e}catch(e){try{await n.rollback()}catch{}let t=e instanceof Error?e.message:String(e);for(let e of[`revision_conflict`,`transaction_conflict`,`invalid_session_pin`])if(t.includes(e))throw new bv(409,t,e);throw e}finally{n.close()}})},close:async()=>{await t,e.close()}}}var Wb={phase:`idle`,message:``,fromVersion:null,toVersion:0},Gb=new Set;function Kb(e){Wb=e;for(let e of Gb)e()}function qb(){return Wb}function Jb(e){return Gb.add(e),()=>Gb.delete(e)}function Yb(e){Kb({phase:`idle`,message:``,fromVersion:null,toVersion:e})}function Xb(e){Kb({...Wb,phase:`checking`,message:e})}function Zb(e,t){Kb({phase:`updating`,message:`Updating local database schema v${e} → v${t}…`,fromVersion:e,toVersion:t})}function Qb(e){Kb({...Wb,phase:`error`,message:e})}var $b=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function ex(e){return e.replace(/^(['"])(.*)\1$/,(e,t,n)=>t===`"`?n.replace(/\\(["\\])/g,`$1`):n)}function tx(e){let t=e.match($b);return t?{meta:nx(t[1].split(/\r?\n/)),body:e.slice(t[0].length)}:{meta:{},body:e}}function nx(e){let t={};for(let n=0;n<e.length;n++){let r=e[n].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!r)continue;let i=r[1],a=r[2].trim();if(a===``){let r=[];for(;n+1<e.length;){let t=e[n+1].match(/^\s+-\s+(.+)$/);if(!t)break;r.push(t[1].trim()),n++}t[i]=r.length>0?r:``}else{let e=/^(['"])(.*)\1$/.test(a),n=ex(a),r=Number(n);t[i]=!e&&n!==``&&!isNaN(r)?r:n}}return t}function rx(e){return nx(e.split(/\r?\n/))}function ix(e){if(e===``)return`""`;let t=!isNaN(Number(e)),n=/^(true|false|null|yes|no|on|off)$/i.test(e);return/[":'\n#{}[\],&*?|<>=%!@`]/.test(e)||e!==e.trim()||e.startsWith(`-`)||t||n?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function ax(e){let t=[];for(let[n,r]of Object.entries(e))if(Array.isArray(r)){if(r.length===0){t.push(`${n}: ""`);continue}t.push(`${n}:`);for(let e of r)t.push(` - ${ix(e)}`)}else typeof r==`number`?t.push(`${n}: ${r}`):t.push(`${n}: ${ix(r)}`);return t.join(`
58
+ `)}function ox(e){return tx(e).body}function sx(e,t){let n=e[t];return typeof n==`string`||typeof n==`number`?n:void 0}function cx(e,t){let n=e[t];return Array.isArray(n)?n:[]}function lx(e){return cx(tx(e).meta,`category`).map(e=>e.toLowerCase())}function ux(e){let t=$b.test(e)?tx(e).meta:rx(e),n=t.tags??t.category,r=Array.isArray(n)?n:typeof n==`string`&&n.trim()?n.trim().startsWith(`[`)&&n.trim().endsWith(`]`)?n.trim().slice(1,-1).split(`,`):[n]:[];return[...new Set(r.map(e=>e.trim()).filter(Boolean))]}function dx(e,t=[]){let n=$b.test(e)?tx(e).meta:rx(e),r=[],i=ux(e);for(let e of i)r.push({label:e});let a=Object.keys(n);for(let e of t){if(e===`tags`||e===`category`)continue;let t=a.find(t=>t.toLowerCase()===e.toLowerCase());if(!t)continue;let i=n[t];if(i==null||i===``)continue;let o=[];if(Array.isArray(i))o=i.map(String);else if(typeof i==`string`&&i.trim()){let e=i.trim();o=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1).split(`,`):[e]}for(let t of o){let n=t.trim();n&&r.push({label:n,type:e})}}let o=new Map;for(let e of r){let t=o.get(e.label);(!t||!t.type&&e.type)&&o.set(e.label,e)}return Array.from(o.values())}function fx(e){let t={};for(let n of e.split(/\r?\n/)){let e=n.match(/^([^:]+):\s*(.*)$/);e&&(t[e[1].trim()]=e[2].trim())}return t}function px(e){let t=e.match(/[?&]v=([a-zA-Z0-9_-]{11})/);if(t)return t[1];let n=e.match(/youtu\.be\/([a-zA-Z0-9_-]+)/);if(n)return n[1];let r=e.match(/youtube\.com\/embed\/([a-zA-Z0-9_-]{11})/);return r?r[1]:null}function mx(...e){return C(et(e))}function hx({id:e,title:t,question:n,query:r,span:i,showQuery:a=!1,onInspect:o,onOpenInExplorer:s,toolbar:c,children:l}){return(0,W.jsxs)(`div`,{id:e,className:mx(`relative group/frame bg-card border border-border rounded-lg p-4 flex flex-col min-h-0`,i),children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-3 mb-2`,children:[(0,W.jsxs)(`div`,{className:`min-w-0`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:t}),n&&(0,W.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:n})]}),(o||s)&&(0,W.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[o&&(0,W.jsx)(`button`,{type:`button`,onClick:o,title:`Inspect widget query`,"aria-label":`Inspect query for ${t||`widget`}`,className:`inline-flex items-center justify-center p-1 max-lg:min-h-11 max-lg:min-w-11 rounded bg-muted/80 text-muted-foreground hover:text-foreground transition-colors`,children:(0,W.jsx)(Mt,{className:`w-3.5 h-3.5`})}),s&&(0,W.jsx)(`button`,{type:`button`,onClick:s,title:`Open in explorer`,"aria-label":`Open ${t||`widget`} in explorer`,className:`inline-flex items-center justify-center p-1 max-lg:min-h-11 max-lg:min-w-11 rounded bg-muted/80 text-muted-foreground hover:text-foreground transition-colors`,children:(0,W.jsx)(Bt,{className:`w-3.5 h-3.5`})})]})]}),c&&(0,W.jsx)(`div`,{className:`mb-3`,children:c}),a&&r!=null&&r!==``&&(0,W.jsx)(`div`,{className:`font-mono text-[11px] text-primary/90 bg-background/60 rounded px-2 py-1 mb-3 whitespace-pre-wrap break-all`,children:r}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:l})]})}function gx({label:e,onClick:t,disabled:n,active:r,children:i}){return(0,W.jsx)(`button`,{type:`button`,onClick:t,title:e,"aria-label":e,disabled:n,className:mx(`inline-flex items-center justify-center p-1 max-lg:min-h-11 max-lg:min-w-11 rounded bg-muted/80 text-muted-foreground hover:text-foreground disabled:opacity-40 disabled:hover:text-muted-foreground transition-colors`,r&&`text-primary bg-primary/10`),children:i})}function _x({title:e,onClick:t}){return(0,W.jsx)(`button`,{type:`button`,onClick:t,title:`Edit widget`,"aria-label":`Edit widget ${e||``}`.trim(),className:`inline-flex items-center justify-center p-1 max-lg:min-h-11 max-lg:min-w-11 rounded bg-muted/80 text-muted-foreground hover:text-foreground transition-colors`,children:(0,W.jsx)(dn,{className:`w-3.5 h-3.5`})})}function vx(e){return(0,U.useMemo)(()=>e?e.parsed.error?{kind:`error`,message:e.parsed.error}:e.series.length===0?{kind:`empty`}:e.series.length===1&&e.series[0].points.length===1?{kind:`scalar`,value:e.series[0].points[0].value}:{kind:e.series.some(e=>e.points.length>1)?`timeseries`:`bars`}:{kind:`empty`},[e])}function yx({result:e,className:t,actions:n}){let r=(0,U.useMemo)(()=>e?e.parsed.error?`Query error: ${e.parsed.error}`:e.series.length===0?`No data for this range.`:null:`Loading…`,[e]);return r===null&&!n?null:(0,W.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center text-sm text-muted-foreground px-4 text-center ${t??``}`,children:[r&&(0,W.jsx)(`div`,{children:r}),n&&(0,W.jsx)(`div`,{className:`mt-3`,children:n})]})}function bx({result:e,unit:t,label:n,thresholds:r}){let i=vx(e),a=e.series[0]?.unit??t??``,o=(0,U.useMemo)(()=>i.kind===`scalar`?i.value:e.series.length===0?0:e.series[0].points[e.series[0].points.length-1]?.value??0,[e,i]),s=(0,U.useMemo)(()=>r?o>=r.green[0]&&o<=r.green[1]?`text-success`:o>=r.red[0]?`text-destructive`:`text-warning`:`text-foreground`,[o,r]);return(0,W.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center`,children:[(0,W.jsx)(yx,{result:e}),e.series.length>0&&!e.parsed.error&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`div`,{className:`text-5xl font-bold tabular-nums ${s}`,children:[o.toLocaleString(void 0,{maximumSignificantDigits:3}),(0,W.jsx)(`span`,{className:`text-lg font-normal text-muted-foreground ml-1`,children:a})]}),(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground mt-2 text-center`,children:n})]})]})}function xx(e){return{parsed:e.parsed,series:e.series??[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],...e.unit===void 0?{}:{unit:e.unit},...e.error?{error:e.error}:{},...e.table?{table:e.table}:{}}}function Sx(e){let t=new Map;for(let n of e)for(let e of n.points)t.has(e.ts)||t.set(e.ts,{ts:e.ts}),t.get(e.ts)[n.label]=e.value;return Array.from(t.values()).sort((e,t)=>e.ts-t.ts)}function Cx(e){let t=typeof e==`number`?e:Number(e);return Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function wx(e){return new Date(e).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`})}function Tx(e){return new Date(e).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`})}var Ex=[`hsl(var(--metric-time))`,`hsl(var(--metric-effort))`,`hsl(var(--metric-rep))`,`hsl(var(--metric-rounds))`,`hsl(var(--metric-distance))`,`hsl(var(--metric-resistance))`,`hsl(var(--metric-action))`,`hsl(var(--primary))`];function Dx({result:e,unit:t}){let n=vx(e),r=(0,U.useMemo)(()=>Sx(e.series),[e]),i=e.series[0]?.unit??t;return n.kind!==`timeseries`&&n.kind!==`scalar`?(0,W.jsx)(yx,{result:e}):(0,W.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,W.jsxs)(kn,{data:r,margin:{top:4,right:8,bottom:0,left:-12},children:[(0,W.jsx)(Te,{stroke:`hsl(var(--border))`,vertical:!1}),(0,W.jsx)(nt,{dataKey:`ts`,tickFormatter:wx,tickLine:!1,axisLine:{stroke:`hsl(var(--border))`},stroke:`hsl(var(--muted-foreground))`,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,W.jsx)(ne,{tickLine:!1,axisLine:!1,width:64,stroke:`hsl(var(--muted-foreground))`,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:10},unit:i?` ${i}`:``}),(0,W.jsx)(qn,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},labelFormatter:e=>Tx(e),formatter:e=>[`${Number(e).toLocaleString()} ${i??``}`.trim(),``]}),e.series.length>1&&(0,W.jsx)(yn,{wrapperStyle:{fontSize:11}}),e.series.map((e,t)=>(0,W.jsx)(ot,{type:`monotone`,dataKey:e.label,name:e.label,stroke:Ex[t%Ex.length],strokeWidth:2,dot:!1},e.key))]})})}function Ox({result:e,unit:t}){let n=vx(e),r=(0,U.useMemo)(()=>e.series.map((e,t)=>({name:e.label,value:e.points[0]?.value??0,fill:Ex[t%Ex.length]})),[e]),i=e.series[0]?.unit??t;return n.kind!==`bars`&&n.kind!==`scalar`?(0,W.jsx)(yx,{result:e}):(0,W.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,W.jsxs)(oe,{data:r,margin:{top:4,right:8,bottom:0,left:48},children:[(0,W.jsx)(Te,{stroke:`hsl(var(--border))`,vertical:!1}),(0,W.jsx)(nt,{dataKey:`name`,tickLine:!1,axisLine:{stroke:`hsl(var(--border))`},stroke:`hsl(var(--muted-foreground))`,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,W.jsx)(ne,{tickLine:!1,axisLine:!1,width:48,tickFormatter:Cx,stroke:`hsl(var(--muted-foreground))`,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:10},unit:i?` ${i}`:``}),(0,W.jsx)(qn,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},formatter:(e,t,n)=>{let r=typeof n?.payload?.name==`string`?n.payload.name:``;return[`${Number(e).toLocaleString()} ${i??``}`.trim(),r]}}),(0,W.jsx)(Qe,{dataKey:`value`,radius:[4,4,0,0],children:r.map(e=>(0,W.jsx)(It,{fill:e.fill},e.name))})]})})}var kx=12;function Ax(e,t){return`${e.toLocaleString()}${t?` ${t}`:``}`}function jx({result:e,unit:t}){let n=vx(e),r=e.series[0]?.unit??t??``,i=(0,U.useMemo)(()=>{if(n.kind===`scalar`)return{head:[`Metric`,`Value`],body:[[e.series[0]?.label??`scalar`,Ax(n.value,r)]],more:0};if(n.kind===`bars`){let t=e.series.map(e=>[e.label,Ax(e.points[0]?.value??0,r)]);return{head:[`Series`,`Value`],body:t.slice(0,kx),more:Math.max(0,t.length-kx)}}if(n.kind===`timeseries`){let t=Array.from(new Set(e.series.flatMap(e=>e.points.map(e=>e.ts)))).sort((e,t)=>t-e),n=new Map;for(let t of e.series)n.set(t.label,new Map(t.points.map(e=>[e.ts,e.value])));return{head:[`Date`,...e.series.map(e=>e.label)],body:t.slice(0,kx).map(t=>[wx(t),...e.series.map(e=>{let i=n.get(e.label)?.get(t);return i===void 0?`—`:Ax(i,r)})]),more:Math.max(0,t.length-kx)}}return{head:[],body:[],more:0}},[e,n,r]);return n.kind===`error`||n.kind===`empty`?(0,W.jsx)(yx,{result:e}):(0,W.jsxs)(`div`,{className:`h-full overflow-auto`,children:[(0,W.jsxs)(`table`,{className:`w-full text-[11px] font-mono`,children:[(0,W.jsx)(`thead`,{children:(0,W.jsx)(`tr`,{className:`border-b border-border text-muted-foreground text-left`,children:i.head.map((e,t)=>(0,W.jsx)(`th`,{className:`py-1 px-2 font-medium ${t===0?`text-left`:`text-right`}`,children:e},e))})}),(0,W.jsx)(`tbody`,{children:i.body.map((e,t)=>(0,W.jsx)(`tr`,{className:`border-b border-border/40 hover:bg-muted/30 transition-colors`,children:e.map((e,t)=>(0,W.jsx)(`td`,{className:`py-1 px-2 text-foreground tabular-nums ${t===0?`text-left`:`text-right`}`,children:e},t))},t))})]}),i.more>0&&(0,W.jsxs)(`div`,{className:`text-[11px] text-muted-foreground pt-2`,children:[`… `,i.more,` more rows`]})]})}function Mx({result:e,unit:t,limit:n=8}){let r=vx(e),i=e.series[0]?.unit??t,a=(0,U.useMemo)(()=>e.series.map(e=>({name:e.label,value:e.points[0]?.value??0})).sort((e,t)=>t.value-e.value).slice(0,n),[e,n]),o=a[0]?.value||1;return r.kind===`error`||r.kind===`empty`?(0,W.jsx)(yx,{result:e}):(0,W.jsx)(`div`,{className:`space-y-2 pt-1`,children:a.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground w-4 text-right`,children:t+1}),(0,W.jsx)(`span`,{className:`text-xs w-36 truncate text-foreground`,children:e.name}),(0,W.jsx)(`div`,{className:`flex-1 h-4 bg-muted/60 rounded-sm overflow-hidden`,children:(0,W.jsx)(`div`,{className:`h-full rounded-sm`,style:{width:`${e.value/o*100}%`,background:Ex[t%Ex.length]}})}),(0,W.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground w-20 text-right`,children:[e.value.toLocaleString(),` `,i]})]},e.name))})}var Nx=[`low`,`moderate`,`high`];function Px({result:e,unit:t}){let n=vx(e),r=(0,U.useMemo)(()=>Sx(e.series),[e]),i=e.series[0]?.unit??t,a=(0,U.useMemo)(()=>e.series.map(e=>e.label).sort((e,t)=>{let n=Nx.indexOf(e),r=Nx.indexOf(t);return n===-1&&r===-1?e.localeCompare(t):n===-1?1:r===-1?-1:n-r}),[e]);return n.kind!==`timeseries`&&n.kind!==`bars`?(0,W.jsx)(yx,{result:e}):(0,W.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,W.jsxs)(oe,{data:r,margin:{top:4,right:8,bottom:0,left:48},children:[(0,W.jsx)(Te,{stroke:`hsl(var(--border))`,vertical:!1}),(0,W.jsx)(nt,{dataKey:`ts`,tickFormatter:wx,tickLine:!1,axisLine:{stroke:`hsl(var(--border))`},stroke:`hsl(var(--muted-foreground))`,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,W.jsx)(ne,{tickLine:!1,axisLine:!1,width:48,tickFormatter:Cx,stroke:`hsl(var(--muted-foreground))`,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:10},unit:i?` ${i}`:``}),(0,W.jsx)(qn,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},labelFormatter:e=>Tx(e),formatter:(e,t,n)=>{let r=typeof n?.payload?.name==`string`?n.payload.name:``;return[`${Number(e).toLocaleString()} ${i??``}`.trim(),r]}}),(0,W.jsx)(yn,{wrapperStyle:{fontSize:11}}),a.map(t=>{let n=e.series.findIndex(e=>e.label===t);return(0,W.jsx)(Qe,{dataKey:t,stackId:`a`,fill:Ex[n>=0?n%Ex.length:0]},t)})]})})}function Fx({result:e,attributes:t,params:n,label:r,unit:i}){if(!e||e.series.length===0)return(0,W.jsx)(yx,{result:e});let a=t?.goal??(n&&n.length>0?n[0]:void 0),o=a?parseFloat(a):void 0,s=o!==void 0&&!isNaN(o)&&o>0,c=i??e.unit??e.parsed.displayUnit??``;return(0,W.jsx)(`div`,{className:`flex flex-wrap items-center justify-around gap-4 h-full p-2`,"data-testid":`goal-rings-widget`,children:e.series.map((t,n)=>{let i=t.points.length>0?t.points[t.points.length-1]:void 0,a=i?i.value:0,l=s?Math.round(a/o*100):void 0,u=t.label||r||(e.series.length===1?`Target`:`Series ${n+1}`);return(0,W.jsx)(Ix,{label:u,current:a,target:o,pct:l,unit:t.unit||c},t.key||n)})})}function Ix({label:e,current:t,target:n,pct:r,unit:i}){let a=t.toLocaleString(),o=n?n.toLocaleString():void 0,s=2*Math.PI*38,c=s-(r===void 0?0:Math.min(Math.max(r,0),100))/100*s,l=`stroke-primary`,u=`text-foreground`;return r!==void 0&&(r>=100?(l=`stroke-signal-positive`,u=`text-signal-positive`):l=r>=75?`stroke-primary`:r>=50?`stroke-signal-caution`:`stroke-signal-negative`),(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-w-28 text-center`,"data-testid":`goal-ring-item`,children:[(0,W.jsxs)(`div`,{className:`relative w-24 h-24 flex items-center justify-center`,children:[(0,W.jsxs)(`svg`,{className:`w-full h-full transform -rotate-90`,viewBox:`0 0 100 100`,children:[(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:38,className:`stroke-muted`,strokeWidth:`8`,fill:`transparent`}),r!==void 0&&(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:38,className:`${l} transition-all duration-500 ease-out`,strokeWidth:`8`,strokeDasharray:s,strokeDashoffset:c,strokeLinecap:`round`,fill:`transparent`})]}),(0,W.jsxs)(`div`,{className:`absolute flex flex-col items-center justify-center`,children:[r===void 0?(0,W.jsx)(`span`,{className:`text-sm font-semibold tabular-nums leading-none text-foreground`,children:a}):(0,W.jsxs)(`span`,{className:`text-base font-bold tabular-nums leading-none ${u}`,children:[r,`%`]}),r!==void 0&&(0,W.jsxs)(`span`,{className:`text-[10px] text-muted-foreground mt-0.5`,children:[a,` `,i]})]})]}),(0,W.jsxs)(`div`,{className:`mt-2 flex flex-col items-center max-w-32`,children:[(0,W.jsx)(`span`,{className:`text-xs font-medium text-foreground truncate w-full`,title:e,children:e}),o&&(0,W.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[`Goal: `,o,` `,i]})]})]})}function Lx(e,t){if(!e)return t;let n=parseFloat(e);return isNaN(n)?t:n}function Rx({result:e,params:t,attributes:n}){if(!e||e.series.length===0)return(0,W.jsx)(yx,{result:e});let r=80,i=0,a=20,o=n?.targets;if(o){let e=o.trim().split(/\s+/);e.length>=3?(r=Lx(e[0],80),i=Lx(e[1],0),a=Lx(e[2],20)):e.length===2?(r=Lx(e[0],80),a=Lx(e[1],20),i=Math.max(0,100-(r+a))):e.length===1&&(r=Lx(e[0],80),a=Math.max(0,100-r),i=0)}else if(t&&t.length>0){let e=t[0].trim().split(/\s+/);e.length>=3&&(r=Lx(e[0],80),i=Lx(e[1],0),a=Lx(e[2],20))}let s=0,c=0,l=0;e.series.forEach((e,t)=>{let n=e.points.length>0?e.points[e.points.length-1]:void 0,r=n?n.value:0,i=(e.label||e.key||``).toLowerCase();i.includes(`low`)||i.includes(`z1`)||i.includes(`z2`)||t===0?s+=r:i.includes(`mod`)||i.includes(`tempo`)||i.includes(`z3`)||t===1?c+=r:i.includes(`high`)||i.includes(`hard`)||i.includes(`z4`)||i.includes(`z5`)||t===2?l+=r:s+=r});let u=s+c+l,d=u>0?Math.round(s/u*100):0,f=u>0?Math.round(c/u*100):0,p=u>0?Math.round(l/u*100):0,m=[{key:`low`,label:`Low / Aerobic`,sublabel:`Zone 1–2`,colorClass:`bg-signal-positive`,bgClass:`text-signal-positive`,target:r,actual:s,pct:d},{key:`moderate`,label:`Moderate / Tempo`,sublabel:`Zone 3`,colorClass:`bg-signal-caution`,bgClass:`text-signal-caution`,target:i,actual:c,pct:f},{key:`high`,label:`High / Anaerobic`,sublabel:`Zone 4–5`,colorClass:`bg-signal-negative`,bgClass:`text-signal-negative`,target:a,actual:l,pct:p}];return(0,W.jsxs)(`div`,{className:`flex flex-col justify-between h-full p-2 gap-4`,"data-testid":`zone-distribution-widget`,children:[(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-muted-foreground px-0.5`,children:[(0,W.jsx)(`span`,{children:`Actual vs Target Distribution`}),(0,W.jsxs)(`span`,{className:`font-mono text-[10px]`,children:[`T: `,r,`/`,i,`/`,a,`%`]})]}),(0,W.jsx)(`div`,{className:`w-full h-5 rounded-md overflow-hidden flex bg-muted/60 p-0.5 gap-0.5`,children:m.map(e=>e.pct>0?(0,W.jsx)(`div`,{className:`${e.colorClass} h-full rounded-sm transition-all duration-500 flex items-center justify-center`,style:{width:`${e.pct}%`},title:`${e.label}: ${e.pct}% (Target: ${e.target}%)`,children:e.pct>=10&&(0,W.jsxs)(`span`,{className:`text-[10px] font-bold text-white leading-none drop-shadow-sm`,children:[e.pct,`%`]})},e.key):null)})]}),(0,W.jsx)(`div`,{className:`grid grid-cols-3 gap-2`,children:m.map(e=>{let t=e.pct-e.target;return(0,W.jsxs)(`div`,{className:`flex flex-col bg-muted/20 border border-border/50 rounded-lg p-2 text-center`,"data-testid":`zone-card-${e.key}`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 mb-1`,children:[(0,W.jsx)(`span`,{className:`w-2 h-2 rounded-full ${e.colorClass}`}),(0,W.jsx)(`span`,{className:`text-xs font-semibold text-foreground truncate`,children:e.label})]}),(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground mb-1.5`,children:e.sublabel}),(0,W.jsxs)(`div`,{className:`flex items-baseline justify-center gap-1`,children:[(0,W.jsxs)(`span`,{className:`text-lg font-bold tabular-nums text-foreground`,children:[e.pct,`%`]}),(0,W.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[`/ `,e.target,`%`]})]}),e.target>0&&(0,W.jsx)(`span`,{className:`text-[10px] font-medium tabular-nums mt-0.5 ${Math.abs(t)<=5?`text-signal-positive`:t>0?`text-signal-caution`:`text-muted-foreground`}`,children:t>0?`+${t}%`:`${t}%`})]},e.key)})})]})}function zx({type:e,result:t,label:n,unit:r,params:i,attributes:a}){if(e!==``&&!c_(e))return(0,W.jsx)(Vx,{message:u_(e)});let o=l_(e);return o===`table`&&t?.table?(0,W.jsx)(`div`,{className:`w-full h-full min-h-[160px]`,children:(0,W.jsx)(Gx,{table:t.table})}):o===`list`&&t?.parsed?.family===`find`?(0,W.jsx)(`div`,{className:`w-full h-full min-h-[160px]`,children:(0,W.jsx)(Kx,{result:t})}):!t||t.parsed.error||`series`in t&&t.series.length===0?(0,W.jsx)(yx,{result:t}):(0,W.jsx)(`div`,{className:`w-full h-full min-h-[160px]`,children:Bx(o,t,n,r,i,a)})}function Bx(e,t,n,r,i,a){switch(e){case`value`:return(0,W.jsx)(bx,{result:t,label:n??``,unit:r});case`donut`:return(0,W.jsx)(Ux,{result:t,unit:r,label:n});case`timeseries`:return(0,W.jsx)(Dx,{result:t,unit:r});case`bar`:case`bars`:return(0,W.jsx)(Ox,{result:t,unit:r});case`top`:case`toplist`:return(0,W.jsx)(Mx,{result:t,unit:r});case`stacked`:case`stacked-bar`:return(0,W.jsx)(Px,{result:t,unit:r});case`goal-rings`:return(0,W.jsx)(Fx,{result:t,attributes:a,params:i,label:n,unit:r});case`zone-distribution`:return(0,W.jsx)(Rx,{result:t,attributes:a,params:i,unit:r});case`table`:return(0,W.jsx)(jx,{result:t,unit:r});default:return(Array.isArray(f_)?f_.includes(e):f_.has?.(e))?(0,W.jsx)(Hx,{type:e}):(0,W.jsx)(jx,{result:t,unit:r})}}function Vx({message:e}){return(0,W.jsx)(`div`,{role:`alert`,"data-testid":`widget-problem`,className:`flex items-center justify-center h-full p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-xs font-medium text-center`,children:e})}function Hx({type:e}){return(0,W.jsxs)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground font-mono bg-muted/20 rounded p-4 text-center`,children:[`widget:`,e,` renderer in progress`]})}function Ux({result:e,unit:t,label:n}){let r=e.series.map((e,t)=>({name:e.label,value:e.points.reduce((e,t)=>e+(t.missing?0:t.value),0),fill:Ex[t%Ex.length]})).filter(e=>e.value>0),i=e.series[0]?.unit??t??``,a=r.length>0?`${n??`distribution`}: ${r.map(e=>`${e.name} ${Cx(e.value)}${i}`).join(`, `)}`:`no data`;return(0,W.jsx)(`div`,{className:`w-full h-full flex flex-col items-center justify-center`,role:`img`,"aria-label":a,"data-testid":`wql-donut`,children:r.length===0?(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`No data`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`w-full h-[220px] min-h-[160px] shrink-0`,children:(0,W.jsx)(Wx,{data:r,unit:i})}),(0,W.jsx)(`ul`,{className:`shrink-0 text-[10px] font-mono text-muted-foreground space-y-0.5`,"aria-hidden":`true`,children:r.map(e=>(0,W.jsxs)(`li`,{className:`flex items-center gap-1.5`,children:[(0,W.jsx)(`span`,{className:`inline-block size-2 rounded-sm`,style:{background:e.fill}}),(0,W.jsx)(`span`,{children:`${e.name} ${Cx(e.value)}${i}`})]},e.name))})]})})}function Wx({data:e,unit:t}){return(0,W.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,W.jsxs)(k,{margin:{top:4,right:8,bottom:4,left:8},children:[(0,W.jsx)(n,{data:e,dataKey:`value`,nameKey:`name`,cx:`50%`,cy:`50%`,innerRadius:`55%`,outerRadius:`85%`,paddingAngle:2,stroke:`hsl(var(--background))`,isAnimationActive:!1,children:e.map(e=>(0,W.jsx)(It,{fill:e.fill},e.name))}),(0,W.jsx)(qn,{formatter:e=>`${Cx(Number(e))}${t}`})]})})}function Gx({table:e}){return(0,W.jsx)(`div`,{className:`h-full overflow-auto`,"data-testid":`tabular-table`,children:(0,W.jsxs)(`table`,{className:`w-full text-[11px] font-mono border-collapse`,children:[(0,W.jsx)(`thead`,{children:(0,W.jsx)(`tr`,{className:`border-b border-border text-muted-foreground text-left`,children:e.columns.map(e=>(0,W.jsxs)(`th`,{className:`py-1 px-2 font-medium`,children:[e.name,e.unit?` (${e.unit})`:``]},e.name))})}),(0,W.jsx)(`tbody`,{children:e.groups?e.groups.map(t=>(0,W.jsxs)(U.Fragment,{children:[(0,W.jsx)(`tr`,{className:`bg-muted/40 font-semibold border-b border-border/60`,children:(0,W.jsx)(`td`,{colSpan:e.columns.length,className:`py-1 px-2`,children:t.label})}),t.rows.map((t,n)=>(0,W.jsx)(`tr`,{className:`border-b border-border/40 hover:bg-muted/20`,children:e.columns.map(e=>(0,W.jsx)(`td`,{className:`py-1 px-2 whitespace-nowrap`,children:String(t[e.name]??``)},e.name))},n))]},t.key)):e.rows.map((t,n)=>(0,W.jsx)(`tr`,{className:`border-b border-border/40 hover:bg-muted/20`,children:e.columns.map(e=>(0,W.jsx)(`td`,{className:`py-1 px-2 whitespace-nowrap`,children:String(t[e.name]??``)},e.name))},n))})]})})}function Kx({result:e}){let t=e.notes?.length?e.notes:e.blocks?.length?e.blocks:e.efforts?.length?e.efforts:e.runs??[];return(0,W.jsx)(`div`,{className:`h-full overflow-auto space-y-1`,"data-testid":`thing-list`,children:t.map((e,t)=>(0,W.jsx)(`div`,{className:`py-1 px-2 text-xs border-b border-border/40 truncate`,children:e.title??e.label??e.noteTitle??e.id??e.resultId},e.id??e.resultId??t))})}function qx({name:e,value:t,disabled:n,onCommit:r}){let[i,a]=(0,U.useState)(t);(0,U.useEffect)(()=>a(t),[t]);let o=()=>{i!==t&&r(i)};return(0,W.jsx)(`input`,{type:`text`,value:i,disabled:n,onChange:e=>a(e.target.value),onBlur:o,onKeyDown:e=>{e.key===`Enter`&&(o(),e.currentTarget.blur())},"aria-label":`Token ${e}`,className:`w-20 rounded-lg border border-border bg-card px-2 py-1 text-xs font-mono text-foreground focus:outline-none focus:border-primary disabled:opacity-60`})}function Jx({tokens:e,values:t,onChange:n}){if(e.length===0)return null;let r=!n;return(0,W.jsx)(`div`,{"data-testid":`dashboard-token-controls`,className:`flex flex-wrap items-center gap-x-5 gap-y-2 mb-4`,children:e.map(e=>{let i=t[e.name]??e.values[0];return(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsxs)(`span`,{className:`font-mono text-[11px] text-muted-foreground`,children:[`$`,e.name]}),e.isList?(0,W.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-border bg-card p-1`,children:e.values.map(t=>(0,W.jsx)(`button`,{type:`button`,disabled:r,onClick:()=>{t!==i&&n?.(e.name,t)},className:mx(`text-xs px-2.5 py-1 rounded-md transition-colors`,t===i?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`,r&&`cursor-default`),children:t},t))}):r?(0,W.jsx)(`span`,{className:`text-xs text-foreground font-mono`,children:i}):(0,W.jsx)(qx,{name:e.name,value:i,onCommit:t=>n?.(e.name,t)})]},e.name)})})}function Yx(e,t={}){return{runAggregate:(n,r)=>e.runQuery(n,{context:r.context,rangeStart:t.rangeStart,rangeEnd:t.rangeEnd,preferredUnit:t.preferredUnit}),runFind:async(n,r)=>{let i=X(n);if(!bm(i))return{kind:`find`,error:`not a content query: ${n}`};let a=await e.runFind(i,{context:r,range:t.rangeStart===void 0?void 0:{start:t.rangeStart,end:t.rangeEnd??2**53-1,endExclusive:!1}});return{kind:`find`,notes:a.notes,blocks:a.blocks,efforts:a.efforts,containers:a.containers,runs:a.runs,table:a.table}},runPipeline:async(n,r)=>await e.runPipeline?.(n,{context:r,rangeStart:t.rangeStart,rangeEnd:t.rangeEnd,preferredUnit:t.preferredUnit})??{error:`pipeline queries are not supported by this executor`},rollupEnsure:t.rollupEnsure}}function Xx(e,t){let n=xx({parsed:e,series:t.series,unit:t.unit,error:t.error,table:t.table});return Object.assign(n,{...t.notes?{notes:t.notes}:{},...t.blocks?{blocks:t.blocks}:{},...t.efforts?{efforts:t.efforts}:{},...t.containers?{containers:t.containers}:{},...t.runs?{runs:t.runs}:{}})}function Zx(e){if(e.spanFull)return`col-span-1 md:col-span-2 lg:col-span-4`;if(e.spanCols!=null)return e.spanCols<=1?`col-span-1`:e.spanCols===2?`col-span-1 md:col-span-2`:e.spanCols===3?`col-span-1 md:col-span-2 lg:col-span-3`:`col-span-1 md:col-span-2 lg:col-span-4`;let t=l_(e.type);return t===`value`?`col-span-1`:t===`table`?`col-span-1 md:col-span-2`:`col-span-1 md:col-span-2 lg:col-span-4`}var Qx=[{label:`Span 1 column`,span:{spanCols:1},testId:`widget-size-1`},{label:`Span 2 columns`,span:{spanCols:2},testId:`widget-size-2`},{label:`Span 4 columns`,span:{spanCols:4},testId:`widget-size-4`},{label:`Full row`,span:{spanFull:!0},testId:`widget-size-full`}];function $x(e,t){return t.spanFull?e.spanFull===!0:!e.spanFull&&(e.spanCols??null)===(t.spanCols??null)}function eS({document:e,headings:t,executor:n,onEnsureRollupFacts:r,tokenValues:i,onTokenChange:a,editMode:o=!1,onEditWidget:s,onInspectWidget:c,onOpenInExplorer:l,onDuplicateWidget:u,onRemoveWidget:d,onMoveWidget:f,onResizeWidget:p,rangeStart:m,rangeEnd:h,preferredUnit:g}){let _=(0,U.useMemo)(()=>({...__(e.tokens),...i}),[e.tokens,i]),v=(0,U.useMemo)(()=>e.widgets.map(e=>{let{query:t,missing:n}=b_(e.body,_),r={},i=new Set(n);for(let[t,n]of Object.entries(e.attributes)){let e=b_(n,_);r[t]=e.query;for(let t of e.missing)i.add(t)}return{widget:e,query:t,missing:[...i],attributes:r}}),[e.widgets,_]),[y,b]=(0,U.useState)({}),[x,S]=(0,U.useState)(!0),C=(0,U.useMemo)(()=>v.map(e=>`${e.widget.key}:${e.query}`).join(`|`),[v]);return(0,U.useEffect)(()=>{let e=!1;S(!0);async function t(){let t={},i=[];for(let{widget:e,query:n,missing:r}of v){if(e.type!==``&&!c_(e.type)){t[e.key]={error:u_(e.type)};continue}if(r.length>0){t[e.key]={error:d_(r)};continue}let a=X(n);if(a.error){t[e.key]={error:a.error};continue}let o=l_(e.type);if(bm(a)){if(o!==`table`&&o!==`list`){t[e.key]={error:`content queries return things — use a table or list widget instead`};continue}}else if(!Sm(a)&&o===`list`){t[e.key]={error:`aggregate queries return numbers — use a chart or value widget instead`};continue}i.push({widget:e,query:n,parsed:a})}if(!n){e||(b(t),S(!1));return}let a=Yx(n,{rangeStart:m,rangeEnd:h,preferredUnit:g,rollupEnsure:r});await Promise.all(i.map(async({widget:e,query:n,parsed:r})=>{try{let i=await new _g(a).run(n),o=i.outputs[0];if(!o){t[e.key]={error:i.diagnostics[0]??`widget produced no output`};return}let s=o.error??i.diagnostics[0];t[e.key]={result:Xx(r,o),...s?{error:s}:{}}}catch(n){t[e.key]={error:n instanceof Error?n.message:String(n)}}})),e||(b(t),S(!1))}return t(),()=>{e=!0}},[C,v,n,r,m,h,g]),(0,W.jsxs)(`div`,{"data-testid":`dashboard-view`,children:[(0,W.jsx)(Jx,{tokens:e.tokens,values:_,onChange:a}),x&&(0,W.jsx)(`div`,{className:`text-sm text-muted-foreground mb-3`,children:`Loading widgets…`}),(0,W.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4`,children:[v.map(({widget:e,query:n,attributes:r},i)=>{let a=y[e.key],m=o&&(s||u||d||f||p),h=(t??[]).filter(e=>e.beforeWidget===i);return(0,W.jsxs)(U.Fragment,{children:[h.map(e=>(0,W.jsx)(`div`,{id:e.id,className:mx(`col-span-full font-semibold text-foreground`,e.level<=2?`text-base mt-2`:`text-sm`),children:e.text},e.id)),(0,W.jsx)(hx,{id:`widget-${e.key}`,title:e.title??``,question:e.question??``,query:n,span:Zx(e),onInspect:c?()=>c(e):void 0,onOpenInExplorer:l?()=>l(e,n):void 0,toolbar:m?(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`widget-toolbar-${e.key}`,children:[s&&(0,W.jsx)(_x,{title:e.title??``,onClick:()=>s(e)}),f&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(gx,{label:`Move ${e.title||`widget`} up`,disabled:i===0,onClick:()=>f(e,-1),children:(0,W.jsx)(Wt,{className:`w-3.5 h-3.5`})}),(0,W.jsx)(gx,{label:`Move ${e.title||`widget`} down`,disabled:i===v.length-1,onClick:()=>f(e,1),children:(0,W.jsx)(nr,{className:`w-3.5 h-3.5`})})]}),p&&(0,W.jsx)(`div`,{className:`flex items-center gap-0 rounded bg-muted/60 p-0.5`,children:Qx.map(t=>(0,W.jsx)(`button`,{type:`button`,"data-testid":`${t.testId}-${e.key}`,title:t.label,"aria-label":`${t.label} for ${e.title||`widget`}`,"aria-pressed":$x(e,t.span),disabled:$x(e,t.span),onClick:()=>p(e,t.span),className:`inline-flex items-center justify-center px-1 py-0.5 max-lg:min-h-11 max-lg:min-w-11 text-xs font-mono rounded text-muted-foreground hover:text-foreground disabled:text-primary disabled:bg-primary/10`,children:t.span.spanFull?(0,W.jsx)(pt,{className:`w-3 h-3`}):t.span.spanCols},t.testId))}),u&&(0,W.jsx)(gx,{label:`Duplicate ${e.title||`widget`}`,onClick:()=>u(e),children:(0,W.jsx)(On,{className:`w-3.5 h-3.5`})}),d&&(0,W.jsx)(gx,{label:`Remove ${e.title||`widget`}`,onClick:()=>d(e),children:(0,W.jsx)(wn,{className:`w-3.5 h-3.5`})})]}):void 0,children:a?.error?(0,W.jsx)(Vx,{message:a.error}):(0,W.jsx)(zx,{type:e.type,result:a?.result,label:e.title,unit:g,attributes:r})},e.key)]},e.key)}),(t??[]).filter(e=>e.beforeWidget>=v.length).map(e=>(0,W.jsx)(`div`,{id:e.id,className:mx(`col-span-full font-semibold text-foreground`,e.level<=2?`text-base mt-2`:`text-sm`),children:e.text},e.id))]})]})}function tS({weeks:e,onWeeksChange:t,className:n}){let[r,i]=(0,U.useState)(16),a=e??r,o=e=>{t?t(e):i(e)};return(0,W.jsx)(`div`,{className:mx(`inline-flex items-center gap-1 rounded-lg border border-border bg-card p-1`,n),children:[4,8,16].map(e=>(0,W.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:mx(`text-xs px-2.5 py-1 rounded-md transition-colors`,a===e?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`),children:[e,`w`]},e))})}var nS=`wod.analytics.unit`,rS=[`kg`,`lb`],iS=new Map,aS={getItem:e=>iS.get(e)??null,setItem:(e,t)=>{iS.set(e,t)},removeItem:e=>{iS.delete(e)}},oS=new Set;function sS(){for(let e of oS)e()}function cS(e){return e??aS}function lS(e){let t=cS(e).getItem(nS);return rS.includes(t??``)?t:`kg`}function uS(e){let t=cS(e),[n,r]=(0,U.useState)(()=>lS(t));(0,U.useEffect)(()=>{r(lS(t));let e=()=>r(lS(t));return oS.add(e),()=>{oS.delete(e)}},[t]);let i=(0,U.useCallback)(e=>{t.setItem(nS,e),r(e),sS()},[t]);return{unit:n,setUnit:i,toggleUnit:(0,U.useCallback)(()=>{i(n===`kg`?`lb`:`kg`)},[n,i])}}function dS(e,t){let n=X(e),r=`displayUnit`in n?n.displayUnit:void 0;return r===`lb`||r===`kg`?{unit:r,forced:!0}:{unit:t,forced:!1}}function fS({className:e,unit:t,forced:n=!1,storage:r}){let{unit:i,setUnit:a}=uS(r),o=t??i;return(0,W.jsxs)(`div`,{"data-testid":`analytics-unit-preference`,className:mx(`inline-flex items-center gap-1 text-xs`,e),children:[(0,W.jsxs)(`div`,{className:mx(`inline-flex items-center rounded-lg border border-border bg-card p-1`,n&&`opacity-70`),title:n?`Unit forced by query directive in this view`:`Display unit preference`,children:[(0,W.jsx)(`button`,{type:`button`,disabled:n,onClick:()=>a(`kg`),className:mx(`px-2.5 py-1 rounded-md transition-colors text-xs font-mono`,o===`kg`?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`,n&&`cursor-default hover:bg-transparent hover:text-muted-foreground`),children:`kg`}),(0,W.jsx)(`button`,{type:`button`,disabled:n,onClick:()=>a(`lb`),className:mx(`px-2.5 py-1 rounded-md transition-colors text-xs font-mono`,o===`lb`?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`,n&&`cursor-default hover:bg-transparent hover:text-muted-foreground`),children:`lb`})]}),n&&(0,W.jsx)(`span`,{className:`text-[11px] text-muted-foreground italic`,children:`forced by note`})]})}function pS(e){let t=Math.floor(Math.max(0,e)/1e3),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function mS(e){return e.toLocaleTimeString(`en-US`,{hour12:!1,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var hS={time:`border-metric-time/40 bg-metric-time/10 text-metric-time`,rep:`border-metric-rep/40 bg-metric-rep/10 text-metric-rep`,effort:`border-metric-effort/40 bg-metric-effort/10 text-metric-effort`,distance:`border-metric-distance/40 bg-metric-distance/10 text-metric-distance`,rounds:`border-metric-rounds/40 bg-metric-rounds/10 text-metric-rounds`,action:`border-metric-action/40 bg-metric-action/10 text-metric-action`,resistance:`border-metric-resistance/40 bg-metric-resistance/10 text-metric-resistance`,rest:`border-metric-rest/40 bg-metric-rest/10 text-metric-rest italic`,muted:`border-border/70 bg-muted/50 text-muted-foreground`,system:`border-border/60 bg-muted/40 text-muted-foreground`,unknown:`border-border/60 bg-muted/40 text-muted-foreground`};function gS({token:e}){return!e.visible||!e.label?null:e.renderKind===`comment`?(0,W.jsx)(`span`,{className:`text-[10px] italic text-muted-foreground`,title:e.tooltip,children:e.label}):(0,W.jsx)(`span`,{className:`rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-tight select-none ${hS[e.tone]??hS.unknown}`,title:e.tooltip,children:e.label})}function _S(e){return(0,W.jsx)(W.Fragment,{children:jo.presentGroup(Array.from(e),`runtime-badge`).map((e,t)=>(0,W.jsx)(gS,{token:e},t))})}var vS={segment:`bg-type-segment/15 text-type-segment border-type-segment/30`,milestone:`bg-type-milestone/15 text-type-milestone border-type-milestone/30`,completion:`bg-type-completion/15 text-type-completion border-type-completion/30`,metric:`bg-type-metric/15 text-type-metric border-type-metric/30`,system:`bg-muted/70 text-muted-foreground border-border/50`,event:`bg-type-event/15 text-type-event border-type-event/30`,group:`bg-type-group/15 text-type-group border-type-group/30`,load:`bg-muted/70 text-muted-foreground border-border/50`,compiler:`bg-muted/70 text-muted-foreground border-border/50`,analytics:`bg-type-analytics/15 text-type-analytics border-type-analytics/30`},yS={segment:`bg-type-segment shadow-type-segment/50`,milestone:`bg-type-milestone shadow-type-milestone/50`,completion:`bg-type-completion shadow-type-completion/50`,metric:`bg-type-metric shadow-type-metric/50`,system:`bg-muted-foreground/40`,event:`bg-type-event shadow-type-event/50`,group:`bg-type-group shadow-type-group/50`,load:`bg-muted-foreground/40`,compiler:`bg-muted-foreground/40`,analytics:`bg-type-analytics shadow-type-analytics/50`};function bS(e){if(!e)return{efforts:[],reps:[],loads:[],rounds:[],durations:[],distances:[],hints:[]};let t=Array.from(e);return{efforts:t.filter(e=>{let t=String(e.type).toLowerCase();return t===`effort`||t===`text`||t===`action`||t===`label`}),reps:t.filter(e=>String(e.type).toLowerCase()===`rep`),loads:t.filter(e=>{let t=String(e.type).toLowerCase();return t===`resistance`||t===`intensity`||t===`load`||t===`volume`}),rounds:t.filter(e=>{let t=String(e.type).toLowerCase();return t===`rounds`||t===`current-round`||t===`increment`}),durations:t.filter(e=>{let t=String(e.type).toLowerCase();return t===`duration`||t===`time`||t===`elapsed`}),distances:t.filter(e=>String(e.type).toLowerCase()===`distance`),hints:t.filter(e=>{let t=String(e.type).toLowerCase();return t===`hint`||t===`custom`||t===`system`||t===`sound`||t===`lap`||t===`group`})}}var xS=`type:segment`,SS=[{label:`All`,query:``},{label:`Segments`,query:`type:segment`},{label:`Events`,query:`type:event`}];function CS(e){if(typeof e==`object`&&e&&`label`in e&&`query`in e)return e;let t=String(e).trim(),n=t.toLowerCase();return n===`all`||n===``?{label:`All`,query:``}:n===`segments`||n===`segment`||n===`type:segment`?{label:`Segments`,query:`type:segment`}:n===`events`||n===`event`||n===`type:event`?{label:`Events`,query:`type:event`}:n===`milestones`||n===`milestone`||n===`type:milestone`?{label:`Milestones`,query:`type:milestone`}:{label:t,query:t}}function wS(e,t){let n=t.toLowerCase().trim();if(!n||n===`all`||n.startsWith(`sum:`)||n.startsWith(`avg:`)||n.startsWith(`count:`))return!0;let r=String(e.outputType||``).toLowerCase();if(n.startsWith(`type:`))return r.includes(n.slice(5).trim());let i=r.includes(n),a=e.sourceBlockKey?.toLowerCase().includes(n),o=e.completionReason?.toLowerCase().includes(n),s=e.metrics&&Array.from(e.metrics).some(e=>{let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value??``);return String(e.type).toLowerCase().includes(n)||t.toLowerCase().includes(n)});return!!(i||a||o||s)}function TS({presets:e,filter:t,onChange:n}){return(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>(0,W.jsx)(`button`,{onClick:()=>n(e.query),"data-testid":`output-filter-preset-${e.label.toLowerCase().replace(/\s+/g,`-`)}`,className:`rounded-lg border px-2.5 py-1 font-mono text-[11px] cursor-pointer transition-all ${t===e.query||e.query===``&&t===``?`border-primary bg-primary/10 text-primary font-bold shadow-xs`:`border-border/70 bg-card text-foreground hover:bg-accent`}`,children:e.label},e.label))})}function ES({rows:e,outputs:t,t0:n,onClearFilter:r}){if(e.length===0){let e=t.length>0;return(0,W.jsxs)(`div`,{className:`rounded-xl border border-dashed border-border/70 bg-card/40 p-6 text-center`,"data-testid":`output-statements-empty`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`No output statements match the current filter.`:`No output statements recorded for this run.`}),e&&r&&(0,W.jsx)(`button`,{type:`button`,onClick:r,className:`mt-3 inline-flex cursor-pointer rounded-md border border-border bg-background px-3 py-1 text-[11px] font-semibold text-foreground shadow-xs transition-colors hover:bg-accent`,children:`Clear filter`})]})}return(0,W.jsx)(`ol`,{className:`flex flex-col`,"data-testid":`output-statements-cards`,children:e.map((t,r)=>{let i=bS(t.metrics),a=t.timeSpan?.started,o=t.timeSpan?.ended,s=o!==void 0&&a!==void 0?pS(o-a):`running`,c=a!==void 0&&n!==void 0?`+${pS(a-n)}`:`+00:00`,l=String(t.outputType),u=`#${t.id??r+1} · Block: ${t.sourceBlockKey||`session`}${t.completionReason?` · Reason: ${t.completionReason}`:``}`,d=[...i.reps,...i.loads,...i.rounds,...i.durations,...i.distances],f=d.length>0;return(0,W.jsxs)(`li`,{className:`relative pb-3 pl-6 last:pb-0`,title:u,children:[r<e.length-1&&(0,W.jsx)(`span`,{"aria-hidden":!0,className:`absolute bottom-0 left-[5px] top-5 w-px bg-border/60`}),(0,W.jsx)(`span`,{"aria-hidden":!0,title:`Type: ${t.outputType} | ${u}`,className:`absolute left-0 top-1.5 size-2.5 rounded-full shadow-md ring-2 ring-background ${yS[l]??yS.system}`}),(0,W.jsxs)(`article`,{className:`rounded-xl border border-border/60 bg-card px-3 py-2.5`,children:[(0,W.jsxs)(`header`,{className:`flex items-start justify-between gap-2 border-b border-border/40 pb-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1`,children:[(0,W.jsx)(`span`,{className:`inline-block shrink-0 rounded px-1.5 py-0.2 text-[9px] font-bold uppercase tracking-wider ${vS[l]??vS.system}`,children:String(t.outputType??`system`).slice(0,4)}),_S(i.efforts)]}),(0,W.jsxs)(`div`,{className:`whitespace-nowrap text-right font-mono text-[11px] tabular-nums leading-tight`,children:[(0,W.jsx)(`span`,{className:`font-bold text-primary`,children:c}),` `,(0,W.jsxs)(`span`,{className:`text-[10px] text-muted-foreground/80`,children:[`(`,s,`)`]})]})]}),f&&(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1 pt-1.5`,children:_S(d)}),i.hints.length>0&&(0,W.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-1 border-t border-border/30 pt-1.5`,children:_S(i.hints)}),!f&&i.hints.length===0&&(0,W.jsx)(`p`,{className:`pt-1.5 text-[11px] text-muted-foreground/60`,children:`No metrics on this statement`})]})]},t.id??r)})})}function DS({outputs:e,filter:t=``,timeOrigin:n,onClearFilter:r}){let i=n??(e.length>0?e[0].timeSpan?.started:void 0),a=(0,U.useMemo)(()=>t.trim()?e.filter(e=>wS(e,t)):e,[e,t]);return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`sm:hidden`,children:(0,W.jsx)(ES,{rows:a,outputs:e,t0:i,onClearFilter:r})}),(0,W.jsx)(`div`,{className:`hidden overflow-x-auto rounded-md border border-border/50 bg-background/40 sm:block`,children:(0,W.jsxs)(`table`,{className:`w-full text-left font-mono text-xs border-collapse`,"data-testid":`output-statements-table`,children:[(0,W.jsx)(`thead`,{children:(0,W.jsxs)(`tr`,{className:`border-b border-border/60 bg-muted/40 text-[10px] uppercase font-bold text-muted-foreground tracking-wider whitespace-nowrap`,children:[(0,W.jsx)(`th`,{className:`p-2 w-12 text-center`,children:`Type`}),(0,W.jsx)(`th`,{className:`p-2 min-w-[110px]`,children:`Time`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[140px]`,children:`🏃 Movement`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[60px]`,children:`🔢 Reps`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[70px]`,children:`💪 Load`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[80px]`,children:`🔄 Rounds`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[70px]`,children:`⏱️ Target`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[70px]`,children:`📏 Distance`}),(0,W.jsx)(`th`,{className:`p-2 font-sans min-w-[110px]`,children:`🏷️ Hints`})]})}),(0,W.jsx)(`tbody`,{className:`divide-y divide-border/40`,children:a.length===0?(0,W.jsx)(`tr`,{children:(0,W.jsx)(`td`,{colSpan:9,className:`p-8 text-center text-muted-foreground font-sans text-xs`,children:e.length===0?`No output statements recorded for this run.`:`No output statements match the current filter.`})}):a.map((e,t)=>{let n=bS(e.metrics),r=e.timeSpan?.started,a=e.timeSpan?.ended,o=a!==void 0&&r!==void 0?pS(a-r):`running`,s=mS(new Date(a??r??0)),c=r!==void 0&&i!==void 0?`+${pS(r-i)}`:`+00:00`,l=`#${e.id??t+1} · Block: ${e.sourceBlockKey||`session`}${e.completionReason?` · Reason: ${e.completionReason}`:``}`,u=e=>(0,W.jsx)(`td`,{className:`p-2 font-sans`,children:e.length>0?(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:_S(e)}):(0,W.jsx)(`span`,{className:`text-muted-foreground/30 font-mono text-[11px] select-none`,children:`—`})});return(0,W.jsxs)(`tr`,{title:l,className:`hover:bg-muted/30 transition-colors group cursor-default`,children:[(0,W.jsx)(`td`,{className:`p-2 text-center whitespace-nowrap`,children:(0,W.jsx)(`span`,{className:`inline-block rounded px-1.5 py-0.2 text-[9px] font-bold uppercase tracking-wider ${vS[String(e.outputType)]??vS.system}`,title:`Type: ${e.outputType} | ${l}`,children:String(e.outputType??`system`).slice(0,4)})}),(0,W.jsxs)(`td`,{className:`p-2 whitespace-nowrap leading-tight`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 font-mono text-[11px]`,children:[(0,W.jsx)(`span`,{className:`font-bold text-primary tabular-nums`,children:c}),(0,W.jsxs)(`span`,{className:`text-[10px] text-muted-foreground/80 tabular-nums`,children:[`(`,o,`)`]})]}),(0,W.jsx)(`div`,{className:`font-mono text-[10px] text-muted-foreground/70 tabular-nums`,children:s})]}),u(n.efforts),u(n.reps),u(n.loads),u(n.rounds),u(n.durations),u(n.distances),u(n.hints)]},e.id??t)})})]})})]})}function OS(e){return new Date(e.timestamp).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`})}function kS({result:e,renderRunHeaderExtra:t,presets:n,filter:r,onFilterChange:i}){let[a,o]=(0,U.useState)(xS),s=r??a,c=i??o,l=(0,U.useMemo)(()=>(n??SS).map(CS),[n]),u=(0,U.useMemo)(()=>e.runs.map(e=>({run:e,statements:e.events,startTime:e.events[0]?.timeSpan?.started??e.timestamp})),[e]);return u.length===0?(0,W.jsx)(`div`,{className:`flex items-center justify-center text-sm text-muted-foreground px-4 py-6 text-center`,children:`No workout logs matched this rows query.`}):(0,W.jsxs)(`div`,{"data-testid":`rows-table`,className:`flex flex-col gap-3`,children:[(0,W.jsx)(TS,{presets:l,filter:s,onChange:c}),u.map(({run:e,statements:n,startTime:r})=>(0,W.jsxs)(`section`,{children:[u.length>1&&(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-[11px] font-semibold text-muted-foreground px-2 py-1.5 bg-muted/40 rounded-t-md border-b border-border/60`,children:[(0,W.jsx)(`span`,{children:OS(e)}),t?.(e)]}),(0,W.jsx)(DS,{outputs:n,filter:s,timeOrigin:r})]},e.resultId))]})}var AS=Array.from({length:10},(e,t)=>t+1);function jS(e){if(e){for(let t of e)for(let e of t.metrics)if((e.type===q.SessionRPE||e.type===`session_rpe`)&&typeof e.value==`number`)return e.value}}function MS({resultId:e,events:t,readOnly:n,onCapture:r}){let i=jS(t),[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(!1);if(n)return i===void 0?null:(0,W.jsxs)(`span`,{className:`text-[10px] font-mono text-muted-foreground`,"data-testid":`rpe-readonly-${e}`,children:[`RPE `,i]});let l=async e=>{c(!0);try{await r(e),o(!1)}finally{c(!1)}};return(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,"data-testid":`rpe-chip-${e}`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),className:mx(`text-[10px] font-mono px-1.5 py-0.5 rounded border transition-colors`,i===void 0?`border-dashed border-muted-foreground/50 text-muted-foreground hover:text-foreground hover:border-primary`:`border-border text-foreground hover:border-primary`),title:i===void 0?`Rate this session’s effort`:`Update session RPE`,children:i===void 0?`RPE —`:`RPE ${i}`}),a&&(0,W.jsx)(`span`,{className:`inline-flex gap-0.5`,"data-testid":`rpe-scale-${e}`,children:AS.map(e=>(0,W.jsx)(`button`,{type:`button`,disabled:s,onClick:()=>void l(e),"aria-label":`RPE ${e}`,className:mx(`h-5 min-w-[1.25rem] px-0.5 text-[10px] font-medium rounded border border-border`,e===i&&`bg-primary text-primary-foreground`,e<=3&&`hover:bg-rpe-easy/15 hover:text-rpe-easy`,e>3&&e<=6&&`hover:bg-rpe-moderate/15 hover:text-rpe-moderate`,e>6&&e<=8&&`hover:bg-rpe-hard/15 hover:text-rpe-hard`,e>8&&`hover:bg-rpe-max/15 hover:text-rpe-max`),children:e},e))})]})}function NS({resultId:e,sessionResult:t,executor:n,onCaptureRpe:r,onCaptured:i}){let[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(void 0),l=t.runs[0],u=l?.events[0]?.blockContentId,d=(0,U.useCallback)(async t=>{r&&await r(e,t),i?.()},[e,r,i]);(0,U.useEffect)(()=>{if(!a||!u||!n){c(void 0);return}let e=!1,t=X(`:session{block:${u}}`);if(bm(t))return(n.runFind?n.runFind(t):n.runRows(t)).then(t=>{e||c(t)}).catch(()=>{e||c(void 0)}),()=>{e=!0}},[a,u,n]);let f=a&&s?s:t,p=s?.runs.length??(a?1:void 0),m=!!u;return(0,W.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":`rows-results-chrome`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-2 pb-2 border-b border-border/60 text-xs`,children:[(0,W.jsxs)(`div`,{className:`inline-flex items-center rounded-md border border-border bg-muted/40 p-0.5`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:()=>o(!1),className:mx(`px-2 py-0.5 rounded text-[11px] font-medium transition-colors`,a?`text-muted-foreground hover:text-foreground`:`bg-background text-foreground shadow-sm`),children:`This session`}),(0,W.jsxs)(`button`,{type:`button`,disabled:!m,onClick:()=>o(!0),title:m?void 0:`No block content association for this run`,className:mx(`px-2 py-0.5 rounded text-[11px] font-medium transition-colors`,a?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`,!m&&`opacity-40 cursor-not-allowed`),children:[`All versions`,p===void 0?``:` (${p})`]})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(`a`,{href:`/results/${encodeURIComponent(e)}`,className:`text-[11px] font-medium text-primary hover:underline inline-flex items-center gap-0.5`,"data-testid":`view-in-results-link`,children:`View in Results →`}),(0,W.jsx)(MS,{resultId:e,events:l?.events,onCapture:d})]})]}),(0,W.jsx)(kS,{result:f,renderRunHeaderExtra:t=>t.resultId===e?(0,W.jsx)(MS,{resultId:e,events:t.events,onCapture:d}):(0,W.jsx)(MS,{resultId:t.resultId,events:t.events,readOnly:!0,onCapture:d})})]})}var PS=/^(\s*query\s*:\s*)(['"]?)(.*?)\2(\s*)$/;function FS(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function IS(e){let t=e.split(`
59
+ `),n=[];for(let e=0;e<t.length;e++){let r=t[e].match(PS);r&&n.push({queryIndex:n.length,query:FS(r[3]),isYamlKey:!0,lineIndex:e})}if(n.length>0)return n;let r=[];for(let e=0;e<t.length;e++){let n=t[e].trim();!n||n.startsWith(`#`)||n.startsWith(`//`)||r.push({queryIndex:r.length,query:n,isYamlKey:!1,lineIndex:e})}return r}function LS(e,t,n=0){let r=IS(e).find(e=>e.queryIndex===n);if(!r)return e;let i=e.split(`
60
+ `),a=i[r.lineIndex];if(r.isYamlKey){let e=a.match(PS);if(e){let n=e[1],a=e[2],o=e[4];i[r.lineIndex]=`${n}${a}${t}${a}${o}`}else i[r.lineIndex]=`query: ${t}`}else{let e=a.match(/^\s*/)?.[0]??``;i[r.lineIndex]=`${e}${t}`}return i.join(`
61
+ `)}var RS=e(Yn(),1);function zS(){if(typeof window>`u`||!window.visualViewport)return{height:null,offsetTop:0,offsetBottom:0};let e=window.visualViewport;return{height:e.height,offsetTop:e.offsetTop,offsetBottom:Math.max(0,window.innerHeight-e.height-e.offsetTop)}}function BS(){let[e,t]=(0,U.useState)(zS);return(0,U.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let n=()=>t(zS());return e.addEventListener(`resize`,n),e.addEventListener(`scroll`,n),()=>{e.removeEventListener(`resize`,n),e.removeEventListener(`scroll`,n)}},[]),e}var VS=`a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function HS({open:e,onClose:t,title:n,description:r,children:i,footer:a,presentation:o=`default`}){let s=(0,U.useId)(),c=(0,U.useId)(),l=(0,U.useRef)(null),u=(0,U.useRef)(null),d=BS(),f=o===`sheet`;if((0,U.useEffect)(()=>{if(!e)return;u.current=document.activeElement;let t=document.body.style.overflow;document.body.style.overflow=`hidden`;let n=requestAnimationFrame(()=>{let e=l.current;e&&(f?e:e.querySelector(`[data-autofocus]`)??e).focus()});return()=>{cancelAnimationFrame(n),document.body.style.overflow=t;let e=u.current;e instanceof HTMLElement&&document.contains(e)&&e.focus()}},[e,f]),!e||typeof document>`u`)return null;let p=e=>{if(e.key===`Escape`){e.stopPropagation(),t();return}if(e.key!==`Tab`)return;let n=l.current;if(!n)return;let r=Array.from(n.querySelectorAll(VS));if(r.length===0){e.preventDefault(),n.focus();return}let i=r[0],a=r[r.length-1],o=document.activeElement;e.shiftKey&&(o===i||!n.contains(o))?(e.preventDefault(),a.focus()):!e.shiftKey&&o===a&&(e.preventDefault(),i.focus())},m={top:d.offsetTop,height:d.height??`100dvh`};return(0,RS.createPortal)((0,W.jsx)(`div`,{className:mx(`fixed left-0 right-0 z-50 flex flex-col bg-black/40 dark:bg-black/60 sm:items-center sm:justify-center sm:bg-background/80 sm:p-4 sm:backdrop-blur-sm`,f&&`max-sm:justify-end`),style:m,onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,W.jsxs)(`div`,{ref:l,role:`dialog`,"aria-modal":`true`,"aria-labelledby":s,"aria-describedby":r?c:void 0,tabIndex:-1,onKeyDown:p,className:mx(`flex min-h-0 w-full flex-col overflow-hidden bg-card outline-none sm:max-h-full sm:max-w-2xl sm:flex-none sm:rounded-xl sm:border sm:border-border sm:shadow-2xl`,f?`max-sm:flex-none max-sm:min-h-[66%] max-sm:max-h-full max-sm:rounded-t-2xl`:`flex-1 sm:max-h-full`),children:[f&&(0,W.jsx)(`div`,{"aria-hidden":!0,className:`flex justify-center pt-2 sm:hidden`,children:(0,W.jsx)(`div`,{className:`h-1 w-10 rounded-full bg-border`})}),(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b border-border/80 px-4 py-3 sm:px-6 sm:py-4`,children:[(0,W.jsxs)(`div`,{className:`min-w-0`,children:[(0,W.jsx)(`h2`,{id:s,className:`text-base font-semibold text-foreground`,children:n}),r&&(0,W.jsx)(`p`,{id:c,className:`mt-0.5 text-xs text-muted-foreground`,children:r})]}),(0,W.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`flex size-11 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground sm:size-9`,children:(0,W.jsx)($t,{className:`size-5 sm:size-4`})})]}),(0,W.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-4 py-4 sm:px-6`,children:i}),a&&(0,W.jsx)(`div`,{className:mx(`border-t border-border/80 bg-muted/10 px-4 py-3 sm:px-6`,f?`max-sm:[&_button]:min-h-12 max-sm:[&_button]:min-w-11`:`max-sm:[&_button]:min-h-11 max-sm:[&_button]:min-w-11`,f&&`max-sm:pb-[max(0.75rem,env(safe-area-inset-bottom))]`),children:a})]})}),document.body)}var US=new class{slots=new Map;listeners=new Set;cachedList=[];registerSlot(e){return this.slots.set(e.type,e),this.cachedList=Array.from(this.slots.values()),this.notify(),()=>this.unregisterSlot(e.type)}unregisterSlot(e){this.slots.delete(e)&&(this.cachedList=Array.from(this.slots.values()),this.notify())}getSlot(e){return this.slots.get(e)}listSlots(){return this.cachedList}getAllSlots(){return this.cachedList}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){for(let e of this.listeners)e()}};function WS(e=US){let t=(0,U.useSyncExternalStore)(t=>e.subscribe(t),()=>e.listSlots());return(0,U.useMemo)(()=>t,[t])}var GS=[{value:`find`,label:`Find`,description:`Find things: notes, blocks, efforts, sessions, tables`},{value:`aggregate`,label:`Measure`,description:`Measure numbers: aggregate a metric by dimensions`}],KS=Pp.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1),description:{note:`Find notes across journal, notebooks and playground`,block:`Find fenced workout/dashboard regions`,effort:`Find registered movements and benchmarks`,session:`Find completed workout sessions`,segment:`Cross-workout segment table`,event:`Telemetry events table`}[e]})),qS=Fp.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1),description:{journal:`Daily journal notes`,feeds:`Notebook notes`,guides:`Static guide pages`,playground:`Playground scratch pages`,dashboards:`Dashboard notes`,efforts:`Exercise library notes`,equipment:`Equipment library notes`}[e]})),JS=Up.map(e=>({value:e,label:e})),YS=[{value:`last 1d`,label:`Past 24 hours`},{value:`last 1w`,label:`Past week`},{value:`last 2w`,label:`Past 2 weeks`},{value:`last 4w`,label:`Past month`},{value:`last 12w`,label:`Past quarter`},{value:`last 52w`,label:`Past year`},{value:`all`,label:`All time`}],XS=Tp.map(e=>({value:e,label:e})),ZS=[{value:`2d`,label:`2 days`},{value:`7d`,label:`7 days`},{value:`14d`,label:`14 days`},{value:`2w`,label:`2 weeks`},{value:`4w`,label:`4 weeks`},{value:`12w`,label:`12 weeks`},{value:`26w`,label:`26 weeks`},{value:`52w`,label:`52 weeks`}],QS=[...Ap,...Dp].map(e=>({value:e,label:e})),$S=[...wp,...Cp,...jp].map(e=>({value:e,label:e})),eC=Gp.map(e=>({value:e,label:e}));[...wp,...Cp,...jp];var tC={source:!0,time:!0},nC={kind:{label:`Kind`,inputType:`radio`,placeholder:`find, measure…`,placeholderText:`Find | Measure`,icon:`🧭`,description:`Find things or measure numbers`},target:{label:`Find`,inputType:`select`,placeholder:`note, block, effort…`,placeholderText:`: [target]`,icon:`🎯`,description:`What to find — singular`,prefix:`:`},source:{label:`Where stored`,inputType:`select`,placeholder:`journal, notebooks…`,placeholderText:`source: [scope]`,icon:`🌐`,description:`Storage scope — all sources means no scope`,prefix:`source:`},text:{label:`Contains`,inputType:`freetext`,placeholder:`Text query...`,placeholderText:`text: [query]`,icon:`🔍`,description:`Raw text substring search`,prefix:`text:`},catalog:{label:`Catalog`,inputType:`select`,placeholder:`crossfit-games, hyrox...`,placeholderText:`catalog: [directory-id]`,icon:`📓`,description:`Filter by catalog directory id, e.g. crossfit-games`,prefix:`catalog:`},notebook:{label:`Notebook`,inputType:`select`,placeholder:`Pick notebook...`,placeholderText:`notebook: [id]`,icon:`📓`,description:`Filter by canonical notebook container id, e.g. notebook/journal, notebook/playground, notebook/guides`,prefix:`notebook:`},tag:{label:`Tag`,inputType:`select`,placeholder:`Pick tag...`,placeholderText:`tags: [tag]`,icon:`🏷`,description:`Filter by note/workout tags`,prefix:`tags:`},effort:{label:`Effort`,inputType:`select`,placeholder:`Pick effort...`,placeholderText:`effort: [movement]`,icon:`💪`,description:`Filter by movement/workout`,prefix:`effort:`},domain:{label:`Domain`,inputType:`select`,placeholder:`crossfit, parkour, swimming…`,placeholderText:`domain: [discipline]`,icon:`🌐`,description:`Filter by sport/training domain`,prefix:`domain:`},format:{label:`Format`,inputType:`select`,placeholder:`for-time, amrap, emom…`,placeholderText:`format: [shape]`,icon:`⏱`,description:`Filter by session time structure`,prefix:`format:`},equipment:{label:`Equipment`,inputType:`select`,placeholder:`kettlebell, barbell…`,placeholderText:`equipment: [gear]`,icon:`🏋`,description:`Filter by required gear`,prefix:`equipment:`},quality:{label:`Quality`,inputType:`select`,placeholder:`strength, conditioning…`,placeholderText:`quality: [stimulus]`,icon:`⚡`,description:`Filter by physical stimulus`,prefix:`quality:`},intent:{label:`Intent`,inputType:`select`,placeholder:`benchmark, competition…`,placeholderText:`intent: [tier]`,icon:`🎯`,description:`Filter by protocol status`,prefix:`intent:`},discipline:{label:`Discipline`,inputType:`select`,placeholder:`Pick discipline...`,placeholderText:`discipline: [name]`,icon:`⚙`,description:`Filter by domain discipline`,prefix:`discipline:`},intensity:{label:`Intensity`,inputType:`select`,placeholder:`low, moderate, high…`,placeholderText:`intensity: [tier]`,icon:`🔥`,description:`Effort intensity tier`,prefix:`intensity:`},origin:{label:`Origin`,inputType:`select`,placeholder:`bundled, user…`,placeholderText:`origin: [registry]`,icon:`🔖`,description:`Effort registry origin`,prefix:`origin:`},type:{label:`Block Type`,inputType:`select`,placeholder:`wod, dashboard...`,placeholderText:`type: [wod|heading]`,icon:`📦`,description:`Fenced block type`,prefix:`type:`},time:{label:`Time Window`,inputType:`select`,placeholder:`Time range`,placeholderText:`last: [time range]`,icon:`⏱`,description:`Date window (last Nw/Nd)`,prefix:`last:`},where:{label:`Metric Join`,inputType:`freetext`,placeholder:`sum:totalVolume{} > 5000`,placeholderText:`where: [metric join]`,icon:`📊`,description:`Cross-store analytics join`,prefix:`where:`},agg:{label:`Aggregate`,inputType:`select`,placeholder:`sum, avg…`,placeholderText:`agg: [sum|avg|…]`,icon:`∑`,description:`Aggregation function`},metric:{label:`Metric`,inputType:`select`,placeholder:`totalVolume, reps…`,placeholderText:`metric: [key]`,icon:`📈`,description:`Canonical metric key to aggregate`},groupby:{label:`Group By`,inputType:`select`,placeholder:`week, effort…`,placeholderText:`by: [dim]`,icon:`🗂`,description:`Group results by dimension`},rollup:{label:`Rollup`,inputType:`select`,placeholder:`2w, 4w, 12w…`,placeholderText:`rollup: [period]`,icon:`🗓`,description:`Multi-unit bucket period (by {week}/by {day} for 1-unit)`},unit:{label:`Unit`,inputType:`select`,placeholder:`kg, lb, km…`,placeholderText:`in: [unit]`,icon:`📏`,description:`Display unit directive`},result:{label:`Session`,inputType:`freetext`,placeholder:`result id…`,placeholderText:`result: [id]`,icon:`🏁`,description:`Scope to one workout session`,prefix:`result:`},block:{label:`Block`,inputType:`freetext`,placeholder:`block content id…`,placeholderText:`block: [contentId]`,icon:`🧱`,description:`Scope to all versions of a block`,prefix:`block:`},note:{label:`Note`,inputType:`freetext`,placeholder:`note id…`,placeholderText:`note: [id]`,icon:`📓`,description:`Scope to one note`,prefix:`note:`},page:{label:`Page`,inputType:`select`,placeholder:`true, false…`,placeholderText:`page: [true|false]`,icon:`📄`,description:`Notes that are (or are not) pages`,prefix:`page:`},plane:{label:`Output Plane`,inputType:`select`,placeholder:`segment, load, event…`,placeholderText:`plane: [type]`,icon:`📋`,description:`Output-statement plane on :session`,prefix:`plane:`},pipes:{label:`Pipes`,inputType:`freetext`,placeholder:`| order by date | limit 10`,placeholderText:`| select | order | limit`,icon:`⇥`,description:`Presentation pipes — select/order/limit/offset`}},rC=`🧩`;function iC(e){let t=nC[e];if(t)return t;let n=US.getSlot(e);return n?{label:n.label,inputType:`freetext`,placeholder:n.placeholder,placeholderText:n.placeholderText,icon:n.icon,description:n.description??``}:{label:e,inputType:`freetext`,placeholder:`${e}...`,placeholderText:`${e}: [value]`,icon:rC,description:``}}function aC({clause:e,isActive:t,invalid:n=!1,invalidReason:r,onClick:i,onRemove:a,compact:o=!1,placeholderOverride:s}){let c=iC(e.type),l=!!(e.value&&e.value.trim()),u=tC[e.type]?`Clear ${c.label}`:`Remove ${c.label}`;return(0,W.jsxs)(`span`,{className:`relative inline-flex items-center`,children:[(0,W.jsxs)(`button`,{type:`button`,"data-testid":`token-slot-${e.type}`,onClick:i,"aria-pressed":t||void 0,title:n?r:void 0,className:mx(`inline-flex items-center gap-1 rounded-full text-xs font-mono transition-all cursor-pointer select-none border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring hover:font-bold hover:scale-[1.02]`,`min-h-11 min-w-11`,n?`bg-destructive/10 text-destructive border-destructive/40 hover:bg-destructive/20`:t?`bg-primary text-primary-foreground border-primary font-medium shadow-sm`:l?`bg-muted/80 text-foreground border-border hover:bg-muted`:`bg-muted/40 text-muted-foreground border-dashed border-border hover:bg-muted/60`,o?`px-2 py-0.5 text-[11px]`:`px-2.5 py-1`),children:[(0,W.jsx)(`span`,{className:`text-[10px] opacity-70`,children:c.icon}),t&&(0,W.jsxs)(`span`,{className:`font-semibold text-[11px] opacity-90`,children:[c.label,`:`]}),(0,W.jsx)(`span`,{"data-testid":`token-slot-value-${e.type}`,className:mx(`truncate max-w-44`,!l&&`italic opacity-60`),children:l?e.value:s||c.placeholder})]}),a&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`token-slot-remove-${e.type}`,onClick:a,"aria-label":u,title:u,className:mx(`inline-flex items-center justify-center -ml-0.5 p-1 rounded-full transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,n?`text-destructive/70 hover:text-destructive`:`text-inherit opacity-70 hover:opacity-100 hover:bg-black/10`,`min-h-11 min-w-11`),children:(0,W.jsx)($t,{className:`w-3 h-3`})})]})}function oC(e,t){return e?`${e}-option-${t}`:void 0}function sC({clause:e,filteredItems:t,selectedValues:n,isMulti:r,typedValue:i,canCommitTyped:a,emptyText:o,highlightIdx:s,onHighlight:c,onCommitValue:l,onCommitTyped:u,listId:d,onDone:f,onReorder:p}){let m=iC(e.type),h=e.value.trim(),g=t.length,_=n.length>0?n:!r&&h?[h]:[],v=(e,t)=>{if(!p)return;let r=e+t;if(r<0||r>=n.length)return;let i=[...n];[i[e],i[r]]=[i[r],i[e]],p(i)};return(0,W.jsxs)(`div`,{className:`mx-0.5 rounded-xl border border-border bg-popover shadow-md p-1`,"data-testid":`wql-clause-editor`,"data-clause-type":e.type,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-2 pt-1 pb-1.5`,children:[(0,W.jsx)(`span`,{"aria-hidden":!0,className:`text-[11px]`,children:m.icon}),(0,W.jsx)(`span`,{className:`text-xs sm:text-[11px] font-semibold text-foreground font-mono`,children:m.label}),(0,W.jsxs)(`span`,{className:`hidden sm:block ml-auto text-[10px] text-muted-foreground/70 font-mono truncate`,children:[`↑↓ move · Enter `,r?`add/remove`:`set`,` · Esc done · Tab exits`]})]}),_.length>0&&(0,W.jsxs)(`div`,{className:mx(`px-2 pb-1.5`,r&&`border-b border-border/50`),children:[(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1.5 sm:gap-1 max-h-24 overflow-y-auto overscroll-contain touch-pan-y sm:max-h-none sm:overflow-visible`,children:_.map((e,t)=>(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-primary/20 text-primary text-xs sm:text-[10px] font-mono min-h-11 sm:min-h-0`,children:[(0,W.jsx)(`span`,{className:`max-w-40 truncate`,children:e}),p&&_.length>1&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`button`,{type:`button`,"aria-label":`Move ${e} up`,disabled:t===0,onClick:()=>v(t,-1),className:`px-0.5 hover:text-foreground disabled:opacity-30 min-h-11 min-w-11 sm:min-h-5 sm:min-w-5`,children:(0,W.jsx)(ur,{className:`w-3 h-3`})}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Move ${e} down`,disabled:t===_.length-1,onClick:()=>v(t,1),className:`px-0.5 hover:text-foreground disabled:opacity-30 min-h-11 min-w-11 sm:min-h-5 sm:min-w-5`,children:(0,W.jsx)(Ie,{className:`w-3 h-3`})})]}),r&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>l(e),"aria-label":`Remove ${e}`,className:`hover:text-destructive min-h-11 min-w-11 sm:min-h-5 sm:min-w-5 -mr-1.5 sm:-mr-1`,children:(0,W.jsx)($t,{className:`w-2.5 h-2.5`})})]},e))}),r&&(0,W.jsx)(`p`,{className:`pt-1 text-xs sm:text-[10px] text-muted-foreground`,"data-testid":`wql-clause-editor-multi-hint`,children:e.type===`groupby`?`Group in this order.`:`Match any selected value (OR).`})]}),(0,W.jsxs)(`div`,{id:d,role:`listbox`,"aria-label":`${m.label} options`,"aria-multiselectable":r||void 0,className:`max-h-[min(45svh,20rem)] sm:max-h-44 overflow-y-auto overscroll-contain touch-pan-y flex flex-col gap-0.5`,children:[a&&(0,W.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":!1,id:oC(d,g),"data-active":s===g||void 0,onMouseEnter:()=>c(g),onClick:()=>u(i),"data-testid":`clause-commit-typed-${e.type}`,className:mx(`flex items-center justify-between px-2 py-2 sm:py-1 text-sm sm:text-xs text-left rounded hover:bg-muted/60 transition-colors font-mono min-h-12 sm:min-h-0`,s===g&&`bg-muted/60`),children:[(0,W.jsxs)(`span`,{className:`truncate`,children:[`Search for `,(0,W.jsxs)(`span`,{className:`font-semibold`,children:[`“`,i,`”`]})]}),(0,W.jsx)(`span`,{className:`text-muted-foreground/60 ml-1 shrink-0`,children:`↵`})]}),t.map((t,i)=>{let a=n.includes(t.value)||!r&&h===t.value,o=i===s;return(0,W.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":a,id:oC(d,i),"data-active":o||void 0,"data-testid":`wql-clause-editor-${e.type}-opt-${i}`,onMouseEnter:()=>c(i),onClick:()=>l(t.value),className:mx(`flex items-center justify-between px-2 py-2 sm:py-1 text-sm sm:text-xs text-left rounded transition-colors font-mono min-h-12 sm:min-h-0`,o?`bg-primary/15 font-semibold`:`hover:bg-muted/60`,a&&`text-primary`),children:[(0,W.jsx)(`span`,{className:`truncate`,children:t.label}),a&&(0,W.jsx)(mr,{className:`w-3 h-3 shrink-0`})]},t.value)}),o&&(0,W.jsx)(`div`,{className:`px-2 py-2 sm:py-1.5 text-sm sm:text-xs text-muted-foreground italic`,children:o})]}),r&&f&&(0,W.jsx)(`div`,{className:`sticky bottom-0 -mx-1 -mb-1 px-3 pt-1.5 pb-[max(0.375rem,env(safe-area-inset-bottom))] bg-popover rounded-b-xl flex justify-end`,children:(0,W.jsxs)(`button`,{type:`button`,onClick:f,"data-testid":`wql-clause-editor-done`,className:`inline-flex w-full sm:w-auto items-center justify-center min-h-12 sm:min-h-9 px-3 rounded-lg bg-primary text-primary-foreground text-sm sm:text-xs font-semibold hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[`Done`,_.length>0?` · ${_.length} selected`:``]})})]})}var cC={tag:!0,catalog:!0,notebook:!0,effort:!0,domain:!0,format:!0,equipment:!0,quality:!0,intent:!0,discipline:!0,intensity:!0,origin:!0,type:!0,source:!0,groupby:!0},lC={kind:GS,target:KS,source:qS,plane:JS,time:YS,agg:XS,rollup:ZS,groupby:QS,metric:$S,unit:eC,intensity:Mp.map(e=>({value:e,label:e}))};function uC(e){let t=new Set;for(let n of e)if(n.sourceId&&n.sourceId.startsWith(`collection:`)){let e=Fg(n);e&&t.add(e)}return Array.from(t).sort((e,t)=>e.localeCompare(t))}function dC(e){let t=new Set;for(let n of e)n.dataType&&n.dataType.trim().length>0&&t.add(n.dataType.trim());return Array.from(t).sort((e,t)=>e.localeCompare(t))}function fC(e,t){return hC([...e,...t].map(e=>({value:e.trim()})),[]).map(e=>e.value)}var pC=[`wod`,`query`,`widget`,`embed`];function mC(e){return e.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1)}))}function hC(e,t){let n=e=>e.trim().toLowerCase(),r=new Map(t.map(e=>[n(e.value),e.value])),i=new Map,a=e=>{let t=n(e.value);!t||i.has(t)||i.set(t,{...e,value:r.get(t)??e.value})};for(let t of e)a(t);for(let e of t)a(e);return Array.from(i.values())}var gC={discipline:{load:async()=>mC(xc),cache:`static`,open:!1,emptyText:`No disciplines available`},catalog:{load:async()=>[],cache:`static`,open:!1,emptyText:`No catalogs in the static corpus`},notebook:{load:async()=>[],cache:`static`,open:!1,emptyText:`No notebooks in the static corpus`},intensity:{load:async()=>mC(Mp),cache:`static`,open:!1,emptyText:`No intensity tiers available`},type:{load:async()=>mC(pC),cache:`static`,open:!1,emptyText:`No indexed block types yet`}},_C={...gC},vC=new Set,yC=Object.keys(_C);function bC(e){return vC.add(e),()=>{vC.delete(e)}}function xC(){return(0,U.useSyncExternalStore)(bC,()=>yC)}function SC(e,t){t?_C[e]=t:gC[e]?_C[e]=gC[e]:delete _C[e],EC(e),yC=Object.keys(_C);for(let e of vC)e()}function CC(e){return _C[e]}var wC=new Map;async function TC(e){let t=CC(e);if(!t)return[];let n=Date.now(),r=wC.get(e);if(r&&r.expiresAt>n)return r.items;try{let r=hC(await t.load(),[]),i=typeof t.cache==`object`?t.cache.ttlMs:1/0;return wC.set(e,{items:r,expiresAt:n+i}),r}catch{return r?r.items:[]}}function EC(e){e?wC.delete(e):wC.clear()}function DC(e){let t=CC(e),[n,r]=(0,U.useState)([]),[i,a]=(0,U.useState)(!!t);return(0,U.useEffect)(()=>{if(!t){r([]),a(!1);return}let n=!1;return a(!0),TC(e).then(e=>{n||(r(e),a(!1))}),()=>{n=!0}},[e,t]),{items:n,loading:i,binding:t}}function OC(e,t){let n=t.trim();if(e===`time`){if(n.toLowerCase()===`all`)return!0;if(!/^last\s+\d+[dw]$/i.test(n))return!1;let e=X(`:note ${n}`);return!e.error&&e.family===`find`&&e.window?.kind===`relative`}if(e===`rollup`){if(!/^\d+[dw]$/i.test(n))return!1;let e=X(`sum:tis{}.rollup(${n})`);return!e.error&&e.family===`aggregate`&&e.rollup!==void 0}if(e===`groupby`){if(!/^[a-zA-Z][\w-]*$/.test(n))return!1;let e=X(`sum:tis{} by {${n}}`);return!e.error&&e.family===`aggregate`&&e.groupBy?.includes(n)===!0}return!0}function kC(e,t,n){let r=e?.type??``,{items:i,loading:a,binding:o}=DC(r),s=lC[r],c=r in cC||!!o,l=e?.value?e.value.split(`|`).map(e=>e.trim()).filter(Boolean):[],u=n?.supportedValues!==void 0,d=u?n.supportedValues.map(e=>({value:e,label:e})):o?i.map(e=>({value:e.value,label:e.label??e.value})):s??i.map(e=>({value:e.value,label:e.label??e.value})),f=l.length>0&&l.every(e=>e.endsWith(`*`))?d.map(e=>e.value.endsWith(`*`)?e:{...e,value:`${e.value}*`}):d,p=new Set(f.map(e=>e.value.toLowerCase())),m=(u||s||o)&&!n?.dropSelected?l.filter(e=>!p.has(e.toLowerCase())).map(e=>({value:e,label:e})):[],h=m.length?[...f,...m]:f,g=t.trim().toLowerCase(),_=g?h.filter(e=>e.value.toLowerCase().includes(g)||e.label.toLowerCase().includes(g)):h,v=u?!1:!s||o?o?.open??!0:r===`metric`||r===`unit`||r===`time`||r===`rollup`,y=t.trim(),b=OC(r,y),x=y.length>0&&v&&b&&!h.some(e=>e.value.toLowerCase()===y.toLowerCase()),S=null;return _.length===0&&!x&&(S=a?`Loading…`:h.length===0?o?.emptyText??`Nothing here yet`:g?v?b?`No matches`:`No matches — not a valid ${iC(r).label.toLowerCase()} value`:`No matches — no such option`:`No options`),{isMulti:c,selectedValues:l,items:h,filteredItems:_,typedValue:y,canCommitTyped:x,loading:a,openSlot:v,hasFilterInput:!0,emptyText:S}}function AC(e){let t=e.filters.find(e=>e.key===`source`),n=t?t.values.map(e=>e.value).join(`,`):`all`;return{target:e.target,scope:n,timeWindow:e.window?e.window.kind===`relative`?`last ${e.window.size}${e.window.unit}`:`from ${e.window.start}${e.window.end?` to ${e.window.end}`:``}`:void 0,groupBy:e.groupBy?.length?e.groupBy.join(`, `):void 0,hasJoin:!!e.join,filterCount:e.filters.length}}function jC(e){return{agg:e.agg,metric:e.metric,groupBy:e.groupBy.length>0?e.groupBy.join(`, `):void 0,rollup:e.rollup?`${e.rollup.size}${e.rollup.unit}`:void 0,unit:e.displayUnit,hasJoin:!!e.join,filterCount:e.filters.length}}function MC(e){return e.kind===`dataset`?e.name:`target`in e.query?`:${e.query.target}`:`:${e.query.agg}`}function NC(e){let t=e.source.kind===`query`?e.source.query:void 0;return{source:MC(e.source),functions:e.transforms.map(e=>`${e.agg}:${e.metric}`),sink:e.sink?`:${e.sink.head}`:void 0,timeWindow:t?.window?t.window.kind===`relative`?`last ${t.window.size}${t.window.unit}`:`from ${t.window.start}${t.window.end?` to ${t.window.end}`:``}`:void 0,filterCount:t?t.filters.length:0}}function PC({label:e,value:t,testId:n,warnTitle:r}){let i=n.startsWith(`diag-`)?n.replace(`diag-`,`wql-`):n;return(0,W.jsxs)(`span`,{"data-testid":n,title:r,className:`inline-flex items-center gap-1 whitespace-nowrap`,children:[(0,W.jsxs)(`span`,{className:`opacity-60`,children:[e,`:`]}),(0,W.jsx)(`span`,{"data-testid":i,className:mx(`font-semibold`,r&&`text-signal-caution underline decoration-wavy underline-offset-2`),children:t})]})}function FC({diagnostics:e,offendingLabel:t,stages:n,hideSummary:r=!1,variant:i=`card`,actions:a,className:o}){let{valid:s,ast:c,error:l}=e,u=i===`header`,d=c.advisories??[],f=new Set(Sm(c)?[]:am(c.family===`find`?c.target:``,c.family)),p=Sm(c)?[]:(c.groupBy??[]).filter(e=>!f.has(e)),m=s&&(d.length>0||p.length>0),h=d[0]??`Unsupported grouping: ${p.join(`, `)}`;return(0,W.jsxs)(`div`,{"data-testid":`wql-diagnostics-strip`,"aria-live":`polite`,className:mx(`flex flex-wrap items-center justify-between gap-x-4 gap-y-1.5 px-3 py-1.5 text-xs font-mono transition-colors`,u?s?`border-b border-primary/30 text-muted-foreground`:`border-b border-destructive/50 bg-destructive/5 text-destructive`:mx(`rounded-lg border`,s?`bg-muted/30 border-border text-muted-foreground`:`bg-destructive/5 border-destructive/30 text-destructive`),o),children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,W.jsx)(`div`,{className:`flex items-center gap-1.5 font-medium`,"data-testid":`wql-validity-badge`,"data-valid":s,"data-warning":m||void 0,role:s?`status`:`alert`,"aria-live":`polite`,children:s?m?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(vt,{className:`w-3.5 h-3.5 text-signal-caution shrink-0`}),(0,W.jsx)(`span`,{className:`text-signal-caution`,children:`Warning`}),(0,W.jsx)(`span`,{className:`opacity-80`,children:h})]}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(hn,{className:`w-3.5 h-3.5 text-signal-positive shrink-0`}),(0,W.jsx)(`span`,{className:`text-signal-positive`,children:`Valid`})]}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(Jt,{className:`w-3.5 h-3.5 text-destructive shrink-0`}),(0,W.jsx)(`span`,{children:`Invalid`}),(0,W.jsxs)(`span`,{children:[t?`${t}: `:``,l||`Syntax error`]})]})}),!r&&s&&bm(c)&&(0,W.jsx)(`div`,{className:`flex flex-wrap items-center gap-x-3 text-[11px] opacity-80 border-l border-border/50 pl-3`,children:(()=>{let e=AC(c);return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(PC,{label:`target`,value:e.target,testId:`diag-summary-target`}),(0,W.jsx)(PC,{label:`scope`,value:e.scope,testId:`diag-summary-scope`}),e.timeWindow&&(0,W.jsx)(PC,{label:`time`,value:e.timeWindow,testId:`diag-summary-time`}),e.groupBy&&(0,W.jsx)(PC,{label:`by`,value:e.groupBy,testId:`diag-summary-groupby`,warnTitle:p.length>0?`Unsupported grouping: ${p.join(`, `)}`:void 0}),e.hasJoin&&(0,W.jsx)(`span`,{"data-testid":`diag-summary-join`,className:`text-primary font-semibold`,children:`+join`})]})})()}),!r&&s&&xm(c)&&(0,W.jsx)(`div`,{className:`flex flex-wrap items-center gap-x-3 text-[11px] opacity-80 border-l border-border/50 pl-3`,children:(()=>{let e=jC(c);return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(PC,{label:`agg`,value:e.agg,testId:`diag-summary-agg`}),e.metric&&(0,W.jsx)(PC,{label:`metric`,value:e.metric,testId:`diag-summary-metric`}),e.groupBy&&(0,W.jsx)(PC,{label:`by`,value:e.groupBy,testId:`diag-summary-groupby`,warnTitle:p.length>0?`Unsupported grouping: ${p.join(`, `)}`:void 0}),e.rollup&&(0,W.jsx)(PC,{label:`every`,value:e.rollup,testId:`diag-summary-rollup`}),e.unit&&(0,W.jsx)(PC,{label:`as`,value:e.unit,testId:`diag-summary-unit`})]})})()}),!r&&s&&Sm(c)&&(0,W.jsx)(`div`,{className:`flex flex-wrap items-center gap-x-3 text-[11px] opacity-80 border-l border-border/50 pl-3`,children:(()=>{let e=NC(c);return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(PC,{label:`source`,value:e.source,testId:`diag-summary-source`}),e.functions.map((e,t)=>(0,W.jsx)(PC,{label:`fn ${t+1}`,value:e,testId:`diag-summary-fn-${t+1}`},t)),e.sink&&(0,W.jsx)(PC,{label:`sink`,value:e.sink,testId:`diag-summary-sink`}),e.timeWindow&&(0,W.jsx)(PC,{label:`time`,value:e.timeWindow,testId:`diag-summary-time`})]})})()}),s&&n&&(0,W.jsx)(`div`,{"data-testid":`diag-stage-counts`,className:`text-[11px] font-semibold text-primary border-l border-border/50 pl-3`,children:n.kind===`find`?(0,W.jsxs)(`span`,{children:[n.matched,` matched of `,n.selected]}):(0,W.jsxs)(`span`,{children:[n.selected,` selected → `,n.aggregated,` aggregated (`,n.groups,` series)`]})})]}),a&&(0,W.jsx)(`div`,{className:`flex items-center gap-1.5 ml-auto`,children:a})]})}function IC(e,t,n,r=150){let[i,a]=(0,U.useState)(void 0),o=(0,U.useRef)(void 0),s=(0,U.useRef)(n);s.current=n;let c=t&&!e.error&&n!==void 0&&!Sm(e);return(0,U.useEffect)(()=>{if(!c){a(void 0);return}a(void 0);let t=!1,n=setTimeout(()=>{s.current?.(e).then(n=>{t||(o.current=e,a(bm(e)?{kind:`find`,...n.stages}:{kind:`aggregate`,...n.stages}))}).catch(()=>{t||a(void 0)})},r);return()=>{t=!0,clearTimeout(n)}},[e,c,r]),c&&o.current===e?i:void 0}var LC={tags:`tag`},RC={tag:`tags`};function zC(e){return Array.isArray(e)?e.map(zC):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).filter(([e,t])=>![`raw`,`advisories`,`error`,`head`].includes(e)&&t!==void 0&&!(e===`groupBy`&&Array.isArray(t)&&t.length===0)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,zC(t)])):e}function BC(e){if(e.error)return!1;let t=X(dh(e));return!t.error&&JSON.stringify(zC(e))===JSON.stringify(zC(t))}function VC(e,t){let n=X(e),r=t?{...n,raw:e,error:t}:n;return{wql:e,ast:r,valid:!r.error,error:r.error}}function HC(e){let t=dh(e),n=VC(t);return n.valid&&!BC(e)?VC(t,`This value cannot be represented losslessly in WQL.`):n}function UC(e,t,n){return{id:`c-${e}`,type:e,...iC(e),value:t,...n}}function WC(e){let t=e.window;return t?t.kind===`relative`?`last ${t.size}${t.unit}`:`from ${t.start}${t.end?` to ${t.end}`:``}`:`all`}function GC(e){if(Sm(e)||e.error||!BC(e)||e.filters.some(e=>e.values.some(e=>e.value.includes(`|`)||!e.wildcard&&e.value.endsWith(`*`))))return null;let t=[UC(`kind`,e.family)];e.family===`find`?t.push(UC(`target`,e.target)):t.push(UC(`agg`,e.agg),UC(`metric`,e.metric)),(e.window||rm(e.family===`find`?e.target:``,e.family).has(`time`))&&t.push(UC(`time`,WC(e))),e.filters.forEach((e,n)=>{let r=e.values.map(e=>`${e.value}${e.wildcard?`*`:``}`).join(`|`),i=US.getAllSlots().find(t=>{if(!t.parseValue)return!1;let n=t.parseValue(r);return n!==void 0&&t.wqlGenerator(n)===KC(e)})?.type??LC[e.key]??e.key;t.push(UC(i,r,{id:`c-filter-${n}`,filterIndex:n,negate:e.negate}))}),e.groupBy?.length&&t.push(UC(`groupby`,e.groupBy.join(`|`))),e.family===`aggregate`&&e.rollup&&t.push(UC(`rollup`,`${e.rollup.size}${e.rollup.unit}`)),e.displayUnit&&t.push(UC(`unit`,e.displayUnit));let n=dh(e);return e.join&&t.push(UC(`where`,n.split(` where `)[1]?.split(` | `)[0]??``)),e.family===`find`&&e.pipes&&t.push(UC(`pipes`,n.split(` | `).slice(1).join(` | `))),t}function KC(e){return dh({family:`find`,raw:``,target:`note`,sourceScope:[...zp],filters:[e]}).replace(/^[^{]*\{/,``).replace(/\}$/,``)}function qC(e,t,n){let r=US.getSlot(e);if(r){let e=r.parseValue?r.parseValue(t):t;if(e===void 0||r.validate?.(e))return;let n=X(`:note{${r.wqlGenerator(e)}}`);return n.error||!bm(n)?void 0:n.filters[0]}let i={key:RC[e]??e,negate:n,values:t.split(`|`).map(e=>{let t=e.endsWith(`*`);return{value:t?e.slice(0,-1):e,wildcard:t}})},a=X(`:note{${KC(i)}}`);return!a.error&&bm(a)&&a.filters.length===1&&JSON.stringify(zC(a.filters[0]))===JSON.stringify(zC(i))?a.filters[0]:void 0}function JC(e,t,n){let r=VC(e);if(!r.valid)return r;let i=r.ast;if(Sm(i))return VC(e,`Pipelines are edited as WQL text — structured pills cannot change a stage without flattening it.`);if(!BC(i))return VC(e,`This query requires Edit WQL to preserve every clause.`);let a=n?.trim()??``;if(t.type===`kind`||t.type===`target`)return YC(e,t.type,a).draft;if(t.filterIndex!==void 0||![`time`,`agg`,`metric`,`groupby`,`rollup`,`unit`,`where`,`pipes`].includes(t.type)){let n=a&&(t.type!==`source`||a!==`all`)?qC(t.type,a,t.negate??!1):void 0;if(a&&!n&&(t.type!==`source`||a!==`all`))return VC(e,`Invalid ${iC(t.type).label} value`);let o=[...i.filters];if(t.filterIndex!==void 0){if(!o[t.filterIndex])return r;n?o[t.filterIndex]=n:o.splice(t.filterIndex,1)}else n&&o.push(n);return HC({...i,filters:o})}if(t.type===`time`){if(!a||a===`all`)return HC({...i,window:void 0});let t=X(`:note ${/^(last|from)\b/.test(a)?a:`last ${a}`}`);return t.error||!bm(t)||!t.window?VC(e,t.error??`Invalid time window`):HC({...i,window:t.window})}if(t.type===`groupby`)return HC({...i,groupBy:[...new Set(a.split(`|`).filter(Boolean))]});if(t.type===`unit`)return HC({...i,displayUnit:a||void 0});if(t.type===`agg`&&i.family===`aggregate`)return VC(dh(i).replace(/^[^:]+:/,`${a}:`));if(t.type===`metric`&&i.family===`aggregate`)return HC({...i,metric:a});if(t.type===`rollup`&&i.family===`aggregate`){if(!a)return HC({...i,rollup:void 0});let t=X(`sum:tis{} by {week}.rollup(${a})`);return t.error||t.family!==`aggregate`||!t.rollup?VC(e,t.error??`Invalid bucket width`):HC({...i,rollup:t.rollup})}if(t.type===`where`){let e=dh({...i,join:void 0});return VC(a?`${e} where ${a}`:e)}if(t.type===`pipes`&&i.family===`find`){let e=dh({...i,pipes:void 0});return VC(a?`${e} | ${a}`:e)}return r}function YC(e,t,n){let r=VC(e),i=r.ast;if(!r.valid)return{draft:r,removed:[]};if(Sm(i))return{draft:VC(e,`Pipelines are pivoted as WQL text — stage order cannot survive a structured pivot.`),removed:[]};let a=t===`kind`?n:`find`,o=t===`target`?n:i.family===`find`?i.target:`note`,s=rm(o,a===`aggregate`?`aggregate`:`find`),c=[],l=i.filters.filter(e=>{let t=(a===`aggregate`||o===`segment`||o===`event`)&&!(e.key in nC)&&!!CC(e.key),n=s.has(LC[e.key]??e.key)||t||!!US.getSlot(e.key);return n||c.push(KC(e)),n});if(a===i.family&&(i.family!==`find`||o===i.target))return{draft:r,removed:[]};let u=s.has(`time`)?i.window:void 0,d=s.has(`groupby`)?i.groupBy:void 0,f=s.has(`unit`)?i.displayUnit:void 0;i.displayUnit&&!f&&c.push(`Unit`),i.window&&!u&&c.push(`Time window`),i.groupBy?.length&&!d&&c.push(`Group By`);let p=a===`find`&&i.family===`find`&&s.has(`where`)?i.join:void 0;return i.join&&!p&&c.push(`Join`),a===`aggregate`?(i.family===`find`&&i.pipes&&c.push(`Presentation pipes`),{draft:HC({family:`aggregate`,raw:``,agg:`sum`,metric:`tis`,filters:l,window:u,groupBy:d??[],displayUnit:f}),removed:c}):(i.family===`aggregate`&&(c.push(`Measure ${i.agg}:${i.metric}`),i.rollup&&c.push(`Bucket width`)),{draft:HC({family:`find`,raw:``,target:o,filters:l,window:u,groupBy:d,displayUnit:f,pipes:i.family===`find`?i.pipes:void 0,join:p}),removed:c})}function XC(e,t=``){if(!t.trim())return VC(e);let n=t.trim();if(!X(t).error||/^(find|sum|avg|min|max|count|last|first|p\d+):/.test(n)||/^[\w-]+:[^{]*\{/.test(n)||/^[:@|]/.test(n))return VC(t);let r=VC(e);if(!r.valid||Sm(r.ast))return VC(t);if(!BC(r.ast))return VC(e,`Use Edit WQL for this query.`);if(/^(last|from)\b/.test(n)){let e=X(`:note ${n}`);return e.error||!bm(e)||!e.window?VC(t,e.error??`Invalid time window`):HC({...r.ast,window:e.window})}if(/^!?[\w-]+:/.test(n)){let e=X(`:note{${n}}`);if(e.error||!bm(e)||!e.filters.length)return VC(t,e.error??`Invalid filter`);let i=[...r.ast.filters];for(let t of e.filters){let e=i.findIndex(e=>e.key===t.key);e<0?i.push(t):i[e]=t}return HC({...r.ast,filters:i})}if(/[{}]/.test(n))return VC(t);let i=n.startsWith(`"`)?n.slice(1).replace(/"$/,``):t;if(!i)return r;let a=[...r.ast.filters],o={key:`text`,negate:!1,values:[{value:i,wildcard:!1}]},s=a.findIndex(e=>e.key===`text`&&!e.negate);return s<0?a.push(o):a[s]=o,HC({...r.ast,filters:a})}var ZC=Je(),QC={search:(0,ZC.renderToStaticMarkup)((0,U.createElement)(Dt,{size:16})),metric:(0,ZC.renderToStaticMarkup)((0,U.createElement)(St,{size:16})),filter:(0,ZC.renderToStaticMarkup)((0,U.createElement)(Qn,{size:16})),value:(0,ZC.renderToStaticMarkup)((0,U.createElement)(Hn,{size:16}))},$C={Head:!0,Filter:!0,TagValue:!0,Rollup:!0};function ew(e){let t=[];return Ir(e).iterate({enter:e=>(($C[e.name]||e.name===`Word`&&e.node.parent?.name===`GroupBy`)&&t.push(e.from),!0)}),t.sort((e,t)=>e-t)}function tw(e,t){let n=e.state.selection.main.head,r=ew(e.state),i=t>0?r.find(e=>e>n):[...r].reverse().find(e=>e<n);return i!==void 0&&(e.dispatch({selection:{anchor:i},scrollIntoView:!0}),!0)}function nw(e){let t=e.state.doc.toString();if(!t.trim())return[];let n=X(t);if(n.error){let r=[];return Ir(e.state).iterate({enter:e=>(e.type.isError&&r.push({from:e.from,to:e.to}),!0)}),(r.length?r:[{from:0,to:t.length}]).map(e=>{let r=Math.min(Math.max(e.to,e.from+1),t.length);return{from:Math.min(e.from,r-1),to:r,severity:`error`,message:n.error}})}if(Sm(n))return[];let r=[];if(Ir(e.state).iterate({enter:e=>(e.name===`Filter`&&r.push({from:e.from,to:e.to,text:t.slice(e.from,e.to)}),!0)}),r.length!==n.filters.length)return[];let i=n.family===`find`?n.target:`this query`,a=[];return n.filters.forEach((e,t)=>{if(om(n.family===`find`?n.target:``,n.family,e.key))return;let o=r[t];a.push({from:o.from,to:o.to,severity:`warning`,message:/^[^\s:]+\s*[<>=~]/.test(o.text)?`Operators on "${e.key}" are ignored for ${i}`:`Filter "${e.key}" is ignored for ${i}`})}),a}function rw(e,t){return[{key:`Mod-Enter`,run:()=>(e(),!0)},{key:`Ctrl-Space`,run:ii},{key:`ArrowDown`,run:e=>Rr(e.state)===`active`&&Sr(!0)(e)},{key:`ArrowUp`,run:e=>Rr(e.state)===`active`&&Sr(!1)(e)},{key:`PageUp`,run:e=>Rr(e.state)===`active`?Sr(!1,`page`)(e):Zr(e)},{key:`PageDown`,run:e=>Rr(e.state)===`active`?Sr(!0,`page`)(e):xi(e)},{key:`Home`,run:e=>Rr(e.state)===`active`?(e.dispatch({effects:Nr(0)}),!0):oi(e)},{key:`End`,run:e=>Rr(e.state)===`active`?(e.dispatch({effects:Nr(Cr(e.state).length-1)}),!0):Yr(e)},{key:`Tab`,run:e=>{if(e.compositionStarted)return!1;let t=Ei(e);return tw(e,1)||t}},{key:`Shift-Tab`,run:e=>{if(e.compositionStarted)return!1;let t=Ei(e);return tw(e,-1)||t}},{key:`Enter`,run:t=>t.compositionStarted?!1:Ei(t)?!0:(xr(t),e(),!0)},{key:`Escape`,run:e=>e.compositionStarted||xr(e)||t()||(e.contentDOM.blur(),!0)},...ci]}function iw({value:e,onChange:t,onSubmit:n,onEscape:r,placeholder:i,autoFocus:a=!1,dense:o=!1}){let s=(0,U.useRef)(null),c=(0,U.useRef)(void 0),l=(0,U.useRef)({onChange:t,onSubmit:n,onEscape:r});l.current={onChange:t,onSubmit:n,onEscape:r};let u=(0,U.useRef)(!1),d=(0,U.useRef)(e);return(0,U.useEffect)(()=>{if(!s.current)return;let e=Hh({values:async e=>(await TC(e===`tags`?`tag`:e)).map(e=>({label:e.value,detail:e.label,type:`constant`}))}),t=new Er({parent:s.current,state:ri.create({doc:d.current,extensions:[ph,Ar(Uh),pi(),Er.lineWrapping,...i?[bi(i)]:[],Er.contentAttributes.of({"aria-label":`WQL`,"data-testid":`wql-text-input`}),Jr({defaultKeymap:!1,selectOnOpen:!1,interactionDelay:0,override:[e],icons:!1,addToOptions:[{position:20,render:e=>{let t=document.createElement(`span`);return t.className=`wql-completion-icon`,t.setAttribute(`aria-hidden`,`true`),t.innerHTML=e.label===`find`?QC.search:e.type===`keyword`||e.type===`variable`?QC.metric:e.type===`property`?QC.filter:QC.value,t}}]}),_i(nw),yr.of(rw(()=>l.current.onSubmit(),()=>l.current.onEscape())),Er.domEventHandlers({mouseup:(e,t)=>{if(e.button!==0)return!1;let{from:n,to:r}=t.state.selection.main;if(n===r){let e=t.state.doc.lineAt(n),i=Array.from(e.text.matchAll(/[\w.*-]+/g)).find(t=>e.from+t.index<=n&&n<=e.from+t.index+t[0].length);if(!i)return!1;n=e.from+i.index,r=n+i[0].length;let a=Ir(t.state).resolveInner(r,-1);for(;a.parent&&![`Head`,`Filter`].includes(a.name);)a=a.parent;if(![`Head`,`Filter`].includes(a.name))return!1;t.dispatch({selection:{anchor:n,head:r}})}return ii(t),!1},keydown:(e,t)=>e.isComposing||t.compositionStarted?!0:((e.key===`Enter`||e.key===`Escape`||[`ArrowDown`,`ArrowUp`].includes(e.key)&&Rr(t.state)===`active`)&&e.stopPropagation(),!1)}),Er.updateListener.of(e=>{e.docChanged&&!u.current&&l.current.onChange(e.state.doc.toString())}),Er.theme({"&":{width:`100%`,fontSize:`14px`,backgroundColor:`transparent`},"&.cm-focused":{outline:`none`},".cm-content":{fontFamily:`var(--font-mono, ui-monospace, monospace)`,padding:o?`8px 0`:`12px 0`,minHeight:o?`34px`:`48px`},".cm-line":{padding:`0 12px`},'.cm-line span[class*="tok-"]:hover, .cm-line span[class^="tok-"]:hover':{fontWeight:`700`,textShadow:`0 0 0.5px currentColor`,cursor:`pointer`},".cm-scroller":{overflow:`auto`},".cm-placeholder":{color:`hsl(var(--muted-foreground))`},".cm-tooltip":{backgroundColor:`hsl(var(--popover))`,color:`hsl(var(--popover-foreground))`,border:`1px solid hsl(var(--border))`,borderRadius:`12px`,boxShadow:`0 8px 24px rgb(0 0 0 / 0.16)`,fontFamily:`var(--font-sans, Inter, system-ui, sans-serif)`,fontSize:`14px`},".cm-tooltip-autocomplete":{overflow:`hidden`,minWidth:`min(18rem, calc(100vw - 2rem))`,maxWidth:`calc(100vw - 2rem)`},".cm-tooltip-autocomplete > ul":{padding:`4px`,maxHeight:`min(20rem, 45vh)`,overscrollBehavior:`contain`},".cm-tooltip-autocomplete > ul > li":{display:`flex`,alignItems:`center`,gap:`8px`,minHeight:`40px`,padding:`8px 10px`,borderRadius:`8px`,lineHeight:`20px`},".cm-tooltip-autocomplete > ul > li:hover":{backgroundColor:`hsl(var(--muted))`},".cm-tooltip-autocomplete > ul > li[aria-selected]":{backgroundColor:`hsl(var(--accent))`,color:`hsl(var(--accent-foreground))`,boxShadow:`inset 2px 0 hsl(var(--primary))`},".wql-completion-icon":{display:`inline-flex`,flexShrink:`0`,color:`hsl(var(--primary))`},".cm-completionLabel":{fontWeight:`500`,overflow:`hidden`,textOverflow:`ellipsis`},".cm-completionMatchedText":{textDecoration:`none`,fontWeight:`700`,color:`hsl(var(--primary))`},".cm-completionDetail":{marginLeft:`auto`,paddingLeft:`12px`,fontSize:`12px`,fontStyle:`normal`,color:`hsl(var(--muted-foreground))`},"@media (pointer: coarse)":{".cm-tooltip-autocomplete > ul > li":{minHeight:`48px`}}})]})});return c.current=t,a&&t.focus(),()=>{t.destroy(),c.current=void 0}},[a,i,o]),(0,U.useEffect)(()=>{let t=c.current;!t||t.state.doc.toString()===e||(u.current=!0,t.dispatch({changes:{from:0,to:t.state.doc.length,insert:e}}),u.current=!1)},[e]),(0,W.jsx)(`div`,{ref:s,className:`min-w-0 w-full rounded-lg border border-border bg-background focus-within:ring-2 focus-within:ring-ring`,"data-testid":`wql-text-editor`})}function aw({initialQuery:e,query:t,onQueryChange:n,onValidationChange:r,onAstChange:i,onSubmit:a,actionLabel:o,compact:s=!1,showDiagnostics:c=!0,diagnosticsPosition:l=`bottom`,execute:u,stages:d,debounceMs:f=150,customSlots:p,diagnosticsActions:m,hiddenClauseTypes:h,preferredChoices:g,autoFocus:_=!1,placeholder:v=`Search text or enter WQL`,className:y}){let[b,x]=(0,U.useState)(!1),[S,C]=(0,U.useState)(t??e??`:note`),[w,T]=(0,U.useState)(``),[E,D]=(0,U.useState)({kind:`closed`}),[O,k]=(0,U.useState)(``),[A,j]=(0,U.useState)(-1),[M,N]=(0,U.useState)(),[P,F]=(0,U.useState)(),[I,L]=(0,U.useState)(),R=(0,U.useRef)(null),ee=(0,U.useRef)(null),te=(0,U.useRef)(null),ne=(0,U.useRef)(t??e??`:note`),re=(0,U.useRef)(t),ie=(0,U.useRef)(XC(S)),ae=(0,U.useRef)({onQueryChange:n,onValidationChange:r,onAstChange:i});ae.current={onQueryChange:n,onValidationChange:r,onAstChange:i};let oe=`${(0,U.useId)()}-options`,se=WS(),ce=xC(),le=t!==void 0&&t!==re.current&&t!==ne.current,z=(0,U.useMemo)(()=>XC(le?t:S,le?``:w),[S,w,le,t]);ie.current=z;let ue=(0,U.useMemo)(()=>GC(z.ast)??[],[z.ast]),de=z.valid&&GC(z.ast)!==null,fe=new Set(h),B=E.kind===`value`?E.clause:void 0,pe=B?US.getSlot(B.type):void 0,me=kC(B,O,{supportedValues:B?.type===`groupby`&&z.ast.family===`find`&&[`note`,`block`].includes(z.ast.target)?Kp:void 0}),he=[...me.filteredItems].sort((e,t)=>{let n=g?.indexOf(e.value)??-1,r=g?.indexOf(t.value)??-1;return(n<0?1/0:n)-(r<0?1/0:r)}),ge=Sm(z.ast)?new Set:rm(z.ast.family===`find`?z.ast.target:``,z.ast.family),_e=Sm(z.ast)?void 0:z.ast.window,ve=()=>{let e=ie.current.ast;return Sm(e)?void 0:e.window},ye=z.ast.family===`aggregate`||z.ast.family===`find`&&[`segment`,`event`].includes(z.ast.target)?ce.filter(e=>!(e in nC)):[],be=[...Object.keys(nC),...ye,...se.map(e=>e.type)].filter((e,t,n)=>n.indexOf(e)===t&&!fe.has(e)).filter(e=>[`kind`,`target`].includes(e)||ge.has(e)||ye.includes(e)||se.some(t=>t.type===e)).filter(e=>e!==`target`||z.ast.family===`find`).filter(e=>e!==`pipes`&&e!==`where`).filter(e=>e.toLowerCase().includes(w.toLowerCase())||iC(e).label.toLowerCase().includes(w.toLowerCase())).sort((e,t)=>Number(t.startsWith(w))-Number(e.startsWith(w))),xe=E.kind===`closed`&&w.trim()!==``&&be.length>0&&!/[{}:]/.test(w),Se=xe||ge.has(`text`),Ce=E.kind===`value`?me.filteredItems.length+Number(me.canCommitTyped):be.length+Number(Se),we=IC(z.ast,z.valid&&!M,d?void 0:u,f),Te=d??we;(0,U.useEffect)(()=>{t!==void 0&&t!==re.current&&(re.current=t,t!==ne.current&&(ne.current=t,C(t),T(``),D({kind:`closed`}),k(``),j(-1),N(void 0),L(void 0)))},[t]),(0,U.useEffect)(()=>{ae.current.onValidationChange?.({valid:z.valid&&!M&&!I,error:M??z.error??(I?`Confirm or cancel the query change`:void 0)}),ae.current.onAstChange?.(z.ast)},[z,M,I]),(0,U.useEffect)(()=>{let e=window.matchMedia?.(`(min-width: 640px)`);if(!e)return;let t=()=>x(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,U.useEffect)(()=>{_&&R.current?.focus()},[_]),(0,U.useEffect)(()=>{E.kind===`value`&&ee.current?.focus()},[E.kind]),(0,U.useEffect)(()=>{A>=0&&document.getElementById(`${oe}-option-${A}`)?.scrollIntoView?.({block:`nearest`})},[A,oe]);let Ee=e=>{ie.current=e;let t=e.wql!==ne.current;ne.current=e.wql,ae.current.onValidationChange?.({valid:e.valid,error:e.error}),ae.current.onAstChange?.(e.ast),t&&ae.current.onQueryChange?.(e.wql)},De=e=>{C(e.wql),T(``),N(void 0),Ee(e)},Oe=()=>{D({kind:`closed`}),k(``),j(-1),N(void 0),te.current?.isConnected?te.current.focus():R.current?.focus()},ke=e=>{w&&ie.current.valid&&De(ie.current),te.current=document.activeElement instanceof HTMLElement?document.activeElement:null,e.type===`where`||e.type===`pipes`?(D({kind:`wql`}),De(ie.current)):(D({kind:`value`,clause:e}),k(``)),j(-1),N(void 0)},Ae=e=>{let t=ue.find(t=>t.type===e);w&&De(XC(S)),ke(t??{id:`new-${e}`,type:e,...iC(e),value:``})},je=(e,t)=>{if(e.type===`kind`||e.type===`target`){let n=YC(ie.current.wql,e.type,t??``);if(!n.draft.valid){N(n.draft.error);return}if(n.removed.length){L(n);return}De(n.draft),Oe();return}let n=JC(ie.current.wql,e,t);if(!n.valid){N(n.error);return}if(De(n),E.kind===`value`){let r=e.filterIndex,i=GC(n.ast)?.find(n=>r===void 0?n.type===e.type:n.filterIndex===r&&!!t);D({kind:`value`,clause:i??{...e,value:t??``,filterIndex:void 0}})}},Me=e=>{if(E.kind===`value`){if(me.isMulti){let t=me.selectedValues,n=E.clause.value!==``&&E.clause.value.split(`|`).every(e=>e.endsWith(`*`))&&!e.endsWith(`*`)?`${e}*`:e;je(E.clause,(t.includes(n)?t.filter(e=>e!==n):[...t,n]).join(`|`))}else{let t=JC(ie.current.wql,E.clause,e);if(!t.valid){N(t.error);return}je(E.clause,e),[`kind`,`target`].includes(E.clause.type)||Oe()}}},Ne=()=>{let e=ie.current;!e.valid||M||I||(De(e),a?.(e.wql))},Pe=e=>{if(!e.nativeEvent.isComposing){if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)){e.preventDefault(),e.stopPropagation(),Ne();return}if(e.key===`Escape`){if(I){e.preventDefault(),e.stopPropagation(),L(void 0);return}if(E.kind!==`closed`){e.preventDefault(),e.stopPropagation(),Oe();return}if(xe){e.preventDefault(),e.stopPropagation(),De(ie.current),j(-1);return}}if(E.kind===`value`&&e.currentTarget instanceof HTMLInputElement&&e.currentTarget===R.current){[`Enter`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`&&(e.preventDefault(),Ne());return}if((E.kind===`value`||xe)&&[`ArrowDown`,`ArrowUp`].includes(e.key)){e.preventDefault(),e.stopPropagation(),j(t=>e.key===`ArrowDown`?(t+1)%Ce:t<=0?Ce-1:t-1);return}if(e.key===`Enter`){e.preventDefault(),e.stopPropagation(),A>=0&&xe&&be[A]?Ae(be[A]):xe&&A===be.length?Ne():E.kind===`value`?A>=0&&A<he.length?Me(he[A].value):me.canCommitTyped&&(A===he.length||A<0)?Me(me.typedValue):O&&!me.openSlot&&N(`Unknown ${iC(E.clause.type).label} value`):Ne();return}e.key===`Backspace`&&E.kind===`closed`&&!w&&Array.from(e.currentTarget.closest(`[data-testid="wql-composer-root"]`)?.querySelectorAll(`[data-testid^="token-slot-"]:not([data-testid^="token-slot-remove-"]):not([data-testid^="token-slot-value-"])`)??[]).at(-1)?.focus()}},Fe=(0,W.jsxs)(W.Fragment,{children:[o&&(0,W.jsx)(`button`,{type:`button`,onClick:Ne,disabled:!z.valid||!!M||!!I,className:`min-h-12 rounded-lg bg-primary px-4 text-primary-foreground disabled:opacity-50`,children:o}),m]}),Ie={...z,valid:z.valid&&!M,error:M??z.error};return(0,W.jsxs)(`div`,{className:mx(`min-w-0 space-y-2`,b&&s&&`flex flex-wrap items-center gap-2 space-y-0 [&>:not([data-wql-inline])]:w-full`,y),"data-testid":`wql-composer-root`,children:[l===`top`&&c&&(0,W.jsx)(FC,{diagnostics:Ie,stages:Te,actions:Fe,variant:`header`}),(b||E.kind===`wql`||!de)&&(0,W.jsx)(`div`,{"data-wql-inline":!0,className:mx(`min-w-0`,b&&s?`flex-1`:`w-full`),children:(0,W.jsx)(iw,{value:z.wql,placeholder:v,dense:b&&s,onChange:e=>De(XC(e)),onSubmit:Ne,onEscape:()=>E.kind!==`closed`&&(Oe(),!0),autoFocus:_})}),(0,W.jsxs)(`div`,{className:mx(`flex min-w-0 flex-wrap items-center gap-1`,!b&&`rounded-xl border border-border p-2`,b&&s&&`hidden`),"data-testid":`wql-composer`,onKeyDown:e=>{if(![`Delete`,`Backspace`].includes(e.key)||!(e.target instanceof HTMLButtonElement))return;let t=Array.from(e.currentTarget.querySelectorAll(`[data-testid^="token-slot-"]:not([data-testid^="token-slot-remove-"]):not([data-testid^="token-slot-value-"])`)),n=ue.filter(e=>!fe.has(e.type))[t.indexOf(e.target)];!n||[`kind`,`target`,`agg`,`metric`].includes(n.type)||(e.preventDefault(),e.stopPropagation(),F(ie.current.wql),je(n,null),R.current?.focus())},children:[de&&E.kind!==`wql`&&ue.filter(e=>!fe.has(e.type)).map(e=>(0,W.jsx)(aC,{clause:e,compact:s,isActive:E.kind===`value`&&E.clause.id===e.id,onClick:()=>ke(e),onRemove:[`kind`,`target`,`agg`,`metric`].includes(e.type)?void 0:()=>{F(ie.current.wql),je(e,null)}},e.id)),!b&&E.kind!==`wql`&&de&&(0,W.jsx)(`input`,{ref:R,type:`text`,role:`combobox`,"aria-label":`Search text or WQL`,"aria-controls":xe?oe:void 0,"aria-expanded":xe,"aria-activedescendant":xe&&A>=0?`${oe}-option-${A}`:void 0,value:w,placeholder:v,onChange:e=>{let t=e.target.value;T(t),j(-1),N(void 0),Ee(XC(S,t))},onKeyDown:Pe,className:`min-h-12 min-w-0 flex-[1_1_140px] bg-transparent font-mono text-base outline-none`,"data-testid":`wql-composer-input`}),p]}),(!b||P)&&(0,W.jsxs)(`div`,{"data-wql-inline":b&&s?``:void 0,className:`flex flex-wrap items-center gap-2`,children:[!b&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>{De(ie.current),E.kind===`wql`?Oe():D({kind:`wql`})},disabled:E.kind===`wql`&&!de,className:`min-h-12 rounded-lg px-3`,children:E.kind===`wql`?`Guided controls`:`Edit WQL`}),P&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>{De(XC(P)),F(void 0)},className:mx(`rounded-lg`,b&&s?`min-h-9 px-2.5 text-xs text-muted-foreground hover:text-foreground`:`min-h-12 px-3`),children:`Undo removal`})]}),E.kind===`value`&&(0,W.jsxs)(`div`,{"data-testid":`wql-field-picker`,className:`min-w-0 rounded-xl border border-border p-2 focus-within:ring-2 focus-within:ring-ring`,onKeyDown:e=>{(e.key===`Escape`||e.key===`Enter`&&(e.ctrlKey||e.metaKey))&&Pe(e)},children:[(0,W.jsx)(`button`,{type:`button`,onClick:Oe,className:`min-h-12 px-3`,children:`Back`}),(0,W.jsxs)(`label`,{className:`block text-sm`,children:[`Search `,iC(E.clause.type).label,(0,W.jsx)(`input`,{ref:ee,type:`search`,role:`combobox`,"aria-label":`Search ${iC(E.clause.type).label}`,"aria-controls":oe,"aria-expanded":`true`,"aria-activedescendant":A>=0?`${oe}-option-${A}`:void 0,value:O,onChange:e=>{k(e.target.value),j(-1),N(void 0)},onKeyDown:Pe,className:`min-h-12 w-full rounded border border-border bg-background px-3 text-base`,"data-testid":`wql-picker-search`})]}),E.kind===`value`&&E.clause.filterIndex!==void 0&&(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,W.jsxs)(`label`,{className:`flex min-h-12 items-center gap-2`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:E.clause.negate??!1,onChange:e=>je({...E.clause,negate:e.target.checked},E.clause.value)}),`Exclude`]}),(0,W.jsxs)(`label`,{className:`flex min-h-12 items-center gap-2`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:E.clause.value.split(`|`).every(e=>e.endsWith(`*`)),onChange:e=>je(E.clause,E.clause.value.split(`|`).map(t=>`${t.replace(/\*$/,``)}${e.target.checked?`*`:``}`).join(`|`))}),`Starts with`]})]}),E.kind===`value`&&E.clause.type===`time`&&(0,W.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,W.jsxs)(`label`,{children:[`Start date`,(0,W.jsx)(`input`,{type:`date`,"aria-label":`Start date`,className:`min-h-12 w-full bg-background text-base`,onChange:e=>{let t=ve();je(E.clause,`from ${e.target.value}${t?.kind===`range`&&t.end?` to ${t.end}`:``}`)},value:_e?.kind===`range`?_e.start:``})]}),(0,W.jsxs)(`label`,{children:[`End date`,(0,W.jsx)(`input`,{type:`date`,"aria-label":`End date`,className:`min-h-12 w-full bg-background text-base`,onChange:e=>{let t=ve();t?.kind===`range`?je(E.clause,`from ${t.start}${e.target.value?` to ${e.target.value}`:``}`):N(`Choose a start date first`)},value:_e?.kind===`range`?_e.end??``:``})]})]}),E.kind===`value`&&(pe?(0,W.jsx)(pe.Editor,{value:pe.parseValue?pe.parseValue(E.clause.value):E.clause.value,onChange:e=>je(E.clause,pe.formatValue?pe.formatValue(e):String(e)),onClose:Oe}):(0,W.jsx)(sC,{clause:E.clause,filteredItems:he,selectedValues:me.selectedValues,isMulti:me.isMulti,typedValue:me.typedValue,canCommitTyped:me.canCommitTyped,emptyText:me.emptyText,highlightIdx:A,onHighlight:j,onCommitValue:Me,onCommitTyped:Me,listId:oe,onDone:Oe,onReorder:e=>je(E.clause,e.join(`|`))}))]}),xe&&(0,W.jsxs)(`div`,{id:oe,role:`listbox`,"aria-label":`Query conditions`,className:`max-h-64 overflow-y-auto rounded-xl border border-border p-1`,"data-testid":`wql-filter-typeahead`,children:[be.map((e,t)=>(0,W.jsxs)(`button`,{id:`${oe}-option-${t}`,type:`button`,role:`option`,"aria-selected":!1,onMouseEnter:()=>j(t),onClick:()=>Ae(e),className:mx(`flex min-h-12 w-full items-center gap-2 rounded px-3 text-left`,t===A&&`bg-muted`),"data-testid":`wql-filter-typeahead-${e}`,children:[(0,W.jsxs)(`span`,{children:[ue.some(t=>t.type===e)?`Edit`:`Add`,` `,iC(e).label]}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e})]},e)),Se&&(0,W.jsxs)(`button`,{id:`${oe}-option-${be.length}`,type:`button`,role:`option`,"aria-selected":!1,onMouseEnter:()=>j(be.length),className:mx(`min-h-12 w-full rounded px-3 text-left`,A===be.length&&`bg-muted`),onClick:Ne,children:[`Search text `,w]})]}),I&&(0,W.jsxs)(`div`,{role:`alertdialog`,"aria-label":`Confirm query pivot`,className:`rounded-xl border border-border p-3`,children:[(0,W.jsx)(`p`,{children:`Changing the query removes incompatible clauses:`}),(0,W.jsx)(`ul`,{children:I.removed.map(e=>(0,W.jsx)(`li`,{children:e},e))}),(0,W.jsx)(`button`,{type:`button`,className:`min-h-12 px-3`,onClick:()=>L(void 0),children:`Cancel`}),(0,W.jsx)(`button`,{type:`button`,className:`min-h-12 px-3`,onClick:()=>{De(I.draft),L(void 0),Oe()},children:`Change query`})]}),!c&&(M??z.error)&&(0,W.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:M??z.error}),!de&&!z.error&&(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Use Edit WQL to preserve every clause.`}),w&&(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,"data-testid":`wql-composer-pending`,children:z.valid?`Current draft includes this text`:z.error}),c&&l===`bottom`?(0,W.jsx)(FC,{diagnostics:Ie,stages:Te,actions:Fe}):l!==`top`||!c?(0,W.jsx)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:Fe}):null]})}function ow({isOpen:e,onClose:t,initialQuery:n,onApply:r,title:i=`Edit Block Query`,subtitle:a=`Use the Omni-Composer to edit this block query.`,applyLabel:o=`Apply to Block`,executor:s}){let[c,l]=(0,U.useState)(n),[u,d]=(0,U.useState)({valid:!X(n).error}),[f,p]=(0,U.useState)(!1),[m,h]=(0,U.useState)(null);(0,U.useEffect)(()=>{e&&(l(n),d({valid:!X(n).error}),h(null))},[e,n]);let g=(0,U.useCallback)(e=>{if(!s)throw Error(`No executor provided`);return bm(e)?s.runFind(e):s.runQuery(e.raw)},[s]),_=async()=>{if(!(f||X(c).error)){p(!0),h(null);try{await r(c),t()}catch(e){h(e instanceof Error?e.message:String(e))}finally{p(!1)}}};return(0,W.jsx)(HS,{open:e,onClose:t,presentation:`sheet`,title:i,description:a,footer:(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`flex-1 min-w-0 truncate font-mono text-xs text-muted-foreground`,"data-testid":`wql-inspector-draft`,children:c}),(0,W.jsx)(`button`,{type:`button`,onClick:t,className:`min-h-12 px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground rounded-lg border border-border hover:bg-muted transition-colors`,children:`Cancel`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-inspector-apply`,onClick:()=>void _(),disabled:!u.valid||f,className:`min-h-12 px-3 py-1.5 text-xs font-medium text-primary-foreground bg-primary hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg shadow transition-colors`,children:f?`Applying…`:o})]}),children:(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsx)(aw,{query:c,onQueryChange:l,onValidationChange:d,execute:s?g:void 0,showDiagnostics:!0}),m&&(0,W.jsx)(`p`,{role:`alert`,className:`rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive font-mono`,children:m})]})})}function sw({query:e,executor:t,onResultSaved:n,onSaveQuery:r,queryIndex:i=0,readOnly:a=!1,widgetType:o,widgetError:s,tokenValues:c,attributes:l,onCaptureRpe:u,onOpenNote:d,noteHref:f}){let[p,m]=(0,U.useState)(!1),h=(0,U.useMemo)(()=>IS(e),[e]),{query:g,missing:_}=(0,U.useMemo)(()=>{let t=b_(h.length>0?h[0].query:e,c??{}),n=new Set(t.missing);for(let e of Object.values(l??{}))for(let t of b_(e,c??{}).missing)n.add(t);return{query:t.query,missing:[...n]}},[h,e,c,l]),v=(0,U.useMemo)(()=>{let e={};for(let[t,n]of Object.entries(l??{}))e[t]=b_(n,c??{}).query;return e},[l,c]),y=(0,U.useMemo)(()=>X(g),[g]),b=o!=null&&o!==``&&!c_(o),[x,S]=(0,U.useState)(void 0),[C,w]=(0,U.useState)(void 0),[T,E]=(0,U.useState)(void 0),[D,O]=(0,U.useState)(void 0),[k,A]=(0,U.useState)(0);(0,U.useEffect)(()=>{if(n){let e=n(()=>{A(e=>e+1)});return()=>{typeof e==`function`&&e()}}},[n]),(0,U.useEffect)(()=>{let e=!1;if(O(void 0),S(void 0),w(void 0),E(void 0),!y.error&&!(s||b||_.length>0)&&t){if(bm(y)){let n,r=y.target===`session`,i=a=>{t.runFind(y).then(t=>{e||(w(t),r&&(t.runs??[]).length===0&&a<4&&(n=setTimeout(()=>{e||i(a+1)},[50,150,350,750][a]??500)))}).catch(t=>{e||O(t instanceof Error?t.message:String(t))})};return i(0),()=>{e=!0,clearTimeout(n)}}if(Sm(y)){if(!t.runPipeline){O(`pipeline queries are not supported by this executor`);return}return t.runPipeline(g).then(t=>{e||E(t)}).catch(t=>{e||O(t instanceof Error?t.message:String(t))}),()=>{e=!0}}return t.runQuery(g).then(t=>{e||S(t)}).catch(t=>{e||O(t instanceof Error?t.message:String(t))}),()=>{e=!0}}},[g,y,s,b,_,t,k]);let j=r!==void 0&&!a,M=j?()=>m(!0):void 0,N=(0,U.useMemo)(()=>{if(!(!bm(y)||y.target!==`session`))return y.filters.find(e=>e.key===`result`)?.values[0]?.value},[y]);return(0,W.jsxs)(`div`,{"data-testid":`query-block-view`,children:[s?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsx)(`div`,{className:`text-xs text-destructive bg-destructive/10 border border-destructive/20 rounded p-2`,children:s})}):b?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsx)(Vx,{message:u_(o)})}):_.length>0?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsx)(Vx,{message:d_(_)})}):y.error?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsxs)(`div`,{className:`text-xs text-destructive bg-destructive/10 border border-destructive/20 rounded p-2`,children:[`Query syntax error: `,y.error]})}):D?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsxs)(`div`,{className:`text-xs text-destructive bg-destructive/10 border border-destructive/20 rounded p-2`,children:[`Query execution error: `,D]})}):bm(y)?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:C?.table?(0,W.jsx)(zx,{type:`table`,result:C}):N&&C?.runs&&C.runs.length>0?(0,W.jsx)(NS,{resultId:N,sessionResult:C,executor:t,onCaptureRpe:u,onCaptured:()=>A(e=>e+1)}):C?.runs?(0,W.jsx)(kS,{result:C}):C?(0,W.jsx)(uw,{target:y.target,notes:C.notes,blocks:C.blocks,containers:C.containers,onOpenNote:d,noteHref:f}):(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground py-2`,children:`Loading rows…`})}):Sm(y)?(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsx)(dw,{result:T,onOpenNote:d,noteHref:f,widgetType:o,attributes:v,fallbackLabel:y.raw})}):(0,W.jsx)(fw,{onEdit:M,readOnly:a,children:(0,W.jsx)(cw,{result:x,metric:y.metric,widgetType:o,attributes:v})}),j&&(0,W.jsx)(ow,{isOpen:p,onClose:()=>m(!1),initialQuery:g,executor:t,onApply:e=>r(e)})]})}function cw({result:e,metric:t,widgetType:n,attributes:r}){let i=vx(e);return n!=null&&n!==``?(0,W.jsx)(zx,{type:n,result:e,label:t,attributes:r}):i.kind===`scalar`?(0,W.jsx)(bx,{result:e,label:t}):i.kind===`timeseries`?(0,W.jsx)(Dx,{result:e}):i.kind===`bars`?(0,W.jsx)(Ox,{result:e}):(0,W.jsx)(yx,{result:e})}function lw(e){if(!e||e.kind!==`page`)return;let{slug:t,date:n}=e;if(t)return`/p/${encodeURIComponent(t)}`;if(n)return`/journal/${encodeURIComponent(n)}`}function uw({target:e,notes:t,blocks:n,containers:r,onOpenNote:i,noteHref:a}){let o=e===`block`,s=o?n:t;return s.length===0?(0,W.jsxs)(`div`,{className:`text-xs text-muted-foreground py-2`,children:[`No `,e,`s matched this query.`]}):(0,W.jsxs)(`div`,{className:`space-y-1`,children:[(0,W.jsxs)(`div`,{className:`text-[11px] font-medium text-muted-foreground mb-1`,children:[s.length,` `,e,s.length===1?``:`s`,` matched`]}),(0,W.jsx)(`ul`,{className:`space-y-0.5 max-h-48 overflow-y-auto font-mono text-xs`,children:s.map(e=>{let t=e,n=o?t.title||t.blockContentId||e.id:t.title||e.id,s=r?lw(r[e.id])??(a?a(t):void 0):a?a(t):void 0;return(0,W.jsx)(`li`,{className:`rounded hover:bg-muted/50 truncate`,children:s?(0,W.jsx)(`a`,{href:s,onClick:e=>{i&&(e.preventDefault(),i(t))},className:`block py-0.5 px-1.5 text-primary hover:underline truncate`,children:n}):i?(0,W.jsx)(`button`,{type:`button`,onClick:()=>i(t),className:`w-full text-left py-0.5 px-1.5 text-primary hover:underline truncate`,children:n}):(0,W.jsx)(`span`,{className:`block py-0.5 px-1.5 text-foreground truncate`,children:n})},e.id)})})]})}function dw({result:e,onOpenNote:t,noteHref:n,widgetType:r,attributes:i,fallbackLabel:a}){if(!e)return(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground py-2`,children:`Loading…`});if(e.error)return(0,W.jsxs)(`div`,{className:`text-xs text-destructive bg-destructive/10 border border-destructive/20 rounded p-2`,children:[`Query execution error: `,e.error]});let o=e.parsed.source.kind===`query`&&e.parsed.source.query.family===`find`?e.parsed.source.query.target:`note`;if((e.notes?.length??0)+(e.blocks?.length??0)>0)return(0,W.jsx)(uw,{target:o,notes:e.notes??[],blocks:e.blocks??[],containers:e.containers,onOpenNote:t,noteHref:n});if(e.runs&&e.runs.length>0){let t={parsed:e.parsed,runs:e.runs,table:e.table};return(0,W.jsx)(kS,{result:t})}let s=r!=null&&r!==``?r:e.chart?.head;if(s){let t=Object.fromEntries((e.chart?.filters??[]).map(e=>[e.key,e.values.map(e=>e.value).join(`,`)]));return(0,W.jsx)(`div`,{className:`w-full h-[220px] min-h-[160px]`,children:(0,W.jsx)(zx,{type:s,result:xx(e),label:a,attributes:{...t,...i}})})}return e.series&&e.series.length>0?(0,W.jsx)(`div`,{className:`w-full h-[220px] min-h-[160px]`,children:(0,W.jsx)(cw,{result:xx(e),metric:a})}):(0,W.jsx)(yx,{result:xx(e)})}function fw({children:e,onEdit:t,readOnly:n}){return(0,W.jsxs)(`div`,{className:`relative group/block my-2 p-3 rounded-lg border border-border/80 bg-card/60 shadow-sm`,children:[t&&!n&&(0,W.jsx)(`button`,{type:`button`,onClick:t,title:`Edit query in Omni-Composer`,className:`absolute top-2 right-2 p-1 rounded bg-muted/80 text-muted-foreground hover:text-foreground opacity-0 group-hover/block:opacity-100 focus-visible:opacity-100 [@media(pointer:coarse)]:opacity-100 transition-opacity z-10`,children:(0,W.jsx)(dn,{className:`w-3.5 h-3.5`})}),e]})}function pw(e){let t=Er.theme({"&":{height:`auto`,minHeight:`100%`,width:`100%`,maxWidth:`100%`,boxSizing:`border-box`,fontSize:`14px`,textAlign:`left`},"&.cm-focused":{outline:`none`},".cm-scroller":{overflow:`visible`,width:`100%`,maxWidth:`100%`,boxSizing:`border-box`},".cm-content":{fontFamily:`JetBrains Mono, ui-monospace, SFMono-Regular, monospace`,lineHeight:`22px`,padding:`0`,margin:`0 3px`,textAlign:`left`},".cm-gutters":{backgroundColor:e?`#252841`:`transparent`,color:e?`#A0AEC0`:`#717D96`,border:`none`,padding:`0`},".cm-activeLine":{backgroundColor:e?`rgba(165, 180, 252, 0.08)`:`rgba(129, 140, 248, 0.08)`},".cm-activeLineGutter":{backgroundColor:e?`rgba(165, 180, 252, 0.08)`:`rgba(129, 140, 248, 0.08)`},"&.cm-focused .cm-selectionBackground":{backgroundColor:e?`rgba(165, 180, 252, 0.3)`:`rgba(129, 140, 248, 0.35)`},".cm-selectionBackground":{backgroundColor:e?`rgba(100, 160, 255, 0.20)`:`rgba(30, 100, 230, 0.25)`},"::selection":{backgroundColor:e?`rgba(100, 160, 255, 0.35) !important`:`rgba(30, 100, 230, 0.50) !important`}},{dark:e});return e?[ni,t]:[t]}var mw=Vr.fromClass(class{decorations;constructor(e){this.decorations=this.getDecorations(e)}update(e){(e.docChanged||e.viewportChanged)&&(this.decorations=this.getDecorations(e.view))}getDecorations(e){let t=new vi,{doc:n}=e.state;for(let r=1;r<=n.lines;r++){let i=n.line(r),a=i.text,o=a.trim(),s=null,c=a.match(/^(#{1,6})\s+(.*)$/);if(c){let e=c[2].trim(),t=e.match(/(\d{1,2}:\d{2})/);if(t){let n=t[1];e=e.replace(n,``).replace(/\s+/g,` `).trim(),e||=n}s=e.toLowerCase().replace(/[^\w]+/g,`-`)}else/^```(time|log)/.test(o)&&(s=`workout-line-${r}`);s&&i.from>=e.viewport.from&&i.to<=e.viewport.to&&t.add(i.from,i.from,Br.line({attributes:{id:s}}))}return t.finish()}},{decorations:e=>e.decorations}),hw=qr.define({combine(e){return e.length>0?e[e.length-1]:null}});function gw(e){return/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)}function _w(e,t){let n=Ir(e.state),r=null;return n.cursorAt(t).iterate(t=>{if(t.name===`URL`){let n=e.state.doc.sliceString(t.from,t.to);if(gw(n))return r=n,!1}if(t.name===`Autolink`){let n=e.state.doc.sliceString(t.from,t.to);if(n.startsWith(`<`)&&n.endsWith(`>`)&&(n=n.slice(1,-1)),gw(n))return r=n,!1}}),r}var vw=[Fr((e,t)=>_w(e,t)?{pos:t,end:t,above:!0,create(){let e=document.createElement(`div`);return e.className=`cm-link-tooltip px-2 py-1 text-[11px] text-muted-foreground bg-popover border border-border rounded shadow-sm flex items-center gap-1.5`,e.innerHTML=`<kbd class="px-1 py-0.5 rounded bg-muted border border-border/70 font-mono text-[10px]">Ctrl</kbd><span>+Click to open link</span>`,{dom:e}}}:null,{hoverTime:300}),Vr.fromClass(class{handler;view;constructor(e){this.view=e,this.handler=t=>{if(!(t.ctrlKey||t.metaKey)||t.button!==0)return;let n=e.posAtCoords({x:t.clientX,y:t.clientY});if(n==null)return;let r=_w(e,n);if(!r)return;t.preventDefault(),t.stopPropagation();let i=e.state.facet(hw);i?i(r,e):typeof window<`u`&&window.open(r,`_blank`,`noopener,noreferrer`)},e.dom.addEventListener(`mousedown`,this.handler,!0)}destroy(){this.view.dom.removeEventListener(`mousedown`,this.handler,!0)}update(e){}}),Er.domEventHandlers({mousemove(e,t){let n=t.posAtCoords({x:e.clientX,y:e.clientY});if(n==null)return!1;let r=_w(t,n);return t.dom.style.cursor=r&&(e.ctrlKey||e.metaKey)?`pointer`:``,!1},keydown(e,t){return t.dom.style.cursor=``,!1}})],yw=qr.define({combine:e=>e[0]}),bw=qr.define({combine:e=>e.length?e.flat():void 0}),xw=Xr.define(),Sw=Xr.define(),Cw=Xr.define(),ww=Xr.define(),Tw=Xr.define({map(e,t){let n={};for(let r of Object.values(e.blocks)){let e=t.mapPos(r.from,1),i=t.mapPos(r.to,-1);e<i&&(n[r.id]={...r,from:e,to:i})}return{rawContent:e.rawContent,blocks:n}}});function Ew(e){let t=[0],n=[0],r=0;for(let i of e.matchAll(/\r\n|\r|\n/g))r+=i[0].length-1,t.push(i.index+i[0].length),n.push(i.index+i[0].length-r);return{rawStarts:t,editorStarts:n}}function Dw(e,t,n){let r=e.doc.lineAt(n);return t[r.number-1]+n-r.from}function Ow(e){let t={};for(let n of Object.values(e.noteBlocks)){let r=e.sections.find(e=>e.id===n.id);r&&(t[n.id]={...n,from:r.from,to:r.to})}return t}function kw(e,t,n,r,i,a=[]){let o=e.facet(bw),s=Na(t,{sourceRevision:n,blocks:r,registeredWidgets:o}),c=Ew(t),l=ja(t,{registeredWidgets:o}).map(e=>{let t=c.editorStarts[e.startLine],n=c.editorStarts[e.endLine]+e.to-c.rawStarts[e.endLine],r=Ma(e)?Object.values(s).find(t=>t.from===e.from&&t.to===e.to):void 0,i=a.find(r=>r.from===t&&r.to===n&&r.type===(e.type===`title`?`markdown`:e.type)),o=e.querySuffix?p_(e.querySuffix):void 0,l=e.subtype;return{id:r?.id??i?.id??e.id,type:e.type===`title`?`markdown`:e.type,...l===`heading`||l===`paragraph`||l===`list`||l===`blockquote`||l===`table`?{subtype:l}:{},from:t,to:n,startLine:e.startLine+1,endLine:e.endLine+1,...e.contentFrom===void 0?{}:{contentFrom:c.editorStarts[e.startLine+1]??n},...e.contentTo===void 0?{}:{contentTo:c.editorStarts[e.endLine]-+(e.type===`frontmatter`)},sport:e.sport,widgetName:e.widgetName,contentId:e.contentId,queryType:o?.type,queryError:o?.error,embed:e.embed}});for(let e of Object.values(s))e.version=i[e.id]??e.version;return{sections:l,rawContent:t,sourceRevision:n,noteBlocks:s,savedVersions:i}}var Aw=si.define({create(e){let t=e.facet(yw),n=t?.rawContent??e.doc.toString();if(n.replace(/\r\n|\r/g,`
62
+ `)!==e.doc.toString())throw Error(`Editor source and identity map disagree`);t&&Pa(n,t.blocks,t.sourceRevision,{registeredWidgets:e.facet(bw)});let r=Object.fromEntries(Object.values(t?.blocks??{}).map(e=>[e.id,e.version]));return kw(e,n,t?.sourceRevision??1,t?.blocks??{},r)},update(e,t){let n=e.rawContent,r=e.noteBlocks,i=e.sourceRevision,a=e.savedVersions;if(t.docChanged){let{rawStarts:i}=Ew(n),a=[],o=n.includes(`\r
63
+ `)?`\r
64
+ `:n.includes(`\r`)?`\r`:`
65
+ `;t.changes.iterChanges((e,n,r,s)=>a.push({from:Dw(t.startState,i,e),to:Dw(t.startState,i,n),insert:t.newDoc.sliceString(r,s,o)})),r=Fa(r,a);for(let e=a.length-1;e>=0;e--){let t=a[e];n=n.slice(0,t.from)+t.insert+n.slice(t.to)}if(t.isUserEvent(`move.drop`)){let i=[];t.changes.iterChanges((e,t,n,r)=>i.push({fromA:e,toA:t,fromB:n,toB:r}));let a=i.filter(e=>e.toA>e.fromA&&e.fromB===e.toB),o=i.filter(e=>e.fromA===e.toA&&e.toB>e.fromB);if(a.length===1&&o.length===1){let i=a[0],s=o[0];if(t.startState.doc.sliceString(i.fromA,i.toA)===t.newDoc.sliceString(s.fromB,s.toB)){let a=Ew(n).rawStarts;for(let n of e.sections){let o=e.noteBlocks[n.id];o&&n.from>=i.fromA&&n.to<=i.toA&&(r[o.id]={...o,from:Dw(t.state,a,s.fromB+n.from-i.fromA),to:Dw(t.state,a,s.fromB+n.to-i.fromA)})}}}}if(t.isUserEvent(`move.line`)){let i=Ew(n).rawStarts;for(let n=0;n<t.startState.selection.ranges.length;n++){let a=t.startState.selection.ranges[n],o=t.newSelection.ranges[n];if(!o)continue;let s=t.startState.doc.lineAt(a.from),c=t.startState.doc.lineAt(a.to>a.from&&t.startState.doc.lineAt(a.to).from===a.to?a.to-1:a.to),l=o.anchor-a.anchor;for(let n of e.sections){let a=e.noteBlocks[n.id];a&&n.from>=s.from&&n.to<=c.to&&(r[a.id]={...a,from:Dw(t.state,i,n.from+l),to:Dw(t.state,i,n.to+l)})}}}}for(let o of t.effects){if(o.is(Sw)){i=Math.max(i,o.value.sourceRevision),a={...a};for(let e of Object.values(o.value.blocks))a[e.id]=Math.max(a[e.id]??1,e.version)}if(o.is(Cw)){if(o.value.rawContent.replace(/\r\n|\r/g,`
66
+ `)!==t.newDoc.toString())throw Error(`Restored source does not match editor`);Pa(o.value.rawContent,o.value.blocks,o.value.sourceRevision,{registeredWidgets:t.state.facet(bw)}),n=o.value.rawContent,r=o.value.blocks,i=o.value.sourceRevision,a={...a,...Object.fromEntries(Object.values(r).map(e=>[e.id,e.version]))}}if(o.is(Tw)){if(t.effects.some(e=>e.is(Tw)&&e.value.rawContent.replace(/\r\n|\r/g,`
67
+ `)===t.newDoc.toString())&&o.value.rawContent.replace(/\r\n|\r/g,`
68
+ `)!==t.newDoc.toString())continue;o.value.rawContent.replace(/\r\n|\r/g,`
69
+ `)===t.newDoc.toString()&&(n=o.value.rawContent);let{rawStarts:e}=Ew(n);r=Object.fromEntries(Object.values(o.value.blocks).map(n=>[n.id,{...n,from:Dw(t.state,e,n.from),to:Dw(t.state,e,n.to)}]))}if(o.is(ww)){let i=e.noteBlocks[o.value.id];if(!i||r[i.id])throw Error(`Explicit move must remove the original occurrence`);let{rawStarts:a}=Ew(n),s=Dw(t.state,a,o.value.from),c=Dw(t.state,a,o.value.to);if(n.slice(s,c)!==e.rawContent.slice(i.from,i.to))throw Error(`Explicit move changed source`);r={...r,[i.id]:{...i,from:s,to:c}}}}if(t.docChanged||t.effects.some(e=>e.is(xw)||e.is(Cw)||e.is(Sw)||e.is(Tw))){let o=e.sections.map(e=>({...e,from:t.changes.mapPos(e.from,1),to:t.changes.mapPos(e.to,-1)}));return kw(t.state,n,i,r,a,o)}return e}}),jw=Gr.of(e=>{let t=e.startState.field(Aw,!1);return t&&e.docChanged?[Tw.of({rawContent:t.rawContent,blocks:Ow(t)})]:[]});function Mw(e,t){return e.field(Aw).sections.find(e=>t>=e.from&&t<=e.to)??null}function Nw(e){return Mw(e,e.selection.main.head)}function Pw(e,t){if(!e.trim())return[];let n=e.endsWith(`
70
+ `)?e:e+`
71
+ `,r=ri.create({doc:n,extensions:[bc]}),i=Ir(r),a=[];return i.iterate({enter(e){if(e.type.isError){let n=t+e.from,r=t+Math.max(e.to,e.from+1);a.push({from:n,to:Math.min(r,n+50),severity:`error`,message:`Syntax error in Whiteboard Script`})}}}),a}function Fw(e){let{sections:t}=e.state.field(Aw,!1)??{sections:[]},n=[];for(let r of t){if(r.type!==`time`&&r.type!==`log`||r.contentFrom===void 0||r.contentTo===void 0)continue;let t=Pw(e.state.doc.sliceString(r.contentFrom,r.contentTo),r.contentFrom);n.push(...t)}return n}var Iw=_i(Fw,{delay:500}),Lw=[{label:"```time",detail:`Whiteboard Script (timer)`,type:`keyword`,apply:ai("```time\n${}\n```"),boost:90},{label:"```log",detail:`Whiteboard Script (log/completed)`,type:`keyword`,apply:ai("```log\n${}\n```"),boost:85},{label:"```query",detail:`WQL Analytics Query`,type:`keyword`,apply:ai("```query\n${}\n```"),boost:80},{label:"```widget",detail:`Custom React Widget`,type:`keyword`,apply:ai("```widget:${name}\n${}\n```"),boost:75}];function Rw(e){let t=e.state.doc.lineAt(e.pos);if(!t.text.slice(0,e.pos-t.from).match(/^`{1,3}(\w*)$/))return null;let n=Nw(e.state);return n&&n.type!==`markdown`?null:{from:t.from,options:Lw,validFor:/^`{1,3}\w*$/}}function zw(e){if(e.state.readOnly)return!1;let{from:t,to:n}=e.state.selection.main,r=e.state.doc.sliceString(t,n);return r?e.dispatch({changes:{from:t,to:n,insert:`\`\`\`time\n${r}\n\`\`\``}}):e.dispatch({changes:{from:t,insert:"```time\n\n```"},selection:{anchor:t+8}}),!0}function Bw(e,t){if(t.state.readOnly||e.data!=="`")return!1;let{from:n,to:r}=t.state.selection.main;if(n===r)return!1;let i=t.state.doc.sliceString(n,r);return t.dispatch({changes:{from:n,to:r,insert:`\`\`\`time\n${i}\n\`\`\``}}),!0}var Vw=Er.domEventHandlers({beforeinput:Bw}),Hw=yr.of([{key:`Mod-Alt-w`,run:zw}]),Uw=[];function Ww(e){Uw.includes(e)||Uw.push(e)}function Gw(e){let t=Uw.indexOf(e);t!==-1&&Uw.splice(t,1)}var Kw=Jr({interactionDelay:0,activateOnCompletion:e=>e.type===`property`&&typeof e.apply==`string`&&e.apply.endsWith(`:
72
+ - `),override:[Rw,async e=>{for(let t of Uw){let n=await t(e);if(n)return n}return null}]}),qw=class{view;rects=[];docVersion=0;listeners=new Set;pendingNotify=null;constructor(e){this.view=e,this.measure()}update(e){e.docChanged&&this.docVersion++,(e.docChanged||e.geometryChanged)&&this.measure()}addListener(e){return this.listeners.add(e),e(this.rects,this.docVersion),()=>{this.listeners.delete(e)}}measure(){try{let e=this.view.state.field(Aw,!1)?.sections??[],t=this.view.state.doc.length;this.rects=e.map(e=>{let n=Math.max(0,Math.min(e.from,t)),r=Math.max(0,Math.min(e.to,t)),i=0,a=20,o;try{let e=this.view.lineBlockAt(n),t=this.view.lineBlockAt(r);i=e.top,o=e.height,a=t.top+t.height}catch{}let s=Math.max(a-i,20);return{sectionId:e.id,top:i,height:s,firstLineHeight:o,type:e.type,subtype:e.subtype,widgetName:e.widgetName}}),this.notify()}catch{}}notify(){if(typeof requestAnimationFrame==`function`){if(this.pendingNotify!==null)return;this.pendingNotify=requestAnimationFrame(()=>{this.pendingNotify=null;for(let e of this.listeners)e(this.rects,this.docVersion)})}else for(let e of this.listeners)e(this.rects,this.docVersion)}destroy(){this.pendingNotify!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(this.pendingNotify),this.listeners.clear()}},Jw=Vr.fromClass(qw),Yw=class extends Tr{eq(e){return!0}toDOM(){let e=document.createElement(`div`);return e.className=`cm-wod-block-footer`,e}get estimatedHeight(){return 28}get block(){return!0}},Xw=class extends Tr{eq(e){return!0}toDOM(){let e=document.createElement(`div`);return e.className=`cm-wod-insert-spacer`,e}get estimatedHeight(){return 28}get block(){return!0}},Zw=new Yw,Qw=new Xw,$w=Br.line({attributes:{class:`cm-wod-fence cm-wod-fence-open`}}),eT=Br.line({attributes:{class:`cm-wod-fence cm-wod-fence-close`}}),tT=Br.line({attributes:{class:`cm-wod-inner`}});function nT(e){let t=new vi,{sections:n}=e.field(Aw),r=e.selection.main.head,i=e.doc.lineAt(r).number;for(let r of n){if(r.type!==`time`&&r.type!==`log`)continue;let n=i>r.startLine&&i<r.endLine,a=e.doc.line(r.startLine),o=e.doc.line(r.endLine);if(r.endLine<=r.startLine){t.add(a.from,a.from,$w);continue}t.add(a.from,a.from,$w);for(let a=r.startLine+1;a<r.endLine;a++){let r=e.doc.line(a);t.add(r.from,r.from,tT),n&&a===i&&t.add(r.to,r.to,Br.widget({widget:Qw,block:!0,side:1}))}n||t.add(o.from,o.from,Br.widget({widget:Zw,block:!0,side:-1})),t.add(o.from,o.from,eT)}return t.finish()}var rT=[si.define({create(e){return nT(e)},update(e,t){return t.docChanged||t.selection?nT(t.state):e},provide:e=>Er.decorations.from(e)}),Er.baseTheme({".cm-wod-fence":{opacity:`0.5`,fontSize:`0.85em`,color:`hsl(var(--metric-time))`,paddingLeft:`8px`,paddingRight:`8px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`},".cm-wod-fence-open":{borderTop:`1px solid hsl(var(--border) / 0.5)`,borderRadius:`6px 6px 0 0`,paddingTop:`26px`,backgroundColor:`transparent`,backgroundImage:`linear-gradient(to bottom, transparent 27px, rgba(128, 128, 128, 0.05) 27px)`},".cm-wod-fence-close":{borderBottom:`1px solid hsl(var(--border) / 0.5)`,borderRadius:`0 0 6px 6px`},".cm-wod-inner":{paddingLeft:`8px`,paddingRight:`8px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`},".cm-wod-block-footer":{height:`28px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`,pointerEvents:`none`},".cm-wod-insert-spacer":{height:`28px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`,pointerEvents:`none`}})],iT=class extends Tr{height;constructor(e){super(),this.height=e}eq(e){return e.height===this.height}toDOM(){let e=document.createElement(`div`);return e.className=`cm-embed-spacer`,e.style.height=`${this.height}px`,e.style.pointerEvents=`none`,e}get estimatedHeight(){return this.height}get block(){return!0}};function aT(e){let t=new vi,{sections:n}=e.field(Aw);for(let r of n)if(r.type===`embed`&&r.embed?.height){let n=e.doc.line(r.startLine);t.add(n.from,n.from,Br.widget({widget:new iT(r.embed.height),side:1}))}return t.finish()}var oT=[si.define({create(e){return aT(e)},update(e,t){return t.docChanged?aT(t.state):e},provide:e=>Er.decorations.from(e)})],sT=qr.define({combine:e=>e[0]??null}),cT=qr.define({combine:e=>e[0]??null}),lT=Xr.define(),uT=qr.define({combine:e=>e[0]??!0}),dT=new WeakMap,fT=new WeakMap,pT=0;function mT(e){return[`tag`,`tags`,`category`].includes(e.trim().toLowerCase())}function hT(e,t,n,r,i,a,o,s=`tags`){let c=t.state.facet(sT);if(!c||!e.parentElement)return;let l=e.parentElement;l.classList.add(`relative`);let u=document.createElement(`div`);u.id=`frontmatter-suggestions-${++pT}`,u.setAttribute(`role`,`listbox`),u.className=`absolute left-0 top-full z-50 max-h-48 overflow-auto rounded-md border border-border bg-background shadow-md min-w-full text-xs`,u.hidden=!0,l.appendChild(u),e.setAttribute(`role`,`combobox`),e.setAttribute(`aria-autocomplete`,`list`),e.setAttribute(`aria-controls`,u.id),e.setAttribute(`aria-expanded`,`false`);let d=0,f=[],p=-1,m=()=>{d++,f=[],p=-1,u.hidden=!0,e.setAttribute(`aria-expanded`,`false`),e.removeAttribute(`aria-activedescendant`)},h=t=>{e.value=t.value,m(),o()},g=t=>{p=t,Array.from(u.children).forEach((e,t)=>{e.setAttribute(`aria-selected`,String(t===p)),e.classList.toggle(`bg-muted`,t===p)});let n=u.children[p];n&&(e.setAttribute(`aria-activedescendant`,n.id),n instanceof HTMLElement&&n.scrollIntoView?.({block:`nearest`}))},_=async(t=!1)=>{m();let n=++d,o=t?``:e.value.trim().toLowerCase();try{let t=await c();if(n!==d||!e.isConnected||document.activeElement!==e)return;let l;l=r===`key`?t.types.map(e=>({value:e,label:e,haystack:e})):s===`effort`||s===`equipment`?(s===`effort`?t.efforts??[]:t.equipment??[]).map(e=>({value:e.slug,label:`${e.label} (${e.slug})`,haystack:[e.label,e.slug,...e.aliases].join(` `).toLowerCase()})):t.tags.filter(e=>mT(i)||e.type?.toLowerCase()===i.trim().toLowerCase()).map(e=>({value:e.label,label:e.label,haystack:e.label.toLowerCase()}));let m=new Set(a.map(e=>e.toLowerCase()));f=l.filter(e=>(o===``||e.haystack.includes(o))&&!m.has(e.value.toLowerCase())),p=-1,e.removeAttribute(`aria-activedescendant`),u.replaceChildren(),f.forEach((e,t)=>{let n=document.createElement(`div`);n.id=`${u.id}-${t}`,n.setAttribute(`role`,`option`),n.setAttribute(`aria-selected`,`false`),n.className=`cursor-pointer px-2 py-1.5 hover:bg-muted`,n.textContent=e.label,n.addEventListener(`mousedown`,e=>e.preventDefault()),n.addEventListener(`click`,()=>h(e)),u.appendChild(n)}),u.hidden=f.length===0,e.setAttribute(`aria-expanded`,String(f.length>0))}catch{n===d&&m()}};e.addEventListener(`focus`,()=>void _(!0)),e.addEventListener(`input`,()=>void _(!1)),e.addEventListener(`blur`,m),e.addEventListener(`keydown`,e=>{if(e.ctrlKey&&(e.code===`Space`||e.key===` `))e.preventDefault(),_(!0);else if(e.key===`Escape`)e.preventDefault(),m();else if((e.key===`ArrowDown`||e.key===`ArrowUp`)&&f.length){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;g(p<0?t===1?0:f.length-1:(p+t+f.length)%f.length)}else(e.key===`Enter`||e.key===`Tab`)&&p>=0&&(e.preventDefault(),h(f[p]))}),fT.get(n)?.push(m)}function gT(e){if(Array.isArray(e))return e.map(String).map(e=>e.trim()).filter(Boolean);if(typeof e==`string`&&e.trim()){let t=e.trim();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/g,``)).filter(Boolean):[t.replace(/^['"]|['"]$/g,``)]}return[]}function _T(e,t,n,r){if(e.state.readOnly)return;let i=e.state.doc.toString(),a=qa(i,n,r);a!==i&&e.dispatch({changes:{from:0,to:i.length,insert:a}})}function vT(e,t,n,r,i){if(e.state.readOnly)return;let a=e.state.doc.toString(),o=qa(qa(a,[r],i),[n],null);o!==a&&e.dispatch({changes:{from:0,to:a.length,insert:o}})}function yT(e){let t=typeof e.type==`string`?e.type.trim().toLowerCase():``;return t===`effort`?`effort`:t===`equipment`?`equipment`:e.registrySource!==void 0||e.baseAttributes!==void 0?`effort`:null}function bT(e){let t={},n=!1;for(let r of e.split(/\r?\n/)){if(/^baseAttributes:\s*(#.*)?$/.test(r)){n=!0;continue}if(!n)continue;if(/^\S/.test(r))break;let e=r.match(/^\s+([\w-]+):\s*(.*)$/);e&&(e[1]===`met`||e[1]===`discipline`||e[1]===`intensityTier`)&&(t[e[1]]=xT(e[2].trim()))}return t}function xT(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1).replace(/\\(["\\])/g,`$1`):e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1).replace(/\\'/g,`'`):e}function ST(e,t){let n=e.trim().toLowerCase();return n===`metrics.effort`?`effort`:n===`metrics.equipment`||n===`equipment`||n===`aliases`&&t===`equipment`?`equipment`:n===`aliases`&&t===`effort`?`effort`:`tags`}function CT(e,t){let n=e.trim().toLowerCase();return n===`metrics.effort`||n===`metrics.equipment`||n===`equipment`&&t===`effort`}function wT(e,t,n,r){let i=document.createElement(`div`);i.className=`flex items-center min-h-[34px] border-b border-dashed border-border/60 last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,i.setAttribute(`data-frontmatter-tag-draft`,`true`);let a=document.createElement(`div`);a.className=`flex items-center gap-2 px-3 py-1.5 w-36 shrink-0 border-r border-dashed border-border/60 text-muted-foreground max-[479px]:w-auto max-[479px]:border-r-0 max-[479px]:border-b`,a.appendChild(kT());let o=document.createElement(`span`);o.className=`truncate font-medium text-foreground/90`,o.textContent=n,a.appendChild(o),i.appendChild(a);let s=document.createElement(`div`);s.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`;let c=document.createElement(`input`);c.className=`flex-1 min-w-[70px] bg-transparent text-xs text-foreground outline-none px-1 py-0.5 placeholder:text-muted-foreground/40`,c.placeholder=`Add tag…`,c.setAttribute(`aria-label`,`Add tag to ${n}`),s.appendChild(c),i.appendChild(s);let l=!1,u=t=>{if(!l){if(l=!0,t){let e=c.value.trim().replace(/^,|,$/g,``);e&&r(e)}i.remove(),e.requestMeasure()}},d=()=>u(!0),f=()=>u(!1);return hT(c,e,t,`value`,n,[],d),c.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),f();return}e.defaultPrevented||(e.key===`Enter`||e.key===`,`)&&(e.preventDefault(),d())}),c.addEventListener(`blur`,()=>queueMicrotask(()=>{c.isConnected&&(c.value.trim()?d():f())})),i}function TT(e,t){let n=e.split(/\r?\n/);for(let e=0;e<n.length;e++)if(RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}:\\s*$`).test(n[e]))return e+1<n.length&&/^\s+\S/.test(n[e+1]);return!1}function ET(e,t,n){let r=t.trim();if(!r||e.resolveEffort(r))return null;let i=e.resolve(r).diagnostics,a=document.createElement(`div`);a.setAttribute(`data-testid`,`editor-ref-unknown`),a.className=`w-full basis-full flex flex-wrap items-center gap-2 text-[10px] text-destructive`;let o=document.createElement(`span`);o.textContent=i[0]?.message||`Unknown effort: ${r}`,a.appendChild(o);for(let e of i[0]?.candidates??[]){let t=document.createElement(`button`);t.type=`button`,t.textContent=`Use ${e}`,t.className=`underline hover:text-foreground cursor-pointer`,t.addEventListener(`click`,t=>{t.preventDefault(),n(e)}),a.appendChild(t)}let s=document.createElement(`a`);return s.href=e.createHref(`effort`),s.textContent=`Create page`,s.className=`underline hover:text-foreground`,a.appendChild(s),a}var DT={effort:{label:`Effort`,path:`metrics.effort`,kind:`effort`},equipment:{label:`Equipment`,path:`metrics.equipment`,kind:`equipment`},rpe:{label:`RPE`,path:`metrics.rpe`,kind:`number`}};function OT(e,t,n,r){let i=document.createElement(`div`);i.className=`flex items-center min-h-[34px] border-b border-dashed border-border/60 last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,i.setAttribute(`data-frontmatter-metric-draft`,`true`);let a=document.createElement(`select`);a.setAttribute(`aria-label`,`Metric kind`),a.className=`mx-3 my-1.5 h-7 w-28 shrink-0 rounded-md border border-input bg-background px-1.5 text-[11px] text-muted-foreground outline-none`;for(let[e,t]of Object.entries(DT)){let n=document.createElement(`option`);n.value=e,n.textContent=t.label,a.appendChild(n)}i.appendChild(a);let o=document.createElement(`div`);o.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`;let s=document.createElement(`input`);s.className=`flex-1 min-w-[70px] bg-transparent text-xs text-foreground outline-none px-1 py-0.5 placeholder:text-muted-foreground/40`,s.placeholder=`Value…`,s.setAttribute(`aria-label`,`Metric value`),o.appendChild(s),i.appendChild(o);let c=!1,l=t=>{if(c)return;c=!0;let n=DT[a.value],o=s.value.trim();if(t&&n&&o){if(n.kind===`equipment`)r([n.path],[o]);else if(n.kind===`number`){let e=Number(o);Number.isNaN(e)||r([n.path],e)}else r([n.path],o)}i.remove(),e.requestMeasure()},u=()=>{let r=DT[a.value];r&&(r.kind===`effort`||r.kind===`equipment`)&&n&&hT(s,e,t,`value`,r.path,[],()=>l(!0),r.kind)};return u(),a.addEventListener(`change`,u),s.addEventListener(`keydown`,e=>{if(!(e.defaultPrevented&&e.key!==`Escape`)){if(e.key===`Escape`){e.preventDefault(),l(!1);return}e.key===`Enter`&&(e.preventDefault(),l(!0))}}),s.addEventListener(`blur`,()=>queueMicrotask(()=>{s.isConnected&&l(s.value.trim().length>0)})),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),l(!1))}),i}function kT(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`shrink-0 h-3.5 w-3.5 text-muted-foreground/70`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,`M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);return n.setAttribute(`cx`,`7`),n.setAttribute(`cy`,`7`),n.setAttribute(`r`,`.5`),n.setAttribute(`fill`,`currentColor`),e.appendChild(n),e}function AT(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`shrink-0 h-3.5 w-3.5 text-muted-foreground/70`);for(let t of[`6`,`12`,`18`]){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`4`),n.setAttribute(`x2`,`20`),n.setAttribute(`y1`,t),n.setAttribute(`y2`,t),e.appendChild(n)}return e}function jT(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`shrink-0 h-3 w-3`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);t.setAttribute(`x1`,`12`),t.setAttribute(`x2`,`12`),t.setAttribute(`y1`,`5`),t.setAttribute(`y2`,`19`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);return n.setAttribute(`x1`,`5`),n.setAttribute(`x2`,`19`),n.setAttribute(`y1`,`12`),n.setAttribute(`y2`,`12`),e.appendChild(n),e}function MT(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`h-3 w-3`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,`M15 3h6v6`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`10`),n.setAttribute(`x2`,`21`),n.setAttribute(`y1`,`14`),n.setAttribute(`y2`,`3`),e.appendChild(n);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`polyline`);return r.setAttribute(`points`,`21 14 21 3 10 3`),e.appendChild(r),e}function NT(e=`md`){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,e===`sm`?`2.5`:`2`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`class`,e===`sm`?`h-2.5 w-2.5`:`h-3.5 w-3.5`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`18`),n.setAttribute(`x2`,`6`),n.setAttribute(`y1`,`6`),n.setAttribute(`y2`,`18`),t.appendChild(n);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);return r.setAttribute(`x1`,`6`),r.setAttribute(`x2`,`18`),r.setAttribute(`y1`,`6`),r.setAttribute(`y2`,`18`),t.appendChild(r),t}var PT=class extends Tr{sectionId;rawContent;readOnly;constructor(e,t,n=!1){super(),this.sectionId=e,this.rawContent=t??``,this.readOnly=n}eq(e){return this.sectionId===e.sectionId&&this.rawContent===e.rawContent&&this.readOnly===e.readOnly}ignoreEvent(){return!0}toDOM(e){let t=document.createElement(`div`);fT.set(t,[]),t.className=`cm-frontmatter-preview py-2 font-sans select-none`;let n=document.createElement(`div`);n.className=`text-xs font-medium text-muted-foreground mb-1.5 px-0.5`,n.textContent=`Properties`,t.appendChild(n);let r=document.createElement(`div`);r.className=`rounded-lg border border-border/80 bg-background/50 text-xs shadow-xs`,t.appendChild(r);let i=this.rawContent.replace(/^---\r?\n?/,``).replace(/\r?\n?---\r?$/,``),a=O_(i),o=Object.entries(a),s=yT(a),c=e.state.facet(cT)?.()??null,l=s===`effort`?bT(i):{};if(o.length===0){let e=document.createElement(`div`);e.className=`px-3 py-2 text-xs text-muted-foreground/60 italic`,e.textContent=`No properties`,r.appendChild(e)}for(let[n,l]of o){let u=mT(n),d=ST(n,s),f=(CT(n,s)||n===`aliases`)&&Array.isArray(l),p=l===``&&TT(i,n),m=document.createElement(`div`);m.className=`flex items-center min-h-[34px] border-b border-dashed border-border/60 last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,r.appendChild(m);let h=document.createElement(`div`);if(h.className=`flex items-center gap-2 px-3 py-1.5 w-36 shrink-0 border-r border-dashed border-border/60 text-muted-foreground max-[479px]:w-auto max-[479px]:border-r-0 max-[479px]:border-b`,h.appendChild(u||f?kT():AT()),this.readOnly||p){let e=document.createElement(`span`);e.className=`truncate font-medium text-foreground/90`,e.textContent=n,h.appendChild(e)}else{let r=document.createElement(`input`);r.className=`w-full bg-transparent text-xs text-foreground/90 font-medium outline-none truncate hover:bg-muted/30 focus:bg-background focus:ring-1 focus:ring-ring rounded px-1 -mx-1`,r.value=n,r.spellcheck=!1,r.setAttribute(`aria-label`,`Property name ${n}`);let i=n,s=()=>{let t=r.value.trim();if(!t||t===i){r.value=i;return}if(!/^[A-Za-z_][\w.-]*$/.test(t)||t in a){r.value=i;return}vT(e,this.sectionId,i,t,l),delete a[i],a[t]=l,i=t},c=()=>queueMicrotask(()=>{r.isConnected&&s()});r.addEventListener(`change`,c),h.appendChild(r),hT(r,e,t,`key`,n,o.map(([e])=>e),s),r.addEventListener(`blur`,c),r.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Enter`&&(e.preventDefault(),r.blur())});let u=dT.get(e);u?.kind===`key`&&u.key===n&&(setTimeout(()=>{r.isConnected&&(r.focus(),r.select())},0),dT.delete(e))}m.appendChild(h);let g=document.createElement(`div`);g.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`;let _=t=>{a[n]=t,_T(e,this.sectionId,[n],t.length>0?t:``)},v=e=>c?d===`effort`?c.resolveEffort(e):d===`equipment`?c.resolveEquipment(e):null:null;if(u||f){let r=gT(l),i=d!==`tags`;for(let e=0;e<r.length;e++){let t=r[e],n=i?v(t):null,a=document.createElement(`span`);a.className=n?`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-muted/60 text-foreground border border-border/60`:i?`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-destructive/10 text-destructive border border-destructive/30`:`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-amber-500/10 text-amber-800 dark:text-amber-300 border border-amber-500/20 dark:border-amber-500/30`;let o=document.createElement(`span`);if(o.textContent=n?n.label:t,a.appendChild(o),n&&c){let e=document.createElement(`a`);e.href=c.openHref(d,n.slug),e.title=`Open ${n.label} page`,e.setAttribute(`aria-label`,`Open ${n.label} page`),e.className=`inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground cursor-pointer`,e.appendChild(MT()),a.appendChild(e)}if(!this.readOnly){let n=document.createElement(`button`);n.type=`button`,n.setAttribute(`aria-label`,u?`Remove tag ${t}`:`Remove ${t}`),n.className=`inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground dark:hover:text-foreground cursor-pointer`,n.appendChild(NT(`sm`)),n.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),_(r.filter((t,n)=>n!==e))}),a.appendChild(n)}g.appendChild(a)}if(!this.readOnly){let a=document.createElement(`input`);a.className=`flex-1 min-w-[70px] bg-transparent text-xs text-foreground outline-none px-1 py-0.5 placeholder:text-muted-foreground/40`,a.placeholder=r.length===0?f?`Add ${d===`effort`?`effort`:`equipment`}…`:`Add tags…`:u?`Add tag…`:`Add…`,a.setAttribute(`aria-label`,u?`Add tag to ${n}`:`Add to ${n}`);let o=()=>{let t=a.value.trim().replace(/^,|,$/g,``);t&&!r.some(e=>e.toLowerCase()===t.toLowerCase())&&(a.value=``,dT.set(e,{kind:`tag`,key:n}),_([...r,t]))};g.appendChild(a),hT(a,e,t,`value`,n,r,o,d),a.addEventListener(`keydown`,t=>{t.defaultPrevented||(t.key===`Enter`||t.key===`,`?(t.preventDefault(),o()):t.key===`Backspace`&&!a.value&&r.length>0&&(t.preventDefault(),dT.set(e,{kind:`tag`,key:n}),_(r.slice(0,-1))))}),a.addEventListener(`blur`,()=>queueMicrotask(()=>{a.isConnected&&a.value.trim()&&o()}));let s=dT.get(e);if(s?.kind===`tag`&&s.key===n&&(setTimeout(()=>{a.isConnected&&a.focus()},0),dT.delete(e)),i&&c){let e=r.filter(e=>!v(e));if(e.length>0){let t=document.createElement(`div`);t.setAttribute(`data-testid`,`editor-ref-unknown`),t.className=`w-full basis-full flex flex-wrap items-center gap-2 text-[10px] text-destructive`;let n=document.createElement(`span`);n.textContent=`Unknown ${d===`effort`?`effort`:`equipment`}: ${e.join(`, `)}`,t.appendChild(n);let r=document.createElement(`button`);r.type=`button`,r.textContent=`Select existing`,r.className=`underline hover:text-foreground cursor-pointer`,r.addEventListener(`click`,e=>{e.preventDefault(),a.focus()}),t.appendChild(r);let i=document.createElement(`a`);i.href=c.createHref(d),i.textContent=`Create page`,i.className=`underline hover:text-foreground`,t.appendChild(i),g.appendChild(t)}}}}else if(p){let e=document.createElement(`span`);e.className=`text-xs text-muted-foreground/60 italic py-0.5 truncate`,e.textContent=`Nested block — edit in YAML`,g.appendChild(e)}else{let r=Array.isArray(l)?l.join(`, `):String(l??``);if(this.readOnly){let e=document.createElement(`span`);e.className=`text-xs text-foreground py-0.5 truncate`,e.textContent=r,g.appendChild(e)}else{let i=document.createElement(`input`);i.className=`w-full bg-transparent text-xs text-foreground outline-none py-0.5 hover:bg-muted/20 focus:bg-background focus:ring-1 focus:ring-ring rounded px-1 -mx-1 transition-colors`,i.value=r,i.spellcheck=!1,i.setAttribute(`aria-label`,`Value for ${n}`);let o=r,s=()=>{let t=i.value.trim();if(t!==o){o=t;let r=Number(t),i=t!==``&&!isNaN(r)?r:t;a[n]=i,_T(e,this.sectionId,[n],i)}},l=()=>queueMicrotask(()=>{i.isConnected&&s()});if(i.addEventListener(`change`,l),g.appendChild(i),hT(i,e,t,`value`,n,[r],s,n.trim().toLowerCase()===`metrics.effort`?`effort`:`tags`),i.addEventListener(`blur`,l),i.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Enter`&&(e.preventDefault(),i.blur())}),n.trim().toLowerCase()===`metrics.effort`&&c){let t=c.resolveEffort(r);if(t){let e=document.createElement(`span`);e.className=`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-muted/60 text-foreground border border-border/60 shrink-0`;let n=document.createElement(`span`);n.textContent=t.label,e.appendChild(n);let r=document.createElement(`a`);r.href=c.openHref(`effort`,t.slug),r.title=`Open ${t.label} page`,r.setAttribute(`aria-label`,`Open ${t.label} page`),r.className=`inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground cursor-pointer`,r.appendChild(MT()),e.appendChild(r),g.insertBefore(e,i),i.className=`flex-1 min-w-[70px] bg-transparent text-xs text-foreground outline-none py-0.5 hover:bg-muted/20 focus:bg-background focus:ring-1 focus:ring-ring rounded px-1 -mx-1 transition-colors`}let o=ET(c,r,t=>{a[n]=t,_T(e,this.sectionId,[n],t)});o&&g.appendChild(o)}}if(/^https?:\/\/\S+$/i.test(r)){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.title=r,e.setAttribute(`aria-label`,`Open ${n} in new tab`),e.className=`shrink-0 inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground transition-colors cursor-pointer`,e.appendChild(MT()),g.appendChild(e)}}if(m.appendChild(g),!this.readOnly&&!p){let t=document.createElement(`div`);t.className=`flex items-center pr-2`;let r=document.createElement(`button`);r.type=`button`,r.setAttribute(`aria-label`,`Remove property ${n}`),r.className=`opacity-0 group-hover:opacity-100 text-muted-foreground/40 hover:text-destructive p-1 rounded transition-opacity cursor-pointer`,r.appendChild(NT(`md`)),r.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),delete a[n],_T(e,this.sectionId,[n],null)}),t.appendChild(r),m.appendChild(t)}}if(s===`effort`&&!this.readOnly&&r.appendChild(this.buildDefinitionRows(e,l)),!this.readOnly){let n=o.find(([e])=>mT(e))?.[0],i=document.createElement(`div`);i.className=`mt-2 flex items-center gap-3`;let s=document.createElement(`button`);s.type=`button`,s.setAttribute(`aria-label`,`Add property`),s.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,s.appendChild(jT());let l=document.createElement(`span`);l.textContent=`Add property`,s.appendChild(l),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation();let n=`property`,r=1;for(;n in a;)r++,n=`property_${r}`;dT.set(e,{kind:`key`,key:n}),_T(e,this.sectionId,[n],``)}),i.appendChild(s);{let n=document.createElement(`button`);n.type=`button`,n.setAttribute(`aria-label`,`Add metric`),n.setAttribute(`data-testid`,`editor-add-metric-note`),n.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,n.appendChild(jT());let a=document.createElement(`span`);a.textContent=`Add metric`,n.appendChild(a),n.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation();let i=t.querySelector(`[data-frontmatter-metric-draft] input`);if(i){i.focus();return}let a=OT(e,t,c,(t,n)=>{_T(e,this.sectionId,t,n)});r.appendChild(a),a.querySelector(`input`)?.focus(),e.requestMeasure()}),i.appendChild(n)}{let a=document.createElement(`button`);a.type=`button`,a.setAttribute(`aria-label`,`Add tag`),a.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,a.appendChild(jT());let o=document.createElement(`span`);o.textContent=`Add tag`,a.appendChild(o),a.addEventListener(`click`,i=>{if(i.preventDefault(),i.stopPropagation(),n){Array.from(t.querySelectorAll(`input`)).find(e=>e.getAttribute(`aria-label`)===`Add tag to ${n}`)?.focus();return}let a=t.querySelector(`[data-frontmatter-tag-draft] input`);if(a){a.focus();return}let o=wT(e,t,`tags`,t=>{dT.set(e,{kind:`tag`,key:`tags`}),_T(e,this.sectionId,[`tags`],[t])});r.appendChild(o),o.querySelector(`input`)?.focus(),e.requestMeasure()}),i.appendChild(a)}{let t=document.createElement(`button`);t.type=`button`,t.setAttribute(`aria-label`,`Edit YAML`),t.setAttribute(`data-testid`,`editor-property-edit-yaml`),t.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`;let n=document.createElement(`span`);n.textContent=`Edit YAML`,t.appendChild(n),t.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation();let{sections:n}=e.state.field(Aw),r=n.find(e=>e.id===this.sectionId&&e.type===`frontmatter`)||n.find(e=>e.type===`frontmatter`);r&&(e.dispatch({selection:{anchor:r.contentFrom??r.from},scrollIntoView:!0}),e.focus())}),i.appendChild(t)}t.appendChild(i)}return t}buildDefinitionRows(e,t){let n=document.createElement(`div`);n.setAttribute(`data-frontmatter-definition`,`true`),n.className=`border-t border-dashed border-border/60`;let r=document.createElement(`div`);r.className=`px-3 pt-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground`,r.textContent=`Definition`,n.appendChild(r);let i=(t,n)=>{if(t===`met`){let t=Number(n);_T(e,this.sectionId,[`baseAttributes`,`met`],n!==``&&!Number.isNaN(t)?t:null);return}_T(e,this.sectionId,[`baseAttributes`,t],n===``?null:n)},a=(e,t)=>{let r=document.createElement(`label`);r.className=`flex items-center gap-2 px-3 py-1.5 min-h-[34px] border-b border-dashed border-border/60 last:border-b-0 max-[479px]:flex-col max-[479px]:items-stretch`;let i=document.createElement(`span`);i.className=`w-28 shrink-0 text-muted-foreground`,i.textContent=e,r.appendChild(i),t.className=`flex-1 min-w-0 bg-transparent text-xs text-foreground outline-none py-0.5`,r.appendChild(t),n.appendChild(r)},o=document.createElement(`input`);o.type=`number`,o.step=`0.1`,o.inputMode=`decimal`,o.value=t.met??``,o.setAttribute(`aria-label`,`MET value`),o.addEventListener(`change`,()=>queueMicrotask(()=>{o.isConnected&&i(`met`,o.value.trim())})),a(`MET`,o);let s=document.createElement(`select`);s.setAttribute(`aria-label`,`Discipline`),s.className=`flex-1 min-w-0 rounded-md border border-input bg-background px-1.5 text-[11px] text-muted-foreground outline-none`;let c=document.createElement(`option`);c.value=``,c.textContent=`Unset`,s.appendChild(c);for(let e of xc){let t=document.createElement(`option`);t.value=e,t.textContent=e,s.appendChild(t)}s.value=t.discipline??``,s.addEventListener(`change`,()=>i(`discipline`,s.value)),a(`Discipline`,s);let l=document.createElement(`select`);l.setAttribute(`aria-label`,`Intensity tier`),l.className=`flex-1 min-w-0 rounded-md border border-input bg-background px-1.5 text-[11px] text-muted-foreground outline-none`;let u=document.createElement(`option`);u.value=``,u.textContent=`Unset`,l.appendChild(u);for(let e of[`low`,`moderate`,`high`]){let t=document.createElement(`option`);t.value=e,t.textContent=e,l.appendChild(t)}return l.value=t.intensityTier??``,l.addEventListener(`change`,()=>i(`intensityTier`,l.value)),a(`Intensity tier`,l),n}destroy(e){fT.get(e)?.forEach(e=>e()),fT.delete(e)}},FT=class extends Tr{eq(e){return!0}ignoreEvent(){return!0}toDOM(e){let t=document.createElement(`div`);t.className=`cm-frontmatter-preview py-2 font-sans select-none`;let n=document.createElement(`div`);n.className=`text-xs font-medium text-muted-foreground mb-1.5 px-0.5`,n.textContent=`Properties`,t.appendChild(n);let r=document.createElement(`div`);r.className=`flex items-center gap-3`;let i=document.createElement(`button`);i.type=`button`,i.setAttribute(`aria-label`,`Add property`),i.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,i.appendChild(jT());let a=document.createElement(`span`);a.textContent=`Add property`,i.appendChild(a),i.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),dT.set(e,{kind:`key`,key:`property`}),_T(e,`new`,[`property`],``)}),r.appendChild(i);let o=document.createElement(`button`);o.type=`button`,o.setAttribute(`aria-label`,`Add tag`),o.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,o.appendChild(jT());let s=document.createElement(`span`);return s.textContent=`Add tag`,o.appendChild(s),o.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation();let r=t.querySelector(`[data-frontmatter-tag-draft] input`);if(r){r.focus();return}let i=wT(e,t,`tags`,t=>{dT.set(e,{kind:`tag`,key:`tags`}),_T(e,`new`,[`tags`],[t])});t.appendChild(i),i.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(o),t.appendChild(r),t}};function IT(e){let t=new vi,{sections:n}=e.field(Aw),r=e.facet(uT),i=!1;for(let a of n){if(a.type!==`frontmatter`)continue;if(i=!0,!r){let n=a.to<e.doc.length?a.to+1:a.to;t.add(a.from,n,Br.replace({block:!0}));continue}if(!e.readOnly&&e.selection.ranges.some(e=>e.from<a.to&&e.to>a.from))continue;let n=e.doc.sliceString(a.from,a.to);t.add(a.from,a.to,Br.replace({widget:new PT(a.id,n,e.readOnly),block:!0}))}return r&&!i&&!e.readOnly&&t.add(0,0,Br.widget({widget:new FT,side:-1,block:!0})),t.finish()}var LT=[si.define({create(e){return IT(e)},update(e,t){return t.docChanged||t.reconfigured||t.selection||t.effects.some(e=>e.is(lT))?IT(t.state):e},provide:e=>[Er.decorations.from(e),Er.atomicRanges.of(t=>t.state.facet(uT)?Br.none:t.state.field(e))]})],RT=/^(#{1,6}) /,zT=/\*\*([^*\n]+)\*\*/g,BT=/(?<!\*)\*([^*\n]+)\*(?!\*)/g,VT=[1,2,3,4,5,6].map(e=>Br.line({attributes:{class:`cm-md-heading cm-md-heading-${e}`}})),HT=Br.replace({}),UT=Br.mark({class:`cm-md-bold font-bold`}),WT=Br.mark({class:`cm-md-italic italic`});function GT(e){let t=new vi,{sections:n}=e.field(Aw),r=e.selection.main.head;for(let i of n)if(i.type===`markdown`)for(let n=i.startLine;n<=i.endLine;n++){let i=e.doc.line(n),a=r>=i.from&&r<=i.to,o=i.text.match(RT);if(o){let e=o[1].length;t.add(i.from,i.from,VT[e-1]),a||t.add(i.from,i.from+o[0].length,HT)}if(!a){let e;for(zT.lastIndex=0;(e=zT.exec(i.text))!==null;){let n=i.from+e.index,r=n+e[0].length;t.add(n,n+2,HT),t.add(n+2,r-2,UT),t.add(r-2,r,HT)}for(BT.lastIndex=0;(e=BT.exec(i.text))!==null;){let n=i.from+e.index,r=n+e[0].length;t.add(n,n+1,HT),t.add(n+1,r-1,WT),t.add(r-1,r,HT)}}}return t.finish()}var KT=si.define({create(e){return GT(e)},update(e,t){return t.docChanged||t.selection?GT(t.state):e},provide:e=>Er.decorations.from(e)}),qT=Er.baseTheme({".cm-md-heading-1":{fontSize:`1.3em`,fontWeight:`bold`},".cm-md-heading-2":{fontSize:`1.2em`,fontWeight:`bold`},".cm-md-heading-3":{fontSize:`1.1em`,fontWeight:`bold`}});function JT(){return[KT,qT]}function YT(e){return/^\|[\s:]*-+[\s:]*(\|[\s:]*-+[\s:]*)*\|$/.test(e.trim())}function XT(e){let t=e.trim();return(t.startsWith(`|`)&&t.endsWith(`|`)?t.slice(1,-1):t).split(`|`).map(e=>e.trim())}var ZT=class extends Tr{head;rows;constructor(e,t){super(),this.head=e,this.rows=t}eq(e){return this.head.length!==e.head.length||this.rows.length!==e.rows.length?!1:this.head.every((t,n)=>t===e.head[n])}toDOM(){let e=document.createElement(`div`);e.className=`cm-table-preview my-2 overflow-auto border border-border/80 rounded-lg`;let t=document.createElement(`table`);t.className=`w-full text-xs font-mono border-collapse`;let n=document.createElement(`thead`),r=document.createElement(`tr`);r.className=`border-b border-border bg-muted/40 text-muted-foreground text-left`;for(let e of this.head){let t=document.createElement(`th`);t.className=`py-1.5 px-3 font-semibold`,t.textContent=e,r.appendChild(t)}n.appendChild(r),t.appendChild(n);let i=document.createElement(`tbody`);for(let e of this.rows){let t=document.createElement(`tr`);t.className=`border-b border-border/40 hover:bg-muted/20`;for(let n of e){let e=document.createElement(`td`);e.className=`py-1.5 px-3 text-foreground`,e.textContent=n,t.appendChild(e)}i.appendChild(t)}return t.appendChild(i),e.appendChild(t),e}};function QT(e,t){let n=[];for(let r=t.startLine;r<=t.endLine;r++){if(!e.doc.line(r).text.trim().startsWith(`|`))continue;let t=n[n.length-1];t&&t.toLine===r-1?t.toLine=r:n.push({fromLine:r,toLine:r})}for(let t of n){let n=[];for(let r=t.fromLine;r<=t.toLine;r++)n.push(e.doc.line(r).text);if(!(n.length<2||!YT(n[1].trim())))return{head:XT(n[0]),rows:n.slice(2).map(XT),fromLine:t.fromLine,toLine:t.toLine}}return null}function $T(e){let t=new vi,{sections:n}=e.field(Aw),r=e.selection.main.head;for(let i of n){if(i.type!==`markdown`)continue;let n=QT(e,i);if(!n)continue;let a=e.doc.line(n.fromLine).from,o=e.doc.line(n.toLine).to;r>=a&&r<=o||t.add(a,o,Br.replace({widget:new ZT(n.head,n.rows),block:!0}))}return t.finish()}var eE=[si.define({create(e){return $T(e)},update(e,t){return t.docChanged||t.selection?$T(t.state):e},provide:e=>Er.decorations.from(e)})],tE=/\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g,nE=/https?:\/\/\S+/g,rE=/`[^`\n]*`/g,iE=/[.,;:!?)\]}>'"]$/;function aE(e){let t=e.match(/[?&]v=([a-zA-Z0-9_-]{11})/);if(t)return t[1];let n=e.match(/youtu\.be\/([a-zA-Z0-9_-]+)/);if(n)return n[1];let r=e.match(/youtube\.com\/embed\/([a-zA-Z0-9_-]{11})/);return r?r[1]:null}function oE(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`h-3 w-3`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,`M15 3h6v6`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`10`),n.setAttribute(`x2`,`21`),n.setAttribute(`y1`,`14`),n.setAttribute(`y2`,`3`),e.appendChild(n);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`polyline`);return r.setAttribute(`points`,`21 14 21 3 10 3`),e.appendChild(r),e}var sE=class extends Tr{label;url;constructor(e,t){super(),this.label=e,this.url=t}eq(e){return this.label===e.label&&this.url===e.url}toDOM(){let e=document.createElement(`span`);e.className=`cm-link-pill`;let t=document.createElement(`span`);t.className=`cm-link-pill-label`,t.textContent=this.label||this.url,e.appendChild(t);let n=document.createElement(`a`);return n.className=`cm-link-pill-open`,n.href=this.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.title=this.url,n.setAttribute(`aria-label`,`Open ${this.label||this.url} in new tab`),n.appendChild(oE()),e.appendChild(n),e}},cE=class extends Tr{videoId;title;constructor(e,t){super(),this.videoId=e,this.title=t}eq(e){return this.videoId===e.videoId&&this.title===e.title}toDOM(){let e=document.createElement(`div`);e.className=`cm-youtube-player`;let t=document.createElement(`iframe`);return t.className=`cm-youtube-player-frame`,t.src=`https://www.youtube-nocookie.com/embed/${encodeURIComponent(this.videoId)}`,t.title=this.title||`YouTube video`,t.setAttribute(`allow`,`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`),t.setAttribute(`allowfullscreen`,``),t.setAttribute(`loading`,`lazy`),e.appendChild(t),e}get block(){return!0}};function lE(e){let t=[],n=[],r;for(rE.lastIndex=0;(r=rE.exec(e.text))!==null;)n.push([r.index,r.index+r[0].length]);let i=e=>n.some(([t,n])=>e>=t&&e<n);for(tE.lastIndex=0;(r=tE.exec(e.text))!==null;)i(r.index)||t.push({from:e.from+r.index,to:e.from+r.index+r[0].length,label:r[1],url:r[2]});for(nE.lastIndex=0;(r=nE.exec(e.text))!==null;){if(i(r.index))continue;let n=r;if(t.some(t=>n.index>=t.from-e.from&&n.index<t.to-e.from))continue;let a=n[0];for(;iE.test(a);)a=a.slice(0,-1);a&&t.push({from:e.from+n.index,to:e.from+n.index+a.length,label:a,url:a})}return t.sort((e,t)=>e.from-t.from)}function uE(e){let t=new vi,{sections:n}=e.field(Aw),r=e.selection.main.head,i=e.readOnly;for(let a of n)if((a.type===`markdown`||a.type===`embed`)&&(a.type!==`markdown`||a.subtype!==`table`))for(let n=a.startLine;n<=a.endLine;n++){let a=e.doc.line(n);if(a.text.trim().startsWith(`|`)||!i&&r>=a.from&&r<=a.to)continue;let o=lE(a),s=a.text.trimStart(),c=a.text.length-s.length,l=a.text.length-a.text.trimEnd().length,u=c+(s.match(/^[-*+]\s+/)?.[0].length??0);for(let e of o){let n=o.length===1&&e.from===a.from+u&&e.to===a.to-l?aE(e.url):null;n?t.add(a.from,a.to,Br.replace({widget:new cE(n,e.label),block:!0})):t.add(e.from,e.to,Br.replace({widget:new sE(e.label,e.url)}))}}return t.finish()}var dE=[si.define({create(e){return uE(e)},update(e,t){return t.docChanged||t.selection?uE(t.state):e},provide:e=>Er.decorations.from(e)}),Er.baseTheme({".cm-link-pill":{display:`inline-flex`,alignItems:`center`,gap:`4px`,padding:`0 5px`,border:`1px solid hsl(var(--border))`,borderRadius:`6px`,backgroundColor:`hsl(var(--muted) / 0.35)`,maxWidth:`100%`},".cm-link-pill-label":{color:`hsl(var(--primary))`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},".cm-link-pill-open":{display:`inline-flex`,alignItems:`center`,flexShrink:`0`,color:`hsl(var(--muted-foreground))`,textDecoration:`none`,cursor:`pointer`},".cm-link-pill-open:hover":{color:`hsl(var(--primary))`},".cm-youtube-player":{width:`100%`,aspectRatio:`16 / 9`,margin:`8px 0`,backgroundColor:`#000`,borderRadius:`6px`,overflow:`hidden`},".cm-youtube-player-frame":{display:`block`,width:`100%`,height:`100%`,border:`none`}})],fE=Xr.define(),pE=si.define({create(){return new Set},update(e,t){for(let e of t.effects)if(e.is(fE))return e.value;return e}}),mE={runtime:`cm-gutter-runtime`,error:`cm-gutter-error`,warning:`cm-gutter-warning`,info:`cm-gutter-info`},hE=class extends zr{kind;constructor(e){super(),this.kind=e}toDOM(){let e=document.createElement(`div`);return e.className=`cm-unified-gutter-marker ${mE[this.kind]}`,e}},gE=new Map([[`runtime`,new hE(`runtime`)],[`error`,new hE(`error`)],[`warning`,new hE(`warning`)],[`info`,new hE(`info`)]]),_E=[pE,Or({class:`cm-unified-gutter`,markers(e){let t=new vi,n=e.state.field(pE),r=new Map;for(let t of n)t>=1&&t<=e.state.doc.lines&&r.set(t,`runtime`);Kr(e.state,t=>{let n=e.state.doc.lineAt(t.from).number;if(r.get(n)===`runtime`)return;let i=r.get(n);(!i||t.severity===`error`&&i!==`error`)&&r.set(n,t.severity)});let i=Array.from(r.keys()).sort((e,t)=>e-t);for(let n of i){let i=e.state.doc.line(n),a=gE.get(r.get(n));a&&t.add(i.from,i.from,a)}return t.finish()},initialSpacer:()=>new hE(`info`)})];function vE(e,t){e.dispatch({effects:fE.of(new Set(t))})}var yE=Xr.define(),bE=Xr.define(),xE=Xr.define(),SE=class extends Tr{height;constructor(e){super(),this.height=e}eq(e){return e.height===this.height}toDOM(){let e=document.createElement(`div`);return e.className=`cm-runtime-panel-spacer`,e.style.height=`${this.height}px`,e.style.pointerEvents=`none`,e}get block(){return!0}};function CE(e){let t=new vi,n=Array.from(e.values()).sort((e,t)=>e.afterPos-t.afterPos);for(let e of n){let n=e.expanded?600:500;t.add(e.afterPos,e.afterPos,Br.widget({widget:new SE(n),block:!0,side:1}))}return t.finish()}si.define({create(){return new Map},update(e,t){let n=e;for(let e of t.effects)if(e.is(yE))n=new Map(n),n.set(e.value.sectionId,e.value);else if(e.is(bE))n.has(e.value.sectionId)&&(n=new Map(n),n.delete(e.value.sectionId));else if(e.is(xE)){let t=n.get(e.value.sectionId);t&&(n=new Map(n),n.set(e.value.sectionId,{...t,expanded:e.value.expanded}))}return n},provide:e=>Er.decorations.compute([e],t=>CE(t.field(e)))});function wE(e){return`:session{result:${e}}`}function TE(e,t,n){let r=e.field(Aw).sections.find(e=>e.id===t);return!r||r.type!==`time`&&r.type!==`log`?null:{from:r.to,insert:`\n\n\`\`\`query:table\n${wE(n)}\n\`\`\``}}function EE(e){let t=e.split(`:`);if(t.length<1||t.length>4)return null;let n=t.map(e=>parseInt(e,10));if(n.some(e=>isNaN(e)))return null;for(;n.length<4;)n.unshift(0);return n}function DE(e,t,n,r){let i=[];return e>0?i.push(e,t,n,r):t>0?i.push(t,n,r):n>0?i.push(n,r):i.push(r),i.map((e,t)=>t===0?String(e):String(e).padStart(2,`0`)).join(`:`)}function OE(e,t,n,r,i,a){let o=e*86400+t*3600+n*60+r,s=[86400,3600,60,1][i]??1;o=Math.max(0,o+a*s);let c=Math.floor(o/86400);o%=86400;let l=Math.floor(o/3600);return o%=3600,[c,l,Math.floor(o/60),o%60]}function kE(e,t){let n=/\b(\d{1,2}(?::\d{2}){1,3})\b/g,r;for(;(r=n.exec(e))!==null;){let e=r.index,n=e+r[0].length;if(t>=e&&t<=n){let i=r[0],a=Math.min(t-e,i.length-1),o=(i.slice(0,a).match(/:/g)||[]).length;return{timeStr:i,startCol:e,endCol:n,digitIndex:4-((i.match(/:/g)||[]).length+1)+o}}}return null}function AE(e,t){let n=e.state.selection.main,r=e.state.doc.lineAt(n.head),i=n.head-r.from,a=kE(r.text,i);if(!a)return!1;let o=EE(a.timeStr);if(!o)return!1;let[s,c,l,u]=OE(o[0],o[1],o[2],o[3],a.digitIndex,t),d=DE(s,c,l,u);return e.dispatch({changes:{from:r.from+a.startCol,to:r.from+a.endCol,insert:d}}),!0}var jE=yr.of([{key:`Alt-ArrowUp`,run:e=>AE(e,1)},{key:`Alt-ArrowDown`,run:e=>AE(e,-1)}]),ME=[],NE={duration:`cm-metric-duration`,rep:`cm-metric-rep`,rounds:`cm-metric-rounds`,distance:`cm-metric-distance`,resistance:`cm-metric-resistance`,action:`cm-metric-action`,pace:`cm-metric-pace`,heart_rate:`cm-metric-heart_rate`,power:`cm-metric-power`,calories:`cm-metric-calories`};function PE(e,t){if(e.type!==`time`&&e.type!==`log`||e.contentFrom===void 0||e.contentTo===void 0)return null;let n=t.doc.sliceString(e.contentFrom,e.contentTo);try{return yc().read(n,e.sport).statements}catch{return null}}function FE(e){let t=new vi,{sections:n}=e.field(Aw),r=e.selection.main.head,i=e.doc.lineAt(r),a=null;for(let o of n){if(o.type!==`time`&&o.type!==`log`)continue;let n=PE(o,e);if(!n)continue;let s=r>=o.from&&r<=o.to;for(let r=0;r<n.length;r++){let c=n[r],l=o.startLine+1+r;if(l>=o.endLine)break;let u=e.doc.line(l),d=s&&i.number===l;for(let e=0;e<c.metrics.length;e++){let i=c.metrics[e],s=NE[i.type]||`cm-metric-generic`;t.add(u.from,u.to,Br.mark({class:`cm-metric-mark ${s}`})),d&&!a&&(a={sectionId:o.id,section:o,lineFrom:u.from,docLine:l,statementIndex:r,statement:c,focusedMetric:i,focusedMetricIndex:e,allStatements:n})}}}return{focus:a,decos:t.finish()}}si.define({create(e){return FE(e)},update(e,t){return FE(t.state)},provide:e=>Er.decorations.from(e,e=>e.decos)});var IE=class extends Tr{queryText;sectionId;widgetType;widgetError;options;root=null;constructor(e,t,n,r,i){super(),this.queryText=e,this.sectionId=t,this.widgetType=n,this.widgetError=r,this.options=i}eq(e){return this.queryText===e.queryText&&this.sectionId===e.sectionId&&this.widgetType===e.widgetType&&this.widgetError===e.widgetError&&this.options?.readOnly===e.options?.readOnly&&this.options?.executor===e.options?.executor&&this.options?.onOpenNote===e.options?.onOpenNote&&this.options?.noteHref===e.options?.noteHref}toDOM(e){let t=document.createElement(`div`);t.className=`cm-query-block-preview my-2`;let n=(0,Oi.createRoot)(t);return this.root=n,n.render((0,W.jsx)(sw,{query:this.queryText,widgetType:this.widgetType,widgetError:this.widgetError,readOnly:this.options?.readOnly,executor:this.options?.executor,onResultSaved:this.options?.onResultSaved,onSaveQuery:t=>{if(this.options?.onSaveQuery)return this.options.onSaveQuery(this.sectionId,t);let n=RE(e,this.sectionId,t);if(!n.ok)throw Error(n.message)},onOpenNote:this.options?.onOpenNote,noteHref:this.options?.noteHref})),t}updateDOM(e,t){return this.root?(this.root.render((0,W.jsx)(sw,{query:this.queryText,widgetType:this.widgetType,widgetError:this.widgetError,readOnly:this.options?.readOnly,executor:this.options?.executor,onResultSaved:this.options?.onResultSaved,onOpenNote:this.options?.onOpenNote,noteHref:this.options?.noteHref,onSaveQuery:e=>{if(this.options?.onSaveQuery)return this.options.onSaveQuery(this.sectionId,e);let n=RE(t,this.sectionId,e);if(!n.ok)throw Error(n.message)}})),!0):!1}destroy(){this.root&&setTimeout(()=>{try{this.root?.unmount()}catch{}},0)}get block(){return!0}};function LE(e,t){let n=new vi,{sections:r}=e.field(Aw),i=e.selection.main.head;for(let a of r){if(a.type!==`query`||i>=a.from&&i<=a.to||a.contentFrom===void 0||a.contentTo===void 0)continue;let r=e.doc.sliceString(a.contentFrom,a.contentTo);n.add(a.from,a.to,Br.replace({widget:new IE(r,a.id,a.queryType,a.queryError,t),block:!0}))}return n.finish()}function RE(e,t,n,r=0){if(e.state.readOnly)return{ok:!1,message:`Cannot modify query source in read-only mode.`};let i=zE(e,t);if(!i||i.contentFrom===void 0||i.contentTo===void 0)return{ok:!1,message:`Query block section not found`};let a=LS(e.state.doc.sliceString(i.contentFrom,i.contentTo),n,r);return e.dispatch({changes:{from:i.contentFrom,to:i.contentTo,insert:a}}),{ok:!0,patchedContent:a}}function zE(e,t){let{sections:n}=e.state.field(Aw);return n.find(e=>e.id===t)??null}function BE(e){return[si.define({create(t){return LE(t,e)},update(t,n){return n.docChanged||n.selection?LE(n.state,e):t},provide:e=>Er.decorations.from(e)})]}var VE={view:`Edit widget`,editing:`Save widget`,error:`Undo changes`};function HE(e,t,n,r){return e===`editing`?n:e===`error`?r:t}function UE(e){return e?`opacity-100 scale-100 rotate-0`:`pointer-events-none opacity-0 scale-75 -rotate-12`}var WE=U.forwardRef(({mode:e,enterEditMode:t,onSave:n,onUndo:r,className:i,type:a=`button`,...s},c)=>{let l=VE[e],u=HE(e,t,n,r);return(0,W.jsx)(`button`,{...s,ref:c,type:a,"aria-label":l,title:l,"data-mode":e,onClick:u,className:mx(`absolute right-2 top-2 inline-flex h-8 w-8 items-center justify-center rounded-full border border-border/80 bg-background/90 shadow-sm backdrop-blur-sm transition-all duration-200 ease-out hover:bg-muted/80 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer`,e===`view`&&`text-muted-foreground hover:text-foreground`,e===`editing`&&`text-signal-positive hover:text-signal-positive/80`,e===`error`&&`text-signal-caution hover:text-signal-caution/80`,i),children:(0,W.jsxs)(`span`,{className:`relative h-4 w-4`,"aria-hidden":`true`,children:[(0,W.jsx)(o,{"data-icon-state":`view`,className:mx(`absolute inset-0 h-4 w-4 transition-all duration-200 ease-out`,UE(e===`view`))}),(0,W.jsx)(z,{"data-icon-state":`editing`,className:mx(`absolute inset-0 h-4 w-4 transition-all duration-200 ease-out`,UE(e===`editing`))}),(0,W.jsx)(hr,{"data-icon-state":`error`,className:mx(`absolute inset-0 h-4 w-4 transition-all duration-200 ease-out`,UE(e===`error`))})]})})});WE.displayName=`WidgetEditButton`;var GE=U.forwardRef(({className:e,hasError:t=!1,spellCheck:n=!1,...r},i)=>(0,W.jsx)(`textarea`,{...r,ref:i,spellCheck:n,className:mx(`min-h-[160px] w-full rounded-xl border bg-background px-4 py-3 font-mono text-sm leading-6 text-foreground shadow-sm outline-none transition-colors duration-200 ease-out placeholder:text-muted-foreground/70`,`focus:border-ring focus:ring-2 focus:ring-ring/20`,t?`border-destructive/70 focus:border-destructive focus:ring-destructive/20`:`border-border/70`,e)}));GE.displayName=`EditableMarkdown`;var KE=Xr.define(),qE=si.define({create:()=>new Set,update(e,t){let n=e;for(let e of t.effects)e.is(KE)&&(n=new Set(n),e.value.editing?n.add(e.value.sectionId):n.delete(e.value.sectionId));return n}});function JE(e){return e.endsWith(`
73
+ `)?e.slice(0,-1):e}function YE(e){return`${e.replace(/\n+$/,``)}\n`}function XE(e){let t=e.trim();if(t.length===0)return{ok:!0,config:{}};try{let e=JSON.parse(t);return!e||Array.isArray(e)||typeof e!=`object`?{ok:!1,config:{},message:`Widget config must be a JSON object.`}:{ok:!0,config:e}}catch(e){return{ok:!1,config:{},message:e instanceof Error?e.message:`Invalid JSON.`}}}function ZE(e,t){let{sections:n}=e.state.field(Aw);return n.find(e=>e.type===`widget`&&e.id===t)??null}function QE(e,t,n){if(e.state.readOnly)return{ok:!1,config:{},message:`Cannot modify widget source in read-only mode.`};let r=XE(n);if(!r.ok)return r;let i=ZE(e,t);return!i||i.contentFrom==null||i.contentTo==null?{ok:!1,config:{},message:`Unable to locate widget source in the editor.`}:(e.dispatch({changes:{from:i.contentFrom,to:i.contentTo,insert:YE(n)}}),r)}function $E(e){return(0,W.jsxs)(`div`,{className:`rounded-xl border border-dashed border-border/70 bg-muted/30 px-4 py-5 text-sm text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,e]}),(0,W.jsx)(`span`,{className:`ml-2 opacity-70`,children:`is not registered`})]})}function eD(e,t){return(0,W.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-5 text-sm text-destructive shadow-sm`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Widget config error`}),(0,W.jsxs)(`p`,{className:`mt-1 font-mono text-xs leading-5 text-destructive/90`,children:[`widget:`,e]}),(0,W.jsx)(`p`,{className:`mt-2 font-mono text-xs leading-5 text-destructive/90`,children:t})]})}function tD({widgetName:e,rawContent:t,sectionId:n,registry:r,view:i}){let a=U.useRef(null),o=U.useRef(null),s=U.useRef(null),c=U.useMemo(()=>JE(t),[t]),[l,u]=U.useState(()=>({isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c,hasFocus:!1}));U.useEffect(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c}))},[c]),U.useEffect(()=>{if(!l.isEditing)return;let e=window.requestAnimationFrame(()=>{o.current?.focus();let e=o.current?.value.length??0;o.current?.setSelectionRange(e,e)});return()=>window.cancelAnimationFrame(e)},[l.isEditing]);let d=r.get(e),f=U.useMemo(()=>XE(l.originalMarkdown),[l.originalMarkdown]),p=U.useCallback(e=>{u(t=>t.hasFocus===e?t:{...t,hasFocus:e})},[]),m=U.useCallback(()=>{u(e=>({...e,isEditing:!0,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),h=U.useCallback(e=>{let t=QE(i,n,e);if(!t?.ok)return u(e=>({...e,error:t?.message??`Invalid JSON.`})),!1;let r=JE(YE(e));return u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1}),!0},[i,n]),g=U.useCallback(()=>{h(o.current?.value??l.currentMarkdown)},[h,l.currentMarkdown]),_=U.useCallback(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),v=U.useCallback(e=>{let t=e.target.value;u(e=>{let n=e.error?XE(t):null;return{...e,currentMarkdown:t,isDirty:t!==e.originalMarkdown,error:n?.ok===!1?n.message:n?.ok?null:e.error}})},[]),y=U.useCallback(()=>{p(!1);let e=o.current?.value;if(e===void 0)return;let t=QE(i,n,e);if(!t?.ok){u(n=>({...n,isDirty:e!==n.originalMarkdown,error:t?.message??`Unable to save widget source.`}));return}let r=JE(YE(e));u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1})},[n,i,p]),b=U.useCallback(e=>{let t=e.relatedTarget;t instanceof Node&&a.current?.contains(t)||p(!1)},[p]),x=U.useCallback(e=>{e.key===`Enter`&&!l.isEditing&&(e.preventDefault(),m())},[m,l.isEditing]);U.useEffect(()=>{let e=s.current;if(e)return e.addEventListener(`keydown`,x),()=>e.removeEventListener(`keydown`,x)},[x]);let S=U.useCallback(e=>{e.key===`Escape`?(e.preventDefault(),_()):e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),g())},[g,_]),C=l.error?`error`:l.isEditing?`editing`:`view`,w=l.hasFocus||l.isEditing||l.error!==null,T;return T=d?f.ok?U.createElement(d,{config:f.config,rawContent:l.originalMarkdown,sectionId:n}):eD(e,f.message):$E(e),(0,W.jsxs)(`div`,{ref:a,"data-widget-section-id":n,"data-widget-mode":C,className:mx(`group relative rounded-2xl border border-transparent bg-background/95 p-3 transition-colors duration-200 ease-out hover:border-border`,l.isEditing&&l.error===null&&`border-signal-positive/40 ring-1 ring-signal-positive/15`,l.error!==null&&`border-destructive/40 ring-1 ring-destructive/15`),onMouseDownCapture:e=>{l.isEditing||e.preventDefault()},onFocusCapture:()=>p(!0),onBlurCapture:b,onKeyDownCapture:x,children:[(0,W.jsx)(WE,{mode:C,enterEditMode:m,onSave:g,onUndo:_,className:mx(`z-10 focus-visible:opacity-100 focus-visible:scale-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-focus-within:scale-100`,w?`pointer-events-auto opacity-100 scale-100`:`pointer-events-none opacity-0 scale-95 group-hover:pointer-events-auto group-hover:opacity-100 group-hover:scale-100`)}),l.isEditing?(0,W.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[l.error!==null&&(0,W.jsxs)(`div`,{"data-testid":`widget-error-inlay`,className:`rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive`,children:[`Invalid JSON: `,l.error]}),(0,W.jsx)(GE,{ref:o,"data-testid":`widget-markdown-editor`,value:l.currentMarkdown,onChange:v,onBlur:y,onKeyDown:S,hasError:l.error!==null})]}):(0,W.jsx)(`div`,{ref:s,"data-testid":`widget-preview-surface`,tabIndex:0,onKeyDown:x,children:T})]})}var nD=class extends Tr{sectionId;constructor(e){super(),this.sectionId=e}eq(e){return this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);return t.className=`relative h-0 w-full`,(0,Oi.createRoot)(t).render((0,W.jsx)(`div`,{className:`absolute right-0 top-1 z-50`,children:(0,W.jsx)(WE,{mode:`editing`,enterEditMode:()=>{},onSave:()=>{e.dispatch({effects:KE.of({sectionId:this.sectionId,editing:!1})})},onUndo:()=>{e.dispatch({effects:KE.of({sectionId:this.sectionId,editing:!1})})}})})),t}ignoreEvent(){return!1}},rD=class extends Tr{widgetName;rawContent;sectionId;registry;root=null;constructor(e,t,n,r){super(),this.widgetName=e,this.rawContent=t,this.sectionId=n,this.registry=r}eq(e){return this.widgetName===e.widgetName&&this.rawContent===e.rawContent&&this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);return t.className=`cm-widget-block-preview`,t.style.cssText=`display:block; width:100%; min-height:1.5em; outline:none;`,this.root=(0,Oi.createRoot)(t),this.root.render(U.createElement(tD,{widgetName:this.widgetName,rawContent:this.rawContent,sectionId:this.sectionId,registry:this.registry,view:e})),t}destroy(){if(this.root){let e=this.root;this.root=null,queueMicrotask(()=>{try{e.unmount()}catch{}})}}ignoreEvent(){return!1}get estimatedHeight(){return 200}};function iD(e,t){let n;try{n=e.field(Aw)}catch{return Br.none}let{sections:r}=n,i=e.field(qE),a=[],o=e.selection.main.head;for(let n of r){if(n.type!==`widget`||!n.widgetName)continue;let r=e.doc;if(n.startLine>r.lines||n.endLine>r.lines)continue;if(i.has(n.id)){a.push(Br.widget({widget:new nD(n.id),side:1,block:!1}).range(n.from));continue}if(o>=n.from&&o<=n.to)continue;let s=n.contentFrom!=null&&n.contentTo!=null?r.sliceString(n.contentFrom,n.contentTo):``;a.push(Br.replace({widget:new rD(n.widgetName,s,n.id,t),block:!0}).range(n.from,n.to))}return a.sort((e,t)=>e.from-t.from),Br.set(a)}function aD(e,t){return e.find(e=>e.type===`widget`&&t.from>=e.from&&t.from<=e.to)??null}function oD(e,t){let{head:n}=e.state.selection.main,r=e.state.doc.lineAt(n),i=Math.max(0,n-r.from),a=Math.min(i,t.length),o=t.from+a;e.dispatch({selection:{anchor:o,head:o},scrollIntoView:!0})}function sD(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(Aw),i=e.state.field(qE),a=aD(r,n);if(a&&!i.has(a.id))return!1;let o=n.number+1;if(o>e.state.doc.lines)return!1;let s=aD(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(oD(e,e.state.doc.line(s.startLine)),!0)}function cD(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(Aw),i=e.state.field(qE),a=aD(r,n);if(a&&!i.has(a.id))return!1;let o=n.number-1;if(o<1)return!1;let s=aD(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(oD(e,e.state.doc.line(s.endLine)),!0)}var lD=fi.high(yr.of([{key:`ArrowDown`,run:sD},{key:`ArrowUp`,run:cD}]));function uD(e){return[si.define({create(t){return iD(t,e)},update(t,n){let r=n.effects.some(e=>e.is(KE)),i=!n.startState.selection.eq(n.newSelection);return n.docChanged||r||i?iD(n.state,e):t},provide:e=>Er.decorations.from(e)}),qE,lD]}var dD=new class{_db;constructor(e){this._db=e}get db(){return this._db??Z}async load(){return this.db.getAllEfforts()}async save(e){await this.db.saveEffort(e)}async delete(e){await this.db.deleteEffort(e)}};function fD(){return new Zc({storage:dD})}async function pD(e){let t=await Z.getAllEfforts();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),gD()}var mD=new Set;function hD(e){return mD.add(e),()=>mD.delete(e)}function gD(){for(let e of mD)e()}var _D=null;function vD(){return _D||=fD(),_D}function yD(e){let t=e.split(/\r?\n\s*\r?\n/).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```")&&!e.startsWith(`|`)&&!e.startsWith(`- `)&&!e.startsWith(`* `));if(t)return t.replace(/^>\s?/,``).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/[`*_~]/g,``).replace(/\s+/g,` `).trim()||void 0}function bD(e){let{meta:t,body:n}=tx(e),r=sx(t,`description`),i=sx(t,`image`),a;if(typeof i==`string`&&i.trim()){let e=i.trim();(/^https?:\/\//.test(e)||e.startsWith(`/`))&&(a=e)}let o=typeof r==`string`&&r.trim()?r.trim():yD(n);return{...o?{description:o}:{},...a?{image:a}:{}}}function xD(e){return e.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var SD={and:!0,or:!0,of:!0,for:!0,to:!0,in:!0,on:!0,at:!0,by:!0,with:!0,the:!0,a:!0,an:!0};function CD(e){let t=e.replace(/\.md$/,``);if(t.toUpperCase()===`README`)return`Overview`;let n=t.replace(/^day-\d+-/,``).split(/[-_]/),r=[];for(let e=0;e<n.length;e++){let t=n[e],i=n[e+1],a=n[e+2],o=n[e-1];if(/^\d{1,2}$/.test(t)&&/^\d{1,2}$/.test(i??``)&&!/^\d+$/.test(o??``)&&!/^\d+$/.test(a??``)){r.push(`${t}.${i}`),e++;continue}if(r.length>0&&SD[t.toLowerCase()]){r.push(t.toLowerCase());continue}r.push(t.charAt(0).toUpperCase()+t.slice(1))}return r.join(` `)}function wD(e,t){let n=new Map,r=e=>{let t=n.get(e);return t||(t={id:e,name:xD(e),categories:[],items:[]},n.set(e,t)),t};for(let[n,i]of Object.entries(t)){if(e===`collections`){let e=n.match(/(?:^|\/)markdown\/collections\/([^/]+)\/([^/]+\.md)$/);if(!e)continue;let[,t,a]=e,o=r(t);a.toLowerCase()===`readme.md`?(o.readme=i,o.categories=lx(i),Object.assign(o,bD(i))):o.items.push({id:a.replace(/\.md$/,``),name:CD(a),content:i,path:n});continue}let t=n.match(/(?:^|\/)markdown\/feeds\/([^/]+)\/README\.md$/i);if(t){let e=r(t[1]);e.readme=i,e.categories=lx(i),Object.assign(e,bD(i));continue}let a=n.match(/(?:^|\/)markdown\/feeds\/([^/]+)\/(\d{4}-\d{2}-\d{2})\/([^/]+\.md)$/);if(a){let[,e,t,o]=a;r(e).items.push({id:o.replace(/\.md$/,``),name:CD(o),content:i,path:n,date:t});continue}}return Array.from(n.values()).filter(({items:e,readme:t})=>e.length>0||t!==void 0)}function TD(e){return wD(`collections`,e).map(e=>({id:e.id,name:e.name,count:e.items.length,items:e.items.map(({id:e,name:t,content:n,path:r})=>({id:e,name:t,content:n,path:r})).sort((e,t)=>e.name.localeCompare(t.name)),readme:e.readme,categories:e.categories})).sort((e,t)=>e.name.localeCompare(t.name))}var ED=null,DD=[];async function OD(){let e=await VD();return ED!==e&&(ED=e,DD=TD(e)),DD}var kD=null,AD=null;function jD(){return kD||=Z.getAllBlockIndex().then(e=>e.filter(e=>e.isStatic===!0)).catch(e=>{throw kD=null,e}),kD}function MD(){kD=null,AD=null}function ND(e){let t=new Map;for(let n of e)for(let e of ja(n.rawContent).filter(e=>e.type===`frontmatter`).flatMap(e=>ux(e.displayContent))){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}return t}function PD(){return AD||=Z.getAllNotes().then(async e=>{let t=ND(e.filter(e=>e.seedOrigin===`seed`));try{let e=await OD();for(let n of e)for(let e of n.categories){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}}catch{}return t}),AD}async function FD(){let e=vD();return e.isInitialized()||await e.loadBundled(),e.list()}SC(`discipline`,{load:async()=>{try{return hC((await FD()).map(e=>e.baseAttributes?.discipline).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),mC(xc))}catch{return mC(xc)}},cache:{ttlMs:6e4},open:!1,emptyText:`No disciplines available`}),SC(`effort`,{load:async()=>{try{return hC((await FD()).filter(e=>e.slug).map(e=>({value:e.slug,label:e.label||e.slug})),[]).sort((e,t)=>e.value.localeCompare(t.value))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No efforts indexed yet — type one to filter`}),SC(`intensity`,{load:async()=>{try{return hC((await FD()).map(e=>e.baseAttributes?.intensityTier).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),mC(sc))}catch{return mC(sc)}},cache:{ttlMs:6e4},open:!1,emptyText:`No intensity tiers indexed yet`}),SC(`type`,{load:async()=>{try{return hC(dC(await jD()).map(e=>({value:e,label:e})),mC(pC))}catch{return mC(pC)}},cache:{ttlMs:3e5},open:!1,emptyText:`No indexed block types yet`}),SC(`catalog`,{load:async()=>uC(await jD()).map(e=>({value:e,label:e})),cache:`static`,open:!1,emptyText:`No notebooks in the static corpus`}),SC(`notebook`,{load:async()=>uC(await jD()).map(e=>({value:e,label:e})),cache:`static`,open:!1,emptyText:`No notebooks in the static corpus`}),SC(`tag`,{load:async()=>{let e=await PD(),t=Array.from(e.keys()),n=[];try{n=(await Z.getAllTags()).map(e=>e.label)}catch{}return fC(n,t).map(e=>({value:e,label:e}))},cache:{ttlMs:3e4},open:!0,emptyText:`No tags yet — type one to filter by it`});for(let e of[`domain`,`format`,`equipment`,`quality`,`intent`])SC(e,{load:async()=>{try{return(await Z.getTags(e)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${e}s indexed yet`});SC(`origin`,{load:async()=>{try{let e=await Z.getAllEfforts(),t=new Set;for(let n of e)n.registrySource&&t.add(n.registrySource);return Array.from(t).sort().map(e=>({value:e,label:e}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No effort origins indexed yet — type one to filter`}),(async()=>{try{let e=await Z.getAllTagTypes();for(let t of e)CC(t.name)||SC(t.name,{load:async()=>{try{return(await Z.getTags(t.name)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${t.label}s indexed yet`})}catch{}})();var ID=null,LD=null,RD=new Set;function zD(){for(let e of RD)e()}async function BD(){let e=await Z.getSeedContent(),t={};for(let{path:n,raw:r}of e)t[n]=r;return t}function VD(){return LD||=BD().then(e=>(ID=e,zD(),e)).catch(e=>{throw LD=null,e}),LD}function HD(){ID=null,LD=null,MD(),VD()}function UD(e){return RD.add(e),()=>RD.delete(e)}function WD(){return ID}function GD(){let e=(0,U.useSyncExternalStore)(UD,WD);return(0,U.useEffect)(()=>{VD()},[]),e}var KD=!1;function qD(){if(KD||typeof BroadcastChannel>`u`)return;KD=!0;let e=new BroadcastChannel(av);e.onmessage=()=>HD()}var JD=200,YD=1e6,XD=500,ZD=50,QD=6e4,$D=3e4,eO=750,tO=`wodwiki-sync`,nO={attachments:`data`};function rO(e,t){let n=e instanceof Error?e.message:String(e);return t&&(n=n.split(t).join(`••••••`)),n||`Sync failed`}function iO(e){let t=0;for(let n of e.ops){if(t+=32,n.op!==`put`)continue;let e=nO[n.store],r=n.value,i=e&&typeof r==`object`&&r&&!Array.isArray(r)?Reflect.get(r,e):void 0;t+=typeof i==`string`?i.length:i instanceof ArrayBuffer?Math.ceil(i.byteLength/3)*4+64:JSON.stringify(n.value)?.length??0}return t}var aO=class{local;settings;connect;db;stopped=!1;chain=Promise.resolve();timers=[];reconciled=!1;halted=!1;retryAt=0;debounceTimer;unsubscribeOutbox;onOnline;onVisible;constructor(e,t,n){this.local=e,this.settings=t,this.connect=n}syncNow(){let e=this.chain.then(()=>this.cycle(!0));return this.chain=e.then(()=>void 0,()=>void 0),e}restoreNow(){let e=this.chain.then(async()=>{if(this.stopped)throw Error(`Restore engine is stopped`);if((await this.local.snapshotAllRows()).some(e=>e.rows.length>0)||(await this.local.readOutbox(0,1)).length>0)throw Error(`Restore requires an empty isolated local database`);let e=await this.remote(),t=await ky(e);if(t===`empty`||t.kind!==`current`||t.schemaVersion!==32)throw Error(`Restore requires a provisioned v32 backup. Migrate older backups with the CLI first.`);let n=0;for(;n<t.rev;){let r=await Py(e,n,XD);if(r.length===0)break;if(r[r.length-1].rev>t.rev)throw Error(`Backup changed during restore. Freeze its writers and retry with a fresh local database.`);n=r[r.length-1].rev,await this.local.applySyncMutations(r.map(e=>e.mutation),n,this.cursorKey())}await this.local.validateSyncState();let r=await ky(e);if(r===`empty`||r.kind!==`current`||r.schemaVersion!==t.schemaVersion||r.rev!==t.rev||n!==t.rev)throw Error(`Backup changed during restore. Freeze its writers and retry with a fresh local database.`);await this.local.setSyncState(this.bootstrappedKey(),{done:!0}),this.reconciled=!0});return this.chain=e.then(()=>void 0,()=>void 0),e}start(){let e=e=>{this.enqueue(()=>this.cycle(!1,e))};return this.onOnline=()=>{e(`full`)},this.onVisible=()=>{typeof document<`u`&&!document.hidden&&e(`full`)},typeof window<`u`&&(window.addEventListener(`online`,this.onOnline),typeof document<`u`&&document.addEventListener(`visibilitychange`,this.onVisible)),this.timers.push(setInterval(()=>{e(`full`)},QD)),this.unsubscribeOutbox=qy(()=>{this.scheduleUpload()}),e(`full`),()=>{this.stop()}}async stop(){this.stopped=!0;for(let e of this.timers)clearInterval(e);this.timers=[],clearTimeout(this.debounceTimer),this.debounceTimer=void 0,typeof window<`u`&&this.onOnline&&window.removeEventListener(`online`,this.onOnline),typeof document<`u`&&this.onVisible&&document.removeEventListener(`visibilitychange`,this.onVisible),this.onOnline=void 0,this.onVisible=void 0,this.unsubscribeOutbox?.(),this.unsubscribeOutbox=void 0,await this.chain.catch(()=>void 0),await this.db?.close().catch(()=>void 0),this.db=void 0}scheduleUpload(){this.stopped||this.debounceTimer!==void 0||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.stopped||this.enqueue(()=>this.cycle(!1,`upload`))},eO))}enqueue(e){this.chain=this.chain.then(e,e),this.chain.catch(()=>{})}async cycle(e=!1,t=`full`){if(this.stopped||this.halted||!e&&Date.now()<this.retryAt)return;let n=globalThis.navigator?.locks;try{n?await n.request(tO,()=>this.cycleInner(e,t)):await this.cycleInner(e,t)}catch(e){this.retryAt=Date.now()+$D,zb(rO(e,this.settings.authToken))}}async cycleInner(e,t){let n=[];if(t===`full`){try{await this.ensureReconciled()}catch(e){n.push(e)}try{await this.pullOnce()}catch(e){n.push(e)}}try{await this.uploadOnce()}catch(e){n.push(e)}if(n.length>0)throw n[0]}async remote(){return this.db||=this.connect?.()??Ub(g({url:this.settings.url,authToken:this.settings.authToken})),this.db}cursorKey(){return`cursor:${this.settings.url}`}watermarkKey(){return`watermark:${this.settings.url}`}bootstrappedKey(){return`bootstrapped:${this.settings.url}`}bootstrapRunKey(){return`bootstrap-run:${this.settings.url}`}async ensureReconciled(){if(this.reconciled)return;let e=await this.remote(),t=await ky(e);if(t!==`empty`&&t.kind===`unknown`){let e=`Backup database contains unrelated tables and no WOD Wiki schema; refusing to adopt it. Point the backup setting at a fresh database.`;throw this.halted=!0,Qb(e),Error(e)}let n=t===`empty`?0:t.schemaVersion;if(n>32){let e=`Backup database schema is newer than this app supports (v${n} > v32). Update the app to sync.`;throw this.halted=!0,Qb(e),Error(e)}if(t===`empty`)await Ay(e,32);else if(t.kind===`legacy`||n<32){let e=`Backup schema v${n} requires an explicit CLI migration into a fresh v32 target. The old database was left untouched.`;throw this.halted=!0,Qb(e),Error(e)}this.reconciled=!0}async bootstrapSnapshot(){let e=await this.remote(),t=await this.local.captureSyncBootstrap(this.bootstrapRunKey());for(let n of t)await Ny(e,[n],{expectSchema:32});await this.local.setSyncState(this.bootstrappedKey(),{done:!0}),await(await this.local.open()).delete(`sync_state`,this.bootstrapRunKey())}async uploadOnce(){if(!this.reconciled||this.stopped||this.halted||!await this.local.getSyncState(this.bootstrappedKey()))return;let e=this.watermarkKey();if((await this.local.readOutbox((await this.local.getSyncState(e))?.seq??0,1)).length===0)return;let t=Ib(`upload`,`Uploading changes to backup`);try{let t=await this.remote(),n=(await this.local.getSyncState(e))?.seq??0,r=0;for(;;){let i=await this.local.readOutbox(n,ZD);if(i.length===0)break;let a=0;for(;a<i.length;){let o=[],s=0,c=0,l=n;for(;a<i.length&&s<JD&&c<YD;){let e=i[a],t=iO(e);if(o.length>0&&(s+e.ops.length>JD||c+t>YD))break;o.push({id:e.id,at:e.at,ops:e.ops}),s+=e.ops.length,c+=t,l=e.seq,a+=1}await Ny(t,o,{expectSchema:32}),r+=o.flatMap(e=>e.ops).filter(e=>e.op===`put`&&(e.store===`notes`||e.store===`efforts`)).length,n=l,await this.local.setSyncState(e,{seq:n}),await this.local.ackOutbox(n)}if(i.length<ZD)break}r>0&&Lb({source:`turso backup`,added:r,updated:0})}finally{t()}}async pullOnce(){if(!this.reconciled||this.stopped||this.halted)return;let e=this.cursorKey(),t=(await this.local.getSyncState(e))?.rev??0,n=Ib(`download`,`Syncing from backup`);try{let n=await this.remote(),r=t,i=0,a=0;for(;;){let t=await Py(n,r,XD);if(t.length===0){if(!await this.local.getSyncState(this.bootstrappedKey())){await this.bootstrapSnapshot();continue}break}let o=t[t.length-1].rev,s=await this.local.applySyncMutations(t.map(e=>e.mutation),o,e);i+=s.added,a+=s.updated,r=o}if(i+a>0){Lb({source:`turso backup`,added:i,updated:a}),HD();let e=vD();e.isInitialized()&&await pD(e)}}finally{n()}}},oO=`wodwiki.dataSettings.v1`;function sO(){let e=mO();return e.state!==`invalid`&&e.localDbName?e.localDbName:Fy}function cO(e,t){let n=e=>{let t=e.trim();try{let e=new URL(t);return`${e.hostname===`[::1]`?`::1`:e.hostname}${e.port?`:${e.port}`:``}${e.pathname.replace(/\/+$/,``)}`}catch{return t}};return n(e)===n(t)}function lO(e){return typeof e==`string`&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(e)}var uO={"libsql:":!0,"https:":!0,"wss:":!0};function dO(e,t){let n;try{n=new URL(e.trim())}catch{return`That is not a valid URL.`}if(n.protocol===`http:`||n.protocol===`ws:`){if(n.hostname!==`localhost`&&n.hostname!==`127.0.0.1`&&n.hostname!==`[::1]`&&n.hostname!==`::1`)return`Plain http:// is only allowed for a local smoke server (localhost / 127.0.0.1).`}else if(!uO[n.protocol])return`Unsupported protocol "${n.protocol}" — use libsql:// or https://.`;if(n.username||n.password)return`The URL must not embed credentials — put the token in the token field.`;if(n.search)return`The URL must not contain a query string.`;if(n.hash)return`The URL must not contain a fragment.`;if(!t||!t.trim())return`A database token is required.`}function fO(e,...t){let n=e instanceof Error?e.message:String(e);for(let e of t)e&&(n=n.split(e).join(`••••••`));return Error(n)}function pO(){try{return localStorage.getItem(oO)}catch{return null}}function mO(){let e=pO();if(e===null)return{state:`indexed-db`};let t;try{t=JSON.parse(e)}catch{return{state:`invalid`,raw:e,error:`Saved data settings are not valid JSON.`}}if(!t||typeof t!=`object`||Array.isArray(t))return{state:`invalid`,raw:e,error:`Saved data settings have an unexpected shape.`};if(!(`kind`in t))return{state:`invalid`,raw:e,error:`Saved data settings have no kind.`};let n=t.kind,r=`localDbName`in t?t.localDbName:void 0;if(r!==void 0&&!lO(r))return{state:`invalid`,raw:e,error:`Saved data settings have an invalid localDbName.`};let i=r===void 0?{}:{localDbName:r};if(n===`indexed-db`)return{state:`indexed-db`,...i};if(n!==`turso`)return{state:`invalid`,raw:e,error:`Saved data settings have an unknown kind "${String(n)}".`};if(!(`url`in t)||!(`authToken`in t))return{state:`invalid`,raw:e,error:`Saved Turso settings are missing the URL or token.`};let a=t.url,o=t.authToken;if(typeof a!=`string`||typeof o!=`string`)return{state:`invalid`,raw:e,error:`Saved Turso settings are missing the URL or token.`};let s=dO(a,o);return s?{state:`invalid`,raw:e,error:s}:{state:`turso`,url:a,authToken:o,...i}}async function hO(e){let t=Ub(g({url:e.url.trim(),authToken:e.authToken}));try{await t.query(`SELECT 1`);let e=Error(`verifyTursoTarget: deliberate rollback`);try{await t.transaction(async t=>{throw await t.exec(`CREATE TABLE IF NOT EXISTS "_wodwiki_write_check" ("v" TEXT)`),await t.exec(`INSERT INTO "_wodwiki_write_check" ("v") VALUES (?)`,[crypto.randomUUID()]),e})}catch(t){if(t!==e)throw t}}finally{await t.close().catch(()=>void 0)}}var gO;async function _O(e){if(gO)throw Error(`A connect is already running — wait for it to finish.`);let t=dO(e.url,e.authToken);if(t)throw Error(t);gO=(async()=>{try{await hO(e)}catch(t){throw fO(t,e.authToken)}let t=mO(),n=t.state!==`invalid`&&t.localDbName?{localDbName:t.localDbName}:{};localStorage.setItem(oO,JSON.stringify({kind:`turso`,url:e.url.trim(),authToken:e.authToken,...n}))})();try{await gO}finally{gO=void 0}}async function vO(e){let t=dO(e.url,e.authToken);if(t)throw Error(t);try{await hO(e)}catch(t){throw fO(t,e.authToken)}}function yO(e){if(!lO(e))throw Error(`A valid local database name is required.`);localStorage.setItem(oO,JSON.stringify({kind:`indexed-db`,localDbName:e}))}function bO(){let e=mO(),t=e.state!==`invalid`&&e.localDbName?{localDbName:e.localDbName}:{};localStorage.setItem(oO,JSON.stringify({kind:`indexed-db`,...t}))}var xO=pO();typeof window<`u`&&window.addEventListener(`storage`,e=>{(e.key===`wodwiki.dataSettings.v1`||e.key===null)&&e.newValue!==xO&&window.location.reload()});var SO=t({DATA_SETTINGS_KEY:()=>oO,IndexedDBStorage:()=>nb,StorageService:()=>hb,getActiveLocalDbName:()=>sO,profileService:()=>wO,readAllLocalRows:()=>LO,readDataSettings:()=>mO,readUnsentEdits:()=>IO,startBackgroundStorageSync:()=>PO,stopBackgroundStorageSync:()=>FO,storage:()=>DO,storageBackend:()=>CO,storageService:()=>Z,whenStorageReady:()=>AO}),CO=`indexed-db`,wO=wb(`indexed-db`);function TO(){return new nb({dbName:sO(),getUserId:()=>wO.currentSync()?.id,onUpgradeStart:e=>Zb(e,32)})}var EO=TO(),DO={readonly(e){return EO.readonly(e)},readwrite(e){return EO.readwrite(e)},transaction(e,t,n){return EO.transaction(e,t,n)},async queryDomain(e){return EO.queryDomain?.(e)},wipe(){return EO.wipe()},close(){return EO.close()}},Z=new hb(DO),OO;async function kO(){try{await Z.ensureDefaultTagTypes()}catch{}}function AO(){return OO||(OO=(async()=>{try{let e=globalThis.indexedDB;if(e&&typeof e.databases==`function`){let t=sO(),n=(await e.databases().catch(()=>[])).find(e=>e.name===t);if(n&&typeof n.version==`number`){if(n.version>32){let e=`local database schema v${n.version} is newer than this app supports (v32); refusing to downgrade`;throw Qb(e),Error(e)}n.version<32&&Xb(`Checking local database schema v${n.version}…`)}}await EO.open(),Yb(32),await kO()}catch(e){throw OO=void 0,qb().phase!==`error`&&Qb(e instanceof Error?e.message:String(e)),e}})(),OO)}var jO,MO,NO;function PO(){if(!jO){if(!(EO instanceof nb))jO={stop:()=>{jO=void 0}};else{let e=mO();if(e.state===`invalid`){let t=`Saved backup settings are invalid: ${e.error}`;zb(t),Qb(t),jO={stop:()=>{jO=void 0}}}else if(e.state===`turso`){let t=new aO(EO,e);NO=t;let n=t.start();jO={stop:()=>{n(),NO===t&&(NO=void 0),jO=void 0}}}else jO={stop:()=>{jO=void 0}}}MO=()=>{jO?.stop(),MO=void 0}}return MO}async function FO(){if(!jO)return!1;let e=NO;return jO.stop(),e&&await e.stop(),e!==void 0}async function IO(){return EO instanceof nb?EO.readOutbox(0,2**53-1):[]}async function LO(){return EO instanceof nb?EO.snapshotAllRows():[]}function RO(e,t=[]){return{startTime:e.startTime,endTime:e.endTime,duration:e.duration,roundsCompleted:e.roundsCompleted,totalRounds:e.totalRounds,repsCompleted:e.repsCompleted,completed:e.completed,logs:kg(t)}}function zO(e){return e.toLocaleDateString(`en-US`,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`})}function BO(e){return e.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`})}function VO(e){return e.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`})}function HO(e){return e.toLocaleString(`en-US`,{dateStyle:`medium`,timeStyle:`short`})}function UO(e){return e.toLocaleString(`en-US`,{dateStyle:`medium`,timeStyle:`medium`})}function WO(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}var GO={registeredWidgets:Da},KO=[`notes`,`block_revisions`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`];function qO(e){let t=new Map(e.pages.map(e=>[e.id,e])),n,r,i;for(let a of[...e.links].sort((e,t)=>(e.position??1/0)-(t.position??1/0)||e.createdAt-t.createdAt)){let e=t.get(a.pageId);e&&(n??=e.id,e.date&&(r??=e.date),e.slug&&!e.date&&(i??=e.slug))}return{id:e.note.id,title:e.note.title,slug:i,pageId:n,journalDate:r,createdAt:e.note.createdAt,updatedAt:e.note.createdAt,targetDate:e.note.date??e.note.createdAt,rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision,tags:e.tags.map(e=>e.label),type:e.note.type??`note`,sourceId:e.note.sourceId,catalog:e.note.catalog,notebookId:e.note.notebookId,seedOrigin:e.note.seedOrigin,schemaVersion:1}}function JO(e){if(e?.dateRange)return e.dateRange;if(e?.daysBack!=null){let t=Date.now();return{start:t-e.daysBack*864e5,end:t}}}var YO=class e{db;constructor(e=Z){this.db=e}get persistenceStorage(){return this.db}mode=`history`;capabilities={canWrite:!0,canDelete:!0,canFilter:!0,canMultiSelect:!0,supportsHistory:!0};async getEntries(e){let t=JO(e),n=[];t&&n.push({field:`date`,start:t.start,end:t.end});for(let t of e?.tags??[])n.push({field:`tags`,values:[t]});let r=await this.db.queryDomain(n.length?{plan:`entries`,selection:n}:{plan:`entries`}),i;if(r?.plan===`entries`)i=r.rows.map(qO);else{let e=t?await this.db.getNotesByDateRange(t.start,t.end):await this.db.getAllNotes();i=[...(await this.db.getEntryBatches(e.map(e=>e.id))).values()].map(qO)}return i=i.filter(n=>(!t||n.targetDate>=t.start&&n.targetDate<=t.end)&&(e?.tags??[]).every(e=>n.tags.includes(e))),i.sort((e,t)=>t.targetDate-e.targetDate)}async getEntry(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t))??await this.db.getNoteBySlug(e)??(t===e?void 0:await this.db.getNoteBySlug(t));if(!n)return null;let r=(await this.db.getEntryBatches([n.id])).get(n.id);if(!r)return null;let i=qO(r),a=(await this.db.getSessionsForNote(n.id)).sort((e,t)=>t.createdAt-e.createdAt)[0],o=ja(n.rawContent,GO).map(e=>{let t=Object.values(n.blocks).find(t=>t.from===e.from&&t.to===e.to);return t?{...e,id:t.id,version:t.version,scriptBlock:e.scriptBlock?{...e.scriptBlock,id:t.id,version:t.version}:void 0}:e});return{...i,sections:o,results:a?RO(a,await this.db.getEventsByResult(a.id)):void 0}}async cloneEntry(e,t){let n=await this.getEntry(e);if(!n)throw Error(`Source entry not found: ${e}`);let r=t??Date.now();return this.saveEntry({title:n.title,rawContent:n.rawContent,tags:n.tags,targetDate:r,journalDate:WO(new Date(r)),type:`journal`,sourceId:n.id})}async saveEntry(t){let n=Date.now(),r=t.id??(t.type===`playground`?ny(n):w());if(!t.id&&t.type===`playground`){let e=r;for(let t=1;await this.db.getNote(r);t++){if(t>100)throw Error(`Unable to allocate unique playground timestamp ID`);r=`${e}-${t}`}}await this.db.withTransaction([...KO],async n=>{let i=await n.getNote(r),a=i?t.sourceRevision:0;if(a===void 0)throw new sb(`STALE_SOURCE`,`An expected source revision is required for ${r}`);let o=await new e(n).changedManualTags(r,t.tags),s=t.blocks??(i?.rawContent===t.rawContent?i.blocks:Na(t.rawContent,{...GO,sourceRevision:a||1}));await n.saveNoteSource({noteId:r,rawContent:t.rawContent,blocks:s,expectedSourceRevision:a,createdAt:t.createdAt,metadata:{title:t.title,type:t.type,tags:o,targetDate:t.targetDate,sourceId:t.sourceId}});let c=new e(n);await c.updateRelationships(r,{journalDate:t.journalDate,slug:t.slug}),await c.updateTags(r,t.rawContent,o)});let i=await this.getEntry(r);if(!i)throw Error(`Saved note disappeared: ${r}`);return i}async updateEntry(t,n){let r=t.startsWith(`playground/`)?t.slice(11):t,i=await this.db.getNote(t)??(r===t?void 0:await this.db.getNote(r))??await this.db.getNoteBySlug(t)??(r===t?void 0:await this.db.getNoteBySlug(r));if(!i)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${t}`);await this.db.withTransaction([...KO],async t=>{let r=await t.getNote(i.id);if(!r)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${i.id}`);let a=n.rawContent??r.rawContent;if(n.rawContent!==void 0&&n.expectedSourceRevision===void 0)throw new sb(`STALE_SOURCE`,`An expected source revision is required for ${r.id}`);let o=n.expectedSourceRevision??r.sourceRevision,s=n.tags===void 0?void 0:await new e(t).changedManualTags(r.id,n.tags),c=n.blocks??(a===r.rawContent?r.blocks:Na(a,{...GO,sourceRevision:o}));await t.saveNoteSource({noteId:r.id,rawContent:a,blocks:c,expectedSourceRevision:o,metadata:{title:n.title,type:n.type,tags:s,targetDate:n.targetDate,sourceId:n.sourceId}});let l=new e(t);if(await l.updateRelationships(r.id,n),(n.tags!==void 0||a!==r.rawContent)&&await l.updateTags(r.id,a,s),n.results){if(!n.blockId||!n.blockVersion)throw Error(`Recording a result requires its frozen block pin`);let e=await t.getBlockRevision(r.id,n.blockId,n.blockVersion);if(!e||e.kind!==`wod`)throw new sb(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision not found`);let i=n.resultId?await t.getSessionById(n.resultId):void 0;if(i&&(i.noteId!==r.id||i.blockId!==n.blockId||i.blockVersion!==n.blockVersion))throw new sb(`RESULT_NOTE_MISMATCH`,`Cannot replace a Session pin`);let a=n.results,o={...i,id:n.resultId??w(),noteId:r.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,origin:n.origin??i?.origin,startTime:a.startTime,endTime:a.endTime,duration:a.duration??0,completed:a.completed,roundsCompleted:a.roundsCompleted,totalRounds:a.totalRounds,repsCompleted:a.repsCompleted,status:`completed`,createdAt:i?.createdAt??a.endTime??Date.now()};if(await t.saveSession(o),a.logs?.length){let e={noteId:o.noteId,resultId:o.id,blockId:o.blockId,blockVersion:o.blockVersion,blockContentId:o.blockContentId,origin:o.origin,pageId:o.pageId,workoutTimestamp:o.endTime};await t.appendEvents(Eg(a.logs,e)),await t.finalizeSummaries(o.id,Dg(a.logs,e))}}});let a=await this.getEntry(i.id);if(!a)throw Error(`Saved note disappeared: ${i.id}`);return a}async updateRelationships(e,t){for(let n of[`journalDate`,`slug`]){let r=t[n];if(r===void 0)continue;let i;r&&(n===`journalDate`?i=await this.db.getOrCreatePageForDate(r):(i=await this.db.getPageBySlug(r),i||(i={id:w(),slug:r,title:(await this.db.getNote(e))?.title,createdAt:Date.now()},await this.db.savePage(i))));for(let t of await this.db.getNotePages(e)){let r=await this.db.getPage(t.pageId);(n===`journalDate`?r?.date:r?.slug&&!r.date)&&r?.id!==i?.id&&await this.db.removeNoteFromPage(e,t.pageId)}i&&await this.db.addNoteToPage(e,i.id)}}async changedManualTags(e,t){let n=(await this.db.getTagsForNote(e)).map(e=>e.label).sort(),r=[...new Set(t.map(e=>e.trim()).filter(Boolean))].sort();return n.length===r.length&&n.every((e,t)=>e===r[t])?void 0:r}async updateTags(e,t,n){let r=(await this.db.getAllTagTypes()).map(e=>e.name),i=ja(t,GO).filter(e=>e.type===`frontmatter`).flatMap(e=>dx(e.displayContent,r)),a=n??(await this.db.getNote(e))?.tags??[];await this.db.setNoteTags(e,[...a,...i.map(e=>e.type?e:e.label)])}async deleteEntry(e){await this.db.deleteNote(e)}async getAttachments(e){return this.db.getAttachmentsForNote(e)}async saveAttachment(e,t){let n={...t,id:t.id??w(),noteId:e,createdAt:Date.now()};return await this.db.saveAttachment(n),n}async deleteAttachment(e){await this.db.deleteAttachment(e)}},XO={beep:{notes:[{freq:880,type:`sine`,duration:.1}]},tick:{notes:[{freq:880,type:`sine`,duration:.1}]},click:{notes:[{freq:1400,type:`sine`,duration:.1}]},buzzer:{notes:[{freq:150,type:`sawtooth`,duration:.5}]},chime:{notes:[{freq:523.25,type:`sine`,duration:.5,offset:0},{freq:659.25,type:`sine`,duration:.5,offset:.1},{freq:783.99,type:`sine`,duration:.5,offset:.2}]},complete:{notes:[{freq:523.25,type:`sine`,duration:.5,offset:0},{freq:659.25,type:`sine`,duration:.5,offset:.1},{freq:783.99,type:`sine`,duration:.5,offset:.2}]},select:{notes:[{freq:880,type:`sine`,duration:.08,offset:0},{freq:1200,type:`sine`,duration:.12,offset:.08}]},start:{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"countdown-beep":{notes:[{freq:880,type:`sine`,duration:.1}]},"timer-complete":{notes:[{freq:523.25,type:`sine`,duration:.4,offset:0},{freq:659.25,type:`sine`,duration:.4,offset:.1},{freq:783.99,type:`sine`,duration:.6,offset:.2}]},"start-beep":{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"interval-start":{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"interval-complete":{notes:[{freq:523.25,type:`sine`,duration:.4,offset:0},{freq:659.25,type:`sine`,duration:.4,offset:.1},{freq:783.99,type:`sine`,duration:.6,offset:.2}]},"rest-over":{notes:[{freq:783.99,type:`sine`,duration:.3,offset:0},{freq:1046.5,type:`sine`,duration:.5,offset:.15}]}};function ZO(e){return XO[e]}var QO=Object.freeze(Object.keys(XO)),$O=class{context=null;masterGain=null;init(){if(this.context)return;let e=window;if(typeof window>`u`)return;let t=window.AudioContext??e.webkitAudioContext;t&&(this.context=new t,this.masterGain=this.context.createGain(),this.masterGain.connect(this.context.destination))}async playNotes(e,t){if(this.context||this.init(),!this.context||!this.masterGain||(this.context.state===`suspended`&&await this.context.resume().catch(()=>{}),this.context.state!==`running`))return;let n=this.context.currentTime;for(let r of e)this.playNote(n+(r.offset??0),r.freq,r.type,r.duration,t)}playNote(e,t,n,r,i){if(!this.context||!this.masterGain)return;let a=this.context.createOscillator(),o=this.context.createGain();a.connect(o),o.connect(this.masterGain),a.type=n,a.frequency.setValueAtTime(t,e),o.gain.setValueAtTime(i*.5,e),o.gain.exponentialRampToValueAtTime(.01,e+r),a.start(e),a.stop(e+r)}},ek=class extends Error{sound;constructor(e){super(`Unknown sound "${e}" — it has no entry in the sound table`),this.sound=e,this.name=`UnknownSoundError`}},tk=new class{enabled;sink;constructor(e,t){if(this.sink=e??new $O,t!==void 0)this.enabled=t;else if(typeof window<`u`)try{let e=localStorage.getItem(`wod-wiki-audio-enabled`);this.enabled=e===null||e===`true`}catch{this.enabled=!0}else this.enabled=!0}setEnabled(e){if(this.enabled=e,typeof window<`u`)try{localStorage.setItem(`wod-wiki-audio-enabled`,String(e))}catch{}}isEnabled(){return this.enabled}async playSound(e,t=1){if(!this.enabled)return;let n=ZO(e);if(!n)throw new ek(e);`init`in this.sink&&typeof this.sink.init==`function`&&this.sink.init(),await this.sink.playNotes(n.notes,t)}},nk=class{listeners=new Set;emit(e){this.listeners.forEach(t=>{try{t(e)}catch(e){console.error(`[SimpleEventBus] Error in listener:`,e)}})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get size(){return this.listeners.size}};new class{bus=new nk;emitScrollToBlock(e,t=`unknown`){this.bus.emit({type:`workbench:scroll-to-block`,payload:{blockId:e,source:t}})}emitHighlightBlock(e,t=`unknown`){this.bus.emit({type:`workbench:highlight-block`,payload:{blockId:e,source:t}})}emitStartWorkout(e){this.bus.emit({type:`workbench:start-workout`,payload:{block:e}})}emitNavigateTo(e,t){this.bus.emit({type:`workbench:navigate-to`,payload:{entryId:e,view:t}})}onScrollToBlock(e){return this.bus.subscribe(t=>{t.type===`workbench:scroll-to-block`&&e(t.payload)})}onHighlightBlock(e){return this.bus.subscribe(t=>{t.type===`workbench:highlight-block`&&e(t.payload)})}onStartWorkout(e){return this.bus.subscribe(t=>{t.type===`workbench:start-workout`&&e(t.payload)})}onNavigateTo(e){return this.bus.subscribe(t=>{t.type===`workbench:navigate-to`&&e(t.payload)})}},new nk;function rk(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`notebook`}var ik=CO===`api`,ak=[`wodwiki.routeWql.v1`,`wodwiki.routeWqlShortcuts.v1`,`wodwiki.soundProfiles.v1`],ok=[`wodwiki:notebooks`,`wodwiki:active-notebook`],sk=new Map,ck={getItem:e=>sk.get(e)??null,setItem:(e,t)=>sk.set(e,t),removeItem:e=>sk.delete(e)};async function lk(){let e=await Promise.all(ak.map(e=>DO.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`)))),t=await Promise.all(ok.map(e=>DO.readonly(`meta`).get(e)));for(let t of e)for(let e of t)sk.set(e.key,e.value);for(let e of t)e&&sk.set(e.key,e.value)}async function uk(e,t){t===null?(await DO.readwrite(`meta`).delete(e),sk.delete(e)):(await DO.readwrite(`meta`).put({key:e,value:t}),sk.set(e,t))}async function dk(e){if(e.length===1)return uk(e[0],null);await DO.transaction([`meta`],`readwrite`,async t=>{for(let n of e)await t.readwrite(`meta`).delete(n)});for(let t of e)sk.delete(t)}async function fk(e){return await DO.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`))}async function pk(e,t){await DO.readwrite(`meta`).put({key:e,value:t})}async function mk(e){await DO.readwrite(`meta`).delete(e)}var hk=`wodwiki.seedSources`,gk=`wodwiki.seedSources.hidden`;function _k(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!==`https:`&&n.protocol!==`http:`||n.username||n.password||n.search||n.hash?null:(n.pathname.endsWith(`/`)||(n.pathname+=`/`),n.toString())}function vk(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!==`https:`||n.username||n.password||n.search||n.hash?null:n.toString()}var yk=`/seed/core/`;function bk(e,t){if(/^https?:\/\//i.test(e))return e;let n=t??(typeof document<`u`?document.baseURI:void 0);if(!n)return e;try{return new URL(e,n).href}catch{return e}}function xk(){try{let e=localStorage.getItem(hk);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.label!=`string`||typeof e.url!=`string`)return[];let{repositoryUrl:t}=e,n=typeof t==`string`?vk(t):null,r={id:e.id,label:e.label,url:e.url};return[n?{...r,repositoryUrl:n}:r]}):[]}catch{return[]}}function Sk(){return xk()}function Ck(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`source`}function wk(e,t,n){let r=_k(t);if(!r)throw Error(`Enter an absolute http(s) URL of a seed directory.`);let i=xk();if(i.some(e=>_k(e.url)===r)||Nk().includes(r))throw Error(`This source is already registered.`);let a=n?.repositoryUrl?.trim(),o;if(a&&(o=vk(a)??void 0,!o))throw Error(`Enter an absolute https repository URL without credentials.`);let s=e.trim()||(()=>{try{return new URL(r).hostname}catch{return`Source`}})(),c={...Hk};for(let e of i)c[e.id]=!0;let l=Ck(s);for(let e=2;c[l];e++)l=`${Ck(s)}-${e}`;let u={id:l,label:s,url:r,...o?{repositoryUrl:o}:{}};return localStorage.setItem(hk,JSON.stringify([...i,u])),u}function Tk(e){localStorage.setItem(hk,JSON.stringify(xk().filter(t=>t.id!==e)))}function Ek(){return Mk.map(e=>e.id)}function Dk(){try{let e=JSON.parse(localStorage.getItem(gk)??`null`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function Ok(e){let t=Vk(e),n=Dk();Ek().includes(t)&&!n.includes(t)&&localStorage.setItem(gk,JSON.stringify([...n,t]))}function kk(){return[...new Set(Dk().map(Vk))]}var Ak=`https://bitcobblers.github.io`;function jk(e,t,n,r,i=!1){return{id:e,label:t,url:`${Ak}/${n}/`,repositoryUrl:`https://github.com/bitcobblers/${n}`,description:r,tier:`community`,...i?{autoImport:!0}:{}}}var Mk=[jk(`seed-core`,`Core Registry`,`wod-wiki-seed-core`,`Shared effort and equipment registries plus prebuilt WQL dashboards.`,!0),jk(`seed-crossfit`,`CrossFit`,`wod-wiki-seed-crossfit`,`CrossFit benchmark collections (Games, Girls, Heroes) and weekly programming.`),jk(`seed-hyrox`,`HYROX`,`wod-wiki-seed-hyrox`,`HYROX race preparation and simulation workouts.`),jk(`seed-kettlebell`,`Kettlebell Coaches`,`wod-wiki-seed-kettlebell`,`Kettlebell coach collections and the Dan John 40-Day Program feed.`),jk(`seed-swimming`,`Swimming`,`wod-wiki-seed-swimming`,`Swimming programs from pre-highschool through college, masters, Olympic, and triathlete.`),jk(`seed-track`,`Track & Field`,`wod-wiki-seed-track`,`High-school track programs — 400m (Raffensperger) and sprints (Arrowhead).`),jk(`seed-zombie-fit`,`ZombieFit`,`wod-wiki-seed-zombie-fit`,`The ZombieFit parkour archive — daily WODs since 2009.`),jk(`seed-golos-method`,`Golos Method`,`wod-wiki-seed-golos-method`,`Daily minimalist strength and conditioning.`),jk(`yt-dan-john`,`Dan John`,`wod-wiki-youtube-dan-john`,`Dan John kettlebell workouts.`),jk(`yt-mark-wildman`,`Mark Wildman`,`wod-wiki-youtube-mark-wildman`,`Mark Wildman athletic kettlebell and club training.`),jk(`yt-strongfirst`,`StrongFirst`,`wod-wiki-youtube-strongfirst`,`StrongFirst hardstyle kettlebell workouts.`),jk(`yt-the-stone-circle`,`The Stone Circle`,`wod-wiki-youtube-the-stone-circle`,`Sandbag power-endurance and density training.`),jk(`example-movement`,`Movement Examples`,`wod-wiki-example-movement`,`Unconventional and parkour-style training examples.`),jk(`example-yoga`,`Yoga Examples`,`wod-wiki-example-yoga`,`Yoga session examples.`),jk(`r-workoutroutines`,`r/WorkoutRoutines`,`wod-wiki-r-workoutroutines`,`Community feed from the r/WorkoutRoutines subreddit.`)];function Nk(){return[yk,...Mk.map(e=>e.url)]}function Pk(e){return Mk.find(t=>t.id===e)}function Fk(e){let t=Pk(e);if(!t)throw Error(`unknown seed source: ${e}`);return t}function Ik(e,t,n,r,i,a){return Fk(e),{id:`community-${t}`,seedId:e,chunkId:n,label:r,category:i,description:a}}var Lk=[Ik(`seed-core`,`efforts`,`efforts`,`Effort Registry`,`efforts`,`The shared effort registry — movement definitions workouts resolve against.`),Ik(`seed-core`,`equipment`,`equipment`,`Equipment Registry`,`equipment`,`The shared equipment registry resolved against workout programming.`),Ik(`seed-core`,`dashboards`,`dashboards`,`Common Dashboards`,`dashboards`,`Prebuilt WQL analytics dashboards tracking training volume, intensity distribution, and movement frequency.`),Ik(`seed-crossfit`,`crossfit-games`,`collection.crossfit-games`,`CrossFit Games`,`collections`,`CrossFit Games workouts — Open, Regionals, and Games programming, formatted for Wod Wiki.`),Ik(`seed-crossfit`,`crossfit-girls`,`collection.crossfit-girls`,`CrossFit Girls`,`collections`,`Classic benchmark workouts — Fran, Helen, Grace, Diane, and more, formatted for Wod Wiki.`),Ik(`seed-crossfit`,`crossfit-heroes`,`collection.crossfit-heroes`,`CrossFit Heroes`,`collections`,`Hero benchmark workouts honoring service members — Murph, DT, Badger, and more.`),Ik(`seed-crossfit`,`crossfit-programming`,`feed.crossfit-programming`,`CrossFit Programming`,`feeds`,`Weekly CrossFit programming — daily strength, conditioning, and skill sessions on a rotation with a weekly benchmark.`),Ik(`seed-hyrox`,`hyrox`,`collection.hyrox`,`HYROX`,`collections`,`HYROX race preparation — running, sled work, ergs, and functional stations in race format.`),Ik(`seed-kettlebell`,`geoff-neupert`,`collection.geoff-neupert`,`Geoff Neupert`,`collections`,`Geoff Neupert kettlebell workouts — strength and conditioning from a Master SFG coach.`),Ik(`seed-kettlebell`,`girevoy-sport`,`collection.girevoy-sport`,`Girevoy Sport`,`collections`,`Competitive kettlebell sport — jerk, snatch, and long-cycle programming.`),Ik(`seed-kettlebell`,`joe-daniels`,`collection.joe-daniels`,`Joe Daniels (Swing This)`,`collections`,`Joe Daniels kettlebell workouts — kettlebell sport and hardstyle fusion.`),Ik(`seed-kettlebell`,`keith-weber`,`collection.keith-weber`,`Keith Weber`,`collections`,`Keith Weber kettlebell workouts — high-intensity kettlebell cardio.`),Ik(`seed-kettlebell`,`steve-cotter`,`collection.steve-cotter`,`Steve Cotter`,`collections`,`Steve Cotter kettlebell workouts — comprehensive kettlebell education.`),Ik(`seed-kettlebell`,`dan-john-40-day`,`feed.dan-john-40-day`,`Dan John 40-Day Program`,`feeds`,`Dan John's 40-day barbell program — five lifts, five sets of five, five days a week for 40 sessions.`),Ik(`yt-dan-john`,`dan-john`,`collection.dan-john`,`Dan John Kettlebell`,`collections`,`Dan John kettlebell workouts — simple, effective programming with clear objectives.`),Ik(`yt-mark-wildman`,`mark-wildman`,`collection.mark-wildman`,`Mark Wildman`,`collections`,`Mark Wildman workouts — athletic kettlebell and club training.`),Ik(`yt-strongfirst`,`strongfirst`,`collection.strongfirst`,`StrongFirst`,`collections`,`StrongFirst workouts — hardstyle kettlebell strength and skill.`),Ik(`yt-the-stone-circle`,`the-stone-circle`,`collection.the-stone-circle`,`The Stone Circle`,`collections`,`Sandbag power endurance and density training — progressive EMOM protocols.`),Ik(`seed-swimming`,`swimming-college`,`collection.swimming-college`,`Swimming: College`,`collections`,`College swimming training sessions.`),Ik(`seed-swimming`,`swimming-highschool`,`collection.swimming-highschool`,`Swimming: High School`,`collections`,`High-school swimming training sessions.`),Ik(`seed-swimming`,`swimming-masters`,`collection.swimming-masters`,`Swimming: Masters`,`collections`,`Masters swimming training sessions.`),Ik(`seed-swimming`,`swimming-olympic`,`collection.swimming-olympic`,`Swimming: Olympic`,`collections`,`Olympic-caliber swimming training sessions.`),Ik(`seed-swimming`,`swimming-post-college`,`collection.swimming-post-college`,`Swimming: Post-College`,`collections`,`Post-college swimming training sessions.`),Ik(`seed-swimming`,`swimming-pre-highschool`,`collection.swimming-pre-highschool`,`Swimming: Pre-Highschool`,`collections`,`Pre-highschool swimming training sessions.`),Ik(`seed-swimming`,`swimming-triathlete`,`collection.swimming-triathlete`,`Swimming: Triathlete`,`collections`,`Triathlete swim training sessions.`),Ik(`seed-track`,`hs-track-400m`,`collection.hs-track-400m`,`HS Track 400m`,`collections`,`High-school 400m program after Raffensperger — speed, tempo, and strength phases.`),Ik(`seed-track`,`hs-track-sprints`,`collection.hs-track-sprints`,`HS Track Sprints`,`collections`,`High-school sprints program after Arrowhead — acceleration, maximum velocity, and speed endurance.`),Ik(`seed-zombie-fit`,`zombiefit`,`collection.zombiefit`,`ZombieFit`,`collections`,`The ZombieFit archive — parkour-inspired fitness WODs, 2009–2013.`),Ik(`seed-golos-method`,`the-golos-method`,`collection.the-golos-method`,`The Golos Method`,`collections`,`Daily minimalist strength and conditioning — dense, repeatable sessions.`),Ik(`example-movement`,`unconventional`,`collection.unconventional`,`Unconventional`,`collections`,`Unconventional training — maces, clubs, sandbags, and parkour movement.`),Ik(`example-yoga`,`yoga`,`collection.yoga`,`Yoga`,`collections`,`Yoga sessions for mobility and recovery.`),Ik(`r-workoutroutines`,`workoutroutines-reddit`,`feed.workoutroutines-reddit`,`r/WorkoutRoutines`,`feeds`,`Community workouts from the r/WorkoutRoutines subreddit.`)];function Rk(){return[...Mk,...Sk().map(e=>({id:e.id,label:e.label,url:e.url,description:`Custom seed synced from ${e.url}`,tier:`imported`,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{}}))]}function zk(){return[...Lk,...Sk().map(e=>({id:e.id,seedId:e.id,chunkId:e.id,label:e.label,category:`custom`,description:`Custom seed synced from ${e.url}`}))]}function Bk(e){return zk().filter(t=>t.seedId===e)}function Vk(e){return Lk.find(t=>t.id===e)?.seedId??e}var Hk=Object.fromEntries([[`core`,!0],[`community`,!0],[`common`,!0],...Mk.map(e=>[e.id,!0]),...Lk.map(e=>[e.id,!0])]),Uk=class{storageInstance;constructor(e){this.storageInstance=e}async getSeedMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async getNoteCommits(e){let t=await this.storageInstance.readonly(`notes`).getMany(e),n=new Map;for(let r=0;r<e.length;r++){let i=t[r];n.set(e[r],i?.seedCommit)}return n}async putSeedMeta(e,t){await this.storageInstance.transaction([`meta`],`readwrite`,async n=>{let r=n.readwrite(`meta`),i=await r.get(e.key);if(t!==void 0&&JSON.stringify(i??null)!==JSON.stringify(t))throw Error(`Seed checkpoint changed during claim`);await r.put(e)})}applyChunk(e){return Gv(this.storageInstance,e)}async removeSourceContent(e){return await this.storageInstance.transaction([`notes`,`attachments`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`meta`],`readwrite`,async t=>{let n=new Set,r=[];for(let[t,i]of Object.entries(e.chunks))if(i.noteIds?.length)for(let e of i.noteIds)n.add(e);else r.push(t);if(r.length)for(let e of await t.readwrite(`notes`).getAll())e.seedOrigin===`seed`&&e.seedChunkId&&r.includes(e.seedChunkId)&&n.add(e.id);let i=t.readwrite(`meta`),a=[];for(let t of await i.getAll()){let n=t;if(!n||typeof n.key!=`string`||!n.key.startsWith(`seed:`)||n.key===e.key)continue;let r=new Set;for(let e of Object.values(n.chunks??{}))for(let t of e.noteIds??[])r.add(t);a.push({key:n.key,sourceId:n.key.slice(5),rank:iv(n.key,n.tier),meta:n,noteIds:r})}a.sort((e,t)=>t.rank-e.rank);let o=e=>a.some(t=>t.noteIds.has(e)),s=e.key.startsWith(`seed:`)?e.key.slice(5):e.key,c=t.readwrite(`notes`),l=0,u=new Set;for(let r of n){if(o(r))continue;let n=await c.get(r);if(!n||n.seedOrigin!==`seed`||n.seedChunkId&&!e.chunks[n.seedChunkId])continue;n.sourcePath&&u.add(n.sourcePath),await c.delete(r);let i=t.readwrite(`attachments`);for(let e of await i.getAllFromIndex(`by-note`,r))await i.delete(e.id);let a=t.readwrite(`note_tags`);for(let e of await a.getAllFromIndex(`by-note`,r))await a.delete(e.id);let s=t.readwrite(`block_index`);for(let e of await s.getAllFromIndex(`by-note`,r))await s.delete(e.id);let d=t.readwrite(`block_efforts`);for(let e of await d.getAllFromIndex(`by-note`,r))await d.delete(e.id);let f=t.readwrite(`block_equipment`);for(let e of await f.getAllFromIndex(`by-note`,r))await f.delete(e.id);let p=t.readwrite(`page_notes`);for(let e of await p.getAllFromIndex(`by-note`,r))await p.delete(e.id);l++}let d=[{storeName:`efforts`,familyPathPrefix:`markdown/efforts/`,parse:Rc},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:zc}];for(let{storeName:e,familyPathPrefix:r,parse:i}of d){let o=t.readwrite(e);for(let t of await o.getAll()){if(t.registrySource!==`bundled`||!(t.sourceId===s||t.ownerNoteId!==void 0&&n.has(t.ownerNoteId)&&(!t.sourceId||t.sourceId===e)||t.sourcePath!==void 0&&t.sourcePath.startsWith(r)&&u.has(t.sourcePath)))continue;let l=!1;for(let n of a){let r=n.meta.chunks?.[e]?.noteIds??[];for(let e of r){let r=await c.get(e);if(!r||r.seedOrigin!==`seed`)continue;let a=i(r.rawContent);if(a&&a.slug===t.slug){await o.put({...a,registrySource:`bundled`,ownerNoteId:r.id,sourceId:n.sourceId,sourcePath:r.sourcePath??``}),l=!0;break}}if(l)break}l||await o.delete(t.slug)}}return await i.delete(e.key),l})}};function Wk(){return new Uk(DO)}var Gk=`wodwiki.seedSubscriptions`,Kk=`wodwiki.seedAutoSync`,qk=null,Jk=null,Yk=new Set;function Xk(e){let t={};try{let n=localStorage.getItem(e),r=n?JSON.parse(n):{};if(r&&typeof r==`object`&&!Array.isArray(r))for(let[e,n]of Object.entries(r))typeof n==`boolean`&&(t[e]=n)}catch{t={}}return t}function Zk(){return qk||(qk=Xk(Gk),qk)}function Qk(e,t){let n=!0;try{localStorage.setItem(e,JSON.stringify(t))}catch{n=!1}return n}function $k(e){qk=e;let t=Qk(Gk,e);for(let e of Yk)e();return t}function eA(e){if(e===`core`)return!0;let t=Zk();return e in t?t[e]===!0:Lk.some(n=>n.seedId===e&&t[n.id]===!0)}function tA(e,t){if(e===`core`)return!0;let n={};for(let[t,r]of Object.entries(Zk()))Lk.some(n=>n.seedId===e&&n.id===t)||(n[t]=r);return n[e]=t,$k(n)}function nA(e,t){if(e===`core`)return!0;let n=Zk(),r=`${e}#${t}`;return r in n?n[r]===!0:eA(e)}function rA(e,t,n){let r=`${e}#${t}`;return $k({...Zk(),[r]:n})}function iA(e){if(e===`core`)return null;let t=Zk();if(t[e]===!0)return null;let n=`${e}#`,r=Object.entries(t).filter(([e,t])=>t===!0&&e.startsWith(n)).map(([e])=>e.slice(n.length));return r.length>0?r:null}function aA(e){return Yk.add(e),()=>{Yk.delete(e)}}function oA(){return Jk||(Jk=Xk(Kk),Jk)}function sA(e){let t=oA();return e in t?t[e]===!0:e===`core`}function cA(e,t){let n={...oA(),[e]:t},r=Qk(Kk,n);Jk=n;for(let e of Yk)e();return r}async function lA(e,t=Wk()){let n={...Zk()},r=[];for(let e of Lk)e.id in n&&(e.seedId in n||(n[e.seedId]=n[e.id],n[e.id]&&r.push(e.seedId)),delete n[e.id]);for(let{id:i}of e)if(!(i===`core`||i in n))try{let e=await t.getSeedMeta(sv(i));e&&e.seedVersion>0&&(n[i]=!0,r.push(i))}catch{}return r.length&&$k(n),r}var uA=`notebooks`,dA=`active-notebook`,fA=[`📓`,`🏋️`,`🔥`,`💪`,`⭐`,`🎯`,`🏃`,`🧘`,`🥊`,`🚴`];function pA(e){let t=e.slug||rk(e.name||e.id);return{...e,slug:t,notebookId:e.notebookId||Ta(t),origin:e.origin||`user`}}var mA=class{store;constructor(e=new _b(`wodwiki:`,ik?ck:void 0)){this.store=e}tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}getAll(){return(this.store.get(uA)??[]).map(pA)}getDefaultNotebooks(){return[{id:`notebook/journal`,slug:`journal`,notebookId:`notebook/journal`,name:`Journal`,description:`Dated training log and scheduled workouts.`,icon:`📅`,origin:`default`,createdAt:0,lastEditedAt:0},{id:`notebook/playground`,slug:`playground`,notebookId:`notebook/playground`,name:`Playground`,description:`Scratchpad workouts and timer experiments.`,icon:`🧪`,origin:`default`,createdAt:0,lastEditedAt:0},{id:`notebook/guides`,slug:`guides`,notebookId:`notebook/guides`,name:`Guides`,description:`Built-in Whiteboard Language and WQL guides.`,icon:`📖`,origin:`default`,sourceEntryId:`core`,sourceUrl:yk,seedChunkId:`canvas`,createdAt:0,lastEditedAt:0}]}getSeedNotebooks(e){let t=new Map(Rk().map(e=>[e.id,e])),n=[];for(let r of zk()){if(r.category===`dashboards`||e?.onlySubscribed&&!eA(r.seedId))continue;let i=r.chunkId.replace(/^(?:collection|feed)\./,``),a=t.get(r.seedId);n.push({id:Ta(i),slug:i,notebookId:Ta(i),name:r.label,description:r.description,icon:r.category===`feeds`?`📡`:`📚`,origin:`seed`,sourceEntryId:r.seedId,packageId:r.id,sourceUrl:a?.url,...a?.repositoryUrl?{repositoryUrl:a.repositoryUrl}:{},seedChunkId:r.chunkId,createdAt:0,lastEditedAt:0})}return n}createNotebookLandingNote(e){return{id:w(),title:e.name,rawContent:e.description?`# ${e.name}\n\n${e.description}\n`:`# ${e.name}\n`,sourceRevision:1,blocks:{},createdAt:e.createdAt,type:`feed`,sourceId:`page:collection:${e.slug}`,catalog:e.slug,notebookId:e.notebookId,seedOrigin:`user`}}getAllCatalogNotebooks(){let e=new Map;for(let t of[...this.getDefaultNotebooks(),...this.getSeedNotebooks(),...this.getAll()])e.set(t.notebookId,t);return[...e.values()]}getById(e){return this.getAll().find(t=>t.id===e||t.notebookId===e||t.slug===e)??null}create(e,t=``,n=`📓`){return this.enqueue(()=>this.createNow(e,t,n))}async createNow(e,t,n){let r=Date.now(),i=this.getAll(),a=rk(e),o=new Set([`journal`,`playground`,`guides`,...i.map(e=>e.slug)]),s=a;for(let e=2;o.has(s);e++)s=`${a}-${e}`;let c=Ta(s),l={id:c,slug:s,notebookId:c,name:e,description:t,icon:n,origin:`user`,createdAt:r,lastEditedAt:r};return await this.saveAll([...i,l]),l}update(e,t){return this.enqueue(async()=>{let n=this.getAll(),r=n.findIndex(t=>t.id===e);if(r===-1)throw Error(`Notebook not found: ${e}`);let i=[...n];return i[r]={...n[r],...t,lastEditedAt:Date.now()},await this.saveAll(i),i[r]})}delete(e){return this.enqueue(async()=>{let t=this.getAll().filter(t=>t.id!==e);await this.saveAll(t),this.getActiveId()===e&&await this.setActiveIdNow(null)})}touchNotebook(e){return this.enqueue(async()=>{let t=this.getAll(),n=t.findIndex(t=>t.id===e);if(n!==-1){let e=[...t];e[n]={...t[n],lastEditedAt:Date.now()},await this.saveAll(e)}})}getActiveId(){return this.store.getRaw(dA)}setActiveId(e){return this.enqueue(()=>this.setActiveIdNow(e))}async setActiveIdNow(e){if(ik){await uk(this.store.qualify(dA),e);return}this.store.setRaw(dA,e)}getLastEdited(){let e=this.getAll();return e.length===0?null:e.reduce((e,t)=>e.lastEditedAt>=t.lastEditedAt?e:t)}ensureDefault(){return this.enqueue(()=>this.ensureDefaultNow())}async ensureDefaultNow(){let e=this.getAll();if(e.length===0){let e=await this.createNow(`My Workouts`,`Default workout notebook`,`📓`);return await this.setActiveIdNow(e.id),e.id}let t=this.getActiveId();if(t&&e.some(e=>e.id===t))return t;let n=this.getLastEdited();return n?(await this.setActiveIdNow(n.id),n.id):e[0].id}static ICONS=fA;async saveAll(e){if(ik){await uk(this.store.qualify(uA),JSON.stringify(e));return}this.store.set(uA,e)}},hA=new mA,gA=null,_A=new Set;function vA(e){gA!==e&&(gA=e,_A.forEach(e=>e(gA)))}function yA(){return gA}function bA(e){return _A.add(e),()=>{_A.delete(e)}}var xA=(0,U.createContext)({transport:null});function SA(){let e=(0,U.useContext)(xA),[t,n]=U.useState(()=>yA());return U.useEffect(()=>bA(n),[]),e.transport??t}var CA=({children:e,transport:t})=>{let n=(0,U.useMemo)(()=>({transport:t}),[t]);return(0,W.jsx)(xA.Provider,{value:n,children:e})},wA=(0,U.createContext)(void 0);function TA({children:e}){let[t,n]=(0,U.useState)(tk.isEnabled()),r=SA();(0,U.useEffect)(()=>{tk.setEnabled(t)},[t]);let i=(0,U.useCallback)((e,n=1)=>{if(t){if(r?.connected){console.log(`[AudioContext] Routing sound '${e}' to cast receiver`);try{r.send({type:`rpc-audio`,name:e,volume:n})}catch(t){console.error(`[AudioContext] Failed to send rpc-audio`,t),tk.playSound(e,n).catch(EA)}}else tk.playSound(e,n).catch(EA)}},[t,r]),a=(0,U.useCallback)(()=>{let e=!t;n(e),e&&(tk.setEnabled(!0),tk.playSound(`beep`).catch(EA))},[t]),o=(0,U.useCallback)(()=>{i(`chime`)},[i]),s=(0,U.useCallback)(()=>{i(`click`,.5)},[i]),c=(0,U.useMemo)(()=>({isEnabled:t,toggleAudio:a,playTestSound:o,playSound:i,playClick:s}),[t,a,o,i,s]);return(0,W.jsx)(wA.Provider,{value:c,children:e})}function EA(e){console.error(`[AudioContext] Sound playback failed`,e)}function DA(){let e=(0,U.useContext)(wA);if(e===void 0)throw Error(`useAudio must be used within an AudioProvider`);return e}var OA=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`SeedSourceError`}},kA=class{baseUrl;fetchImpl;constructor(e,t=fetch.bind(globalThis)){this.baseUrl=e,this.fetchImpl=t}async fetchManifest(){let e=await this.fetchImpl(`${this.baseUrl}manifest.json`,{cache:`no-cache`});if(!e.ok)throw new OA(`seed manifest fetch failed: HTTP ${e.status}`,e.status);return Iv(await e.json())}async fetchChunk(e){let t=await this.fetchImpl(`${this.baseUrl}${e}`);if(!t.ok)throw new OA(`seed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}},AA={core:1};function jA(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function MA(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}var NA=`sound-`;function PA(e){if(!e.startsWith(`sound-`))return;let t=e.slice(6);return t.length>0?t:void 0}function FA(e){let t=PA(e);return t?[{kind:`metric`,type:`sound`,value:t}]:[]}function IA(e){let t=[];for(let n of e){let e=n.label.trim();if(e.length===0)continue;let r=n.contributions?.length?n.contributions:FA(e);t.push({slug:e,contributions:r})}return t}var LA=new class{async loadTags(){return IA(await Z.getAllTags())}},RA=va([]),zA=new Set;function BA(){return RA}var VA=null;function HA(){return VA||=LA.loadTags().then(e=>{RA=va(e);for(let e of zA)e();return RA}).finally(()=>{VA=null}),VA}async function UA(){RA=va(await LA.loadTags());for(let e of zA)e();return RA}function WA(e){return zA.add(e),()=>zA.delete(e)}var GA=new class{_db;constructor(e){this._db=e}get db(){return this._db??Z}async load(){return this.db.getAllEquipment()}async save(e){await this.db.saveEquipment(e)}async delete(e){await this.db.deleteEquipment(e)}},KA=class{userEquipment=new Map;bundledEquipment=new Map;initialized=!1;storage;constructor(e){this.storage=e?.storage}async loadBundled(e){let t=this.storage?await this.storage.load():[];if(this.bundledEquipment.clear(),e)for(let t of e){let e=this.bundledEquipment.get(t.slug);(!e||ac(t)>=ac(e))&&this.bundledEquipment.set(t.slug,t)}this.userEquipment.clear();for(let e of t)e.registrySource===`user`&&this.userEquipment.set(e.slug,e);this.initialized=!0}isInitialized(){return this.initialized}resolve(e){return this.userEquipment.get(e)??this.bundledEquipment.get(e)??null}resolveByAlias(e){let t=uc(e);for(let e of this.userEquipment.values()){if(uc(e.label)===t)return e;for(let n of e.aliases)if(uc(n)===t)return e}let n=[...this.bundledEquipment.values()].filter(e=>!this.userEquipment.has(e.slug)).sort((e,t)=>ac(t)-ac(e));for(let e of n){if(uc(e.label)===t)return e;for(let n of e.aliases)if(uc(n)===t)return e}return null}list(){let e=new Map(this.bundledEquipment);for(let t of this.userEquipment.values())e.set(t.slug,t);return[...e.values()]}listByOrigin(e){return e===`user`?[...this.userEquipment.values()]:[...this.bundledEquipment.values()]}async upsert(e){if(e.registrySource!==`user`)throw Error(`Cannot upsert equipment with registrySource '${e.registrySource}'; clone it as 'user' first`);this.userEquipment.set(e.slug,e),this.storage&&await this.storage.save(e)}async delete(e){if(!this.userEquipment.get(e))throw Error(`Cannot delete equipment '${e}': not a user-owned record`);this.userEquipment.delete(e),this.storage&&await this.storage.delete(e)}};async function qA(e){let t=await Z.getAllEquipment();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),XA()}var JA=new Set;function YA(e){return JA.add(e),()=>JA.delete(e)}function XA(){for(let e of JA)e()}var ZA=null;function QA(){return ZA||=new KA({storage:GA}),ZA}var $A=class{storage;source;sourceId;now;constructor(e,t,n,r=Date.now){this.storage=e,this.source=t,this.sourceId=n,this.now=r}async applyAll(e={}){let t=Iv(await this.source.fetchManifest()),n=sv(this.sourceId),r=await this.storage.getSeedMeta(n),i=r?.schema===9?r:void 0,a=i??cv(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=t.version!==a.seedVersion||t.builtAt!==a.builtAt,s=t.chunks.filter(t=>e.notebookIds&&!e.notebookIds.includes(t.id)?!1:e.forceAll||o||a.chunks[t.id]?.sha256!==t.sha256);s.sort((e,t)=>Number(t.id===ov)-Number(e.id===ov));let c=Object.keys(a.chunks).filter(e=>!t.chunks.some(t=>t.id===e)),l={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0};if(!s.length&&!c.length&&!o)return l;l.status=`imported`;let u=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:l.appliedChunks,totalChunks:s.length,totalNotes:l.totalNotes,totalEfforts:l.totalEfforts,totalEquipment:l.totalEquipment,totalBlocks:l.totalBlocks,skippedUserOwned:l.skippedUserOwned,deleted:l.deleted,addedNotes:l.addedNotes,updatedNotes:l.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}});for(let n=0;n<s.length;){let r=s.slice(n,n+(s[n]?.id===`canvas`?1:4));for(let n of r){let r,o=t.notebooks?.find(e=>e.notebookId===n.id)?.records??n.records;if(e.granularRecords&&o&&o.length>0){let t=!e.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(o.map(e=>e.uuid)):void 0,i=t?o.filter(e=>t.get(e.uuid)!==e.commit):o;if(i.length===0&&!e.forceAll){l.appliedChunks++;continue}let a=[],s=0;for(let e of i){u(`fetching`,n.id,e.uuid,s,i.length);let t=await this.source.fetchChunk(e.recordPath),r=Array.isArray(t)?Lv(t):[Rv(t)];a.push(...r),s++}r=a}else if(u(`fetching`,n.id),r=Lv(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`);let s=await Promise.all(r.map(e=>zv(e.path))),c={...a,chunks:{...a.chunks,[n.id]:{sha256:n.sha256,noteIds:s}},importedAt:this.now()};u(`applying`,n.id);let d=await this.storage.applyChunk({chunkId:n.id,rows:r,manifest:t,expectedMeta:i,meta:c});l.totalNotes+=d.totalNotes,l.totalEfforts+=d.totalEfforts,l.totalEquipment+=d.totalEquipment,l.totalBlocks+=d.totalBlocks,l.skippedUserOwned+=d.skippedUserOwned,l.deleted+=d.deleted,l.addedNotes+=d.addedNotes,l.updatedNotes+=d.updatedNotes,l.appliedChunks++,a=c,i=c,u(`committed`,n.id),n.id===`canvas`&&e.onFirstPaintApplied?.()}n+=r.length}for(let e of c){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()},o=await this.storage.applyChunk({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r});l.deleted+=o.deleted,a=r,i=r}let d={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};return await this.storage.applyChunk({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:d}),u(`finalizing`,null),l}},ej=45e3;function tj(e){return(e instanceof Error?e.message:String(e)).replace(/(authToken["'=:\s]+)[^&\s,"']+/gi,`$1…`).replace(/(Bearer\s+)[\w.-]+/gi,`$1…`).replace(/https?:\/\/[^\s]+/gi,e=>{try{let t=new URL(e);return`${t.protocol}//${t.host}/…`}catch{return`…`}}).slice(0,300)}function nj(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function rj(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=sv(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);if(s.hadCheckpoint=(c?.seedVersion??0)>0,!t.force&&!t.probeManifests&&MA(c,e.embeddedVersion))return s.outcome=`current`,s;if(nj(c,i,a()))return s.outcome=`busy`,s;let l=Iv(await e.source.fetchManifest());s.manifestChecked=!0;let u=t.force?`import`:jA(c?.seedVersion,l.version);if(u===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);if(t.background&&!e.autoSyncOn)return s.outcome=u===`import`?`update-pending`:`current`,s;if(!t.force&&u===`current`&&c?.schema===9&&c.builtAt===l.builtAt)return s.outcome=`current`,s;let d={...c??cv(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(d,c??null);try{let i=await new $A(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:e.granularRecords});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=l.version,s.added=i.addedNotes,s.updated=i.updatedNotes)}finally{let e=await r.getSeedMeta(o);e?.claim?.owner===i&&await r.putSeedMeta({...e,claim:null},e)}return s}catch(t){return console.warn(`[seedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=tj(t),s}}function ij(){try{return typeof localStorage<`u`&&localStorage.getItem(`wodwiki.seedImport.enabled`)!==`0`}catch{return!1}}function aj(){let e=new Set(kk()),t=bk(yk);return[{id:`core`,label:`Core (playground)`,source:new kA(t),url:t,embeddedVersion:AA.core??0},...Mk.map(e=>({id:e.id,label:e.label,source:new kA(e.url),url:e.url,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},embeddedVersion:0,autoImport:e.autoImport??!1,tier:e.tier,...e.description?{description:e.description}:{}})),...Sk().map(e=>({id:e.id,label:e.label,source:new kA(e.url),url:e.url,repositoryUrl:e.repositoryUrl,embeddedVersion:AA[e.id]??0,autoImport:!1}))].filter(t=>!e.has(t.id))}function oj(e){try{if(typeof BroadcastChannel<`u`){let t=new BroadcastChannel(av);t.postMessage(e),t.close()}}catch{}}async function sj(){HD(),await UA().catch(()=>{});let e=vD();e.isInitialized()&&await pD(e);let t=QA();t.isInitialized()&&await qA(t)}function cj(e){return e.includes(`error`)?`error`:e.includes(`imported`)?`imported`:e.includes(`update-pending`)?`update-pending`:e.includes(`server-stale`)?`server-stale`:e.includes(`busy`)?`busy`:`current`}function lj(e,t,n,r){let i=n.now??Date.now,a=n.broadcast??oj,o=n.reportActivity!==!1;if(t.manifestChecked&&xj(e.id,i()),t.outcome===`error`){let i=t.error??`seed sync failed`;n.mode===`background`&&r?.set(e.id,{sourceId:e.id,label:e.label,state:`error`}),o&&zb(i);return}t.outcome===`imported`&&t.applied&&(a({kind:`seed-imported`,source:e.id,version:t.importedVersion}),sj(),o&&Lb({source:e.label,added:t.added??0,updated:t.updated??0}),r&&t.hadCheckpoint&&r.set(e.id,{sourceId:e.id,label:e.label,state:`updated`})),r&&t.outcome===`update-pending`&&r.set(e.id,{sourceId:e.id,label:e.label,state:`pending`})}function uj(){return typeof Worker<`u`&&!0}async function dj(e,t,n){return await new Promise(r=>{let i;try{i=new Worker(new URL(`/assets/seedSync.worker-CNP45WoU.js`,``+import.meta.url),{type:`module`})}catch(e){console.warn(`[seedSync] seed worker unavailable; running on main thread`,e),r(null);return}let a=t.mode===`background`?new Map:void 0,o=[],s=e.length,c=!1,l=e=>{Rb(null),i.terminate(),r(e)};i.onerror=e=>{console.warn(`[seedSync] seed worker failed`,e.message??`unknown error`),l(c?cj(o):null)},i.onmessage=n=>{c=!0;let r=n.data;if(r.type===`progress`){let n=e.find(e=>e.id===r.sourceId);Rb({sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,chunkId:r.progress.chunkId,recordId:r.progress.recordId,completedRecords:r.progress.completedRecords,totalRecords:r.progress.totalRecords,completedChunks:r.progress.completedChunks,totalChunks:r.progress.totalChunks,phase:r.progress.phase}),t.onProgress?.({...r.progress,sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,sourceIndex:e.indexOf(n)+1,totalSources:s});return}if(r.type===`first-paint`){sj(),t.onFirstPaint?.();return}if(r.type===`source-result`){let n=e.findIndex(e=>e.id===r.sourceId),i=e[n];if(!i)return;o.push(r.result.outcome),lj(i,r.result,t,a),t.onProgress?.({phase:`finished`,outcome:r.result.outcome,error:r.result.error,sourceId:i.id,sourceLabel:i.label,sourceIndex:n+1,totalSources:s});return}a&&_j([...a.values()]),l(cj(r.outcomes.length?r.outcomes:o))},i.postMessage({type:`run`,dbName:sO(),userId:wO.currentSync()?.id??null,owner:n,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`,sources:e.map(e=>({id:e.id,label:e.label,url:bk(e.url),...e.tier?{tier:e.tier}:{},embeddedVersion:e.embeddedVersion,autoSyncOn:sA(e.id),notebookIds:iA(e.id)??void 0,granularRecords:!0}))})})}var fj=null,pj=0,mj=new Set;function hj(){return fj}function gj(e){return mj.add(e),()=>{mj.delete(e)}}function _j(e){fj=e.length?{id:++pj,updates:e}:null;for(let e of mj)e()}function vj(e){fj?.updates.some(t=>t.sourceId===e)&&_j(fj.updates.filter(t=>t.sourceId!==e))}var yj=`wodwiki.seedChecks`;function bj(){try{let e=JSON.parse(localStorage.getItem(yj)??`null`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`number`))}catch{return{}}}function xj(e,t){try{localStorage.setItem(yj,JSON.stringify({...bj(),[e]:t}))}catch{}}function Sj(e){return bj()[e]??null}async function Cj(e={}){let t=[],n=e.storage??Wk(),r=e.mode===`background`?new Map:void 0;if(!(e.isEnabled??ij)())return`disabled`;let i=e.owner??`seed-${(e.now??Date.now)()}-${Math.random().toString(36).slice(2,8)}`,a=e.sources??aj();if(!e.storage&&!e.now&&uj()){let t=await dj(a,e,i);if(t)return t}for(let[o,s]of a.entries()){let c=await Tj(s,e,n,i,o+1,a.length,r);console.debug(`[seedSync] ${s.id} outcome: ${c}`),t.push(c)}return r&&_j([...r.values()]),cj(t)}async function wj(e={}){let t=e.sources??aj(),n=e.storage??Wk(),r;try{r=await n.getSeedMeta(sv(`core`))}catch(e){return console.warn(`[seedSync] boot provider probe failed`,e),`error`}if(!r||r.seedVersion<=0)return Cj({...e,sources:t.filter(e=>e.autoImport!==!1)});let i=t.filter(e=>e.id===`core`||eA(e.id)||iA(e.id)!==null);return Cj({...e,sources:i,probeManifests:!0,mode:`background`,reportActivity:!1})}async function Tj(e,t,n,r,i,a,o){let s=t.now??Date.now,c=t.onProgress,l=t.reportActivity!==!1,u=(t,n=null)=>c?.({phase:`finished`,outcome:t,error:n,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a});c?.({phase:`checking`,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a});let d=l?Ib(`download`,e.label):()=>{};try{let l=await rj({id:e.id,label:e.label,source:e.source,embeddedVersion:e.embeddedVersion,autoSyncOn:sA(e.id),...e.tier?{tier:e.tier}:{},notebookIds:iA(e.id)??void 0,granularRecords:!0},{storage:n,owner:r,now:s,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`},{onProgress:t=>{Rb({sourceId:e.id,sourceLabel:e.label,chunkId:t.chunkId,recordId:t.recordId,completedRecords:t.completedRecords,totalRecords:t.totalRecords,completedChunks:t.completedChunks,totalChunks:t.totalChunks,phase:t.phase}),c?.({...t,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a})},onFirstPaint:()=>{HD(),t.onFirstPaint?.()}});return lj(e,l,t,o),u(l.outcome,l.error),l.outcome}finally{Rb(null),d()}}async function Ej(e,t={}){let n=(t.sources??aj()).find(t=>t.id===e);if(!n)return console.warn(`[seedSync] unknown seed source: ${e}`),`error`;let r=await Cj({...t,sources:[n]});return(r===`imported`||r===`current`)&&(t.subscribe===!1?eA(e)||tA(e,!1):tA(e,!0),vj(e)),r}async function Dj(e,t={}){if(e===`core`)return{deleted:0};let n=t.storage??Wk(),r=await n.getSeedMeta(sv(e)),i=r?await n.removeSourceContent(r):0;tA(e,!1),cA(e,!1),vj(e),HD();let a=vD();a.isInitialized()&&await pD(a);let o=QA();return o.isInitialized()&&await qA(o),oj({kind:`seed-removed`,source:e}),{deleted:i}}async function Oj(e,t={}){if(e===`core`)return{deleted:0};let n=await Dj(e,t);return Sk().some(t=>t.id===e)?Tk(e):Ok(e),n}async function kj(e={}){let t=e.storage??Wk(),n=!1,r=!1;return await Promise.all((e.sources??aj()).map(async e=>{try{let i=await t.getSeedMeta(sv(e.id));if(!i||i.seedVersion<=0)return;e.autoImport===!1?r=!0:n=!0}catch{}})),{coreImported:n,libraryImported:r}}async function Aj(e={}){let t=e.storage??Wk();return{sources:await Promise.all((e.sources??aj()).map(async n=>{let r=await t.getSeedMeta(sv(n.id)),i=null,a=null,o=null,s=n.repositoryUrl;try{o=Iv(await n.source.fetchManifest()),i={version:o.version,schema:o.schema,builtAt:o.builtAt},s??=vk(o.repositoryUrl??``)??void 0,xj(n.id,(e.now??Date.now)())}catch(e){a=e instanceof Error?e.message:String(e)}let c=jj(n.id,o,r);return{id:n.id,label:n.label,url:n.url,...s?{repositoryUrl:s}:{},...n.description?{description:n.description}:{},autoImport:n.autoImport!==!1,notebooks:c,stored:r?{version:r.seedVersion,schema:r.schema,builtAt:r.builtAt,importedAt:r.importedAt}:null,remote:i,remoteError:a,upToDate:r!=null&&i!=null&&r.schema===9&&r.seedVersion===i.version,count:c.reduce((e,t)=>e+t.count,0),bytes:c.reduce((e,t)=>e+t.bytes,0),checkedAt:Sj(n.id),subscribed:eA(n.id),autoSync:sA(n.id)}}))}}function jj(e,t,n){let r={};for(let t of Bk(e))r[t.chunkId]=t;let i=(t?.chunks??[]).map(t=>({id:r[t.id]?.id??t.id,label:r[t.id]?.label??t.id,chunkId:t.id,count:t.count,bytes:t.bytes,imported:!!n?.chunks[t.id],subscribed:nA(e,t.id)}));return i.length>0?i:Bk(e).map(t=>({id:t.id,label:t.label,chunkId:t.chunkId,count:0,bytes:0,imported:!!n?.chunks[t.chunkId],subscribed:nA(e,t.chunkId)}))}async function Mj(e={}){let t=e.storage??Wk(),n=0;for(let e of Mk){let r=sv(e.id);try{let i=await t.getSeedMeta(r);if(i&&i.seedVersion>0)continue;let a=[];for(let n of Bk(e.id)){if(n.id===e.id)continue;let r=await t.getSeedMeta(sv(n.id));r&&r.seedVersion>0&&a.push(r)}if(a.length===0)continue;let o=a.reduce((e,t)=>t.seedVersion>e.seedVersion?t:e),s=a.find(e=>e.tier)?.tier,c={key:r,schema:o.schema,seedVersion:o.seedVersion,builtAt:o.builtAt,importedAt:Math.max(...a.map(e=>e.importedAt)),chunks:Object.assign({},...a.map(e=>e.chunks)),...s?{tier:s}:{},claim:null};await t.putSeedMeta(c,i??null);for(let e of a)await t.putSeedMeta({...e,seedVersion:0,chunks:{},claim:null},e);n+=1}catch(t){console.warn(`[seedSync] legacy checkpoint adoption failed for ${e.id}`,t)}}return n}var Nj=(0,U.createContext)(null);function Pj({children:e}){let[{isReady:t,error:n,revision:r},i]=(0,U.useState)({isReady:!1,error:null,revision:0}),a=vD(),o=(0,U.useCallback)(async()=>{try{await pD(a),i(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){i(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[a]),s=(0,U.useCallback)(async()=>{await o()},[o]);return(0,U.useEffect)(()=>{o()},[o]),(0,U.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(av);return e.onmessage=()=>{s()},()=>e.close()},[s]),(0,W.jsx)(Nj.Provider,{value:{registry:a,isReady:t,error:n,revision:r,refresh:s},children:e})}function Fj(){let e=(0,U.useContext)(Nj);if(!e)throw Error(`useEffortRegistry must be within EffortRegistryProvider`);return e}var Ij=(0,U.createContext)(null);function Lj({children:e}){let[t,n]=(0,U.useState)(!1),[r,i]=(0,U.useState)(null),a=QA(),o=(0,U.useCallback)(async()=>{try{await qA(a),n(!0),i(null)}catch(e){i(e instanceof Error?e:Error(String(e))),n(!1)}},[a]),s=(0,U.useCallback)(async()=>{n(!1),await o()},[o]);return(0,U.useEffect)(()=>{o()},[o]),(0,U.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(av);return e.onmessage=()=>{s()},()=>e.close()},[s]),(0,W.jsx)(Ij.Provider,{value:{registry:a,isReady:t,error:r,refresh:s},children:e})}function Rj(){let e=(0,U.useContext)(Ij);if(!e)throw Error(`useEquipmentRegistry must be within EquipmentRegistryProvider`);return e}var zj=sr,Bj=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(rr,{ref:n,className:G(`pointer-events-none fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]`,e),...t}));Bj.displayName=rr.displayName;var Vj=y(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background text-foreground`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),Hj=U.forwardRef(({className:e,variant:t,...n},r)=>(0,W.jsx)(Ne,{ref:r,className:G(Vj({variant:t}),e),...n}));Hj.displayName=Ne.displayName;var Uj=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)($n,{ref:n,className:G(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));Uj.displayName=$n.displayName;var Wj=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(dr,{ref:n,className:G(`absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-destructive-foreground group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-background`,e),"toast-close":``,...t,children:(0,W.jsx)(we,{className:`h-4 w-4`})}));Wj.displayName=dr.displayName;var Gj=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(p,{ref:n,className:G(`text-sm font-semibold`,e),...t}));Gj.displayName=p.displayName;var Kj=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(yt,{ref:n,className:G(`text-sm opacity-90`,e),...t}));Kj.displayName=yt.displayName;var qj=3,Jj=1e6,Yj=0;function Xj(){return Yj=(Yj+1)%(2**53-1),Yj.toString()}var Zj=new Map,Qj=e=>{if(Zj.has(e))return;let t=setTimeout(()=>{Zj.delete(e),nM({type:`REMOVE_TOAST`,toastId:e})},Jj);Zj.set(e,t)},$j=(e,t)=>{switch(t.type){case`ADD_TOAST`:return{...e,toasts:[t.toast,...e.toasts].slice(0,qj)};case`UPDATE_TOAST`:return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case`DISMISS_TOAST`:{let{toastId:n}=t;return n?Qj(n):e.toasts.forEach(e=>Qj(e.id)),{...e,toasts:e.toasts.map(e=>!n||e.id===n?{...e,open:!1}:e)}}case`REMOVE_TOAST`:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},eM=[],tM={toasts:[]};function nM(e){tM=$j(tM,e),eM.forEach(e=>e(tM))}function Q(e){let t=Xj(),n=()=>nM({type:`DISMISS_TOAST`,toastId:t}),r=e=>nM({type:`UPDATE_TOAST`,toast:{...e,id:t}});return nM({type:`ADD_TOAST`,toast:{...e,id:t,open:!0,onOpenChange:e=>{e||n()}}}),{id:t,dismiss:n,update:r}}function rM(){let[e,t]=U.useState(tM);return U.useEffect(()=>(eM.push(t),()=>{let e=eM.indexOf(t);e>-1&&eM.splice(e,1)}),[e]),{...e,toast:Q,dismiss:e=>nM({type:`DISMISS_TOAST`,toastId:e})}}function iM(){let{toasts:e}=rM();return(0,W.jsxs)(zj,{children:[e.map(function({id:e,title:t,description:n,action:r,...i}){return(0,W.jsxs)(Hj,{...i,children:[(0,W.jsxs)(`div`,{className:`grid gap-1`,children:[t&&(0,W.jsx)(Gj,{children:t}),n&&(0,W.jsx)(Kj,{children:n})]}),r,(0,W.jsx)(Wj,{})]},e)}),(0,W.jsx)(Bj,{})]})}var aM={activeL1Id:null,activeL2Id:null,activeL3Id:null,leftDrawerOpen:!1,rightDrawerOpen:!1,expandedIds:new Set,journalFilter:{selectedDate:null,selectedTags:[]},searchFilter:{scope:`all`}};function oM(e,t){switch(t.type){case`SET_ACTIVE_L1`:return e.activeL1Id===t.id?e:{...e,activeL1Id:t.id};case`SET_ACTIVE_L2`:return e.activeL2Id===t.id?e:{...e,activeL2Id:t.id};case`SET_ACTIVE_L3`:return e.activeL3Id===t.id?e:{...e,activeL3Id:t.id};case`SET_LEFT_DRAWER`:return e.leftDrawerOpen===t.open?e:{...e,leftDrawerOpen:t.open};case`SET_RIGHT_DRAWER`:return e.rightDrawerOpen===t.open?e:{...e,rightDrawerOpen:t.open};case`TOGGLE_EXPANDED`:{let n=new Set(e.expandedIds);return n.has(t.id)?n.delete(t.id):n.add(t.id),{...e,expandedIds:n}}case`SET_JOURNAL_DATE`:return{...e,journalFilter:{...e.journalFilter,selectedDate:t.date}};case`SET_JOURNAL_TAGS`:return{...e,journalFilter:{...e.journalFilter,selectedTags:t.tags}};case`SET_SEARCH_SCOPE`:return{...e,searchFilter:{scope:t.scope}};default:return e}}var sM=e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-80;window.scrollTo({top:e,behavior:`smooth`})}},cM=(0,U.createContext)({tree:[],navState:aM,dispatch:()=>{},l3Items:[],setL3Items:()=>{},secondarySpec:void 0,setSecondarySpec:()=>{},contextNav:void 0,setContextNav:()=>{},streamControls:null,setStreamControls:()=>{},scrollToSection:sM,registerScrollFn:()=>{},openCreateJournal:()=>{},registerCreateJournal:()=>{}});function lM(){return(0,U.useContext)(cM)}function uM(e){let{tree:t,dispatch:n}=lM();(0,U.useEffect)(()=>{e&&t.some(t=>t.id===e)&&n({type:`SET_ACTIVE_L1`,id:e})},[e,t,n])}function dM({tree:e,children:t}){let[n,r]=(0,U.useReducer)(oM,aM),[i,a]=(0,U.useState)([]),[o,s]=(0,U.useState)(void 0),[c,l]=(0,U.useState)(void 0),[u,d]=(0,U.useState)(null),f=Xt(),p=(0,U.useRef)(sM),m=(0,U.useRef)(null);(0,U.useEffect)(()=>{let t=e.find(e=>e.isActive?e.isActive(f,n):e.action.type===`route`?e.action.to===`/`?f.pathname===`/`||f.pathname===``:f.pathname.startsWith(e.action.to):!1);r({type:`SET_ACTIVE_L1`,id:t?.id??null})},[f.pathname]),(0,U.useEffect)(()=>{r({type:`SET_LEFT_DRAWER`,open:!1})},[f.pathname]);let h=(0,U.useCallback)(e=>{a(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n]?.id&&t.label===e[n]?.label&&t.secondaryAction?.id===e[n]?.secondaryAction?.id&&t.secondaryRunIcon===e[n]?.secondaryRunIcon)?t:e)},[]),g=(0,U.useCallback)(e=>{r({type:`SET_ACTIVE_L3`,id:e}),p.current(e)},[]),_=(0,U.useCallback)(e=>{p.current=e},[]),v=(0,U.useCallback)(e=>{m.current?.(e)},[]),y=(0,U.useCallback)(e=>{m.current=e},[]),b=(0,U.useMemo)(()=>({tree:e,navState:n,dispatch:r,l3Items:i,setL3Items:h,secondarySpec:o,setSecondarySpec:s,contextNav:c,setContextNav:l,streamControls:u,setStreamControls:d,scrollToSection:g,registerScrollFn:_,openCreateJournal:v,registerCreateJournal:y}),[e,n,i,h,o,c,l,u,g,_,v,y]);return(0,W.jsx)(cM.Provider,{value:b,children:t})}function fM(e){if(!e)return null;let t=X(e);return t.error?`Couldn't parse "${e}" — ${t.error}`:null}var pM=1e3;function mM(e){let t=(0,U.useRef)(e);t.current=e;let[n,r]=zn(),i=n.get(`q`)??``,[a,o]=(0,U.useState)(()=>{let{defaultQuery:e,legacy:r}=t.current;return i?X(i).error?r?.salvageQ?.(i,n)??e:i:r?.toQuery(n)??e}),[s,c]=(0,U.useState)(()=>!i||!X(i).error||t.current.legacy?.salvageQ?.(i,n)?null:fM(i)),l=(0,U.useRef)(a);l.current=a;let u=(0,U.useRef)(n);u.current=n;let d=(0,U.useRef)(!1);(0,U.useEffect)(()=>{if(d.current)return;d.current=!0;let{legacy:e}=t.current,n=u.current,i=n.get(`q`)??``,a=null;if(i?X(i).error&&(a=e?.salvageQ?.(i,n)??null):a=e?.toQuery(n)??null,!a)return;let o=new URLSearchParams(n);for(let t of e?.keys??[])o.delete(t);o.set(`q`,a),r(o,{replace:!0})},[r]);let f=(0,U.useRef)(!0),p=(0,U.useRef)(null),m=(0,U.useRef)(i);(0,U.useEffect)(()=>{if(i===m.current)return;m.current=i,f.current=!0,clearTimeout(p.current),p.current=null,c(fM(i));let e=i&&!X(i).error?i:t.current.defaultQuery;o(t=>t===e?t:e)},[i]);let h=(0,U.useRef)(t.current.defaultQuery);return(0,U.useEffect)(()=>{let e=t.current.defaultQuery;e!==h.current&&(h.current=e,!i&&o(t=>t===e?t:e))},[i,t.current.defaultQuery]),(0,U.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`q`)??``;e!==m.current&&(m.current=e,f.current=!0,clearTimeout(p.current),p.current=null,c(fM(e)),o(e&&!X(e).error?e:t.current.defaultQuery))};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e),clearTimeout(p.current)}},[]),{query:a,setQuery:(0,U.useCallback)(e=>{if(o(e),!X(e).error&&e!==l.current){let t=new URLSearchParams(u.current);t.set(`q`,e),m.current=e,r(t,{replace:!f.current}),f.current=!1,clearTimeout(p.current),p.current=setTimeout(()=>{f.current=!0,p.current=null},pM)}},[r]),urlQueryError:s}}var hM=[`origin`,`discipline`];function gM(e){return/\s/.test(e)?`text:"${e}"`:`text:${e}`}function _M(e){let t=e.filter(Boolean);return`:effort${t.length?`{${t.join(`,`)}}`:``}`}function vM(e,t){let n=e.trim();if(!n||n.startsWith(`:`)||n.includes(`{`)||n.includes(`}`))return null;let r=t.get(`origin`),i=t.get(`discipline`)?.trim();return _M([gM(n),...r&&r!==`all`?[`origin:${r}`]:[],...i?[`discipline:${i}`]:[]])}function yM(e){if(!hM.some(t=>e.get(t)))return null;let t=e.get(`origin`),n=e.get(`discipline`)?.trim();return _M([...t&&t!==`all`?[`origin:${t}`]:[],...n?[`discipline:${n}`]:[]])}var bM={keys:hM,toQuery:yM,salvageQ:vM};function xM(e){return e.endsWith(`/`)&&e.length>1?e.slice(0,-1):e}function SM(e){let t=[`note`,`session`,`post`,`text`,`timePreset`,`rangeStart`,`rangeEnd`,`s`,`tags`,`mode`];return{keys:t,toQuery(n){if(!t.some(e=>n.has(e)))return null;let r=null;if(n.has(`note`)||n.has(`session`)||n.has(`post`)){let e=[];(n.get(`note`)??`include`)!==`hide`&&e.push(`journal`),(n.get(`session`)??`include`)!==`hide`&&e.push(`feeds`),e.length===1&&(r=`source:${e[0]}`)}else e&&(r=`source:${e}`);let i=n.get(`timePreset`)??`2w`,a=i===`all`||i===`custom`?null:`last ${i}`,o=n.get(`text`)?.trim(),s=n.get(`tags`)?.trim(),c=o?/\s/.test(o)?`text:"${o}"`:`text:${o}`:null,l=s?`tags:${s}`:null,u=`:note`,d=[c,l].filter(Boolean);r===`source:journal`?u=`:journal`:r===`source:feeds`?u=`:notebook`:r===`source:playground`?u=`:playground`:r&&d.unshift(r);let f=d.length?`{${d.join(`,`)}}`:``;return[`${u}${f}`,a].filter(Boolean).join(` `)}}}var CM={route:`/journal`,title:`Journal`,defaultWql:`:journal{} last 4w`,level:`note`,target:`note`,scopeOptions:[`journal`],legacy:SM(`journal`)},wM={route:`/catalogs`,title:`Notebooks`,defaultWql:`:notebook{} by {tag}`,level:`session`,target:`note`,scopeOptions:[`feeds`],shelfVisible:!1,seedNotice:!0,legacy:SM(`feeds`)},TM={route:`/feeds`,title:`Notes`,defaultWql:`:notebook{}`,level:`note`,target:`note`,scopeOptions:[`feeds`],emptyMessage:`No note entries match your search.`,seedNotice:!0,legacy:SM(`feeds`)},EM={route:`/efforts`,title:`Efforts`,defaultWql:`:effort`,level:`effort`,target:`effort`,scopeOptions:[],emptyMessage:`No efforts match your search.`,legacy:bM},DM={route:`/equipment`,title:`Equipment`,defaultWql:`:note{source:equipment}`,level:`note`,target:`note`,scopeOptions:[`equipment`],emptyMessage:`No equipment matches your search.`},OM={route:`/sessions`,title:`Sessions`,defaultWql:`:session{} last 1d`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No completed session results recorded in this period.`},kM={route:`/playgrounds`,title:`Playgrounds`,defaultWql:`:playground{} by {date} last 1w`,level:`note`,target:`note`,scopeOptions:[`playground`],shelfVisible:!0,legacy:SM(`playground`)};function AM(e){return{route:`/session/${e}`,defaultWql:`:session{} from ${e} to ${e}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No session results recorded on ${e}.`}}function jM(e){return{route:`/results/${e}`,defaultWql:`:session{result:${e}, plane:segment}`,level:`segment`,target:`session`,scopeOptions:[],emptyMessage:`No segment records found for result ${e}.`}}function MM(e){return{route:`/c/${e}`,title:xD(e),defaultWql:`:note{notebook:${e}} by {date}`,level:`session`,target:`note`,scopeOptions:[`feeds`],shelfVisible:!1,defaultLayout:`cards`,catalog:e,legacy:SM(`feeds`)}}var NM={"/journal":CM,"/catalogs":wM,"/feeds":TM,"/feed":TM,"/efforts":EM,"/equipment":DM,"/sessions":OM,"/playgrounds":kM};function PM(e){let t=xM(e),n=NM[t];if(n)return n;if(t.startsWith(`/results/`)){let e=t.slice(9);if(e)return jM(e)}if(t.startsWith(`/session/`)){let e=t.slice(9);if(e)return AM(e)}if(t.startsWith(`/c/`)){let e=t.slice(3);if(e&&!e.includes(`/`))return MM(e)}}function FM(e){return PM(e)??CM}function IM(e){let t=NM[xM(e)]?.title;if(t)return t;if(xM(e).startsWith(`/c/`)){let t=xM(e).slice(3);if(t&&!t.includes(`/`))return xD(t)}}function LM(e){let t=xM(e);if(NM[t])return!0;if(t.startsWith(`/results/`)||t.startsWith(`/session/`))return t.slice(9)!==``;if(t===`/results`||t===`/results/segments`)return!0;if(t.startsWith(`/c/`)){let e=t.slice(3);return!!(e&&!e.includes(`/`))}return!1}var $={home:`/`,playgroundRoot:`/playground`,playground:`/playground/:id`,notePlaygroundAlias:`/note/playground/:name`,note:`/note/:category/:name`,journal:`/journal`,journalEntry:`/journal/:identity`,journalNote:`/journal/:date/:uuid`,noteById:`/notes/:noteId`,plan:`/plan`,aiFirst:`/ai-first`,feeds:`/feeds`,feed:`/feed`,feedDetail:`/feeds/:feedSlug`,feedItem:`/feeds/:feedSlug/:feedDate/:feedItem`,catalogs:`/catalogs`,subscribe:`/subscribe`,collections:`/collections`,collectionDetail:`/collections/:slug`,collectionWorkout:`/collections/:collection/:workout`,collection:`/c/:slug`,collectionTarget:`/c/:collection/:workout`,effortSlug:`/e/:slug`,equipment:`/equipment`,equipmentSlug:`/equipment/:slug`,sessions:`/sessions`,sessionDetail:`/results/:sessionId`,sessionDate:`/session/:date`,tags:`/tags`,dashboards:`/dashboards`,dashboardSlug:`/d/:slug`,pages:`/p/*`,playgrounds:`/playgrounds`,tracker:`/tracker/:runtimeId`,run:`/run/:runtimeId`,load:`/load`,loadJournal:`/load/journal`,loadJournalDate:`/load/journal/:date`,efforts:`/efforts`,effort:`/effort/:slug`,analytics:`/analytics`,analyticsExplorer:`/analytics/explorer`,dashboard:`/dashboard`,dashboardView:`/dashboard/:slug`,settings:`/settings`,settingsAppearance:`/settings/appearance`,settingsProfile:`/settings/profile`,settingsStorage:`/settings/storage`,settingsSync:`/settings/sync`,settingsSystem:`/settings/system`,settingsTags:`/settings/tags`,settingsSoundProfiles:`/settings/sound-profiles`,settingsData:`/settings/data`,settingsDatabase:`/settings/database`,settingsQueries:`/settings/queries`};function RM(e){return`/playground/${encodeURIComponent(e)}`}function zM(e){return`/journal/${encodeURIComponent(e)}/`}function BM(e){return`/journal/${encodeURIComponent(e)}`}function VM(e){return`/notes/${encodeURIComponent(e)}`}function HM(e,t){return`/journal/${encodeURIComponent(e)}?autoStart=${encodeURIComponent(t)}`}function UM(e){return`/feeds/${encodeURIComponent(e)}`}function WM(e){return`/c/${encodeURIComponent(e)}`}function GM(e,t){return`/c/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function KM(e){return`/run/${encodeURIComponent(e)}`}function qM({zip:e}){return`/load?zip=${encodeURIComponent(e)}`}function JM(e){return`/results/${encodeURIComponent(e)}`}function YM(e){return`/p/${e}`}function XM(){return`/playgrounds`}function ZM(){return`/efforts`}function QM(e){return`/equipment/${encodeURIComponent(e)}`}function $M(e){let t=new URLSearchParams;e?.q&&t.set(`q`,e.q),e?.weeks&&t.set(`weeks`,String(e.weeks));let n=t.toString();return`/dashboards${n?`?${n}`:``}`}function eN(){return`/dashboards`}function tN(e){return`/dashboard/${encodeURIComponent(e)}`}function nN(e,t,n){let r=new URLSearchParams;if(t)for(let[e,n]of Object.entries(t))r.set(e,n);n?.mode&&r.set(`mode`,n.mode),n?.tab&&r.set(`tab`,n.tab);let i=r.toString();return i?`/e/${encodeURIComponent(e)}?${i}`:`/e/${encodeURIComponent(e)}`}function rN(e){return{mode:e.get(`mode`)??void 0,tab:e.get(`tab`)??void 0,q:e.get(`q`)??void 0,origin:e.get(`origin`)??void 0}}function iN(e){return e.startsWith(`/playground/`)||e.startsWith(`/note/playground/`)}function aN(e){return e===`/efforts`||e.startsWith(`/effort/`)||e.startsWith(`/e/`)}function oN(e){return e===`/equipment`||e.startsWith(`/equipment/`)}function sN(e){let t=e.match(/^\/feeds\/([^/]+)\/([^/]+)\/([^/]+)$/);return t?[t[1],t[2],t[3]]:null}function cN(e){let t=e.match(/^\/feeds\/([^/]+)$/);return t?t[1]:null}function lN(e){if(!e)return``;let t=e.split(`-`);return t.length>1?t[t.length-1]:e}function uN(e){return typeof File<`u`&&e instanceof File?!1:`file`in e&&e.file!==void 0||`data`in e&&e.data!==void 0}async function dN(e){let t=Date.now();if(!uN(e))return{label:e.name,mimeType:e.type,data:await e.arrayBuffer(),timeSpan:{start:t,end:t}};let n=`file`in e?e.file:void 0,r=`data`in e?e.data:void 0,i;if(r!==void 0)i=r;else{if(!n)throw Error(`Attachment input requires either file or data, but neither was provided`);i=await n.arrayBuffer()}return{id:e.id,label:e.label??n?.name??`Attachment`,mimeType:e.mimeType??n?.type??`application/octet-stream`,data:i,timeSpan:e.timeSpan??{start:t,end:t}}}function fN(e){return{id:e.id,outputType:e.outputType,timeSpan:{started:e.timeSpan.started,ended:e.timeSpan.ended},metrics:e.metrics.toArray(),hints:(()=>{let t=$a(e);return t.length?t:void 0})(),sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,parent:e.parent,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,completionReason:e.completionReason}}function pN(e){return new ga({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function mN(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function hN(e,t){let{engine:n}=If(t.block,{effortResolver:t.effortResolver,userProfile:t.userProfile,calcs:t.calcs}),r=[];for(let t of e){if(t.outputType===`analytics`)continue;if(t.outputType!==`segment`){r.push(t);continue}let e=mN(t),i=n.run(pN(e)),a=t.metrics.filter(e=>e.origin===`analyzed`&&!i.metrics.some(t=>t.origin===`analyzed`&&t.type===e.type));r.push(fN(a.length?new ga({...i,metrics:[...i.metrics,...a]}):i))}return[...r,...n.finalize().map(fN)]}function gN(e,t,n){return hN(kg(t),{block:e,...n})}var _N={soreness:{unit:`rating`,label:`Soreness`,min:1,max:10},sleep:{unit:`h`,label:`Sleep`},hrv:{unit:`ms`,label:`HRV`},weight:{unit:`kg`,label:`Bodyweight`},hang:{unit:`kg`,label:`Max Hang Weight`},hr:{unit:`bpm`,label:`Avg Heart Rate`},planned:{unit:`count`,label:`Planned Sessions`}};function vN(e){let t=/^(-?\d+(?:\.\d+)?)\s*([a-z%]*)$/i.exec(e.trim());if(t)return{value:parseFloat(t[1]),unit:t[2]||void 0}}function yN(e){let t=new Map;for(let n of e.split(`
74
+ `)){let e=/^([a-z][a-z0-9]*)\s*[:=]\s*(.+)$/i.exec(n.trim());if(!e)continue;let r=e[1].toLowerCase(),i=_N[r];if(!i)continue;let a=vN(e[2]);a&&(i.min!==void 0&&a.value<i.min||i.max!==void 0&&a.value>i.max||t.set(r,{key:r,value:a.value,unit:a.unit??i.unit,label:i.label}))}return[...t.values()]}function bN(e){let t=new Map,n=/```wellness[^\S\n]*\n([\s\S]*?)```/g,r;for(;(r=n.exec(e))!==null;)for(let e of yN(r[1]))t.set(e.key,e);return[...t.values()]}function xN(e,t,n={}){let r=bN(t);if(r.length===0)return[];let i=n.targetDate??n.now??Date.now(),a=new Date(i),o=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,`0`)}-${String(a.getDate()).padStart(2,`0`)}`,s=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime();return r.map(t=>({id:SN(e,t.key),resultId:`wellness:${e}`,noteId:e,timestamp:s,grain:`summary`,origin:`user`,outputType:`wellness`,representationKind:`direct`,metrics:[{type:t.key,value:t.value,unit:t.unit,origin:`user`,metadata:{canonicalKey:t.key}}],metricTemporal:[{temporalKind:`civil-date`,civilDate:o}]}))}function SN(e,t){return`wellness:${e}:${t}`}async function CN(e,t,n,r={}){let i=xN(e,t,r),a=new Set(i.map(e=>e.id)),o=(await n.getEventsForNote(e)).filter(t=>t.id.startsWith(`wellness:${e}:`)),s=i.filter(e=>{let t=o.find(t=>t.id===e.id);return!t||t.metrics[0]?.value!==e.metrics[0]?.value||t.timestamp!==e.timestamp}),c=o.filter(e=>!a.has(e.id)).map(e=>e.id);return s.length>0&&await n.appendEvents(s),c.length>0&&await n.deleteEvents(c),{written:s.length,deleted:c.length}}function wN(e){return[...e].sort((e,t)=>t.createdAt-e.createdAt)}function TN(e,t){return t==null?e:e.slice(0,t)}var EN=class e{storage;contentProvider;constructor(e=Z,t=new YO(e)){this.storage=e,this.contentProvider=t}async createNote(e){if(await this.contentProvider.persistenceReady,await this.storage.getNote(e.id))throw Error(`Note already exists: ${e.id}`);return this.contentProvider.saveEntry({id:e.id,title:e.title,rawContent:e.rawContent,tags:e.tags??[],targetDate:e.targetDate,journalDate:e.journalDate,type:e.type??`note`,slug:e.slug,sourceId:e.sourceId})}async getNote(e,t={}){await this.contentProvider.persistenceReady;let n=await this.resolveNote(e);if(!n)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);let r=t.projection??`workbench`,i=t.includeSections??r!==`summary`,a=t.includeAttachments??!1,o=await this.contentProvider.getEntry(n.id);if(!o)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);let s=r===`summary`?{}:await this.selectResults(n,t.resultSelection),c=a?await this.storage.getAttachmentsForNote(n.id):void 0;return{...o,...s,sections:i?o.sections:void 0,attachments:c}}async listNotes(e={}){if(e.ids&&e.ids.length>0){let t=e.projection??`summary`;return Promise.all(e.ids.map(e=>this.getNote(e,{projection:t,...t===`history-detail`&&{resultSelection:{mode:`all-for-note`}}})))}let t=await this.contentProvider.getEntries(e);if(e.journalDate&&(t=t.filter(t=>t.journalDate===e.journalDate)),e.kind&&(t=t.filter(t=>t.type===e.kind)),e.search){let n=e.search.toLowerCase();t=t.filter(e=>e.title.toLowerCase().includes(n)||e.rawContent.toLowerCase().includes(n))}return e.projection===`history-detail`&&(t=await Promise.all(t.map(e=>this.getNote(e.id,{projection:`history-detail`,resultSelection:{mode:`all-for-note`}})))),(e.offset||e.limit)&&(t=t.slice(e.offset??0,(e.offset??0)+(e.limit??t.length))),t}async mutateNote(e,t){await this.contentProvider.persistenceReady;let n=await this.resolveNote(e);if(!n)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);if(t.expectedSourceRevision!==void 0&&t.expectedSourceRevision!==n.sourceRevision)throw new sb(`STALE_SOURCE`,`Note ${n.id} changed since it was loaded`);let r=t.attachments?.add?await Promise.all(t.attachments.add.map(e=>dN(e))):[];return await this.storage.withTransaction([`notes`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`block_revisions`,`sessions`,`events`,`attachments`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`],async e=>{let i=new YO(e);if(await i.updateEntry(n.id,{...t.metadata,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:t.expectedSourceRevision,results:t.workoutResult?.data,blockId:t.workoutResult?.blockId,blockVersion:t.workoutResult?.blockVersion,blockContentId:t.workoutResult?.blockContentId,origin:t.workoutResult?.origin,resultId:t.workoutResult?.id}),t.rawContent!==void 0&&t.rawContent!==n.rawContent){let r=await i.getEntry(n.id);await CN(n.id,t.rawContent,e,{targetDate:r?.targetDate})}for(let i of r)await e.saveAttachment({...i,id:i.id??w(),noteId:n.id,resultId:t.workoutResult?.id,createdAt:Date.now()});for(let n of t.attachments?.remove??[])await e.deleteAttachment(n)}),this.getNote(n.id,{includeAttachments:!!t.attachments})}async saveNote(e){if(await this.contentProvider.persistenceReady,await this.storage.getNote(e.noteId))return this.mutateNote(e.noteId,{rawContent:e.rawContent,blocks:e.blocks,expectedSourceRevision:e.expectedSourceRevision,metadata:e.metadata});if(e.expectedSourceRevision!==0)throw new sb(`STALE_SOURCE`,`Note ${e.noteId} no longer exists`);return this.contentProvider.saveEntry({id:e.noteId,rawContent:e.rawContent,blocks:e.blocks,sourceRevision:0,title:e.metadata?.title??`Workout Note`,tags:e.metadata?.tags??[],targetDate:e.metadata?.targetDate??Date.now(),journalDate:e.metadata?.journalDate,slug:e.metadata?.slug??void 0,type:e.metadata?.type??e.noteType,sourceId:e.metadata?.sourceId??void 0,createdAt:e.createdAt})}async startSession(t,n){if(await this.contentProvider.persistenceReady,n.noteId!==t.noteId)throw new sb(`RESULT_NOTE_MISMATCH`,`Session belongs to another Note`);return this.storage.withTransaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`sessions`,`events`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`],async r=>{await new e(r,new YO(r)).saveNote(t);let i=await r.getNote(t.noteId),a=i?.blocks[n.blockId];if(!i||!a||a.kind!==`wod`)throw new sb(`BLOCK_REVISION_NOT_FOUND`,`Selected workout is not in the saved Note`);let o=await r.getBlockRevision(i.id,a.id,a.version);if(!o)throw new sb(`BLOCK_REVISION_NOT_FOUND`,`Selected workout revision is missing`);if(await r.getSessionById(n.id))throw Error(`Session already exists: ${n.id}`);let s=ja(o.rawContent,{registeredWidgets:Da}).find(e=>e.scriptBlock),c={...n,blockId:a.id,blockVersion:o.version,blockContentId:s?.scriptBlock?.contentId,status:`in-progress`};return await r.saveSession(c),{note:i,revision:o,session:c}})}async finishSession(e,t,n){return await this.contentProvider.persistenceReady,this.storage.withTransaction([`sessions`,`block_revisions`,`events`],async r=>{let i=await r.getSessionById(e);if(!i)throw new sb(`RESULT_NOT_FOUND`,`Session not found: ${e}`);if(!await r.getBlockRevision(i.noteId,i.blockId,i.blockVersion))throw new sb(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision is missing`);let a={...i,startTime:t.startTime,endTime:t.endTime,duration:t.duration??0,roundsCompleted:t.roundsCompleted,totalRounds:t.totalRounds,repsCompleted:t.repsCompleted,completed:t.completed,status:`completed`,createdAt:n??i.createdAt};if(await r.saveSession(a),t.logs?.length){let e={noteId:a.noteId,resultId:a.id,blockId:a.blockId,blockVersion:a.blockVersion,blockContentId:a.blockContentId,origin:a.origin,pageId:a.pageId,workoutTimestamp:a.endTime};await r.appendEvents(Eg(t.logs,e)),await r.finalizeSummaries(a.id,Dg(t.logs,e))}return a})}async getBlockRevision(e,t,n){return await this.contentProvider.persistenceReady,this.storage.getBlockRevision(e,t,n)}async getBlockHistory(e,t){return await this.contentProvider.persistenceReady,this.storage.getBlockHistory(e,t)}async getNoteBlockHistory(e){return await this.contentProvider.persistenceReady,this.storage.getNoteBlockHistory(e)}async deleteNote(e){await this.contentProvider.persistenceReady;let t=await this.resolveNote(e);if(!t)throw new sb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);await this.contentProvider.deleteEntry(t.id)}async getSessionById(e){return await this.contentProvider.persistenceReady,this.storage.getSessionById(e)}async rederiveResultAnalytics(e){await this.contentProvider.persistenceReady;let t=await this.storage.getSessionById(e);if(!t)throw new sb(`RESULT_NOT_FOUND`,`Result not found: ${e}`);let n=await this.storage.getBlockRevision(t.noteId,t.blockId,t.blockVersion),r=n&&ja(n.rawContent).find(e=>e.scriptBlock)?.scriptBlock;if(!r||n?.kind!==`wod`)throw new sb(`BLOCK_REVISION_NOT_FOUND`,`Cannot re-derive result ${e}: pinned workout revision is missing`);let i={...r,id:t.blockId,version:t.blockVersion,dialect:n.dialect,sport:n.sport,statements:yc().read(r.content,n.sport).statements},a=this.storage.getEventsByResult?await this.storage.getEventsByResult(e):[],o=gN(i,a);if(this.storage.appendEvents&&this.storage.finalizeSummaries){let e={noteId:t.noteId,resultId:t.id,blockId:t.blockId,blockVersion:t.blockVersion,blockContentId:t.blockContentId,origin:t.origin,pageId:t.pageId,workoutTimestamp:t.createdAt};await this.storage.withTransaction([`events`],async n=>{a.length>0&&await n.deleteEvents(a.map(e=>e.id)),await n.appendEvents(Eg(o,e)),await n.finalizeSummaries(t.id,Dg(o,e))})}return t}async resolveNote(e){if(typeof e==`string`)return this.resolveByAnyId(e);if(e.id)return this.resolveByAnyId(e.id);if(e.slug)return this.resolveByAnyId(e.slug);let t=await this.storage.getAllNotes();if(e.shortId)return t.find(t=>lN(t.id)===e.shortId);let n=e.title;if(n)return t.find(e=>e.title.toLowerCase()===n.toLowerCase())}async resolveByAnyId(e){return await this.storage.getNote(e)||await this.storage.getNoteBySlug?.(e)||(await this.storage.getAllNotes()).find(t=>lN(t.id)===e||t.title.toLowerCase()===e.toLowerCase())}describeLocator(e){return typeof e==`string`?e:e.id??e.slug??e.shortId??e.title??`<empty locator>`}async getSimilarSessions(e,t={}){let n=await this.storage.getSessionsByContentId(e);return t.excludeNoteId&&(n=n.filter(e=>e.noteId!==t.excludeNoteId)),t.includePlayground||(n=n.filter(e=>e.origin!==`playground`)),TN(wN(n),t.limit)}async selectResults(e,t={mode:`latest`}){let n=async e=>!e||!this.storage.getEventsByResult?[]:this.storage.getEventsByResult(e.id);if(t.mode===`by-result-id`){let r=await this.storage.getSessionById(t.resultId);if(!r)throw new sb(`RESULT_NOT_FOUND`,`Result not found: ${t.resultId}`);if(r.noteId!==e.id)throw new sb(`RESULT_NOTE_MISMATCH`,`Result ${t.resultId} does not belong to note ${e.id}`);return{results:RO(r,await n(r))}}if(t.mode===`latest-for-section`||t.mode===`all-for-section`){let n=wN(await this.storage.getSessionsForSection(e.id,t.blockId));if(t.mode===`all-for-section`){let e=TN(n,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(n[0])}}let r=wN(await this.storage.getSessionsForNote(e.id));if(t.mode===`all-for-note`){let e=TN(r,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(r[0])}}async payloadOf(e){return e?RO(e,this.storage.getEventsByResult?await this.storage.getEventsByResult(e.id):[]):void 0}},DN=new EN;function ON(e){return Object.entries(e).filter(([e])=>e.startsWith(`markdown/dashboards/`)).map(([e,t])=>{let{meta:n}=tx(t),r=e.split(`/`).pop().replace(/\.md$/,``);return{slug:typeof n.slug==`string`&&n.slug?n.slug:r,title:typeof n.title==`string`&&n.title?n.title:r,rawContent:t}}).sort((e,t)=>e.title.localeCompare(t.title))}function kN(e){return e.map(e=>{let{meta:t}=tx(e.rawContent);if(t.dashboard!==`true`)return null;let n=typeof t.slug==`string`&&t.slug?t.slug:null,r=typeof t.title==`string`&&t.title?t.title:n??e.id;return n?{noteId:e.id,slug:n,title:r,rawContent:e.rawContent}:null}).filter(e=>e!==null)}function AN(e,t){let n=GD(),r=(0,U.useMemo)(()=>n?ON(n):[],[n]),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(!0);return(0,U.useEffect)(()=>{if(!e){a(null),s(!1);return}let t=!1;return s(!0),DN.listNotes({kind:`dashboard`}).then(n=>{if(t)return;let i=kN(n).find(t=>t.slug===e);if(i)a({slug:e,title:i.title,rawContent:i.rawContent,editable:!0,noteId:i.noteId});else{let t=r.find(t=>t.slug===e);a(t?{slug:t.slug,title:t.title,rawContent:t.rawContent,editable:!1}:null)}}).catch(()=>{t||a(null)}).finally(()=>{t||s(!1)}),()=>{t=!0}},[e,t,r]),{source:i,loading:o}}function jN(){let e=GD(),t=(0,U.useMemo)(()=>e?ON(e):[],[e]),[n,r]=(0,U.useState)([]),[i,a]=(0,U.useState)(!0);return(0,U.useEffect)(()=>{let e=!1;return DN.listNotes({kind:`dashboard`}).then(n=>{if(e)return;let i=kN(n),a=new Set(i.map(e=>e.slug)),o=[...i.map(e=>({slug:e.slug,title:e.title,editable:!0})),...t.filter(e=>!a.has(e.slug)).map(e=>({slug:e.slug,title:e.title,editable:!1}))];e||r(o)}).catch(()=>{e||r(t.map(e=>({slug:e.slug,title:e.title,editable:!1})))}).finally(()=>{e||a(!1)}),()=>{e=!0}},[t]),{items:n,loading:i}}var MN=/^#{1,6}\s+/;function NN(e){return(e??``).replace(MN,``).trim()}function PN(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function FN(){return PN(new Date)}function IN(e){return e<FN()}function LN(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;let n=Number(t[1]),r=Number(t[2])-1,i=Number(t[3]),a=new Date(n,r,i),o=PN(a);return o===e?{dateKey:o,date:a}:null}function RN(e){let t=LN(e);if(!t)throw Error(`Invalid journal date: ${e}`);return t.date.getTime()}function zN({persistence:e,uuid:t=w}){let n=new Map;return{async create(n){let r=n.journalDate?RN(n.journalDate):Date.now();return e.createNote({id:t(),title:NN(n.title),rawContent:n.rawContent,tags:n.tags??[],targetDate:r,journalDate:n.journalDate||void 0,type:n.type??`journal`,slug:n.slug,sourceId:n.sourceId})},getById(t){return e.getNote({id:t},{projection:`workbench`,resultSelection:{mode:`all-for-note`},includeSections:!0,includeAttachments:!0})},resolve(t){return e.getNote(t,{projection:`workbench`,resultSelection:{mode:`all-for-note`},includeSections:!0,includeAttachments:!0})},async listByDate(t){return RN(t),(await e.listNotes({journalDate:t,kind:`journal`,projection:`summary`})).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id))},update(t,r,i){let a=t.id,o=NN(r.match(/^#\s+(.+)$/m)?.[1]?.trim()),s=t.sourceRevision;if(s===void 0)return Promise.reject(Error(`Loaded Note source revision is required`));let c=0;for(;c<t.rawContent.length&&c<r.length&&t.rawContent[c]===r[c];)c++;let l=t.rawContent.length,u=r.length;for(;l>c&&u>c&&t.rawContent[l-1]===r[u-1];)l--,u--;let d=Fa(t.blocks??{},i?.changes??[{from:c,to:l,insert:r.slice(c,u)}]);for(let e of i?.retainedBlocks??[]){let n=Object.values(t.blocks??{}).find(t=>t.from===e.from&&t.to===e.to);n&&(d[n.id]={...n,from:e.nextFrom,to:e.nextTo})}let f=Na(r,{sourceRevision:s,registeredWidgets:Da,blocks:d}),p=async()=>e.mutateNote({id:a},{rawContent:r,blocks:f,expectedSourceRevision:s,metadata:o?{title:o}:void 0}),m=(n.get(a)??Promise.resolve()).then(p,p);n.set(a,m);let h=()=>{n.get(a)===m&&n.delete(a)};return m.then(h,h),m},moveToDate(t,n){let r=RN(n);return e.mutateNote({id:t},{metadata:{journalDate:n,targetDate:r}})},delete(t){return e.deleteNote({id:t})}}}var BN=zN({persistence:DN});function VN({persistence:e,journal:t}){async function n(n){let r=await e.listNotes({kind:`dashboard`});for(let e of r){if(n&&e.id===n)continue;let{meta:r,body:i}=tx(e.rawContent);if(r.dashboard!==`true`||r[`dashboard.active`]!==`true`)continue;let a={...r};delete a[`dashboard.active`],await t.update(e,`---\n${ax(a)}\n---\n${i}`)}}return{async createDashboard(e=A_){return await n(),t.create({title:e,rawContent:M_(e),type:`dashboard`,sourceId:`dashboards`})},async cloneDashboard(e,r,i){await n();let{meta:a,body:o}=tx(r),s={...a,slug:e};i&&(s.title=i);let c=`---\n${ax(s)}\n---\n${o}`;return t.create({title:typeof s.title==`string`?s.title:e,rawContent:c,type:`dashboard`,sourceId:`dashboards`})}}}var HN=VN({persistence:DN,journal:BN}),UN=[{query:`sum:totalVolume{discipline:strength} by {week}`,label:`Weekly strength volume`,question:`Is strength volume rising?`},{query:`avg:tis{effort:thruster} by {week}`,label:`Thruster time-in-motion`,question:`Is time-in-motion improving?`},{query:`sum:totalReps{discipline:strength} by {effort}`,label:`Reps by lift`,question:`Where do the reps go?`},{query:`last:sessionLoad{note:benchmark} by {session}`,label:`Benchmark loads`,question:`Is session load dropping?`},{query:`sum:sessionLoad{} by {intensity, week}`,label:`Polarized weekly load`,question:`Is my intensity 80/20?`},{query:`avg:calc.acwr{} by {day}`,label:`Injury risk (ACWR)`,question:`Am I spiking my workload?`},{query:`count:totalReps{tags:mobility} by {week}`,label:`Mobility habit`,question:`Did I do mobility work?`},{query:`avg:tis{} by {round}`,label:`TIS by round`,question:`Where does the pace fall apart?`},{query:`sum:totalVolume{} by {effort}`,label:`Volume by lift`,question:`Where does the volume go?`},{query:`:note{tags:pr,source:journal}`,label:`Find PR notes`,question:`Which notes are tagged PR?`},{query:`:note{type:wod,source:journal} last 8w`,label:`Recent workouts`,question:`What workouts did I do recently?`},{query:`:note{source:feeds}`,label:`Notebook workouts`,question:`What workouts are in the library?`},{query:`:block{text:fran}`,label:`Find Fran everywhere`,question:`Which blocks mention Fran?`}],WN=(0,U.createContext)(()=>{});function GN({close:e,children:t}){return(0,W.jsx)(WN.Provider,{value:e,children:t})}function KN(){return(0,U.useContext)(WN)}function qN(e,t){if(!e)return!1;if(e===t)return!0;let n=X(e),r=X(t);return!n.error&&!r.error&&dh(n)===dh(r)}function JN(e){let t=Xt(),n=ht(),r=KN(),{items:i,loading:a}=jN(),[o,s]=(0,U.useState)(!1),c=async()=>{s(!0);try{let e=await HN.createDashboard(),{meta:t}=tx(e.rawContent),i=typeof t.slug==`string`&&t.slug?t.slug:e.id;n(tN(i)),r()}finally{s(!1)}},l=t.pathname===`/dashboards`,u=l?new URLSearchParams(t.search).get(`q`):null;return(0,W.jsxs)(`div`,{className:`flex flex-col gap-1 px-2 py-3`,"data-testid":`dashboards-nav-panel`,children:[(0,W.jsx)(YN,{label:`Explorer`,active:l,onClick:()=>{n(eN()),r()}}),l?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`mt-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 px-3`,children:`Examples`}),UN.map(e=>(0,W.jsx)(YN,{label:e.label,title:e.question,active:qN(u,e.query),onClick:()=>{n($M({q:e.query})),r()}},e.query))]}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`mt-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 px-3`,children:`Dashboards`}),a?(0,W.jsx)(`div`,{className:`px-3 py-2 text-xs text-muted-foreground/60`,children:`Loading…`}):i.length===0?(0,W.jsx)(`div`,{className:`px-3 py-2 text-xs text-muted-foreground/60`,children:`No dashboards yet.`}):i.map(e=>(0,W.jsx)(YN,{label:e.title,badge:e.editable?void 0:`prebuilt`,active:t.pathname===`/dashboard/${e.slug}`||t.pathname===`/d/${e.slug}`,onClick:()=>{n(tN(e.slug)),r()}},e.slug)),(0,W.jsxs)(`button`,{type:`button`,onClick:c,disabled:o,"data-testid":`dashboards-nav-new`,className:`mt-2 flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-muted hover:text-foreground transition-colors disabled:opacity-50`,children:[(0,W.jsx)(En,{className:`size-3.5`}),`New dashboard`]})]})]})}function YN({label:e,active:t,onClick:n,badge:r,title:i}){return(0,W.jsxs)(`button`,{type:`button`,onClick:n,title:i,className:G(`flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-left transition-colors`,t?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:[(0,W.jsx)(`span`,{className:G(`size-2 rounded-full shrink-0`,t?`bg-primary`:`bg-border`)}),(0,W.jsx)(`span`,{className:`truncate`,children:e}),r&&(0,W.jsx)(`span`,{className:`ml-auto text-[9px] font-bold uppercase tracking-wide text-muted-foreground/50 shrink-0`,children:r})]})}function XN({children:e}){return(0,W.jsx)(W.Fragment,{children:e})}var ZN=(0,U.forwardRef)(function(e,t){return(0,W.jsx)(jn,{children:(0,W.jsx)(Nt,{...e,to:e.href,ref:t})})});function QN({className:e,...t}){return(0,W.jsx)(`nav`,{...t,className:et(e,`flex h-full min-h-0 flex-col`)})}function $N({className:e,...t}){return(0,W.jsx)(`div`,{...t,className:et(e,`flex flex-col border-b border-zinc-950/5 p-4 dark:border-white/5 [&>[data-slot=section]+[data-slot=section]]:mt-2.5`)})}function eP({className:e,...t}){return(0,W.jsx)(`div`,{...t,className:et(e,`flex flex-1 flex-col overflow-y-auto p-4 [&>[data-slot=section]+[data-slot=section]]:mt-8`)})}function tP({className:e,...t}){let n=(0,U.useId)();return(0,W.jsx)(ut,{id:n,children:(0,W.jsx)(`div`,{...t,"data-slot":`section`,className:et(e,`flex flex-col gap-0.5`)})})}var nP=(0,U.forwardRef)(function({current:e,className:t,children:n,...r},i){let a=et(`group flex w-full items-center gap-3 rounded-xl px-2 py-2.5 text-left text-base/6 font-medium text-foreground sm:py-2 sm:text-sm/5 transition-all duration-200`,`[&>[data-slot=icon]]:size-6 [&>[data-slot=icon]]:shrink-0 [&>[data-slot=icon]]:text-muted-foreground sm:[&>[data-slot=icon]]:size-5 [&>[data-slot=icon]]:transition-colors`,`[&>[data-slot=icon]:last-child]:ml-auto [&>[data-slot=icon]:last-child]:size-5 sm:[&>[data-slot=icon]:last-child]:size-4`,`[&>[data-slot=avatar]]:-m-0.5 [&>[data-slot=avatar]]:size-7 sm:[&>[data-slot=avatar]]:size-6`,`data-[hover]:bg-primary/10 data-[hover]:text-primary data-[hover]:[&>[data-slot=icon]]:text-primary`,`data-[active]:bg-primary/15 data-[active]:scale-[0.98]`,`data-[current]:bg-primary/10 data-[current]:text-primary data-[current]:[&>[data-slot=icon]]:text-primary font-bold`);return(0,W.jsxs)(`span`,{className:et(t,`relative`),children:[e&&(0,W.jsx)(Vt.span,{layoutId:`current-indicator`,className:`absolute inset-y-2 -left-4 w-1 rounded-full bg-primary shadow-[0_0_8px_rgba(129,140,248,0.5)]`}),typeof r.href==`string`?(0,W.jsx)(ie,{as:ZN,...r,className:a,"data-current":e?`true`:void 0,ref:i,children:(0,W.jsx)(XN,{children:n})}):(0,W.jsx)(it,{...r,className:et(`cursor-default`,a),"data-current":e?`true`:void 0,ref:i,children:(0,W.jsx)(XN,{children:n})})]})});function rP({className:e,...t}){return(0,W.jsx)(`span`,{...t,className:et(e,`truncate`)})}var iP={bookmark:Ut,calendar:zt,"clipboard-list":Ee,clock:st,dumbbell:Ye,flame:gr,folder:ue,"flask-conical":Ae,heart:E,library:v,rss:Xn,star:at,tag:M,activity:ze,wrench:O},aP=new _b(`wodwiki.routeWqlShortcuts.v1`,ik?ck:void 0);function oP(e,t){return{id:`all`,label:e,icon:t,wql:``}}var sP={"/journal":`All entries`,"/catalogs":`All notebooks`,"/feeds":`All notes`,"/playgrounds":`All playgrounds`,"/efforts":`All Efforts`,"/equipment":`All Equipment`,"/sessions":`All Sessions`},cP={"/journal":`calendar`,"/catalogs":`library`,"/feeds":`rss`,"/playgrounds":`flask-conical`,"/efforts":`dumbbell`,"/equipment":`wrench`,"/sessions":`clipboard-list`};function lP(e){let t=uP(e);return[oP(sP[t]??`Landing link`,cP[t]??`bookmark`)]}function uP(e){return e.startsWith(`/`)?e:`/${e}`}function dP(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(typeof r!=`object`||!r||Array.isArray(r))continue;let e=r;typeof e.id!=`string`||!e.id.trim()||n.has(e.id)||typeof e.label!=`string`||!e.label.trim()||typeof e.icon!=`string`||!iP[e.icon]||typeof e.wql==`string`&&(e.to!==void 0&&(typeof e.to!=`string`||!/^\/(?!\/)/.test(e.to))||(n.add(e.id.trim()),t.push({id:e.id.trim(),label:e.label.trim(),icon:e.icon,wql:e.wql.trim(),...typeof e.to==`string`?{to:e.to}:{}})))}return t}function fP(e,t=aP){return dP(t.get(uP(e)))}function pP(e,t=aP){let n=uP(e);if(t.getRaw(n)!=null){let n=fP(e,t);return n.some(e=>e.id===`all`)?n:[lP(e)[0],...n]}return lP(e)}async function mP(e,t,n=aP){let r=uP(e),i=dP(t);if(ik){try{await uk(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlShortcuts] server write failed:`,e),!1}return yP(),!0}return n.set(r,i),n.getRaw(r)===JSON.stringify(i)&&(yP(),!0)}var hP=0,gP=new Set;function _P(e){return gP.add(e),()=>{gP.delete(e)}}function vP(){return hP}function yP(){hP++;for(let e of gP)e()}function bP(e,t=aP){return(0,U.useSyncExternalStore)(_P,vP),pP(e,t)}function xP(e){return bm(e)?dh({...e,filters:(e.filters??[]).map(e=>({...e,values:[...e.values??[]].sort((e,t)=>e.value.localeCompare(t.value))})).sort((e,t)=>e.key.localeCompare(t.key)||Number(e.negate)-Number(t.negate)||e.values.map(e=>e.value).join(`|`).localeCompare(t.values.map(e=>e.value).join(`|`))),groupBy:[...e.groupBy??[]].sort((e,t)=>e.localeCompare(t))}):dh(e)}function SP(e,t){return e.to?t.pathname===e.to||t.pathname.startsWith(`${e.to}/`):CP(e.wql,t.query)}function CP(e,t){if(!e.trim())return t.trim()===``;if(t.trim()===``)return!1;if(t===e)return!0;let n=X(t),r=X(e);return!n.error&&!r.error&&xP(n)===xP(r)}var wP=`w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary/40`;function TP({open:e,onOpenChange:t,route:n,editing:r=null,initialQuery:i=``}){let[a,o]=(0,U.useState)(r?.label??``),[s,c]=(0,U.useState)(r?.icon??`bookmark`),[l,u]=(0,U.useState)(r?r.wql:i),[d,f]=(0,U.useState)(null);(0,U.useEffect)(()=>{e&&(o(r?.label??``),c(r?.icon??`bookmark`),u(r?r.wql:i),f(null))},[e,r,i]);let p=r!==null&&!!r.to,m=r?.id!==`all`,h=a.trim(),g=l.trim(),_=g?XC(g).error??null:null,v=h?null:`Label is required.`,y=!!h&&!p&&(!m||!!g)&&!_;return(0,W.jsx)(HS,{open:e,onClose:()=>t(!1),title:r?`Edit shortcut`:`Save search shortcut`,description:`Saved shortcuts appear in this route's navigation panel. Stored ${ik?`on the server.`:`in this browser only.`}`,footer:(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(K,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>t(!1),children:`Cancel`}),(0,W.jsx)(K,{type:`submit`,form:`save-wql-shortcut-form`,size:`sm`,disabled:!y,"data-testid":`shortcut-save`,children:`Save`})]}),children:(0,W.jsxs)(`form`,{id:`save-wql-shortcut-form`,onSubmit:async e=>{if(e.preventDefault(),!y)return;let i={id:r?.id??crypto.randomUUID(),label:h,icon:s,wql:p?r.wql:g,...r?.to===void 0?{}:{to:r.to}};if(!await mP(n,[...pP(n).filter(e=>e.id!==i.id),i])){f(`Couldn’t save — storage is unavailable. Your input is kept.`);return}t(!1)},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,W.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`shortcut-label`,className:`text-xs font-semibold text-muted-foreground`,children:`Label`}),(0,W.jsx)(`input`,{id:`shortcut-label`,value:a,onChange:e=>o(e.target.value),placeholder:`e.g. Strength this month`,"data-testid":`shortcut-label-input`,"aria-invalid":v?!0:void 0,className:wP}),v&&(0,W.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`shortcut-label-error`,children:v})]}),p?(0,W.jsxs)(`p`,{className:`rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:[`Route action — always opens `,r?.to,`. Label and icon are editable.`]}):(0,W.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`shortcut-query`,className:`text-xs font-semibold text-muted-foreground`,children:`Query (WQL)`}),(0,W.jsx)(`textarea`,{id:`shortcut-query`,rows:2,value:l,onChange:e=>u(e.target.value),placeholder:m?`find …`:`Empty — the plain route landing`,"data-testid":`shortcut-query-input`,"aria-invalid":_?!0:void 0,className:`${wP} font-mono text-xs`}),_?(0,W.jsxs)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`shortcut-query-error`,children:[`Couldn't parse — `,_]}):!g&&(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:m?`A shortcut needs a query.`:`Empty — opens the plain route landing.`})]}),(0,W.jsxs)(`fieldset`,{className:`space-y-1.5`,children:[(0,W.jsx)(`legend`,{className:`text-xs font-semibold text-muted-foreground`,children:`Icon`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Object.entries(iP).map(([e,t])=>(0,W.jsxs)(`label`,{title:e,className:s===e?`cursor-pointer rounded-md border border-primary bg-primary/10 p-1.5 text-primary`:`cursor-pointer rounded-md border border-border p-1.5 text-muted-foreground hover:text-foreground`,children:[(0,W.jsx)(`input`,{type:`radio`,name:`shortcut-icon`,value:e,checked:s===e,onChange:()=>c(e),"aria-label":`Icon ${e}`,"data-testid":`shortcut-icon-${e}`,className:`sr-only`}),(0,W.jsx)(t,{className:`size-4`,"aria-hidden":`true`})]},e))})]}),d&&(0,W.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`shortcut-storage-error`,children:d})]})})}var EP=[{id:`date`,label:`Date`},{id:`week`,label:`Week`},{id:`month`,label:`Month`},{id:`year`,label:`Year`},{id:`tag`,label:`Tags`},{id:`type`,label:`Type`},{id:`discipline`,label:`Discipline`},{id:`source`,label:`Source`},{id:`origin`,label:`Origin`}],DP=EP.map(e=>e.id),OP=Object.fromEntries(EP.map(e=>[e.id,e.label]));function kP(e){return OP[e]??e}function AP(e,t,n){let r=n?.sink,i=n?.priority??[],a=e=>{let t=i.indexOf(e);return t===-1?1/0:t};return[...e].sort((e,n)=>{if(t===`chronological-desc`)return n[0].localeCompare(e[0]);if(t===`priority-then-alpha`){let t=a(e[0]),r=a(n[0]);return t===r?e[0].localeCompare(n[0]):t-r}if(r){if(e[0]===r)return 1;if(n[0]===r)return-1}return e[0].localeCompare(n[0])})}function jP(e,t){let n=new Set(e);if(!t||t.length===0)return EP.filter(e=>n.has(e.id));let r=t.filter(e=>n.has(e)),i=new Set(r);return[...r.map(e=>({id:e,label:kP(e)})),...EP.filter(e=>n.has(e.id)&&!i.has(e.id))]}function MP(e,t,n){if(!e)return n;let r=new Set(t);return e.find(e=>r.has(e))??n}function NP(e){if(!e)return{options:[],invalid:[]};let t=[],n=[],r=new Set;for(let i of e){if(!DP.includes(i)){n.includes(i)||n.push(i);continue}r.has(i)||(r.add(i),t.push(i))}return{options:t,invalid:n}}var PP=`/palette`,FP=new _b(`wodwiki.routeWql.v1`,ik?ck:void 0),IP=[...Pp,...Fp],LP={notes:`note`,blocks:`block`,efforts:`effort`,collections:`feeds`};function RP(e){return e.startsWith(`/`)?e:`/${e}`}function zP(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim())}function BP(e,t,n){let r=[],i=[],a=new Set;for(let o of e){let e=n[o]??o;if(!t.includes(e)){i.includes(o)||i.push(o);continue}a.has(e)||(a.add(e),r.push(e))}return{options:r,invalid:i}}var VP={"/sessions":`/results`,"/dashboards":`/dashboard`,"/feeds":`/collections`};function HP(e){return e.replace(/^:(collections?)(?![\w:])/,e=>e===`:collections`?`:feeds`:`:feed`).replace(/(^|[{,\s])source:collections(?![\w:])/g,`$1source:feeds`).replace(/(^|[{,\s])type:collection(?![\w:])/g,`$1type:feed`)}function UP(e,t=FP){let n=RP(e),r=VP[n],i=t.get(n,{alias:r});if(!i)return{};let a=zP(i.typeOptions),o=zP(i.groupByOptions),s=a&&BP(a,IP,LP),c=o?NP(o):void 0;return{defaultWql:typeof i.defaultWql==`string`&&i.defaultWql.trim().length>0?HP(i.defaultWql.trim()):void 0,typeOptions:s?.options,groupByOptions:c?.options,...s?.invalid.length?{invalidTypeOptions:s.invalid}:{},...c?.invalid.length?{invalidGroupByOptions:c.invalid}:{}}}async function WP(e,t,n=FP){let r=RP(e),i={defaultWql:t.defaultWql?.trim()||void 0,typeOptions:zP(t.typeOptions),groupByOptions:zP(t.groupByOptions)};if(ik){try{await uk(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlConfig] server write failed:`,e),!1}return XP(),!0}return n.set(r,i),XP(),!0}async function GP(e,t=FP){let n=RP(e),r=VP[n];if(ik){try{await dk(r?[t.qualify(n),t.qualify(r)]:[t.qualify(n)])}catch(e){return console.error(`[routeWqlConfig] server delete failed:`,e),!1}return XP(),!0}return t.remove(n,r),XP(),!0}var KP=0,qP=new Set;function JP(e){return qP.add(e),()=>{qP.delete(e)}}function YP(){return KP}function XP(){KP+=1;for(let e of qP)e()}function ZP(e){let t=(0,U.useSyncExternalStore)(JP,YP,YP);return(0,U.useMemo)(()=>UP(e),[e,t])}function QP(e,t){let n=t??UP(e.route);return!n.defaultWql&&!n.typeOptions&&!n.groupByOptions?e:{...e,defaultWql:n.defaultWql??e.defaultWql,scopeOptions:n.typeOptions?n.typeOptions.filter(e=>Fp.includes(e)):e.scopeOptions,groupByOptions:n.groupByOptions}}function $P(e){let t=ZP(e?.route??``);return(0,U.useMemo)(()=>e?QP(e,t):void 0,[e,t])}function eF(e,t){if(e)switch(e.type){case`route`:t.navigate(e.to,{replace:!(e.pushHistory??!0)});break;case`query`:t.setQueryParam(e.params,!(e.pushHistory??!1));break;case`scroll`:t.scrollToSection?.(e.sectionId);break;case`view-source`:t.swapSource?.(e.source);break;case`view-state`:t.setPanelState?.(e.state,e.open);break;case`pipeline`:{let n=e.steps.filter(e=>e.type===`scroll`),r=e.steps.filter(e=>e.type!==`scroll`);r.forEach(e=>eF(e,t)),n.length>0&&(r.length>0?setTimeout(()=>{n.forEach(e=>eF(e,t))},0):n.forEach(e=>eF(e,t)));break}case`call`:e.handler();break;case`external`:window.open(e.href,`_blank`,`noopener,noreferrer`)}}function tF(e,t=`dialog`){if(e.action===`set-source`)return{type:`view-source`,source:e.value};if(e.action===`navigate`)return/^https?:\/\//.test(e.value)?{type:`external`,href:e.value}:{type:`route`,to:e.value};if(e.action===`set-state`){if(e.value===`note`)return{type:`view-state`,state:`note`};if(e.value===`review`)return{type:`view-state`,state:`review`};if(e.value===`track`)return{type:`view-state`,state:`track`,open:t}}return{type:`none`}}function nF(e,t){let n=e.pipeline.map(t=>tF(t,e.open));return{id:`btn-${t}`,label:e.label,action:n.length===1?n[0]:{type:`pipeline`,steps:n}}}function rF(e){let{action:t}=e;return t.type===`view-state`?t.state===`track`:t.type===`pipeline`&&t.steps.some(e=>e.type===`view-state`&&e.state===`track`)}var iF=`sticky top-0 z-10 bg-card`;function aF({title:e,defaultOpen:t=!1,collapsible:n=!0,children:r,count:i,className:a,sticky:o,trailing:s,bodyClassName:c,buttonClassName:l}){if(!n)return(0,W.jsxs)(`div`,{className:a,children:[(0,W.jsxs)(`div`,{className:et(`group flex w-full items-center gap-1 px-2 py-3 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground/80`,o&&iF),children:[(0,W.jsx)(`div`,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e}),i!==void 0&&(0,W.jsx)(`span`,{className:`ml-auto flex size-5 items-center justify-center rounded-full bg-border/50 text-[9px] font-black tabular-nums text-muted-foreground`,children:i})]}),(0,W.jsx)(`div`,{className:et(`flex flex-col gap-0.5`),children:r})]});let u=(0,W.jsxs)(_r,{className:et(`group flex items-center gap-1 px-2 py-3 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground/80 hover:text-primary transition-colors`,s?`min-w-0 flex-1`:`w-full`,l,o&&!s&&iF),children:[(0,W.jsx)(L,{className:`size-4 shrink-0 fill-muted-foreground/50 transition-transform duration-300 group-data-[open]:rotate-90 group-hover:fill-primary`}),(0,W.jsx)(`span`,{children:e}),i!==void 0&&(0,W.jsx)(`span`,{className:`ml-auto flex size-5 items-center justify-center rounded-full bg-border/50 text-[9px] font-black tabular-nums text-muted-foreground group-hover:bg-primary/10 group-hover:text-primary transition-colors`,children:i})]});return(0,W.jsxs)(je,{as:`div`,defaultOpen:t,className:a,children:[s?(0,W.jsxs)(`div`,{className:et(`flex w-full items-center bg-card`,o&&iF),children:[u,s]}):u,(0,W.jsx)(de,{className:et(`flex flex-col gap-0.5`,c),transition:!0,children:r})]})}var oF=null,sF=new Set;function cF(e){oF=e;for(let e of sF)e()}function lF(e){return sF.add(e),()=>{sF.delete(e)}}function uF(){return oF}function dF(){return(0,U.useSyncExternalStore)(lF,uF)}var fF={tags:`tag`},pF={source:!0},mF={text:!0};function hF(e){return fF[e]??e}function gF(e){return!!mF[e]}function _F(e){switch(e){case`note`:return`note`;case`effort`:return`effort`;default:return null}}function vF(e){return e.wildcard?`${e.value}*`:e.value}function yF(e,t){return e.filters.map((e,t)=>({filter:e,filterIndex:t})).filter(({filter:e})=>e.key===t).map(({filter:e,filterIndex:n})=>({filterIndex:n,key:t,negate:e.negate,values:e.values.map(e=>({value:e.value,wildcard:e.wildcard}))}))}function bF(e,t,n){let r=[];for(let i of yF(e,t))i.values.forEach((e,t)=>{let a=vF(e);r.push({display:a,negate:i.negate,label:n?.get(i.negate?a:e.value),occurrence:i,valueIndex:t})});return r}function xF(e,t,n){if(t===`source`)return OF(e,n);let r=X(e);if(r.error||!bm(r))return e;let i=yF(r,t).filter(e=>!e.negate);if(i.length>0&&!pF[t]){let r=i[i.length-1];return jF(e,t,r,[...r.values.map(vF),n].join(`|`))}if(i.length>0)return jF(e,t,i[i.length-1],n);let a=JC(e,MF(t,hF(t),``),n);return a.valid?a.wql:e}function SF(e,t,n){let r=n.occurrence.values.filter((e,t)=>t!==n.valueIndex).map(vF).join(`|`);return jF(e,t,n.occurrence,r||null)}function CF(e,t,n){let r=X(e);if(r.error||!bm(r))return`off`;if(t===`source`&&AF(r)===n)return`include`;let i=yF(r,t);return i.some(e=>!e.negate&&e.values.some(e=>vF(e)===n))?`include`:i.some(e=>e.negate&&e.values.some(e=>vF(e)===n))?`exclude`:`off`}function wF(e,t,n,r){return CF(e,t,n)===r?e:r===`off`?TF(e,t,n,`both`):r===`include`?xF(TF(e,t,n,`negative`),t,n):EF(TF(e,t,n,`positive`),t,n)}function TF(e,t,n,r){let i=e;for(;;){let e=X(i);if(e.error||!bm(e))return i;if(t===`source`&&r!==`negative`&&AF(e)===n){let e=OF(i,null);if(e===i)return i;i=e;continue}let a=yF(e,t).find(e=>(r===`both`||r===(e.negate?`negative`:`positive`))&&e.values.some(e=>vF(e)===n));if(!a)return i;let o=a.values.findIndex(e=>vF(e)===n),s=SF(i,t,{display:n,negate:a.negate,occurrence:a,valueIndex:o});if(s===i)return i;i=s}}function EF(e,t,n){let r=X(e);if(r.error||!bm(r))return e;let i=yF(r,t).filter(e=>e.negate);if(i.length>0){let r=i[i.length-1];return r.values.some(e=>vF(e)===n)?e:jF(e,t,r,[...r.values.map(vF),n].join(`|`))}let a=JC(e,{...MF(t,hF(t),``),negate:!0},n);return a.valid?a.wql:e}function DF(e,t){let n=t.trim(),r=e,i=!1;for(;;){let e=X(r);if(e.error||!bm(e))return r;let t=yF(e,`text`).filter(e=>!e.negate);if(t.length===0){if(!n||i)return r;let e=JC(r,MF(`text`,hF(`text`),``),n);return e.valid?e.wql:r}if(!n){let e=jF(r,`text`,t[0],null);if(e===r)return r;r=e;continue}if(!i){let e=jF(r,`text`,t[0],n);if(e===r)return r;r=e,i=!0;continue}if(t.length===1)return r;let a=jF(r,`text`,t[1],null);if(a===r)return r;r=a}}function OF(e,t){let n=X(e);if(n.error||!bm(n))return e;let r=new Set,i=n.filters.filter(e=>{if(e.key!==`source`||e.negate)return!0;let t=e.values.map(e=>`${e.value}${e.wildcard?`*`:``}`).join(`|`);return!r.has(t)&&(r.add(t),!0)}),a=Ip.find(t=>e.startsWith(`:${t}`)),o=a?Lp[a]:void 0;if(!t){if(!o)return dh({...n,sourceScope:void 0,filters:i});let e=!1,t=i.filter(t=>e||t.key!==`source`||t.negate?!0:t.values.length===1&&!t.values[0].wildcard&&t.values[0].value===o?(e=!0,!1):!0);return dh({...n,sourceScope:void 0,filters:t})}let s=t===`journal`?`:journal`:t===`feeds`?`:notebook`:t===`playground`?`:playground`:`:note{source:${t}}`,c=X(s.startsWith(`:note`)?s:`${s}{}`);if(c.error||!bm(c)||!c.filters.length)return e;let l=i.findIndex(e=>e.key===`source`&&!e.negate),u=l>=0?i.map((e,t)=>t===l?c.filters[0]:e):[...i,c.filters[0]];return dh({...n,sourceScope:void 0,filters:u})}function kF(e,t,n){let r=X(e);if(r.error||!bm(r))return e;let i=r.groupBy??[];if(n===i.some(e=>e.toLowerCase()===t.toLowerCase()))return e;let a=n?[...i,t.toLowerCase()]:i.filter(e=>e.toLowerCase()!==t.toLowerCase());return dh({...r,groupBy:a.length>0?a:void 0})}function AF(e){return e.filters.find(e=>e.key===`source`&&!e.negate)?null:e.sourceScope?.length===1?e.sourceScope[0]:null}function jF(e,t,n,r){let i=JC(e,{...MF(t,hF(t),n.values.map(vF).join(`|`)),filterIndex:n.filterIndex,negate:n.negate},r);return i.valid?i.wql:e}function MF(e,t,n){return{id:`nav-${e}`,type:t,...iC(t),value:n}}function NF(e,t,n){let r=new Map,i=(e,t)=>{let n=r.get(e);n?(n.count+=1,!n.label&&t&&(n.label=t)):r.set(e,{value:e,label:t,count:1})},a=Ep.includes(t)?t:t===`tags`?`tags`:null;if(a&&!n.tagMembership)return[];let o=(e===`note`||e===`block`)&&t===`effort`;if(o&&!n.effortMembership)return[];let s=e=>{r.has(e)||r.set(e,{value:e,count:0})};for(let r of n.entries)switch(`${e}:${t}`){case`note:catalog`:case`block:catalog`:r.catalog&&i(r.catalog);break;case`note:notebook`:case`block:notebook`:(r.notebookId||r.catalog)&&i(r.notebookId??r.catalog);break;case`note:type`:r.noteType&&i(r.noteType);break;case`block:type`:r.block?.dataType&&i(r.block.dataType);break;case`note:page`:i(r.noteType===`page`?`true`:`false`,r.noteType===`page`?`Pages`:`Non-pages`);break;case`effort:discipline`:r.effort?.discipline&&i(r.effort.discipline);break;case`effort:intensity`:r.effort?.intensityTier&&i(r.effort.intensityTier);break;case`effort:origin`:r.effort?.registrySource&&i(r.effort.registrySource);break;case`effort:effort`:r.effort?.slug&&i(r.effort.slug,r.effort.label);break;case`session:result`:r.execution?.resultId&&i(r.execution.resultId,r.title);break;case`session:block`:{let e=new Set;for(let t of r.execution?.events??[])t.blockContentId&&e.add(t.blockContentId);for(let t of e)i(t,r.title);break}case`session:note`:{let e=new Set;for(let t of r.execution?.events??[])t.noteId&&e.add(t.noteId);for(let t of e)i(t,r.title);break}case`session:plane`:for(let e of r.execution?.events??[])i(e.outputType);break;default:if(a){let e=n.tagMembership.get(r.catalog??r.noteId??r.id)??n.tagMembership.get(r.noteId??r.id)??[];for(let t of e)(a===`tags`||t.type===a)&&i(t.label)}else if(o){let e=n.effortMembership.get(r.catalog??r.noteId??r.id)??n.effortMembership.get(r.noteId??r.id)??[];for(let t of e)i(t)}}if(e===`note`&&t===`source`)return Fp.map(e=>({value:e,count:n.entries.filter(t=>Lg({id:t.noteId??t.id,sourceId:t.sourceId,type:t.noteType},e)).length})).filter(e=>e.count>0);if(e===`block`&&t===`source`)return Fp.map(e=>({value:e,count:n.entries.filter(t=>Lg({id:t.id,noteId:t.noteId,sourceId:t.sourceId,type:void 0},e)).length})).filter(e=>e.count>0);if((e===`note`||e===`block`)&&t===`note`)for(let e of n.entries)i(e.noteId??e.id,e.title);if(a)for(let e of n.tagMembership.values())for(let t of e)(a===`tags`||t.type===a)&&s(t.label);if(o)for(let e of n.effortMembership.values())for(let t of e)s(t);return[...r.values()].sort((e,t)=>t.count-e.count||(e.label??e.value).localeCompare(t.label??t.value))}var PF=e=>e.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1)})),FF={source:{enabled:!1,expectedValues:PF(Fp)},page:{enabled:!1,expectedValues:[{value:`true`,label:`Pages`},{value:`false`,label:`Non-pages`}]},intensity:{expectedValues:PF(Mp)},discipline:{expectedValues:PF(fh)}};function IF(e){return FF[e]??{}}var LF=[],RF=e=>new URLSearchParams(e.search).get(`q`)??``;async function zF(){let[e,t]=await Promise.all([Z.getNoteTagLabelsBatch(),Z.getAllNotes()]);for(let n of t){let t=e.get(n.id);if(!n.catalog||!t?.length)continue;let r=e.get(n.catalog);if(r)for(let e of t)r.some(t=>t.label===e.label)||r.push(e);else e.set(n.catalog,t.map(({label:e,type:t})=>({label:e,type:t})))}return e}function BF(e,t,n){let r=new URLSearchParams(e.search);r.set(`q`,n),t(`${e.pathname}?${r.toString()}`)}function VF({profile:e}){let t=Xt(),n=ht(),r=dF(),i=RF(t),a=$P(e),o=i&&!X(i).error?i:a.defaultWql,s=(0,U.useMemo)(()=>X(o),[o]),c=(0,U.useMemo)(()=>!s.error&&bm(s)?s:null,[s]),l=r&&r.pathname===t.pathname&&r.query===o?r.entries:null,[u,d]=(0,U.useState)(null);(0,U.useEffect)(()=>{r&&r.pathname===t.pathname&&d(r)},[r,t.pathname]);let f=l===null&&u!==null&&u.pathname===t.pathname,p=l??(f?u.entries:LF),m=c?_F(c.target):null,h=!!c&&!!m&&yF(c,m).length>0,g=(0,U.useMemo)(()=>c?im(c.target,`find`).filter(e=>e!==m||h):[],[c,m,h]),_=g.some(e=>e===`tags`||Ep.includes(e)),v=g.includes(`effort`),[y,b]=(0,U.useState)({tags:null,efforts:null});(0,U.useEffect)(()=>{if(!_&&!v||p.length===0)return;let e=!1;return Promise.all([_?zF():null,v?Z.getEffortSlugsByNoteBatch():null]).then(([t,n])=>{e||b({tags:t,efforts:n})}).catch(()=>{e||b({tags:null,efforts:null})}),()=>{e=!0}},[_,v,p]);let x=(0,U.useMemo)(()=>({entries:p,tagMembership:y.tags,effortMembership:y.efforts}),[p,y]),S=(0,U.useRef)(new Map),C=S.current.get(t.pathname);C||(C=new Map,S.current.set(t.pathname,C));let w=l!==null||u!==null,T=e=>BF(t,n,e),E=c?AF(c):null,D=(0,U.useMemo)(()=>g.filter(e=>IF(e).enabled!==!1).sort((e,t)=>(IF(e).order??0)-(IF(t).order??0)),[g]);return c?(0,W.jsx)(`div`,{className:`flex flex-col`,"aria-busy":f||void 0,children:D.map(e=>(0,W.jsx)(`div`,{"data-testid":`conditions-section-${e}`,children:(0,W.jsx)(KF,{query:o,parsed:c,entryKey:e,facetContext:x,labels:HF(c.target,e,p),headScope:e===`source`?E:null,pending:f,hasEverPublished:w,routeKnownOptions:C,onApply:T})},e))}):null}function HF(e,t,n){let r=new Map,i=(e,t)=>{e&&!r.has(e)&&r.set(e,t)};if((e===`note`||e===`block`)&&t===`note`)for(let e of n)i(e.noteId??e.id,e.title);if(e===`session`)for(let e of n){t===`result`&&i(e.execution?.resultId,e.title);for(let n of e.execution?.events??[])t===`block`&&i(n.blockContentId,e.title),t===`note`&&i(n.noteId,e.title)}return r}var UF=[`off`,`include`,`exclude`],WF={off:`Off`,include:`Include`,exclude:`Exclude`},GF={off:tt,include:a,exclude:Oe};function KF({query:e,parsed:t,entryKey:n,facetContext:r,labels:i,headScope:a,pending:o,hasEverPublished:s,routeKnownOptions:c,onApply:l}){let u=Xt(),d=IF(n);if(d.enabled===!1)return null;let f=iC(hF(n)),p=gF(n)||JF[n]!==void 0,m=bF(t,n,i),h=n===`text`?yF(t,`text`).filter(e=>!e.negate).map(e=>e.values.map(e=>e.value).join(`|`)).join(`|`):null,g=NF(t.target,n,r),_=c.get(n);_||(_=new Map,c.set(n,_));for(let e of g)_.has(e.value)||_.set(e.value,{value:e.value,label:e.label,count:0});let v=new Map(m.map(e=>[e.display,e])),y=new Map(g.map(e=>[e.value,e])),b=d.expectedValues,x=[],S=new Set,C=(t,r,i)=>{S.has(t)||(S.add(t),x.push({value:t,label:i??r?.label??v.get(t)?.label??t,count:r?r.count:null,state:CF(e,n,t)}))};if(s){for(let e of b??[]){let t=y.get(e.value);C(e.value,t,e.label)}if(!b){for(let e of g)C(e.value,e);for(let e of _.values())C(e.value,y.get(e.value),e.label)}}for(let e of m)C(e.display,y.get(e.display));n===`source`&&a&&C(a,y.get(a));let w=new Map((b??[]).map((e,t)=>[e.value,t]));x.sort((e,t)=>(w.get(e.value)??2**53-1)-(w.get(t.value)??2**53-1)||e.label.localeCompare(t.label));let T=u.pathname.startsWith(`/journal`),E=d.hideZero||n===`effort`||T&&(n===`tags`||Ep.includes(n))?x.filter(e=>e.count!==null&&e.count>0||e.state!==`off`):x;return E.length===0&&!p?null:(0,W.jsxs)(aF,{title:d.label??f.label,count:E.length,defaultOpen:x.some(e=>e.state!==`off`)||p,sticky:!0,buttonClassName:`gap-1.5 py-1.5 text-[11px] font-semibold normal-case tracking-normal [&>span:last-child]:h-auto [&>span:last-child]:w-auto [&>span:last-child]:min-w-0 [&>span:last-child]:rounded-sm [&>span:last-child]:px-1 [&>span:last-child]:bg-transparent [&>span:last-child]:text-[10px] [&>span:last-child]:font-semibold [&>span:last-child]:text-muted-foreground`,bodyClassName:`px-6`,children:[(0,W.jsx)(`ul`,{className:`flex flex-col`,children:E.map(t=>(0,W.jsx)(qF,{query:e,entryKey:n,row:t,pending:o,onApply:l},t.value))}),p&&(0,W.jsx)(YF,{entryKey:n,placeholder:f.placeholder,pending:o,currentText:h??void 0,onTextChange:t=>l(DF(e,t)),onApply:t=>l(wF(e,n,t,`include`))})]})}function qF({query:e,entryKey:t,row:n,pending:r,onApply:i}){let a=UF[(UF.indexOf(n.state)+1)%UF.length],o=GF[n.state],s=`${WF[a]} “${n.label}” (currently ${WF[n.state]})`,c=n.count===0&&n.state===`off`;return(0,W.jsx)(`li`,{"data-testid":`conditions-row-${t}:${n.value}`,className:et(`px-1 py-0.5`,r&&`opacity-60`,c&&`opacity-40`),children:(0,W.jsxs)(`div`,{className:`flex h-11 items-center gap-1.5`,children:[(0,W.jsx)(`span`,{className:et(`min-w-0 flex-1 truncate text-xs leading-4`,c?`text-muted-foreground`:`text-foreground`),children:n.label}),n.count!==null&&(0,W.jsx)(`span`,{className:`text-[10px] leading-4 tabular-nums text-muted-foreground`,children:n.count}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`conditions-state-${t}:${n.value}`,"data-state":n.state,onClick:()=>i(wF(e,t,n.value,a)),disabled:r,"aria-label":s,title:s,className:et(`flex size-11 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent transition-colors hover:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:cursor-default`,n.state===`include`&&`bg-primary/10 text-primary`,n.state===`exclude`&&`bg-destructive/10 text-destructive`,n.state===`off`&&`text-muted-foreground`),children:(0,W.jsx)(o,{"aria-hidden":`true`,className:`size-4`})})]})})}var JF={note:!0,block:!0,result:!0};function YF({entryKey:e,placeholder:t,pending:n,currentText:r,onTextChange:i,onApply:a}){let[o,s]=(0,U.useState)(``),c=KN();return e===`text`?(0,W.jsxs)(`div`,{className:`px-1 py-1.5`,children:[(0,W.jsx)(`input`,{value:r??``,onChange:e=>i?.(e.target.value),placeholder:t,"aria-label":t,"data-testid":`conditions-input-text`,className:`h-8 w-full min-w-0 rounded-md border border-border/60 bg-background px-2 text-xs text-foreground placeholder:text-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-primary/40`}),(0,W.jsxs)(`button`,{type:`button`,"data-testid":`conditions-jump-wql-text`,onClick:()=>{c(),document.querySelector(`[data-testid="stream-query-bar"]`)?.click()},className:`mt-1 inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground`,children:[(0,W.jsx)(lt,{"aria-hidden":`true`,className:`size-3`}),`Edit in WQL bar`]})]}):(0,W.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=o.trim();t&&(a(t),s(``))},className:`flex items-center gap-1 px-1 py-1.5`,children:[(0,W.jsx)(`input`,{value:o,onChange:e=>s(e.target.value),placeholder:t,"aria-label":t,"data-testid":`conditions-input-${e}`,disabled:n,className:`h-8 min-w-0 flex-1 rounded-md border border-border/60 bg-background px-2 text-xs text-foreground placeholder:text-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-primary/40`}),(0,W.jsx)(`button`,{type:`submit`,"aria-label":`Add ${t}`,"data-testid":`conditions-add-${e}`,disabled:n||!o.trim(),className:`flex size-8 shrink-0 items-center justify-center rounded-md border border-border/60 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:(0,W.jsx)(En,{"aria-hidden":`true`,className:`size-3.5`})})]})}var XF=e=>new URLSearchParams(e.search).get(`q`)??``;function ZF(e){return function(t){let n=Xt(),r=ht(),{openCreateJournal:i}=lM(),a=$P(e.profile),o=XF(n),s=o&&!X(o).error?o:a.defaultWql,c=e=>BF(n,r,e),l=KN(),u=bP(e.route),d={pathname:n.pathname,query:XF(n)},f=u.find(e=>e.id===`all`)??null,p=u.filter(e=>e.to===void 0&&e.id!==`all`),m=f?.wql??``,h=f?.label??e.landingLabel,g=f?iP[f.icon]:e.icon,_=d.query&&!X(d.query).error&&!u.some(e=>SP(e,d))?s:null,[v,y]=(0,U.useState)(!1);return(0,W.jsxs)(`div`,{className:`-mx-4 flex flex-col gap-1 py-3`,"data-testid":`conditions-nav-panel`,children:[(0,W.jsxs)(tP,{className:`px-6`,children:[e.createAction&&(()=>{let t=e.createAction.icon??En;return(0,W.jsx)(`div`,{className:`mb-2`,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":e.createAction.testId??`conditions-nav-create`,onClick:()=>{e.createAction.onClick({navigate:r,openCreateJournal:e=>i?.(e)}),l()},className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,W.jsx)(t,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e.createAction.label})]})})})(),_?(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,"data-testid":`conditions-nav-custom`,children:[(0,W.jsxs)(nP,{current:!0,className:`min-w-0 flex-1`,title:_,"aria-label":`Custom query: ${_}`,onClick:()=>{c(_),l()},children:[g&&(0,W.jsx)(g,{"data-slot":`icon`}),(0,W.jsx)(rP,{children:`Custom`})]}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>y(!0),"aria-label":`Save shortcut`,title:`Save shortcut`,"data-testid":`conditions-nav-custom-save`,className:`grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,W.jsx)(ft,{className:`size-4`,"aria-hidden":`true`})}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>{m?c(m):r(e.route),l()},"aria-label":`Clear query`,title:`Clear to all entries`,"data-testid":`conditions-nav-custom-clear`,className:`grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,W.jsx)(we,{className:`size-4`,"aria-hidden":`true`})})]}):(0,W.jsxs)(nP,{onClick:()=>{m?c(m):r(e.route),l()},current:m&&f?SP(f,d):e.familyActive(n)&&XF(n).trim()===``,children:[g&&(0,W.jsx)(g,{"data-slot":`icon`}),(0,W.jsx)(rP,{children:h})]}),p.map(t=>{let n=iP[t.icon];return(0,W.jsxs)(nP,{onClick:()=>{t.wql?c(t.wql):r(e.route),l()},current:SP(t,d),"data-testid":`nav-shortcut-${t.id}`,children:[(0,W.jsx)(n,{"data-slot":`icon`}),(0,W.jsx)(rP,{children:t.label})]},`shortcut-${t.id}`)}),(e.extraChildren??[]).map(e=>{let t=e.action.type===`route`?e.action.to:null,i=t?u.find(e=>e.to===t):null,a=i?iP[i.icon]:null;return(0,W.jsxs)(nP,{onClick:()=>{e.action&&(eF(e.action,{navigate:r,setQueryParam:()=>{}}),l())},current:e.isActive?.(n)??!1,"data-testid":i?`nav-shortcut-${i.id}`:void 0,children:[a?(0,W.jsx)(a,{"data-slot":`icon`}):e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(rP,{children:i?.label??e.label})]},e.id)})]}),(0,W.jsx)(VF,{profile:e.profile}),(0,W.jsx)(TP,{open:v,onOpenChange:y,route:e.route,initialQuery:s})]})}}var QF=`https://www.buymeacoffee.com/sergeigolos`,$F=({className:e,...t})=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 884 1279`,fill:`currentColor`,className:e,"aria-hidden":`true`,...t,children:[(0,W.jsx)(`path`,{d:`M791.109 297.518L790.231 297.002L788.201 296.383C789.018 297.072 790.04 297.472 791.109 297.518V297.518Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M803.896 388.891L802.916 389.166L803.896 388.891Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M791.484 297.377C791.359 297.361 791.237 297.332 791.118 297.29C791.111 297.371 791.111 297.453 791.118 297.534C791.252 297.516 791.379 297.462 791.484 297.377V297.377Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M791.113 297.529H791.244V297.447L791.113 297.529Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M803.111 388.726L804.591 387.883L805.142 387.573L805.641 387.04C804.702 387.444 803.846 388.016 803.111 388.726V388.726Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M793.669 299.515L792.223 298.138L791.243 297.605C791.77 298.535 792.641 299.221 793.669 299.515V299.515Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M430.019 1186.18C428.864 1186.68 427.852 1187.46 427.076 1188.45L427.988 1187.87C428.608 1187.3 429.485 1186.63 430.019 1186.18Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M641.187 1144.63C641.187 1143.33 640.551 1143.57 640.705 1148.21C640.705 1147.84 640.86 1147.46 640.929 1147.1C641.015 1146.27 641.084 1145.46 641.187 1144.63Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M619.284 1186.18C618.129 1186.68 617.118 1187.46 616.342 1188.45L617.254 1187.87C617.873 1187.3 618.751 1186.63 619.284 1186.18Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M281.304 1196.06C280.427 1195.3 279.354 1194.8 278.207 1194.61C279.136 1195.06 280.065 1195.51 280.684 1195.85L281.304 1196.06Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M247.841 1164.01C247.704 1162.66 247.288 1161.35 246.619 1160.16C247.093 1161.39 247.489 1162.66 247.806 1163.94L247.841 1164.01Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M472.623 590.836C426.682 610.503 374.546 632.802 306.976 632.802C278.71 632.746 250.58 628.868 223.353 621.274L270.086 1101.08C271.74 1121.13 280.876 1139.83 295.679 1153.46C310.482 1167.09 329.87 1174.65 349.992 1174.65C349.992 1174.65 416.254 1178.09 438.365 1178.09C462.161 1178.09 533.516 1174.65 533.516 1174.65C553.636 1174.65 573.019 1167.08 587.819 1153.45C602.619 1139.82 611.752 1121.13 613.406 1101.08L663.459 570.876C641.091 563.237 618.516 558.161 593.068 558.161C549.054 558.144 513.591 573.303 472.623 590.836Z`,fill:`#FFDD00`}),(0,W.jsx)(`path`,{d:`M78.6885 386.132L79.4799 386.872L79.9962 387.182C79.5987 386.787 79.1603 386.435 78.6885 386.132V386.132Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M879.567 341.849L872.53 306.352C866.215 274.503 851.882 244.409 819.19 232.898C808.711 229.215 796.821 227.633 788.786 220.01C780.751 212.388 778.376 200.55 776.518 189.572C773.076 169.423 769.842 149.257 766.314 129.143C763.269 111.85 760.86 92.4243 752.928 76.56C742.604 55.2584 721.182 42.8009 699.88 34.559C688.965 30.4844 677.826 27.0375 666.517 24.2352C613.297 10.1947 557.342 5.03277 502.591 2.09047C436.875 -1.53577 370.983 -0.443234 305.422 5.35968C256.625 9.79894 205.229 15.1674 158.858 32.0469C141.91 38.224 124.445 45.6399 111.558 58.7341C95.7448 74.8221 90.5829 99.7026 102.128 119.765C110.336 134.012 124.239 144.078 138.985 150.737C158.192 159.317 178.251 165.846 198.829 170.215C256.126 182.879 315.471 187.851 374.007 189.968C438.887 192.586 503.87 190.464 568.44 183.618C584.408 181.863 600.347 179.758 616.257 177.304C634.995 174.43 647.022 149.928 641.499 132.859C634.891 112.453 617.134 104.538 597.055 107.618C594.095 108.082 591.153 108.512 588.193 108.942L586.06 109.252C579.257 110.113 572.455 110.915 565.653 111.661C551.601 113.175 537.515 114.414 523.394 115.378C491.768 117.58 460.057 118.595 428.363 118.647C397.219 118.647 366.058 117.769 334.983 115.722C320.805 114.793 306.661 113.611 292.552 112.177C286.134 111.506 279.733 110.801 273.333 110.009L267.241 109.235L265.917 109.046L259.602 108.134C246.697 106.189 233.792 103.953 221.025 101.251C219.737 100.965 218.584 100.249 217.758 99.2193C216.932 98.1901 216.482 96.9099 216.482 95.5903C216.482 94.2706 216.932 92.9904 217.758 91.9612C218.584 90.9319 219.737 90.2152 221.025 89.9293H221.266C232.33 87.5721 243.479 85.5589 254.663 83.8038C258.392 83.2188 262.131 82.6453 265.882 82.0832H265.985C272.988 81.6186 280.026 80.3625 286.994 79.5366C347.624 73.2302 408.614 71.0801 469.538 73.1014C499.115 73.9618 528.676 75.6996 558.116 78.6935C564.448 79.3474 570.746 80.0357 577.043 80.8099C579.452 81.1025 581.878 81.4465 584.305 81.7391L589.191 82.4445C603.438 84.5667 617.61 87.1419 631.708 90.1703C652.597 94.7128 679.422 96.1925 688.713 119.077C691.673 126.338 693.015 134.408 694.649 142.03L696.731 151.752C696.786 151.926 696.826 152.105 696.852 152.285C701.773 175.227 706.7 198.169 711.632 221.111C711.994 222.806 712.002 224.557 711.657 226.255C711.312 227.954 710.621 229.562 709.626 230.982C708.632 232.401 707.355 233.6 705.877 234.504C704.398 235.408 702.75 235.997 701.033 236.236H700.895L697.884 236.649L694.908 237.044C685.478 238.272 676.038 239.419 666.586 240.486C647.968 242.608 629.322 244.443 610.648 245.992C573.539 249.077 536.356 251.102 499.098 252.066C480.114 252.57 461.135 252.806 442.162 252.771C366.643 252.712 291.189 248.322 216.173 239.625C208.051 238.662 199.93 237.629 191.808 236.58C198.106 237.389 187.231 235.96 185.029 235.651C179.867 234.928 174.705 234.177 169.543 233.397C152.216 230.798 134.993 227.598 117.7 224.793C96.7944 221.352 76.8005 223.073 57.8906 233.397C42.3685 241.891 29.8055 254.916 21.8776 270.735C13.7217 287.597 11.2956 305.956 7.64786 324.075C4.00009 342.193 -1.67805 361.688 0.472751 380.288C5.10128 420.431 33.165 453.054 73.5313 460.35C111.506 467.232 149.687 472.807 187.971 477.556C338.361 495.975 490.294 498.178 641.155 484.129C653.44 482.982 665.708 481.732 677.959 480.378C681.786 479.958 685.658 480.398 689.292 481.668C692.926 482.938 696.23 485.005 698.962 487.717C701.694 490.429 703.784 493.718 705.08 497.342C706.377 500.967 706.846 504.836 706.453 508.665L702.633 545.797C694.936 620.828 687.239 695.854 679.542 770.874C671.513 849.657 663.431 928.434 655.298 1007.2C653.004 1029.39 650.71 1051.57 648.416 1073.74C646.213 1095.58 645.904 1118.1 641.757 1139.68C635.218 1173.61 612.248 1194.45 578.73 1202.07C548.022 1209.06 516.652 1212.73 485.161 1213.01C450.249 1213.2 415.355 1211.65 380.443 1211.84C343.173 1212.05 297.525 1208.61 268.756 1180.87C243.479 1156.51 239.986 1118.36 236.545 1085.37C231.957 1041.7 227.409 998.039 222.9 954.381L197.607 711.615L181.244 554.538C180.968 551.94 180.693 549.376 180.435 546.76C178.473 528.023 165.207 509.681 144.301 510.627C126.407 511.418 106.069 526.629 108.168 546.76L120.298 663.214L145.385 904.104C152.532 972.528 159.661 1040.96 166.773 1109.41C168.15 1122.52 169.44 1135.67 170.885 1148.78C178.749 1220.43 233.465 1259.04 301.224 1269.91C340.799 1276.28 381.337 1277.59 421.497 1278.24C472.979 1279.07 524.977 1281.05 575.615 1271.72C650.653 1257.95 706.952 1207.85 714.987 1130.13C717.282 1107.69 719.576 1085.25 721.87 1062.8C729.498 988.559 737.115 914.313 744.72 840.061L769.601 597.451L781.009 486.263C781.577 480.749 783.905 475.565 787.649 471.478C791.392 467.391 796.352 464.617 801.794 463.567C823.25 459.386 843.761 452.245 859.023 435.916C883.318 409.918 888.153 376.021 879.567 341.849ZM72.4301 365.835C72.757 365.68 72.1548 368.484 71.8967 369.792C71.8451 367.813 71.9483 366.058 72.4301 365.835ZM74.5121 381.94C74.6842 381.819 75.2003 382.508 75.7337 383.334C74.925 382.576 74.4089 382.009 74.4949 381.94H74.5121ZM76.5597 384.641C77.2996 385.897 77.6953 386.689 76.5597 384.641V384.641ZM80.672 387.979H80.7752C80.7752 388.1 80.9645 388.22 81.0333 388.341C80.9192 388.208 80.7925 388.087 80.6548 387.979H80.672ZM800.796 382.989C793.088 390.319 781.473 393.726 769.996 395.43C641.292 414.529 510.713 424.199 380.597 419.932C287.476 416.749 195.336 406.407 103.144 393.382C94.1102 392.109 84.3197 390.457 78.1082 383.798C66.4078 371.237 72.1548 345.944 75.2003 330.768C77.9878 316.865 83.3218 298.334 99.8572 296.355C125.667 293.327 155.64 304.218 181.175 308.09C211.917 312.781 242.774 316.538 273.745 319.36C405.925 331.405 540.325 329.529 671.92 311.91C695.905 308.686 719.805 304.941 743.619 300.674C764.835 296.871 788.356 289.731 801.175 311.703C809.967 326.673 811.137 346.701 809.778 363.615C809.359 370.984 806.139 377.915 800.779 382.989H800.796Z`,fill:`#0D0C22`})]}),eI={"/guide/start":0,"/guide/protocols":1,"/guide/structure":2,"/guide/metrics":3,"/guide/clock":4,"/guide/wql":5,"/guide/dashboards":6,"/guide/sessions":7};function tI(e){return e.filter(e=>!e.route.startsWith(`/collections`)).filter(e=>e.page.frontmatter?.type===`guide`).sort((e,t)=>(eI[e.route]??99)-(eI[t.route]??99)).map(e=>({id:`guide-${e.route}`,label:e.page.sections[0]?.heading??`Untitled`,level:2,icon:T,action:{type:`route`,to:e.route},isActive:t=>t.pathname===e.route}))}function nI(e){return[{id:`home-new-journal`,label:`New journal entry`,level:2,icon:Dn,variant:`notable`,action:{type:`route`,to:`/journal?create=1`},isActive:()=>!1},...tI(e)]}var rI=(e,...t)=>t.some(t=>e===t||e.startsWith(`${t}/`)),iI={id:`journal-all-notes`,label:`All`,level:2,icon:s,action:{type:`route`,to:`/journal?q=%3Anote%7B!source%3Aplayground%7D`},isActive:e=>e.pathname===$.journal&&new URLSearchParams(e.search).get(`q`)===`:note{!source:playground}`};function aI(e){return{id:e.id,label:e.label,level:1,icon:e.icon,action:{type:`route`,to:e.route},isActive:t=>e.familyActive(t),applyFooter:!0,panel:ZF({landingLabel:e.landingLabel,icon:e.icon,route:e.route,profile:e.profile,extraChildren:e.extraChildren,familyActive:e.familyActive,createAction:e.createAction})}}var oI={id:`collections-catalog-crosswalk`,label:`Notebook crosswalk`,level:2,icon:v,action:{type:`route`,to:$.catalogs},isActive:e=>e.pathname===$.catalogs},sI=[{id:`journal`,label:`Journal`,landingLabel:`All entries`,icon:zt,route:$.journal,profile:CM,familyActive:e=>rI(e.pathname,`/journal`),extraChildren:[iI],createAction:{label:`New journal entry`,icon:Dn,testId:`journal-create-entry`,onClick:({openCreateJournal:e,navigate:t})=>{e?e({mode:`blank`}):t(`/journal?create=1`)}}},{id:`catalogs`,label:`Notebooks`,landingLabel:`All notebooks`,icon:v,route:$.catalogs,profile:wM,familyActive:e=>e.pathname===$.catalogs},{id:`feeds`,label:`Notes`,landingLabel:`All notes`,icon:Xn,route:$.feeds,profile:TM,familyActive:e=>rI(e.pathname,`/feeds`,`/feed`,`/c`)&&e.pathname!==$.catalogs,extraChildren:[oI],createAction:{label:`New note`,testId:`collections-create-note`,onClick:({openCreateJournal:e,navigate:t})=>{e?e({mode:`source`}):t(`/feeds?create=1&mode=source`)}}},{id:`playgrounds`,label:`Playgrounds`,landingLabel:`All playgrounds`,icon:Ae,route:$.playgrounds,profile:kM,familyActive:e=>rI(e.pathname,`/playgrounds`,`/playground`),createAction:{label:`New playground`,testId:`playgrounds-create-playground`,onClick:({navigate:e})=>{e(`/playground`)}}}];function cI(e,t=[]){let n=nI(t);return[{id:`home`,label:`Home`,level:1,icon:B,action:{type:`route`,to:$.home},isActive:e=>e.pathname===`/`||e.pathname===``||e.pathname.startsWith(`/guide/`)||e.pathname.startsWith(`/canvas`)||e.pathname===$.home||e.pathname===$.aiFirst||e.pathname.startsWith(`/ai-first/`),children:n},...sI.map(aI),{id:`dashboards`,label:`Dashboard`,level:1,icon:un,action:{type:`route`,to:$.dashboards},isActive:e=>e.pathname===$.dashboards||e.pathname===`/dashboard`||e.pathname.startsWith(`/dashboard/`)||e.pathname.startsWith(`/d/`),panel:JN},{id:`efforts`,label:`Efforts`,level:1,icon:Ye,action:{type:`route`,to:$.efforts},isActive:e=>aN(e.pathname),applyFooter:!0,panel:ZF({landingLabel:`All Efforts`,icon:Ye,route:$.efforts,profile:EM,familyActive:e=>aN(e.pathname),createAction:{label:`New effort`,testId:`efforts-create-effort`,onClick:({navigate:e})=>{e(`/e/new?mode=create`)}}})},{id:`equipment`,label:`Equipment`,level:1,icon:O,action:{type:`route`,to:$.equipment},isActive:e=>oN(e.pathname),applyFooter:!0,panel:ZF({landingLabel:`All Equipment`,icon:O,route:$.equipment,profile:DM,familyActive:e=>oN(e.pathname),createAction:{label:`New equipment`,testId:`equipment-create-equipment`,onClick:({navigate:e})=>{e(`/equipment/new?mode=create`)}}})},{id:`sessions`,label:`Sessions`,level:1,icon:Ee,action:{type:`route`,to:$.sessions},isActive:e=>e.pathname.startsWith(`/sessions`)||e.pathname.startsWith(`/session/`)||e.pathname.startsWith(`/results`),applyFooter:!0,panel:ZF({landingLabel:`All Sessions`,icon:Ee,route:$.sessions,profile:OM,familyActive:e=>e.pathname.startsWith(`/sessions`)||e.pathname.startsWith(`/session/`)||e.pathname.startsWith(`/results`)})},{id:`tags`,label:`Tags`,level:1,icon:M,action:{type:`route`,to:$.tags},isActive:e=>e.pathname.startsWith(`/tags`)},{id:`settings`,label:`Settings`,level:1,icon:gt,action:{type:`route`,to:$.settingsAppearance},isActive:e=>e.pathname.startsWith(`/settings`),children:[{id:`settings-profile`,label:`Profile`,level:2,icon:Me,action:{type:`route`,to:$.settingsProfile},isActive:e=>e.pathname===$.settingsProfile},{id:`settings-appearance`,label:`Appearance`,level:2,icon:cr,action:{type:`route`,to:$.settingsAppearance},isActive:e=>e.pathname===$.settings||e.pathname===$.settingsAppearance},{id:`settings-tags`,label:`Tag Types`,level:2,icon:M,action:{type:`route`,to:$.settingsTags},isActive:e=>e.pathname===$.settingsTags},{id:`settings-sound-profiles`,label:`Sound Profiles`,level:2,icon:fe,action:{type:`route`,to:$.settingsSoundProfiles},isActive:e=>e.pathname===$.settingsSoundProfiles},{id:`settings-sync`,label:`Sync`,level:2,icon:$e,action:{type:`route`,to:$.settingsSync},isActive:e=>e.pathname===$.settingsSync},{id:`settings-storage`,label:`Storage`,level:2,icon:se,action:{type:`route`,to:$.settingsStorage},isActive:e=>e.pathname===$.settingsStorage},{id:`settings-system`,label:`System`,level:2,icon:Gn,action:{type:`route`,to:$.settingsSystem},isActive:e=>e.pathname===$.settingsSystem}]},{id:`buy-me-a-coffee`,label:`Buy Me a Coffee`,level:1,icon:$F,action:{type:`external`,href:QF}}]}cI(()=>{});var lI={slate:{panel:`border-slate-500/35 shadow-slate-500/12`,accent:`from-slate-500/70 via-slate-400/25 to-transparent`,progress:`from-slate-500 to-slate-400`},amber:{panel:`border-amber-500/35 shadow-amber-500/12`,accent:`from-amber-500/75 via-amber-400/25 to-transparent`,progress:`from-amber-500 to-orange-400`},emerald:{panel:`border-emerald-500/35 shadow-emerald-500/12`,accent:`from-emerald-500/75 via-emerald-400/25 to-transparent`,progress:`from-emerald-500 to-teal-400`},sky:{panel:`border-sky-500/35 shadow-sky-500/12`,accent:`from-sky-500/75 via-sky-400/25 to-transparent`,progress:`from-sky-500 to-cyan-400`},violet:{panel:`border-violet-500/35 shadow-violet-500/12`,accent:`from-violet-500/75 via-fuchsia-400/25 to-transparent`,progress:`from-violet-500 to-fuchsia-400`},rose:{panel:`border-rose-500/35 shadow-rose-500/12`,accent:`from-rose-500/75 via-pink-400/25 to-transparent`,progress:`from-rose-500 to-pink-400`}};function uI(e){return e.proseChunks.filter(e=>e.kind===`prose`).map(e=>e.text).join(``)}function dI(e){let t=new Map;for(let n of e.sections)for(let e of n.proseChunks)e.kind===`challenge`&&t.set(e.id,n.id);return t}function fI(e){return e.toLowerCase().replace(/[^\w\s-]/g,``).replace(/\s+/g,`-`).replace(/^-+|-+$/g,``)}function pI(e){let t=e.match(/^(#{1,6}) (.+)$/);if(!t)return null;let n=t[1].length,r=t[2],i=r.match(/\{([^}]+)\}$/),a=i?i[1].trim().split(/\s+/).filter(Boolean):[];return{level:n,text:i?r.slice(0,i.index).trim():r.trim(),attrs:a}}function mI(e){let t={};for(let n of e){let e=n.match(/^([a-zA-Z][\w-]*):\s*(.+)$/);e&&(t[e[1]]=e[2].trim())}return t}function hI(e){let t=[];for(let n of e){let e=n.match(/^\s*-\s+([\w-]+):\s+(.+)$/);e&&t.push({action:e[1],value:e[2].trim()})}return t}function gI(e){let t=e.split(`
75
+ `),n=mI(t),r=[];for(let e of t){let t=e.match(/^button:\s*(.+)$/);if(!t)continue;let n=t[1].split(`|`).map(e=>e.trim()),i=n[0]??`Run`,a,o=[];for(let e of n.slice(1)){let t=e.match(/^open:\s*(view|dialog|route)$/);if(t){a=t[1];continue}o.push(`- ${e}`)}r.push({label:i,open:a,pipeline:hI(o)})}return{name:n.name??`view`,state:n.state??`note`,source:n.source??``,runtime:n.runtime,launch:n.launch,align:n.align??`right`,width:n.width??`50%`,buttons:r}}function _I(e){let t=e.split(`
76
+ `),n=``,r;for(let e of t){let t=e.match(/^target:\s*(.+)$/);if(t){n=t[1].trim();continue}let i=e.match(/^open:\s*(view|dialog|route)$/);if(i){r=i[1];continue}}return{target:n,open:r,pipeline:hI(t)}}function vI(e){let t=e.split(`
77
+ `),n=`Button`,r=``,i;for(let e of t){let t=e.match(/^label:\s*(.+)$/);if(t){n=t[1].trim();continue}let a=e.match(/^target:\s*(.+)$/);if(a){r=a[1].trim();continue}let o=e.match(/^open:\s*(view|dialog|route)$/);if(o){i=o[1];continue}}return{label:n,target:r,open:i,pipeline:hI(t)}}function yI(e){let t=mI(e.split(`
78
+ `));return{label:t.label??`Example`,source:t.source??``}}function bI(e){let t={},n={},r=!1;for(let i of e.split(`
79
+ `)){let e=i.trim();if(e===``)continue;let a=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!a)continue;let o=a[1],s=a[2].trim().replace(/^["']|["']$/g,``);if(o===`validation`){r=!0;continue}r?n[o]=s:t[o]=s}if(!t.id)return null;let i={id:t.id,label:t.label??t.id};if(t.desc&&(i.desc=t.desc),Object.keys(n).length>0){let e={...n};for(let t of Object.keys(e)){let n=Number(e[t]);e[t]!==``&&!isNaN(n)&&String(n)===e[t]&&(e[t]=n)}i.validation=e}return i}function xI(e){let t=e.split(`
80
+ `),n=[],r=[],i=!1,a=[],o=()=>{let e=bI(a.join(`
81
+ `));e&&n.push(e),a=[]};for(let e of t){if(i){/^```\s*$/.test(e)?(o(),i=!1):a.push(e);continue}let t=e.match(/^```(\w+)\s*$/);if(t){t[1]===`quest`?i=!0:r.push(e);continue}r.push(e)}return i&&o(),{quests:n,body:r.join(`
82
+ `)}}function SI(e){let t={};for(let n of e.split(`
83
+ `)){let e=n.trim();if(e===``)continue;let r=e.match(/^(\w[\w-]*):\s*(.*)$/);r&&(t[r[1]]=r[2].trim().replace(/^["']|["']$/g,``))}return!t.id||!t.title?null:{id:t.id,title:t.title,badge:t.badge||`trophy`,questIds:CI(t.quests),sectionIds:CI(t.sections)}}function CI(e){if(!e)return[];let t=e.replace(/^\[|\]$/g,``).trim();return t?t.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function wI(e){let t=e.split(`
84
+ `),n=[],r=[],i=!1,a=[],o=()=>{let e=SI(a.join(`
85
+ `));e&&n.push(e),a=[]};for(let e of t){if(i){/^```\s*$/.test(e)?(o(),i=!1):a.push(e);continue}let t=e.match(/^```(\w+)\s*$/);if(t){t[1]===`chapter`?i=!0:r.push(e);continue}r.push(e)}return i&&o(),{chapters:n,body:r.join(`
86
+ `)}}function TI(e){let t=e.match(/^\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]$/);if(t)return[Number(t[1]),Number(t[2])]}function EI(e){return e.trim().replace(/^["']|["']$/g,``)}function DI(e){let t=[],n=-1,r=null,i=null,a=null;for(let o of e){if(o.trim()===``)continue;let e=o.match(/^\s*/)[0].length,s=o.trim(),c=s.match(/^-\s+([\w-]+):\s*(.*)$/);if(c&&(i!==`effects`||e<=n)){n===-1&&(n=e),r={id:EI(c[2]),range:[0,1]},t.push(r),i=null,a=null;continue}if(c&&i===`effects`&&r){a={target:EI(c[2]),stages:r.id?[r.id]:[]},(r.effects??=[]).push(a);continue}let l=s.match(/^(\w[\w-]*):\s*(.*)$/);if(!l||!r)continue;let u=l[1],d=l[2].trim();if(i===`ring`){if(r.ring&&r.ring!==!0&&(u===`tag`&&(r.ring.tag=EI(d)),u===`key`&&(r.ring.key=EI(d)),u===`lines`)){let e=TI(d);if(e){let t=Math.max(1,Math.round(e[0])),n=Math.max(1,Math.round(e[1]));r.ring.lines=[Math.min(t,n),Math.max(t,n)]}}continue}if(i===`effects`&&a){switch(u){case`target`:a.target=EI(d);break;case`stages`:a.stages=CI(d);break;case`opacity`:a.opacity=TI(d);break;case`translateY`:a.translateY=TI(d);break;case`ease`:(d===`linear`||d===`quad-out`)&&(a.ease=d);break;case`in`:a.in=TI(d)}continue}switch(u){case`range`:{let e=TI(d);e&&(r.range=e);break}case`screen`:(d===`editor`||d===`timer`||d===`analytics`||d===`result`)&&(r.screen=d);break;case`label`:r.label=EI(d);break;case`source`:r.source=EI(d);break;case`caption`:r.caption=EI(d);break;case`accent`:r.accent=EI(d);break;case`toast`:r.toast=EI(d);break;case`quest`:r.quest=EI(d);break;case`ring`:d===``?(r.ring={},i=`ring`):d===`true`&&(r.ring=!0);break;case`effects`:r.effects=[],a=null,i=`effects`}}return t}function OI(e){try{let t=e.split(`
87
+ `),n=t.findIndex(e=>/^\s*stages:\s*$/.test(e)),r=mI(n===-1?t:t.slice(0,n)),i=n===-1?[]:DI(t.slice(n+1));return i.length===0?null:{runway:r.runway??`600vh`,screen:`editor`,typewriter:r.typewriter!==`false`,stages:i}}catch(e){return console.warn("[canvas] malformed ```scroll block:",e),null}}function kI(e){let t=e.split(`
88
+ `),n=null,r={},i=[],a=!1,o=null,s=[],c=()=>{let e=OI(s.join(`
89
+ `));e?o?r[o]?console.warn(`[canvas] duplicate named \`\`\`scroll:${o} block ignored`):r[o]=e:n===null?n=e:console.warn("[canvas] duplicate unnamed ```scroll block ignored"):console.warn("[canvas] ```scroll block ignored: missing or malformed stages"),s=[],o=null};for(let e of t){if(a){/^```\s*$/.test(e)?(c(),a=!1):s.push(e);continue}let t=e.match(/^```scroll(?::([\w-]+))?\s*$/);if(t){a=!0,o=t[1]??null;continue}i.push(e)}return a&&c(),{scroll:n,namedScrolls:r,body:i.join(`
90
+ `)}}function AI(e){if(!e)return[];let t=[{token:`{{hero-carousel}}`,widget:`hero-carousel`}],n=[{kind:`prose`,text:e}];for(let{token:e,widget:r}of t){let t=[];for(let i of n){if(i.kind!==`prose`){t.push(i);continue}let n=i.text.split(e);for(let e=0;e<n.length;e++)e>0&&t.push({kind:`widget`,widget:r}),t.push({kind:`prose`,text:n[e]})}n=t}let r=/\{\{challenge:([^}]+)\}\}/g,i=[];for(let e of n){if(e.kind!==`prose`){i.push(e);continue}let t=e.text,n=0,a;for(r.lastIndex=0;(a=r.exec(t))!==null;)i.push({kind:`prose`,text:t.slice(n,a.index)}),i.push({kind:`challenge`,id:a[1].trim()}),n=a.index+a[0].length;i.push({kind:`prose`,text:t.slice(n)})}return n=i,n.filter(e=>e.kind!==`prose`||e.text!==``)}function jI(e){let t=/^```(\w+)\n([\s\S]*?)^```[ \t]*$/gm,n=[],r;for(;(r=t.exec(e))!==null;)n.push({start:r.index,end:r.index+r[0].length,type:r[1],content:r[2]});let i,a=[],o=[],s=[],c=[];for(let e=0;e<n.length;e++){let{type:t,content:r}=n[e];if(t===`view`)i=gI(r),c.push(null);else if(t===`command`)a.push(_I(r)),c.push(null);else if(t===`button`){let e=vI(r);o.push(e),c.push(e)}else t===`example`&&s.push(yI(r)),c.push(null)}let l=new Set([`view`,`command`,`example`]),u=[],d=0;for(let t=0;t<n.length;t++){let r=n[t],i=c[t];i?(u.push(...AI(e.slice(d,r.start))),u.push({kind:`button`,button:i}),d=r.end):l.has(r.type)&&(u.push(...AI(e.slice(d,r.start))),d=r.end)}return u.push(...AI(e.slice(d))),{proseChunks:u,view:i,commands:a,buttons:o,examples:s}}function MI(e,t=`/`){let{meta:n,body:r}=tx(e);if(String(n.template??``)!==`canvas`)return null;let{quests:i,body:a}=xI(r),{scroll:o,namedScrolls:s,body:c}=kI(a),{chapters:l}=wI(c),u=String(n.route??t),d=[],f=null,p=e=>{let{proseChunks:t,view:n,commands:r,buttons:i,examples:a}=jI(e.lines.join(`
91
+ `)),o=e.attrs.find(e=>e.startsWith(`#`))?.slice(1),s=e.attrs.filter(e=>!e.startsWith(`#`)),c=e=>s.includes(e),l=e=>s.find(t=>t.startsWith(`${e}:`))?.slice(e.length+1);d.push({id:o||fI(e.heading)||`section-${d.length}`,heading:e.heading,level:e.level,attrs:s,theme:l(`theme`)??`slate`,density:l(`density`)??`default`,isDark:c(`dark`),isFullBleed:c(`full-bleed`),isSticky:c(`sticky`),prose:uI({proseChunks:t}),proseChunks:t,view:n,commands:r,buttons:i,examples:a})},m=!1;for(let e of c.split(`
92
+ `)){/^`{3,}/.test(e)&&(m=!m);let t=m?null:pI(e);t?(f&&p(f),f={heading:t.text,level:t.level,attrs:t.attrs,lines:[]}):f&&f.lines.push(e)}return f&&p(f),{template:`canvas`,route:u,type:n.type?String(n.type):void 0,sections:d,frontmatter:n,quests:i,chapters:l,scroll:o,namedScrolls:s}}function NI(e){if(!e)return`/`;let t=e.trim();return t.startsWith(`/`)||(t=`/`+t),t=t.replace(/\/+/g,`/`),t.length>1&&t.endsWith(`/`)&&(t=t.slice(0,-1)),t}function PI(e,t){let n=NI(t);for(let t of e)if(t.route===n)return t.page;return null}function FI(e){let t=NI(e),n=[t],r=t.match(/^\/p\/(.+)$/);if(r){let e=r[1];n.push(`/${e}`),n.push(`/guide/${e}`)}return n}function II(e,t){for(let n of FI(t)){let t=PI(e,n);if(t!==null)return t}return null}function LI(e){let t=[];for(let[n,r]of Object.entries(e))if(n.match(/^markdown\/canvas\/(.+\.md)$/)){let e=MI(r);e&&t.push({route:e.route,page:e});continue}return t}function RI(e,t){return II(e,t)}function zI(){let e=GD();return(0,U.useMemo)(()=>e?LI(e):[],[e])}function BI(e){let t=zI();return(0,U.useMemo)(()=>RI(t,e),[t,e])}function VI({className:e,...t}){return(0,W.jsx)(`nav`,{...t,className:et(e,`flex flex-1 items-center gap-2 sm:gap-4 py-2.5 min-w-0`)})}var HI=(0,U.forwardRef)(function({current:e,className:t,children:n,...r},i){let a=et(`group relative flex min-w-0 items-center gap-3 rounded-lg p-2 text-left text-base/6 font-medium text-foreground sm:text-sm/5`,`[&>[data-slot=icon]]:size-6 [&>[data-slot=icon]]:shrink-0 [&>[data-slot=icon]]:fill-muted-foreground sm:[&>[data-slot=icon]]:size-5`,`[&>*:not(:nth-child(2)):last-child[data-slot=icon]]:ml-auto [&>*:not(:nth-child(2)):last-child[data-slot=icon]]:size-5 sm:[&>*:not(:nth-child(2)):last-child[data-slot=icon]]:size-4`,`[&>[data-slot=avatar]]:-m-0.5 [&>[data-slot=avatar]]:size-7 [&>[data-slot=avatar]]:[--avatar-radius:theme(borderRadius.md)] sm:[&>[data-slot=avatar]]:size-6`,`data-[hover]:bg-muted/50 data-[hover]:[&>[data-slot=icon]]:fill-foreground`,`data-[active]:bg-muted/50 data-[active]:[&>[data-slot=icon]]:fill-foreground`,`dark:data-[hover]:bg-white/5 dark:data-[hover]:[&>[data-slot=icon]]:fill-foreground`,`dark:data-[active]:bg-white/5 dark:data-[active]:[&>[data-slot=icon]]:fill-foreground`);return(0,W.jsxs)(`span`,{className:et(t,`relative`),children:[e&&(0,W.jsx)(Vt.span,{layoutId:`current-indicator`,className:`absolute inset-x-2 -bottom-2.5 h-0.5 rounded-full bg-foreground`}),typeof r.href==`string`?(0,W.jsx)(ZN,{...r,className:a,"data-current":e?`true`:void 0,ref:i,children:(0,W.jsx)(XN,{children:n})}):(0,W.jsx)(it,{...r,className:et(`cursor-default`,a),"data-current":e?`true`:void 0,ref:i,children:(0,W.jsx)(XN,{children:n})})]})});function UI(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `)}function WI(e){let t=e,n=t.key??t.metadata?.target;if(typeof n==`string`&&n.trim().length>0)return n;switch(e.type){case`rep`:return`reps`;case`distance`:return`distance`;case`resistance`:return`resistance`;default:return e.type}}function GI(e){let t={},n=e.flat();for(let e of n)if(e.value!==void 0&&typeof e.value==`number`){let n=WI(e),r=e.value;if(e.type===`duration`)continue;t[n]=(t[n]||0)+r}return t}var KI=class{fromOutputStatements(e,t,n=rl){if(!e||e.length===0)return[];let r=e.map(e=>e.timeSpan.started).filter(e=>!isNaN(e)),i=t??(r.length>0?Math.min(...r):0);return e.map(e=>{let t=J.from(e.metrics,e.id),r=t.find(e=>e.type===`duration`),a=r?.value===void 0?void 0:r.value/1e3,o=t.find(e=>e.type===q.Elapsed),s=(typeof o?.value==`number`?o.value:0)/1e3,c=t.find(e=>e.type===q.Total),l=(typeof c?.value==`number`?c.value:0)/1e3,u=e.timeSpan?.started??i,d=e.timeSpan?.ended??n.nowMs(),f=GI([t.toArray()]),p=t.find(e=>e.type===`effort`||e.type===`action`||e.type===`duration`||e.type===`rounds`||e.type===`current-round`||e.type===`label`),m=p?.image||e.sourceBlockKey,h=p?.type||e.outputType,g=t.find(e=>e.type===q.Spans),_=Array.isArray(g?.value)?g.value:[],v=(_.length>0?_:e.timeSpan?[e.timeSpan]:[]).map(e=>({started:(e.started-i)/1e3,ended:e.ended===void 0?void 0:(e.ended-i)/1e3}));return{id:e.id,name:m,type:h,startTime:(u-i)/1e3,endTime:(d-i)/1e3,absoluteStartTime:u,duration:a,elapsed:s,total:l,parentId:e.parent??null,depth:e.stackLevel,metric:f,lane:e.stackLevel,spans:v,metrics:t,tags:(()=>{let t=$a(e);return t.length?t:void 0})(),context:{outputType:e.outputType,sourceStatementId:e.sourceStatementId,sourceBlockKey:e.sourceBlockKey,completionReason:e.completionReason},spanType:e.outputType}})}toAnalyticsGroup(e){let t=[],n=new Set;e.forEach(e=>Object.keys(e.metric).forEach(e=>n.add(e)));let r={power:{id:`power`,label:`Power`,unit:`W`,color:`#8b5cf6`,dataKey:`power`,icon:`Zap`},heart_rate:{id:`heart_rate`,label:`Heart Rate`,unit:`bpm`,color:`#ef4444`,dataKey:`heart_rate`,icon:`Activity`},cadence:{id:`cadence`,label:`Cadence`,unit:`rpm`,color:`#3b82f6`,dataKey:`cadence`,icon:`Wind`},speed:{id:`speed`,label:`Speed`,unit:`km/h`,color:`#10b981`,dataKey:`speed`,icon:`Gauge`},resistance:{id:`resistance`,label:`Resistance`,unit:`kg`,color:`#f59e0b`,dataKey:`resistance`,icon:`Dumbbell`},reps:{id:`reps`,label:`Reps`,unit:`reps`,color:`#6366f1`,dataKey:`reps`,icon:`Hash`},calories:{id:`calories`,label:`Calories`,unit:`cal`,color:`#f97316`,dataKey:`calories`,icon:`Flame`},duration:{id:`duration`,label:`Duration`,unit:`s`,color:`#0ea5e9`,dataKey:`duration`,icon:`Timer`},elapsed:{id:`elapsed`,label:`Elapsed`,unit:`s`,color:`#14b8a6`,dataKey:`elapsed`,icon:`Clock`},total:{id:`total`,label:`Total`,unit:`s`,color:`#f43f5e`,dataKey:`total`,icon:`Timer`}},i=[];return n.forEach(e=>{r[e]?i.push(r[e]):i.push({id:e,label:UI(e),unit:``,color:`#888888`,dataKey:e})}),i.length>0&&t.push({id:`performance`,name:`Performance`,graphs:i}),t}filterByTags(e,t){return!t||t.length===0?e:e.filter(e=>{let n=e.tags||[];return t.every(e=>n.includes(e))})}filterByType(e,t){return e.filter(e=>e.spanType===t)}getDebugContext(e){return e.context||{}}isFromStrategy(e,t){return this.getDebugContext(e).strategyUsed===t}};function qI(e){if(!e)return{segments:[],groups:[]};let t=new KI,n=e.getOutputStatements().filter(e=>e.outputType===`segment`||e.outputType===`analytics`||e.outputType===`milestone`),r=e.getLiveAnalytics?.()??[],i=r.length>0?[...n,...r]:n,a=t.fromOutputStatements(i);return a.length===0?{segments:[],groups:[]}:{segments:a,groups:t.toAnalyticsGroup(a)}}function JI(e,t,n){if(!e||e.length===0)return{segments:[],groups:[]};let r=new KI,i=e.filter(e=>e.outputType===`segment`||e.outputType===`analytics`||e.outputType===`milestone`),a=new Map,o=[];for(let e=i.length-1;e>=0;e--){let t=i[e];if(t.outputType===`analytics`){let e=t.metrics.find(e=>e.type===q.Label),n=t.metrics.find(e=>e.type!==q.Label&&typeof e.value==`number`);if(e&&n){let r=[String(e.value??e.image??``),String(n.value),n.unit??``].join(`|`),i=a.get(r);if(i!==void 0&&Math.abs(i-t.timeSpan.started)<1e3)continue;a.set(r,t.timeSpan.started)}}o.unshift(t)}let s=r.fromOutputStatements(o,t,n);return s.length===0?{segments:[],groups:[]}:{segments:s,groups:r.toAnalyticsGroup(s)}}function YI(e,t){let n=e.blocks[t.blockId],r=n?``:e.rawContent.endsWith(`
93
+ `)?`
94
+ `:`
95
+
96
+ `,i=n?.from??e.rawContent.length,a=n?.to??i,o=r+t.rawContent,s=o.length-(a-i),c={};for(let[n,r]of Object.entries(e.blocks))n!==t.blockId&&(c[n]=r.from>=a?{...r,from:r.from+s,to:r.to+s}:r);return c[t.blockId]={id:t.blockId,kind:t.kind,version:n?.version??t.version,sourceRevision:e.sourceRevision,from:i+r.length,to:i+o.length,...t.dialect?{dialect:t.dialect}:{},...t.sport?{sport:t.sport}:{}},{...e,rawContent:e.rawContent.slice(0,i)+o+e.rawContent.slice(a),blocks:c}}function XI({noteId:e,sourceRevision:t,blocks:n={},persistence:r=DN,onRevert:i}){let[a,o]=(0,U.useState)([]),[s,c]=(0,U.useState)(``),[l,u]=(0,U.useState)(0),[d,f]=(0,U.useState)(0),[p,m]=(0,U.useState)(null),[h,g]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let t=!1;return m(null),r.getNoteBlockHistory(e).then(e=>{t||o(e.toSorted((e,t)=>e.savedAt-t.savedAt||e.version-t.version))}).catch(e=>{t||m(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e,t,r]);let _=Array.from(new Set(a.map(e=>e.blockId))),v=_.includes(s)?s:_[0]??``,y=a.filter(e=>e.blockId===v).toSorted((e,t)=>e.version-t.version),b=y.find(e=>e.version===l)??y[0],x=y.find(e=>e.version===d)??y.at(-1),S=async()=>{if(!(!b||!i)){g(!0),m(null);try{await i(b),o(await r.getNoteBlockHistory(e))}catch(e){m(e instanceof Error?e.message:String(e))}finally{g(!1)}}};return(0,W.jsxs)(`details`,{className:`rounded-lg border border-border p-3`,children:[(0,W.jsx)(`summary`,{className:`cursor-pointer font-medium focus-visible:ring-2`,children:`Saved block history`}),(0,W.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[p&&(0,W.jsx)(`p`,{role:`alert`,children:p}),_.length===0?(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No saved actionable blocks.`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`label`,{className:`block text-sm`,children:[`Block occurrence`,(0,W.jsx)(`select`,{className:`mt-1 block max-w-full rounded border bg-background p-2 text-foreground focus-visible:ring-2`,value:v,onChange:e=>{c(e.target.value),u(0),f(0)},children:_.map((e,t)=>(0,W.jsxs)(`option`,{value:e,children:[`Block `,t+1,` · `,e,n[e]?``:` · removed`]},e))})]}),(0,W.jsx)(`ol`,{"aria-label":`Saved versions`,className:`space-y-1 text-sm`,style:{contentVisibility:`auto`},children:y.map(e=>(0,W.jsxs)(`li`,{children:[`v`,e.version,` · `,(0,W.jsx)(`time`,{dateTime:new Date(e.savedAt).toISOString(),children:UO(new Date(e.savedAt))}),` · `,e.kind,e.dialect?` · ${e.dialect}`:``,e.sport?` · ${e.sport}`:``]},e.version))}),(0,W.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[{label:`Compare saved version`,row:b,set:u},{label:`With saved version`,row:x,set:f}].map(({label:e,row:t,set:n})=>(0,W.jsxs)(`div`,{className:`min-w-0`,children:[(0,W.jsxs)(`label`,{className:`block text-sm`,children:[e,(0,W.jsx)(`select`,{className:`ml-2 rounded border bg-background p-1 text-foreground focus-visible:ring-2`,value:t?.version??0,onChange:e=>n(Number(e.target.value)),children:y.map(e=>(0,W.jsxs)(`option`,{value:e.version,children:[`v`,e.version]},e.version))})]}),(0,W.jsx)(`pre`,{"aria-label":`${e} source`,className:`mt-2 max-h-80 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-3 text-xs`,children:t?.rawContent})]},e))}),(0,W.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-sm`,children:b?.rawContent===x?.rawContent&&b?.kind===x?.kind&&b?.dialect===x?.dialect&&b?.sport===x?.sport?`Saved states are identical.`:`Saved states differ.`}),i&&b&&(0,W.jsx)(`button`,{type:`button`,disabled:h,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2 disabled:opacity-50`,onClick:()=>void S(),children:h?`Saving…`:`Restore v${b.version} as a new saved version`})]})]})]})}async function ZI(e){let t=await VD(),n=[`markdown/collections/${e}.md`,`markdown/canvas/${e}.md`];for(let e of n)if(t[e])return t[e];let r=`/${e}.md`.toLowerCase(),i=Object.entries(t).find(([e])=>e.toLowerCase().endsWith(r));return i?i[1]:void 0}async function QI(e){return await ZI(e)??null}var $I=class{transport;handlers=new Set;transportUnsub=null;disposed=!1;constructor(e){this.transport=e,this.transportUnsub=this.transport.onMessage(e=>{if(e.type===`rpc-event`){let t={name:e.name,timestamp:new Date(e.timestamp),data:e.data};for(let e of this.handlers)e(t)}})}dispatch(e){this.disposed||!this.transport.connected||this.transport.send({type:`rpc-event`,name:e.name,timestamp:e.timestamp.getTime(),data:e.data})}onEvent(e){return this.disposed?()=>{}:(this.handlers.add(e),()=>this.handlers.delete(e))}dispose(){this.disposed||(this.disposed=!0,this.transportUnsub?.(),this.transportUnsub=null,this.handlers.clear())}};function eL(e){let t=e.getMemoryByTag(`time`);if(t.length===0)return null;let n=t[0].metrics;if(n.length===0)return null;let r=n[0]?.value;if(!r||!Array.isArray(r.spans))return null;let i=r.spans.map(e=>({started:e.started,ended:e.ended})),a=r.direction??`up`,o=r.role,s=o===`hidden`?`auto`:o;return{label:r.label,format:a,durationMs:r.durationMs,direction:a,spans:i,isRunning:i.some(e=>e.ended===void 0),role:s}}function tL(e){let t=e.getMetricMemoryByVisibility(`display`).map(e=>e.metrics.toArray()),n=e.getMetricMemoryByVisibility(`promote`).map(e=>e.metrics.toArray()),r=e.getMetricMemoryByVisibility(`result`).map(e=>e.metrics.toArray()),i=e.getMetricMemoryByVisibility(`private`),a={};for(let e of i)a[e.tag]||(a[e.tag]=[]),a[e.tag].push(e.metrics.toArray());let o=e.getMemoryByTag(`metric:next`).flatMap(e=>e.metrics.toArray()),s;try{e.behaviors&&e.behaviors.length>0&&(s=e.behaviors.map(e=>({name:e.constructor.name})))}catch{}return{key:e.key.toString(),blockType:e.blockType??`Block`,label:e.label,sourceIds:[...e.sourceIds],isComplete:e.isComplete,completionReason:e.completionReason,displayFragments:t,promoteFragments:n.length>0?n:void 0,resultFragments:r.length>0?r:void 0,privateFragments:Object.keys(a).length>0?a:void 0,timer:eL(e),nextFragments:o,behaviorsMetadata:s}}function nL(e){return{type:`rpc-stack-update`,snapshotType:e.type,blocks:e.blocks.map(tL),affectedBlockKey:e.affectedBlock?.key.toString(),depth:e.depth,clockTime:e.clockTime.getTime()}}function rL(e){let t=e.timeSpan.started,n=e.timeSpan.ended,r=n===void 0?0:n-t;return{type:`rpc-output`,outputType:e.outputType,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,metrics:Array.isArray(e.metrics)?e.metrics:e.metrics.toArray(),completionReason:e.completionReason,timeSpan:{started:t,ended:n},elapsed:r}}function iL(e,t,n){return{type:`rpc-analytics-summary`,totalDurationMs:t,completedSegments:n,projections:e}}function aL(e){return(e??[]).map(e=>e.map(e=>`${e?.type??``}:${e?.value==null||typeof e.value==`object`?``:String(e.value)}:${e?.image??``}:${e?.unit??``}`).join(`,`)).join(`;`)}var oL=class{transport;id;lastFingerprint=``;constructor(e,t){this.transport=e,this.id=t?.id??`chromecast`}onStackSnapshot(e){if(!this.transport.connected)return;let t=nL(e),n=this.computeFingerprint(t);n!==this.lastFingerprint&&(this.lastFingerprint=n,this.transport.send(t))}onOutput(e){this.transport.connected&&this.transport.send(rL(e))}sendAnalyticsSummary(e,t,n){this.transport.connected&&this.transport.send(iL(e,t,n))}dispose(){this.lastFingerprint=``}computeFingerprint(e){let t=[e.snapshotType,String(e.depth)];for(let n of e.blocks){t.push(`${n.key}:${n.blockType}:${n.label}:${n.isComplete}`),n.timer&&t.push(`timer:${n.timer.isRunning}:${n.timer.spans.length}:${n.timer.durationMs}:${n.timer.spans[0]?.started??``}:${n.timer.role??``}`),t.push(`frags:${aL(n.displayFragments)}`),t.push(`promote:${aL(n.promoteFragments)}`),t.push(`result:${aL(n.resultFragments)}`);let e=Object.keys(n.privateFragments??{}).sort().join(`,`);t.push(`private:${e}`);let r=n.nextFragments?.map(e=>`${e.type??``}:${e.image??(e.value==null?``:String(e.value))}`).join(`,`)??``;t.push(`next:${r}`);let i=n.behaviorsMetadata?.map(e=>e.name).join(`,`)??``;t.push(`behaviors:${i}`)}return t.join(`|`)}},sL=class{transport;options;disposed=!1;syncSamples=[];constructor(e,t={}){this.transport=e,this.options=t}async sync(){let e=this.options.samples??3,t=this.options.maxRttMs??500;console.log(`[ClockSyncService] Starting sync (${e} samples, max RTT: ${t}ms)`),this.syncSamples.length=0;for(let n=0;n<e;n++){if(this.disposed)throw Error(`ClockSyncService was disposed during sync`);let r=await this.performSyncSample(t);r===null?console.warn(`[ClockSyncService] Sample ${n+1} failed (RTT exceeded ${t}ms)`):(this.syncSamples.push(r),console.log(`[ClockSyncService] Sample ${n+1}/${e}: offset=${r.offsetMs.toFixed(2)}ms, RTT=${r.rttMs.toFixed(2)}ms`)),n<e-1&&await new Promise(e=>setTimeout(e,100))}if(this.syncSamples.length===0)throw Error(`Clock sync failed: all samples exceeded max RTT`);let n=[...this.syncSamples].map(e=>e.offsetMs).sort((e,t)=>e-t),r=n.length%2==0?(n[n.length/2-1]+n[n.length/2])/2:n[Math.floor(n.length/2)],i=this.syncSamples.reduce((e,t)=>e+t.rttMs,0)/this.syncSamples.length,a={offsetMs:r,avgRttMs:i};return console.log(`[ClockSyncService] Sync complete: offset=${r.toFixed(2)}ms (median), avg RTT=${i.toFixed(2)}ms`),this.sendResult(a),a}sendResult(e){if(this.disposed||!this.transport.connected)return;let t={type:`rpc-clock-sync-result`,offsetMs:e.offsetMs,rttMs:e.avgRttMs};this.transport.send(t)}async performSyncSample(e){let t=Date.now(),n={type:`rpc-clock-sync-request`,timestamp:t};this.transport.send(n);let r=await this.waitForResponse(e=>e.type===`rpc-clock-sync-response`&&e.requestTimestamp===t,2e3),i=Date.now()-t;if(i>e)return null;let a=i/2;return{offsetMs:r.receiverTimestamp-(t+a),rttMs:i}}waitForResponse(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>{a(),r(Error(`Clock sync response timeout after ${t}ms`))},t),a=this.transport.onMessage(t=>{e(t)&&(clearTimeout(i),a(),n(t))})})}dispose(){this.disposed=!0,this.syncSamples.length=0}};function cL(e,...t){console.warn(`[${e}]`,...t)}function lL(e,...t){console.error(`[${e}]`,...t)}var uL={createSubscription:(e,t)=>new oL(e,{id:t}),createEventProvider:e=>new $I(e),createClockSync:e=>new sL(e)},dL=new class{deps;activeHandle=null;activeMeta=null;constructor(e=uL){this.deps=e}get isConnected(){return this.activeHandle!==null}getActiveHandle(){return this.activeHandle}setSubscriptionRegistry(e){!this.activeHandle||!this.activeMeta||this.activeMeta.registry!==e&&(this.activeMeta.registry&&this.activeMeta.registry.remove(this.activeMeta.subscriptionId),this.activeMeta.registry=e,e&&e.add(this.activeHandle.subscription))}connect(e,t=null,n={}){this.dispose();let r=n.subscriptionId??`chromecast`,i=this.deps.createSubscription(e,r),a=this.deps.createEventProvider(e),o=e.needsClockSync?this.deps.createClockSync(e):null;t?.add(i),o&&o.sync().catch(e=>{lL(`CastSessionManager`,`Clock sync failed`,e)});let s=e.onDisconnected(()=>this.dispose());return this.activeHandle={transport:e,eventProvider:a,subscription:i,pushInitialWorkbench:t=>{try{e.send(t)}catch{}},dispose:()=>this.dispose()},this.activeMeta={registry:t,subscriptionId:r,unsubDisconnected:s,clockSync:o},this.activeHandle}sendDisposeSignal(){this.activeHandle?.transport.connected&&this.activeHandle.transport.send({type:`rpc-dispose`})}pushInitialWorkbench(e){if(!this.activeHandle)return!1;try{return this.activeHandle.transport.send(e),!0}catch{return!1}}dispose(e=!1){if(!this.activeHandle)return;let t=this.activeHandle,n=this.activeMeta;if(this.activeHandle=null,this.activeMeta=null,n?.unsubDisconnected(),e&&t.transport.connected)try{t.transport.send({type:`rpc-dispose`})}catch{}n?.registry&&n.registry.remove(n.subscriptionId),t.subscription.dispose(),t.eventProvider.dispose(),n?.clockSync?.dispose()}};function fL(){return(0,U.useSyncExternalStore)(WA,BA,BA)}function pL(e,t){if(!e||e.trim().length===0)return{statements:[],errors:[],success:!0};try{let n=e.endsWith(`
97
+ `)?e:e+`
98
+ `;return{statements:Zs(ri.create({doc:n,extensions:[bc]}),t),errors:[],success:!0}}catch(e){return{statements:[],errors:[{message:e instanceof Error?e.message:`Unknown parse error`,severity:`error`}],success:!1}}}function mL(e,...t){console.warn(`[${e}]`,...t)}function hL(e,...t){console.error(`[${e}]`,...t)}function gL(e,t={}){let n=t.sourceRevision??1,r=Na(e,{...t,blocks:t.noteBlocks,sourceRevision:n}),i=ja(e,t),a=[];for(let e of i){if(!Ma(e))continue;let t=Object.values(r).find(t=>t.from===e.from&&t.to===e.to);t&&(e.id=t.id,e.version=t.version,e.scriptBlock&&(e.scriptBlock=_L({...e.scriptBlock,id:t.id,version:t.version}),a.push(e.scriptBlock)))}return{sections:i,blocks:a,noteBlocks:r,rawContent:e,sourceRevision:n}}function _L(e){try{let t=pL(e.content,e.sport);return{...e,statements:t.statements,errors:t.errors,state:t.success?`parsed`:`error`}}catch(t){return hL(`WorkbenchDocumentModel`,`Block parse error:`,t),e}}function vL(e){if(e.kind!==`wod`||!e.dialect)throw Error(`The saved revision is not a workout.`);let t=ja(e.rawContent).find(t=>t.type===e.dialect);if(!t?.scriptBlock)throw Error(`The saved workout fence cannot be read.`);let n=t.scriptBlock.content;return{id:e.blockId,content:n,dialect:e.dialect,sport:e.sport,statements:yc().read(n,e.sport).statements,startLine:0,endLine:e.rawContent.split(`
99
+ `).length-1,version:e.version,state:`idle`,widgetIds:{},createdAt:e.savedAt}}async function yL(e,t,n,r,i=DN){let a=Date.now(),o=await i.startSession(e,{id:n,noteId:e.noteId,blockId:t.id,blockContentId:t.contentId,origin:r??`journal`,startTime:a,endTime:a,duration:0,completed:!1,status:`in-progress`,createdAt:a});return{...o,block:vL(o.revision)}}async function bL(e,t,n,r){let i=await Z.getNote(e);if(!i)throw Error(`The note is unavailable. Save the note before starting a workout.`);return yL({noteId:i.id,rawContent:i.rawContent,blocks:i.blocks,expectedSourceRevision:i.sourceRevision},t,n,r)}var xL={content:``,sections:null,noteBlocks:{},sourceRevision:0,capturedRun:null,saveError:null,blocks:[],activeBlockId:null,saveState:`idle`,lastSavedContent:``,loadedRouteId:null,results:[],currentEntry:null,historyEntries:[],panelLayouts:{},attachments:[],runtime:null,execution:{status:`idle`,elapsedTime:0,stepCount:0,startTime:null,start:()=>{},pause:()=>{},stop:()=>{},reset:()=>{},step:()=>{}},handles:{handleStart:()=>{},handlePause:()=>{},handleStop:()=>{},handleNext:()=>{},handleStartWorkoutAction:()=>{}},activeSegmentIds:new Set,activeStatementIds:new Set,analyticsSegments:[],analyticsGroups:[],selectedAnalyticsIds:new Set,lastSelectedAnalyticsId:null,outputStatementList:[],logOutputList:[],userOutputOverrides:new Map,gridViewPreset:`default`,hoveredBlockKey:null,documentItems:[],selectedBlock:null,selectedBlockId:null,cursorLine:1,highlightedLine:null,subscriptionManager:null,viewMode:`plan`},SL=5e3;function CL(e={}){let t=e.listeners??[],n=e.nowProvider??rl,r=e.notePersistence,i=e.setTimeout??((e,t)=>window.setTimeout(e,t)),a=e.clearTimeout??(e=>{typeof e==`number`&&window.clearTimeout(e)}),o=null,s=[],c=fn()((t,n)=>{let c=Promise.resolve(),l=async i=>{let a=n(),o=a.currentEntry?.id??a.loadedRouteId;if(!(!o||!r||!e.provider?.capabilities.canWrite)&&(i.rawContent!==a.lastSavedContent||JSON.stringify(Object.values(i.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(a.currentEntry?.blocks??{}).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])))){t({saveState:`saving`,saveError:null});try{let e=await r.saveNote({noteId:o,rawContent:i.rawContent,blocks:i.blocks,expectedSourceRevision:a.sourceRevision,metadata:{title:i.rawContent.match(/^#\s+(.+)$/m)?.[1]?.trim()??`Untitled Session`},noteType:`playground`}),s=n();t({currentEntry:e,...s.content===i.rawContent&&JSON.stringify(Object.values(s.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(i.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))?{noteBlocks:e.blocks}:{},sourceRevision:e.sourceRevision??a.sourceRevision,lastSavedContent:i.rawContent,saveState:`saved`})}catch(e){throw t({saveState:`error`,saveError:e instanceof Error?e.message:String(e)}),e}}},u=()=>{o=null;let e=n(),t={rawContent:e.content,blocks:e.noteBlocks,sourceRevision:e.sourceRevision},r=c.catch(()=>{}).then(()=>l(t));return c=r,r};return{...xL,setContent:r=>{let s=gL(r,{noteBlocks:n().noteBlocks,sourceRevision:Math.max(1,n().sourceRevision)}),c=n(),l={content:r,sections:s.sections,blocks:s.blocks,noteBlocks:s.noteBlocks};r!==c.lastSavedContent&&(c.saveState===`idle`&&(l.saveState=`changed`),o!==null&&a(o),e.provider&&e.provider.capabilities.canWrite&&(o=i(()=>{u().catch(()=>{})},SL))),t(l)},setBlocks:e=>t({blocks:e}),setEditorIdentity:r=>{let s=JSON.stringify(Object.values(n().noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(r.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));t({content:r.rawContent,noteBlocks:r.blocks}),s&&e.provider?.capabilities.canWrite&&(o!==null&&a(o),o=i(()=>{u().catch(()=>{})},SL))},acceptSaved:e=>t(t=>({...t.content===e.rawContent&&JSON.stringify(Object.values(t.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))?{noteBlocks:e.blocks}:{},sourceRevision:e.sourceRevision,lastSavedContent:e.rawContent})),restoreBlock:async e=>{if(!r)throw Error(`Note persistence is unavailable.`);await u();let i=n(),a=YI({rawContent:i.content,blocks:i.noteBlocks,sourceRevision:i.sourceRevision},e),o=await r.saveNote({noteId:e.noteId,rawContent:a.rawContent,blocks:a.blocks,expectedSourceRevision:i.sourceRevision}),s=gL(o.rawContent,{noteBlocks:o.blocks,sourceRevision:o.sourceRevision});t({content:o.rawContent,noteBlocks:o.blocks,sourceRevision:o.sourceRevision,lastSavedContent:o.rawContent,currentEntry:o,sections:s.sections,blocks:s.blocks})},startPinnedRun:async e=>{await c.catch(()=>{});let i=n(),a=i.currentEntry?.id??i.loadedRouteId;if(!a||!r)throw Error(`Save the note before starting a workout.`);try{let n=await yL({noteId:a,rawContent:i.content,blocks:i.noteBlocks,expectedSourceRevision:i.sourceRevision},e,w(),void 0,r);return t({capturedRun:n,noteBlocks:n.note.blocks,sourceRevision:n.note.sourceRevision,currentEntry:{...i.currentEntry,...n.note,updatedAt:Date.now(),targetDate:i.currentEntry?.targetDate??Date.now(),schemaVersion:1},lastSavedContent:n.note.rawContent,saveError:null}),n.block}catch(e){throw t({saveState:`error`,saveError:e instanceof Error?e.message:String(e)}),e}},setActiveBlockId:e=>t({activeBlockId:e}),setSaveState:e=>t({saveState:e}),flushSave:async()=>{o!==null&&a(o),o=null,await u()},markSaved:e=>t({lastSavedContent:e,saveState:`saved`}),setResults:e=>t({results:e}),resetResults:()=>t({results:[]}),setCurrentEntry:e=>{if(e&&e.id!==n().currentEntry?.id){let n=gL(e.rawContent,{noteBlocks:e.blocks,sourceRevision:Math.max(1,e.sourceRevision??0)});t({currentEntry:e,content:e.rawContent,noteBlocks:n.noteBlocks,sections:n.sections,blocks:n.blocks,sourceRevision:e.sourceRevision??0,lastSavedContent:e.rawContent})}else t({currentEntry:e})},setHistoryEntries:e=>t({historyEntries:e}),setPanelLayouts:e=>t({panelLayouts:e}),expandPanel:(e,n)=>t(t=>{let r=t.panelLayouts[e]??{viewId:e,panelSpans:{},expandedPanelId:null},i=r.expandedPanelId?r.panelSpans:{...r.panelSpans};return{panelLayouts:{...t.panelLayouts,[e]:{...r,panelSpans:{...i,[n]:3},expandedPanelId:n}}}}),collapsePanel:e=>t(t=>{let n=t.panelLayouts[e];return n?{panelLayouts:{...t.panelLayouts,[e]:{...n,expandedPanelId:null}}}:t}),setAttachments:e=>t({attachments:e}),addAttachment:async r=>{let i=e.notePersistence,a=e.provider,o=n().currentEntry?.id;if(!o||!a?.capabilities.canWrite||!i)return;console.log(`[WorkbenchSession] Processing attachment: ${r.name}`);let s=await Qv.process(r),{v7:c}=await wt(async()=>{let{v7:e}=await import(`./vendor-C_ZAMcXI.js`).then(e=>e.Tt);return{v7:e}},__vite__mapDeps([0,1]));console.log(`[WorkbenchSession] Saving attachment to entry ${o}`),await i.mutateNote(o,{attachments:{add:[{id:c(),label:s.label,mimeType:s.mimeType,data:s.data,timeSpan:s.timeSpan??{start:Date.now(),end:Date.now()}}]}}),t({attachments:(await i.getNote(o,{projection:`workbench`,includeAttachments:!0})).attachments??[]}),console.log(`[WorkbenchSession] Attachment saved successfully`)},deleteAttachment:async r=>{let i=e.notePersistence,a=n().currentEntry?.id;!a||!i||(await i.mutateNote(a,{attachments:{remove:[r]}}),t({attachments:(await i.getNote(a,{projection:`workbench`,includeAttachments:!0})).attachments??[]}))},patchCurrentEntryResults:e=>t(t=>t.currentEntry?{currentEntry:{...t.currentEntry,results:e}}:t),completeWorkout:async(e,i)=>{let a=n().capturedRun,o=i??a?.session.id;if(!o||!r?.finishSession)throw Error(`The saved run pin is unavailable.`);let s=await r.finishSession(o,e,e.endTime);return t(t=>({results:[...t.results,e]})),s.id},loadEntry:async r=>{let i=e.notePersistence,a=e.provider;if(!i||!a)return null;let{routeId:o,routeView:s,routeSectionId:c,routeResultId:l,resultFromLocationState:u,initialActiveEntryId:d,propInitialContent:f}=r;if(n().setContent(``),n().setBlocks([]),t({currentEntry:null,loadedRouteId:o??null}),o){if(a.mode===`history`||a.mode===`static`)try{let e=l?{mode:`by-result-id`,resultId:l}:c&&s===`review`?{mode:`latest-for-section`,blockId:c}:{mode:`latest`},d=await i.getNote(o,{projection:s===`review`?`review`:`workbench`,includeAttachments:!0,includeSections:!0,resultSelection:e}).catch(async t=>(console.warn(`[WorkbenchSession] Note persistence projection failed, falling back to provider entry:`,{routeId:o,projection:s===`review`?`review`:`workbench`,resultSelectionMode:e.mode,err:t}),a.getEntry(o)));if(d){let e=gL(d.rawContent,{noteBlocks:d.blocks,sourceRevision:Math.max(1,d.sourceRevision??0)});return t({currentEntry:d,content:d.rawContent,sections:e.sections,blocks:e.blocks,noteBlocks:e.noteBlocks,sourceRevision:d.sourceRevision??0,lastSavedContent:d.rawContent,saveState:`saved`}),s===`review`&&u&&t(e=>e.currentEntry?{currentEntry:{...e.currentEntry,results:u}}:e),r.onLoaded?.(d),d}if(a.mode===`static`){let e=await QI(o);if(e)return n().setContent(e),null}}catch(e){console.error(`[WorkbenchSession] Failed to load entry for ID:`,o,e)}}else d&&e.navigate?.({type:`goToPlan`,noteId:d});return n().setContent(f??``),null},setActiveSegmentIds:e=>t({activeSegmentIds:e}),setActiveStatementIds:e=>t({activeStatementIds:e}),setAnalytics:(e,n)=>t({analyticsSegments:e,analyticsGroups:n}),appendOutputStatement:e=>t(t=>{let n=[...t.outputStatementList,e],{segments:r,groups:i}=qI(t.runtime);return t.runtime?{outputStatementList:n,analyticsSegments:r,analyticsGroups:i}:{outputStatementList:n}}),clearOutputStatementList:()=>t({outputStatementList:[]}),feedLogOutputs:(e,n)=>{let{segments:r,groups:i}=JI(e,n);t({logOutputList:e,analyticsSegments:r,analyticsGroups:i})},toggleAnalyticsSegment:(e,n,r)=>t(t=>{let i=new Set(t.selectedAnalyticsIds);if(n?.shiftKey&&t.lastSelectedAnalyticsId!==null&&r){let n=r.indexOf(t.lastSelectedAnalyticsId),a=r.indexOf(e);if(n!==-1&&a!==-1){let e=Math.min(n,a),t=Math.max(n,a);r.slice(e,t+1).forEach(e=>i.add(e))}}else n?.ctrlKey?i.has(e)?i.delete(e):i.add(e):(i.clear(),i.add(e));return{selectedAnalyticsIds:i,lastSelectedAnalyticsId:e}}),setUserOverride:(e,n)=>t(t=>{let r=new Map(t.userOutputOverrides);return r.set(e,J.from(n,e)),{userOutputOverrides:r}}),clearUserOverride:e=>t(t=>{let n=new Map(t.userOutputOverrides);return n.delete(e),{userOutputOverrides:n}}),setGridViewPreset:e=>t({gridViewPreset:e}),setHoveredBlockKey:e=>t({hoveredBlockKey:e}),setDocumentItems:e=>t({documentItems:e}),setSelectedBlock:e=>t({selectedBlock:e,selectedBlockId:e?.id??null}),setSelectedBlockId:e=>t({selectedBlockId:e}),setCursorLine:e=>t({cursorLine:e}),setHighlightedLine:e=>t({highlightedLine:e}),setSubscriptionManager:e=>{t({subscriptionManager:e}),dL.setSubscriptionRegistry(e)},setViewMode:e=>t({viewMode:e}),setRuntime:e=>{for(let e of s)e();if(s=[],e){let r=qI(e);t({runtime:e,outputStatementList:[],analyticsSegments:r.segments,analyticsGroups:r.groups}),s.push(e.subscribeToOutput(()=>{n().appendOutputStatement({})})),s.push(e.subscribeToStack(e=>{let n=e.blocks[0],r=new Set;for(let t of e.blocks)r.add(Mi(t.key.toString()));let i=new Set;if(n&&Array.isArray(n.sourceIds))for(let e of n.sourceIds)i.add(e);t({activeSegmentIds:r,activeStatementIds:i})}));let i=yA();if(i?.connected){let t=new oL(i);s.push(e.subscribeToStack(e=>t.onStackSnapshot(e)),e.subscribeToOutput(e=>t.onOutput(e)),()=>t.dispose());try{t.onStackSnapshot(e.getStackSnapshot())}catch{}}}else t({runtime:null,outputStatementList:[]})},setExecution:e=>t({execution:e}),setHandles:e=>t({handles:e}),getNote:async(e,t)=>{if(!r)throw Error(`[WorkbenchSession] getNote called without a notePersistence port`);return r.getNote(e,t)},resetStore:()=>{o!==null&&(a(o),o=null);for(let e of s)e();s=[],t({...xL})}}});return t.length>0&&c.subscribe(e=>{for(let n of t)n(e)}),Object.assign(c,{__nowProvider:n})}var wL=CL();function TL(e){let t=wL;return wL=e,t}function EL(){return wL}var DL=e=>Tn(wL,e),OL=({nowProvider:e,notePersistence:t,provider:n,navigate:r,children:i})=>{let a=(0,U.useMemo)(()=>CL({nowProvider:e,notePersistence:t,provider:n,navigate:r}),[e,t,n,r]);return(0,U.useEffect)(()=>{let e=TL(a);return()=>{TL(e),a.getState().resetStore()}},[a]),U.createElement(U.Fragment,null,i)},kL={getEventsByTimeRange:(e,t)=>Z.getEventsByTimeRange(e,t),getEventsByMetricDates:e=>Z.getEventsByMetricDates(e),getEventsByResult:e=>Z.getEventsByResult(e),getEventsForNote:e=>Z.getEventsForNote(e),getEventsByContent:e=>Z.getEventsByContent(e),scanAll:()=>Z.scanAll(),appendEvents:e=>Z.appendEvents(e),finalizeSummaries:(e,t)=>Z.finalizeSummaries(e,t),deleteEvents:e=>Z.deleteEvents(e)},AL={getAllNotes:()=>Z.getAllNotes(),getNotesByIds:async e=>[...(await Z.getEntryBatches(e)).values()].map(e=>e.note),getNoteIdsForTag:async e=>new Set((await Z.getNotesForTag(e)).map(e=>e.id)),getNoteTagLabels:async e=>(await Z.getTagsForNote(e)).map(e=>e.label),queryDomain:async e=>{if(!Z.queryDomain)return;let t=await Z.queryDomain({...e,plan:`notes`});return t&&t.plan===`notes`?t:void 0}},jL={getAllBlocks:()=>Z.getAllBlockIndex(),queryDomain:async e=>{if(!Z.queryDomain)return;let t=await Z.queryDomain({...e,plan:`blocks`});return t&&t.plan===`blocks`?t:void 0}},ML=class{async getAllEfforts(){let e=vD();return e.isInitialized()||await pD(e),[...e.list()]}},NL=new hg,PL={events:[],notes:[]},FL={events:[],notes:[]};NL.set(`@session`,PL),NL.set(`@today`,FL);function IL(){let e=EL().getState(),t=e.runtime?.getOutputStatements()??[],n=e.currentEntry;return PL.notes=n?[{id:n.id,title:n.title,createdAt:n.createdAt,date:n.targetDate,rawContent:n.rawContent,sourceRevision:n.sourceRevision??1,blocks:n.blocks??{}}]:[],t.length===0?(PL.events=[],PL):(PL.events=Eg(t.map(Sp),{noteId:n?.id??``,resultId:`live:${n?.id??`session`}`,origin:`playground`,workoutTimestamp:n?.targetDate}),PL)}function LL(e,t,n,r){let i=[...t].sort((e,t)=>(e.position??1/0)-(t.position??1/0)||e.createdAt-t.createdAt);for(let e of i){let t=n.get(e.pageId)?.date;if(t)return t}return $h(e.date??e.createdAt,r)}async function RL(e,t){let n=$h(e.instant,e.timeZone),r=ig(n,e.timeZone),i=ig(eg(n,1),e.timeZone),[a,o,s,c]=await Promise.all([Z.getEventsByTimeRange(r,i),Z.getAllNotes(),Z.getAllPageNotes(),Z.getAllPages()]),l=a.filter(e=>e.timestamp>=r&&e.timestamp<i),u=new Map(c.map(e=>[e.id,e])),d=new Map;for(let e of s){let t=d.get(e.noteId);t?t.push(e):d.set(e.noteId,[e])}let f=[];for(let t of o)LL(t,d.get(t.id)??[],u,e.timeZone)===n&&f.push(t);t===VL&&(FL.events=l,FL.notes=f,IL())}var zL=null,BL=null,VL=0,HL=!1,UL=new Set;function WL(){for(let e of UL)e()}function GL(e,t){BL=t;let n=++VL;return zL=RL(e,n),zL.then(()=>{n===VL&&KL()},()=>{n===VL&&KL()}),zL}function KL(){HL=!0,WL()}function qL(){let e=qh(),t=$h(e.instant,e.timeZone);return!zL||BL!==t?GL(e,t):zL}function JL(){HL=!1;let e=qh();return GL(e,$h(e.instant,e.timeZone))}function YL(){return HL}function XL(e){return UL.add(e),()=>{UL.delete(e)}}var ZL=class extends o_{async runQuery(e,t){return await qL(),super.runQuery(e,t)}async runPipeline(e,t){return await qL(),super.runPipeline(e,t)}async runFind(e,t){return await qL(),super.runFind(e,t)}async runRows(e,t){return await qL(),super.runRows(e,t)}async run(e,t){return await qL(),super.run(e,t)}};function QL(){return new ZL({eventStore:kL,noteStore:AL,blockStore:jL,effortStore:new ML,blockEffortsStore:{getAllFromIndex:(e,t)=>Z.getAllFromIndex(`block_efforts`,e,t)},tagsStore:{getAllFromIndex:(e,t)=>Z.getAllFromIndex(`tags`,e,t)},noteTagsStore:{getAllFromIndex:(e,t)=>Z.getAllFromIndex(`note_tags`,e,t)},pageStore:{getNotePages:e=>Z.getNotePages(e),getPage:e=>Z.getPage(e)},relationStore:{getBatches:e=>Z.getEntryBatches(e)},datasetStore:{getDataset:e=>e===`@session`?IL():NL.getDataset(e)}})}var $L=QL();function eR(e){let t=e.split(`/`),n=t[0]??e,r=t[1]??``;return n===`journal`?{kind:`journal`,id:r,raw:e}:n===`playground`?{kind:`playground`,id:r,raw:e}:t.length<2?{kind:`workout`,id:n,raw:e}:{kind:`workout`,category:n,id:r,raw:e}}var tR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nR(e){return typeof e==`string`&&e&&!tR.test(e)?e:void 0}function rR(e){return!!e.sourceId?.startsWith(`collection:`)||!!e.sourceId?.startsWith(`page:collection:`)||e.type===`feed`||/^markdown\/collections\/[^/]+\/.+/.test(e.sourcePath??``)}function iR(e){return!!e.sourceId?.startsWith(`feed:`)||e.sourcePath?.startsWith(`markdown/feeds/`)===!0}function aR(e){return e.type===`dashboard`||e.sourceId===`dashboards`||e.sourcePath?.startsWith(`markdown/dashboards/`)===!0}function oR(e){return e.sourceId===`efforts`||e.sourcePath?.startsWith(`markdown/efforts/`)===!0}function sR(e){return e.sourceId===`equipment`||e.sourcePath?.startsWith(`markdown/equipment/`)===!0}function cR(e,t){let n=e.sourcePath?.replace(/^markdown\/[^/]+\//,``).replace(/\.md$/,``);if(!n)return;let r=n.split(`/`);return r.length===t?r[t-1]:void 0}function lR(e){let t=e.sourceId;if(t?.startsWith(`page:collection:`)){let e=t.slice(16);if(e)return{catalog:e,item:``}}else if(t?.startsWith(`collection:`)){let e=t.slice(11);if(e){let t=e.indexOf(`/`);return t===-1?{catalog:e,item:``}:{catalog:e.slice(0,t),item:e.slice(t+1)}}}let n=/^markdown\/collections\/([^/]+)\/(.+)\.md$/.exec(e.sourcePath??``);if(n)return{catalog:n[1],item:n[2].toLowerCase()===`readme`?``:n[2]};let r=e.id.replace(/^page:collection:/,``);if(tR.test(r))return{catalog:e.catalog??``,item:``};let[i,...a]=r.split(`/`);return{catalog:i,item:a.join(`/`)}}function uR(e){return e.sourceId===`playground`||e.type===`playground`||e.id.startsWith(`playground/`)}function dR(e){return e.id.startsWith(`playground/`)?e.id.slice(11):e.id}function fR(e){return{...pR(e),noteType:e.type,catalog:Fg(e),notebookId:Ig(e),editable:Ea(e),noteId:e.id}}function pR(e){let t=e.id,n=e.title,r=e.tags&&e.tags.length>0?e.tags:void 0;if(uR(e))return{id:t,kind:`note`,sourceCatalog:`playground`,sourceItem:dR(e),sourceId:e.sourceId,title:n,date:null,createdAt:e.createdAt,...r?{tags:r}:{}};if(rR(e)){let i=t.replace(/^page:collection:/,``),{catalog:a,item:o}=lR(e);return{id:i,kind:`session`,sourceCatalog:a,sourceItem:!o||e.type===`feed`||e.type===`page`?``:o,sourceId:e.sourceId,sourcePath:e.sourcePath,pageId:`pageId`in e&&typeof e.pageId==`string`?e.pageId:void 0,pageSlug:`slug`in e?nR(e.slug):void 0,title:n,date:e.date?PN(new Date(e.date)):null,createdAt:e.createdAt,subtitle:e.catalog??a,...r?{tags:r}:{}}}if(iR(e)){let i=e.sourceId?.startsWith(`feed:`)?e.sourceId.slice(5):e.sourcePath?.startsWith(`markdown/feeds/`)?e.sourcePath.slice(9).replace(/\.md$/,``):e.id,a=(i.startsWith(`feeds/`)?i.slice(6):i).split(`/`),o=a[1]&&/^\d{4}-\d{2}-\d{2}$/.test(a[1])?a[1]:null;return{id:t,kind:`post`,sourceCatalog:a[0],sourceItem:a.slice(2).join(`/`)||a[a.length-1],sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:o,createdAt:e.createdAt,subtitle:e.catalog??a[0],...r?{tags:r}:{}}}if(aR(e))return{id:t,kind:`dashboard`,sourceCatalog:`dashboards`,sourceItem:cR(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:e.catalog??`dashboards`,...r?{tags:r}:{}};if(oR(e)){let i=cR(e,2)??t,a=e.sourcePath?.match(/^markdown\/efforts\/([^/]+)\//)?.[1];return{id:t,kind:`effort`,sourceCatalog:`efforts`,sourceItem:i,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:a,effort:{slug:i},...r?{tags:r}:{}}}if(sR(e))return{id:t,kind:`equipment`,sourceCatalog:`equipment`,sourceItem:cR(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:`equipment`,...r?{tags:r}:{}};if(e.sourceId?.startsWith(`guides:`)){let i=e.sourceId.slice(7)||t;return{id:t,kind:`note`,sourceCatalog:`guides`,sourceItem:i,sourceId:e.sourceId,sourcePath:e.sourcePath,pageSlug:nR(i.replace(/^\//,``).replace(/^guide\//,``)),title:n,date:null,createdAt:e.createdAt,...r?{tags:r}:{}}}let i=null;return`journalDate`in e&&typeof e.journalDate==`string`?i=e.journalDate:`date`in e&&typeof e.date==`string`?i=e.date:`targetDate`in e&&e.targetDate&&(typeof e.targetDate==`number`||typeof e.targetDate==`string`)?i=PN(new Date(e.targetDate)):e.createdAt&&(i=PN(new Date(e.createdAt))),{id:t,kind:`note`,sourceCatalog:`journal`,sourceItem:t,sourceId:e.sourceId,sourcePath:e.sourcePath,pageId:`pageId`in e&&typeof e.pageId==`string`?e.pageId:void 0,pageSlug:`slug`in e?nR(e.slug):void 0,title:n,date:i,createdAt:e.createdAt,...r?{tags:r}:{}}}function mR(e){return{id:e.noteId,title:e.noteTitle,createdAt:e.createdAt,type:`note`,sourceId:e.sourceId,sourcePath:e.sourcePath,rawContent:``,sourceRevision:1,blocks:{}}}var hR=3,gR=120;function _R(e){return e.split(`
100
+ `).map(e=>e.trim()).filter(Boolean).slice(0,hR).map(e=>e.length>gR?`${e.slice(0,119)}…`:e)}function vR(e){let t=fR(mR(e));return{...t,blockContentId:e.blockContentId??t.blockContentId,catalog:Fg(e),block:{blockId:e.blockId,dataType:e.dataType,preview:_R(e.rawContent)}}}function yR(e){return e?e.split(`-`).map(e=>{let t=e.toLowerCase();return t===`c2b`?`C2B`:t===`t2b`?`T2B`:t===`ghd`?`GHD`:t===`hspu`?`HSPU`:e.charAt(0).toUpperCase()+e.slice(1)}).join(` `):``}function bR(e){if(!Number.isFinite(e)||e<=0)return`00:00`;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;if(n>=60){let e=Math.floor(n/60),t=n%60;return`${e}:${String(t).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function xR(e){if(!e)return`Workout Session`;let t=eR(e);return t.kind===`journal`?t.id?`Journal: ${t.id}`:`Journal Entry`:t.kind===`workout`?yR(t.id)||t.id:t.id?yR(t.id):e}function SR(e){let t=[e.baseAttributes?.discipline,e.baseAttributes?.met==null?void 0:`MET ${e.baseAttributes.met.toFixed(1)}`,e.baseAttributes?.intensityTier].filter(Boolean);return{id:e.slug,kind:`effort`,sourceCatalog:e.registrySource??`effort`,sourceItem:e.slug,title:e.label,date:null,subtitle:t.join(` • `),detail:e.aliases&&e.aliases.length>0?`Aliases: ${e.aliases.join(`, `)}`:void 0,effort:{slug:e.slug,label:e.label,discipline:e.baseAttributes?.discipline,met:e.baseAttributes?.met,intensityTier:e.baseAttributes?.intensityTier,aliases:e.aliases,registrySource:e.registrySource}}}function CR(e){let t=(e.type??``).toLowerCase(),n=(`name`in e&&typeof e.name==`string`?e.name:``).toLowerCase(),r=typeof e.value==`number`?e.value:Number(e.value);return Number.isFinite(r)?t===`rep`||n===`reps`||n===`rep`?{kind:`rep`,val:r}:t===`weight`||t===`load`||n===`load`||n===`weight`||n===`volume`?{kind:`load`,val:r}:t===`distance`||n===`distance`?{kind:`distance`,val:r}:t===`tis`||n===`tis`?{kind:`tis`,val:r}:t===`duration`||n===`duration`?{kind:`duration`,val:r}:null:null}function wR(e){let t=1/0,n=-1/0,r=0,i=0,a=0,o=0,s=new Set;for(let c of e.events)if(c.outputType===`segment`&&o++,c.effortSlug&&s.add(c.effortSlug),c.timeSpan?.started!=null&&(c.timeSpan.started<t&&(t=c.timeSpan.started),c.timeSpan.ended!=null&&c.timeSpan.ended>n&&(n=c.timeSpan.ended)),Array.isArray(c.metrics))for(let e of c.metrics){let t=CR(e);t&&(t.kind===`rep`?r+=t.val:t.kind===`load`?i+=t.val:t.kind===`tis`&&t.val>a&&(a=t.val))}return{elapsedMs:Number.isFinite(t)&&Number.isFinite(n)&&n>t?n-t:void 0,reps:r>0?r:void 0,loadLbs:i>0?i:void 0,tis:a>0?a:void 0,segmentCount:o>0?o:void 0,effortSlugs:Array.from(s)}}function TR(e,t){let n=wR(e),r=[];n.elapsedMs!=null&&r.push(bR(n.elapsedMs)),n.tis!=null&&r.push(`TIS ${n.tis.toFixed(1)}`),n.loadLbs!=null&&r.push(`Volume: ${n.loadLbs.toLocaleString()} lbs`),n.reps!=null&&r.push(`${n.reps} reps`),n.segmentCount!=null&&r.push(`${n.segmentCount} splits`);let i=n.effortSlugs.map(yR),a=PN(new Date(e.timestamp)),o=e.events.find(e=>!!e.blockContentId)?.blockContentId;return{id:e.resultId,kind:`result`,sourceCatalog:`results`,sourceItem:e.resultId,title:t?.noteTitle??xR(e.noteId),date:a,blockContentId:o,subtitle:r.join(` • `),detail:i.length>0?i.join(`, `):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:`all`,elapsedMs:n.elapsedMs,reps:n.reps,loadLbs:n.loadLbs,tis:n.tis,segmentCount:n.segmentCount,events:e.events}}}function ER(e,t){let n;e.timeSpan?.started!=null&&e.timeSpan?.ended!=null&&(n=e.timeSpan.ended-e.timeSpan.started);let r,i,a,o;if(Array.isArray(e.metrics))for(let t of e.metrics){let e=CR(t);e&&(e.kind===`rep`?r=e.val:e.kind===`load`?i=e.val:e.kind===`distance`?a=e.val:e.kind===`tis`?o=e.val:e.kind===`duration`&&!n&&(n=e.val))}let s=e.outputType===`segment`?`segment`:`event`,c=t?.index??0,l=e.effortSlug?yR(e.effortSlug):e.outputType===`segment`?`Round ${c+1}`:`${e.outputType.charAt(0).toUpperCase()+e.outputType.slice(1)} ${c+1}`,u=[];n!=null&&u.push(bR(n)),r!=null&&i!=null?u.push(`${r} reps @ ${i} lbs`):r==null?i!=null&&u.push(`${i} lbs`):u.push(`${r} reps`),a!=null&&u.push(`${a}m`),o!=null&&u.push(`TIS ${o.toFixed(1)}`);let d=PN(new Date(e.timestamp));return{id:e.id,kind:s,sourceCatalog:`results`,sourceItem:e.id,title:l,date:d,blockContentId:e.blockContentId,subtitle:u.join(` • `),detail:e.effortSlug?yR(e.effortSlug):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:e.outputType,effortSlug:e.effortSlug,elapsedMs:n,reps:r,loadLbs:i,distanceMeters:a,tis:o,metrics:e.metrics}}}function DR(e,t){if(!e||e.error||!e.runs)return[];let n=e.parsed?.filters?.find(e=>e.key===`plane`&&!e.negate),r=e.parsed?.outputType??n?.values[0]?.value;if(r===`segment`){let t=[];for(let n of e.runs){let e=0;for(let r of n.events)r.outputType===`segment`&&t.push(ER(r,{index:e++}))}return t}if(r&&r!==`all`){let t=[];for(let n of e.runs){let e=0;for(let i of n.events)i.outputType===r&&t.push(ER(i,{index:e++}))}return t}return e.runs.map(e=>TR(e,{noteTitle:t?.noteTitles?.get(e.noteId)}))}function OR(e,t,n){let r=typeof e.__id==`string`&&e.__id?e.__id:void 0,i=typeof e.__resultId==`string`&&e.__resultId?e.__resultId:void 0,a=typeof e.effort==`string`&&e.effort?e.effort:void 0,o=[];for(let[t,n]of Object.entries(e))t.startsWith(`__`)||t===`date`||t===`effort`||(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&o.push(`${t}: ${n}`);return{id:r??i??`${t}:${n}`,kind:t,sourceCatalog:`results`,sourceItem:i??r??`${t}:${n}`,title:a?yR(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function kR(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function AR(e){return typeof e==`object`&&!!e&&`runFind`in e}var jR=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){AR(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver)}get service(){return this.customService??$L}withNoteBlockInfo(){let t=new e({service:this.service,noteTitleResolver:this.noteTitleResolver,noteTagsResolver:this.noteTagsResolver,noteBlockInfo:!0});return Object.prototype.hasOwnProperty.call(this,`query`)&&(t.query=this.query),t}async hydrateEntries(e,t){let n=e=>e.noteId??e.id,r=new Set;for(let i of e)i.sourceCatalog===`journal`&&r.add(n(i)),t&&(!i.title||!i.tags||i.tags.length===0)&&r.add(n(i));if(r.size===0)return;let i=await Z.getEntryBatches([...r]);for(let t of e){if(t.sourceCatalog!==`journal`)continue;let e=i.get(n(t)),r=[...e?.links??[]].sort((e,t)=>(e.position??1/0)-(t.position??1/0)||e.createdAt-t.createdAt);for(let n of r){let r=e?.pages.find(e=>e.id===n.pageId);if(r&&(t.pageId??=r.id,!r.date&&r.slug)){t.pageSlug=r.slug;break}}}if(t)for(let t of e){let e=i.get(n(t));!t.title&&e?.note.title&&(t.title=e.note.title),e&&e.tags.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.tags.map(e=>e.label)),t.typedTags=e.tags.map(e=>({label:e.label,type:e.type})))}}async query(e,t){let n=typeof e==`string`?X(e):e;if(!n||n.error)return[];if(bm(n)){if(n.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(n):await this.service.runFind(n),r=(e.efforts??[]).map(SR);return kR(t,e.stages,r),r}if(n.target===`block`){let e=await this.service.runFind(n),r=e.blocks.map(vR);return await this.hydrateEntries(r,!0),kR(t,e.stages,r),r}if(n.target===`session`){let e=await this.service.runFind(n);t?.(e.stages);let r;if(this.noteTitleResolver&&e.runs){r=new Map;for(let t of e.runs)if(!r.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&r.set(t.noteId,e)}}let i=DR(e,{noteTitles:r});return kR(t,e.stages,i),i}if(n.target===`segment`||n.target===`event`){let e=n.target,r=await this.service.runFind(n),i=(r.table?.rows??[]).map((t,n)=>OR(t,e,n));return kR(t,r.stages,i),i}let e=await this.service.runFind(n),r=e.notes.map(fR);if(this.noteTagsResolver?(await this.hydrateEntries(r,!1),await Promise.all(r.map(async e=>{if(!e.tags||e.tags.length===0){let t=await this.noteTagsResolver(e.id);t&&t.length>0&&(e.tags=t)}}))):await this.hydrateEntries(r,!0),kR(t,e.stages,r),this.noteBlockInfo)for(let t=0;t<r.length;t++){let n=r[t],i=e.notes[t];n.excerpt=_R(i.rawContent);try{Pa(i.rawContent,i.blocks,i.sourceRevision)}catch{continue}let a=Object.values(i.blocks).sort((e,t)=>e.from-t.from).find(e=>e.kind===`wod`),o=a&&ja(i.rawContent).find(e=>e.from===a.from&&e.scriptBlock);if(a&&o?.scriptBlock){let e=o.scriptBlock.content,t=xa(e);n.wodBlock={blockId:a.id,blockVersion:a.version,blockContentId:t,content:e},n.blockContentId=t}}return r}return[]}};async function MR(e,t=jR,n){return t.query(e,n)}function NR(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function PR(e){try{let t=(await MR(e.query)).filter(t=>!e.filterEntry||e.filterEntry(t)).slice(0,e.limit??6).map(t=>({kind:`link`,id:`${e.id}:${t.id}`,label:e.labelFromEntry?e.labelFromEntry(t):t.title,to:e.toEntry?e.toEntry(t):void 0,muted:!0}));return{kind:`section`,id:e.id,label:e.label,entries:t}}catch{return{kind:`section`,id:e.id,label:e.label,entries:[]}}}function FR(e){let t=NR(e),n=(0,U.useRef)(e);n.current=e;let[r,i]=(0,U.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,U.useEffect)(()=>{let e=n.current;if(!e){i([]);return}if(!e.some(e=>e.kind===`wql`)){i(e);return}let t=!1;return Promise.all(e.map(e=>e.kind===`wql`?PR(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),r}function IR(){let[e]=Gt(`s`,{shallow:!0}),{navState:t}=lM(),n=t.activeL3Id??``;return e||n||``}function LR({entry:e,active:t,onActivate:n}){let r=e.onRun;return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:G(`group flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors`,e.muted?`text-[11.5px]`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:G(`hover:bg-muted/60 hover:text-foreground`,e.muted?`text-muted-foreground/70`:`text-muted-foreground`)),children:[e.icon&&(0,W.jsx)(e.icon,{className:`size-4 shrink-0`}),e.timestamp&&(0,W.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60`,children:e.timestamp}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,W.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground/50`,children:e.badge}),r&&(0,W.jsx)(`span`,{role:`button`,tabIndex:-1,title:e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,onClick:t=>{t.stopPropagation(),e.onRun?.()},className:`flex size-5 shrink-0 items-center justify-center rounded text-primary opacity-0 transition-all group-hover:opacity-100 hover:bg-primary/10`,children:e.runIcon===`link`?(0,W.jsx)(l,{className:`size-3.5`}):e.runIcon===`stop`?(0,W.jsx)(x,{className:`size-3.5`}):e.runIcon===`edit`?(0,W.jsx)(o,{className:`size-3.5`}):(0,W.jsx)(rn,{className:`size-3.5`})})]})}function RR({entries:e,activeId:t,onSection:n}){let r=ht(),{scrollToSection:i}=lM(),a=e=>{if(n)return n(e);if(e.onRun)return e.onRun();if(e.to)return r(e.to);if(e.sectionId)return i(e.sectionId)};return(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,W.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,W.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,W.jsx)(RR,{entries:e.entries,activeId:t,onSection:n})]},e.id):e.kind===`wql`?null:(0,W.jsx)(LR,{entry:e,active:t!=null&&e.sectionId===t,onActivate:a},e.id))})}function zR(){let e=ht(),{scrollToSection:t}=lM();return{navigate:(t,n)=>e(t,{replace:n?.replace}),setQueryParam:(e,t)=>{},scrollToSection:t}}function BR(){let e=zR(),{openCreateJournal:t}=lM();return n=>{if(n.id===`home-new-journal`){t({mode:`blank`});return}eF(n.action,e)}}function VR(e,t,n){return e.isActive?e.isActive(n,t):e.action.type===`route`?e.action.to===`/`?n.pathname===`/`||n.pathname===``:n.pathname===e.action.to:e.action.type===`scroll`?t.activeL3Id===e.action.sectionId:e.action.type===`query`&&t.activeL3Id===e.id}function HR({items:e}){let{navState:t}=lM(),n=Xt(),r=BR();return(0,W.jsx)(tP,{children:e.map(e=>{if(e.variant===`notable`)return(0,W.jsx)(`div`,{className:`mb-2`,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`nav-item-${e.id}`,onClick:()=>r(e),className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,W.jsx)(En,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e.label})]})},e.id);let i=VR(e,t,n);return e.children&&e.children.length>0?(0,W.jsx)(aF,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>VR(e,t,n)),collapsible:e.id!==`syntax-group`,children:e.children.map(e=>{let i=VR(e,t,n);return(0,W.jsxs)(nP,{onClick:()=>r(e),current:i,children:[e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(rP,{children:e.label})]},e.id)})},e.id):(0,W.jsxs)(nP,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:e.disabled?`opacity-60`:void 0,children:[e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(rP,{children:e.disabled?`+`:e.label})]},e.id)})})}function UR({navSpec:e}){let{tree:t,navState:n,dispatch:r,contextNav:i}=lM(),a=Xt(),o=FR(e),s=(t??[]).find(e=>e?.id===n.activeL1Id)??null,c=i?.pathname===a.pathname?i:null;return(0,W.jsxs)(QN,{children:[(0,W.jsx)($N,{children:(0,W.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:s?.label??`Wod Wiki`})}),(0,W.jsxs)(eP,{children:[(()=>{if(c||!s)return null;if(s.panel){let e=s.panel;return(0,W.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,W.jsx)(e,{item:s,navState:n,dispatch:r})})}return s.children&&s.children.length>0?(0,W.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,W.jsx)(HR,{items:s.children})}):null})(),c?(0,W.jsx)(`div`,{className:`pt-1`,children:(0,W.jsx)(RR,{entries:c.spec})}):o.length>0&&(0,W.jsx)(`div`,{className:`pt-1`,children:(0,W.jsx)(RR,{entries:o})})]})]})}var WR=`0.44.2155`,GR=`https://github.com/bitcobblers/wod-wiki/releases`;function KR(e){return/-pr\.\d+$/.test(e)?GR:`${GR}/tag/v${e}`}function qR({onSearch:e,onCreate:t}){let{tree:n,navState:r,dispatch:i}=lM(),a=ht(),o=Xt(),s=KN(),c={navigate:(e,t)=>a(e,{replace:t?.replace}),setQueryParam:()=>{},scrollToSection:()=>{}},l=(n??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),u=o.pathname.startsWith(`/settings`);return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`button`,{type:`button`,onClick:()=>a(`/`),"aria-label":`Wod Wiki home`,className:`mb-3 grid size-8 shrink-0 place-items-center rounded-xl bg-primary text-primary-foreground shadow-md shadow-primary/20 rotate-3`,children:(0,W.jsx)(Ye,{size:17})}),(0,W.jsx)(`nav`,{"aria-label":`Primary`,className:`flex flex-col items-center gap-1.5`,children:l.map(e=>{let t=e.icon,n=VR(e,r,o);return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{i({type:`SET_ACTIVE_L1`,id:e.id}),eF(e.action,c)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,className:G(`relative grid size-9 place-items-center rounded-lg transition-colors`,n?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[n&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(t,{className:`size-5`})]},e.id)})}),(0,W.jsx)(`div`,{className:`flex-1`}),(0,W.jsx)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,className:`grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,W.jsx)(en,{className:`size-5`})}),(0,W.jsx)(`a`,{href:QF,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:`grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,W.jsx)($F,{className:`size-5`})}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{s(),a(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":o.pathname.startsWith(`/settings/profile`)?`page`:void 0,"data-testid":`nav-profile`,className:G(`relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,o.pathname.startsWith(`/settings/profile`)?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[o.pathname.startsWith(`/settings/profile`)&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(Me,{className:`size-5`})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{s(),a(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":u?`page`:void 0,"data-testid":`nav-settings`,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,u?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[u&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(gt,{className:`size-5`}),(0,W.jsxs)(`span`,{role:`tooltip`,className:`pointer-events-none absolute bottom-0 left-full z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 font-mono text-[10px] text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`v`,WR]})]})]})}function JR({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,W.jsx)(`nav`,{className:G(`lg:sticky z-20 flex items-center gap-1 px-4 py-2 bg-background/95 backdrop-blur-sm border-b border-border/50 overflow-x-auto`,n===`top-fixed`?`lg:top-0`:`lg:top-[104px]`,i),children:e.map(e=>(0,W.jsx)(`button`,{onClick:()=>eF(e.action,r),className:G(`px-3 py-1.5 rounded-full text-[10px] font-black uppercase tracking-[0.12em] whitespace-nowrap transition-all ring-1`,t===e.id?`bg-primary text-primary-foreground ring-primary/30 shadow-md`:`bg-muted/50 text-muted-foreground ring-transparent hover:bg-muted hover:ring-border`),children:e.label},e.id))})}var YR=class e{now;name=`tick`;timestamp;data;static _counter=0;constructor(t,n=rl){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this.data=t}},XR=20,ZR=e=>{let[t,n]=(0,U.useState)(`idle`),[r,i]=(0,U.useState)(0),[a,o]=(0,U.useState)(0),[s,c]=(0,U.useState)(null),l=(0,U.useRef)(null),u=(0,U.useRef)(null),d=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),n(`idle`)},[]),f=(0,U.useCallback)(()=>{if(e)try{let t=new YR(void 0,e.nowProvider);e.handle(t),o(e=>e+1)}catch{d(),n(`error`)}},[e,d]);(0,U.useEffect)(()=>{if(e)return e.subscribeToStack(e=>{e.blocks.length===0&&t!==`completed`&&(l.current&&=(clearInterval(l.current),null),n(`completed`))})},[e,t]),(0,U.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]);let p=(0,U.useCallback)(()=>{if(!e){console.warn(`useRuntimeExecution: Cannot start execution without a runtime`);return}if(t===`running`){console.warn(`useRuntimeExecution: Runtime is already running`);return}t===`paused`&&e.handle({name:`timer:resume`,timestamp:new Date,data:{}}),n(`running`);let i=e?.nowProvider?.nowMs()??rl.nowMs();u.current=i-r,r===0&&c(i),l.current=setInterval(f,XR)},[e,t,r,f]),m=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),e&&e.handle({name:`timer:pause`,timestamp:new Date,data:{}}),n(`paused`)},[e]),h=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),i(0),o(0),n(`idle`),c(null),u.current=null},[e]),g=(0,U.useCallback)(()=>{!e||t===`running`||(n(`paused`),f())},[e,t,f]);return(0,U.useEffect)(()=>{if(t!==`running`||!u.current)return;let n=setInterval(()=>{i((e?.nowProvider?.nowMs()??rl.nowMs())-u.current)},100);return()=>clearInterval(n)},[t,e?.nowProvider]),(0,U.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]),(0,U.useEffect)(()=>{h()},[e,h]),(0,U.useMemo)(()=>({status:t,elapsedTime:r,stepCount:a,startTime:s,start:p,pause:m,stop:d,reset:h,step:g}),[t,r,a,s,p,m,d,h,g])},QR=(e,t)=>!e||!Array.isArray(e)?0:e.reduce((e,n)=>{if(`started`in n){let r=n.started,i=n.ended??t;return e+Math.max(0,i-r)}let r=n.start instanceof Date?n.start.getTime():n.start||0,i=n.stop?n.stop instanceof Date?n.stop.getTime():n.stop:t;return e+Math.max(0,i-r)},0);function $R(e,t){let n=t,r=()=>{let t=e?.getMemoryByTag(n)[0];if(t)return n===`round`?t.metrics[0]:t.metrics[0]?.value},[i,a]=(0,U.useState)(r);return(0,U.useEffect)(()=>{if(!e){a(void 0);return}a(r());let t=e.getMemoryByTag(n)[0];if(t)return t.subscribe(e=>{a(n===`round`?e[0]:e[0]?.value)})},[e,t]),i}function ez(e){return $R(e,`round`)}function tz(e){return $R(e,`display`)}function nz(e){let t=ez(e),n=tz(e);return(0,U.useMemo)(()=>{if(!t)return null;let e=n?.roundDisplay??(t.total===void 0?`Round ${t.current}`:`Round ${t.current} of ${t.total}`),r=t.total===void 0?void 0:Math.min(1,(t.current-1)/t.total);return{current:t.current,total:t.total,label:e,progress:r}},[t,n?.roundDisplay])}var rz=(0,U.createContext)(void 0),iz=({runtime:e,children:t})=>(0,W.jsx)(rz.Provider,{value:e,children:t});function az(){let e=(0,U.useContext)(rz);if(!e)throw Error(`useScriptRuntime must be used within ScriptRuntimeProvider`);return e}function oz(e){let t=az(),n=e===void 0?t:e,[r,i]=(0,U.useState)(()=>n?.getOutputStatements?.()??[]);return(0,U.useEffect)(()=>{if(!n){i([]);return}return i(n.getOutputStatements()),n.subscribeToOutput?.(()=>{i(n.getOutputStatements())})},[n]),(0,U.useMemo)(()=>{let e=new Map,t=new Map,n=[],i=[];for(let a of r){e.set(a.id,a);let r=t.get(a.sourceBlockKey)??[];switch(r.push(a),t.set(a.sourceBlockKey,r),a.outputType){case`segment`:n.push(a);break;case`metric`:i.push(a)}}let a=n.filter(e=>e.completionReason!==void 0);return{outputs:r,byId:e,byBlockKey:t,segments:n,completions:a,metrics:i}},[r])}function sz(e){let t=az(),n=e===void 0?t:e,[r,i]=(0,U.useState)(()=>n?.getLiveAnalytics?.()??[]);return(0,U.useEffect)(()=>{if(!n){i([]);return}return i(n.getLiveAnalytics?.()??[]),n.subscribeToOutput?.(()=>{i(n.getLiveAnalytics?.()??[])})},[n]),r}function cz(){let e=az(),[t,n]=(0,U.useState)({type:`initial`,blocks:e.stack.blocks,depth:e.stack.count,clockTime:e.clock.currentDate});return(0,U.useEffect)(()=>e.subscribeToStack(e=>{n(e)}),[e]),t}function lz(){return cz().blocks}function uz(){let e=lz(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`metric:next`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{for(let t of e){let e=t.getMemoryByTag(`metric:next`);if(e.length===0)continue;let n=J.empty(t.key.toString());for(let t of e)n.merge(t.metrics);if(n.length>0)return{metrics:n,block:t}}return null},[e,t])}function dz(){let e=lz(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`time`)[0];if(e){let r=e.subscribe(()=>{n(e=>e+1)});t.push(r)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{let t=[];for(let n of e){let e=n.getMemoryByTag(`time`)[0];if(!e)continue;let r=e.metrics[0]?.value;r&&t.push({block:n,timer:r,isPinned:r.role===`primary`})}return t},[e,t])}function fz(){let e=dz();return(0,U.useMemo)(()=>{if(e.length===0)return;let t=e[0];return t.block.blockType===`Rest`?t:[...e].reverse().find(e=>e.isPinned)||t},[e])}function pz(){let e=dz(),t=fz();return(0,U.useMemo)(()=>t?e.filter(e=>e.block!==t.block):[],[e,t])}function mz(){let e=lz(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`controls`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{let t=[],n=[];for(let r=0;r<e.length;r++){let i=e[r].getMemoryByTag(`controls`);if(i.length===0)continue;let a=i[0].metrics.map(e=>e.value).filter(Boolean),o=r===e.length-1;for(let e of a)e.isPinned?t.push(e):o&&n.push(e)}let r=new Set,i=[];for(let e of t)r.has(e.id)||(r.add(e.id),i.push(e));for(let e of n)r.has(e.id)||(r.add(e.id),i.push(e));return i},[e,t])}function hz(){let e=lz(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`metric:display`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{if(e.length===0)return;let t=[],n=[...e].reverse();return n.forEach((e,r)=>{if(e.blockType===`Root`&&!e.label)return;let i=e.getMemoryByTag(`metric:display`),a=i.map(e=>e.metrics);if(a.length===0&&!e.label)return;let o=r===n.length-1,s=i.length>1?i.map(e=>e.metrics):void 0;t.push({block:e,displayRows:a,label:e.label,depth:r,isLeaf:o,metricGroups:s})}),t.length>0?t:void 0},[e,t])}function gz(e){let t=az(),n=(0,U.useMemo)(()=>t.stack.blocks.find(t=>t.key.toString()===e),[t,e]),[r,i]=(0,U.useState)(()=>n?.getMemoryByTag(`time`)[0]?.metrics[0]?.value);(0,U.useEffect)(()=>t.stack.subscribe(()=>{let n=t.stack.blocks.find(t=>t.key.toString()===e);if(n){let e=n.getMemoryByTag(`time`)[0];i(e?.metrics[0]?.value)}else i(void 0)}),[t,e]),(0,U.useEffect)(()=>{if(!n){i(void 0);return}let e=n.getMemoryByTag(`time`)[0];if(i(e?.metrics[0]?.value),e)return e.subscribe(e=>{i(e[0]?.value)})},[n]);let a=(0,U.useMemo)(()=>r?.spans??[],[r]),o=a.length>0&&a[a.length-1].ended===void 0,[s,c]=(0,U.useState)(Gl()),l=(0,U.useMemo)(()=>a.length===0?0:QR(a,s),[a,s]);return(0,U.useEffect)(()=>{if(!o)return;let e,t=()=>{c(Gl()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[o]),{elapsed:l,isRunning:o,timeSpans:a}}var _z=(0,U.createContext)(void 0),vz=(0,U.createContext)(null),yz={getState:()=>EL().getState(),setState:(e,t)=>{let n=EL();typeof e==`function`?n.setState(e(n.getState()),t):n.setState(e,t)},subscribe:e=>EL().subscribe(e)},bz=({factory:e,children:t})=>{let[n,r]=(0,U.useState)(null),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(!1),[c,l]=(0,U.useState)(null),u=(0,U.useRef)(e);u.current=e;let d=(0,U.useRef)(null),f=(0,U.useRef)(null),p=(0,U.useRef)(!1),m=(0,U.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),yz.getState().setSubscriptionManager(null);let e=d.current;if(d.current=null,e)try{u.current.disposeRuntime(e)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime:`,e)}r(null),l(null)},[]),h=(0,U.useCallback)((e,t)=>{if(!p.current){p.current=!0,s(!0),l(null);try{f.current&&=(f.current.dispose(),null);let n=d.current;if(d.current=null,n)try{u.current.disposeRuntime(n)}catch(e){console.error(`[RuntimeProvider] Error disposing existing runtime:`,e)}let i=u.current.createRuntime(e,t);if(d.current=i,r(i),i){let e=new ap(i);e.add(new ip({id:`local`})),f.current=e,a(e),yz.getState().setSubscriptionManager(e)}else f.current=null,a(null),yz.getState().setSubscriptionManager(null)}catch(e){console.error(`[RuntimeProvider] Error creating runtime:`,e),l(e instanceof Error?e:Error(String(e))),d.current=null}finally{p.current=!1,s(!1)}}},[]);(0,U.useEffect)(()=>()=>{if(f.current&&f.current.dispose(),d.current)try{u.current.disposeRuntime(d.current)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime on unmount:`,e)}},[]);let g={runtime:n,isInitializing:o,error:c,initializeRuntime:h,disposeRuntime:m};return(0,W.jsx)(_z.Provider,{value:g,children:(0,W.jsx)(vz.Provider,{value:i,children:t})})};function xz({factory:e,children:t}){return(0,W.jsx)(bz,{factory:e,children:t})}var Sz=`bg-background ring-1 ring-zinc-950/5 shadow-sm lg:shadow-[-18px_0_36px_-28px_rgba(15,23,42,0.16),18px_0_36px_-28px_rgba(15,23,42,0.16)] dark:shadow-none dark:ring-white/10`,Cz=`flex flex-col flex-1 min-w-0 xl:max-w-[984px] 2xl:max-w-none min-h-screen lg:rounded-[2.5rem]`;function wz({id:e,title:t,subtitle:n,titleAccessory:r,actions:i,queryBar:a,subheader:o,titleTestId:s,className:c}){return(0,W.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:G(`max-lg:hidden lg:sticky lg:top-0 z-30 bg-background/80 backdrop-blur-md transition-colors`,c),children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,children:[t&&(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[(0,W.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,W.jsxs)(`div`,{className:`min-w-0`,children:[(0,W.jsx)(`h1`,{"data-testid":s,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:t}),n&&(0,W.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:n})]}),r]})]}),a&&(0,W.jsx)(`div`,{className:`min-w-0 flex-1`,children:a}),i&&(0,W.jsx)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:i})]}),o&&(0,W.jsx)(`div`,{className:`bg-background/40`,children:o})]})}function Tz({ids:e,enabled:t=!0,rootMargin:n=`-10% 0px -40% 0px`,threshold:r=[0,.3,1],onChange:i,shouldAcceptChange:a,scrollDirection:o=`ratio`,dataAttribute:s,debounceMs:c=0}){let l=(0,U.useRef)(``),u=(0,U.useRef)(i),d=(0,U.useRef)(a),f=(0,U.useRef)(null),p=(0,U.useRef)(1);(0,U.useEffect)(()=>{u.current=i},[i]),(0,U.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,U.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,U.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,U.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,U.useEffect)(()=>{if(!t||g.length===0||typeof IntersectionObserver>`u`)return;let e=new Map,r=e=>s?e.getAttribute(s):e.id||null,i;if(o===`topmost-when-up`){let e=window.scrollY,t=()=>{let t=window.scrollY;t!==e&&(p.current=t>e?1:-1),e=t};window.addEventListener(`scroll`,t,{passive:!0}),i=()=>window.removeEventListener(`scroll`,t)}let a=new IntersectionObserver(t=>{if(t.forEach(t=>{let n=r(t.target);n&&(t.isIntersecting?e.set(n,t.intersectionRatio):e.delete(n))}),e.size===0)return;let n=``;if(o===`topmost-when-up`&&p.current===-1){let t=1/0;e.forEach((e,r)=>{let i=g.indexOf(r);i>=0&&i<t&&(t=i,n=r)})}else{let t=-1;e.forEach((e,r)=>{e>t&&(t=e,n=r)})}!n||n===l.current||d.current&&!d.current(n)||(l.current=n,c>0?(v(),f.current=setTimeout(()=>{u.current(n),f.current=null},c)):u.current(n))},{rootMargin:n,threshold:_});return g.forEach(e=>{let t=s?document.querySelector(`[${s}="${e}"]`):document.getElementById(e);t&&a.observe(t)}),()=>{a.disconnect(),v(),i?.()}},[t,g,_,n,o,s,c,v])}function Ez({title:e,titleAccessory:t,actions:n,subheader:r,children:i,index:a=[],activeSectionId:o,hero:s,sections:c,className:l}){let u=!!(c&&c.length>0)&&!e,[,d]=Gt(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,U.useState)(c?.[0]?.id??``);if(Tz({ids:a.map(e=>e.id),enabled:!u&&a.length>0,rootMargin:`-10% 0px -40% 0px`,threshold:[0,.3,1],onChange:e=>{d(e)},shouldAcceptChange:()=>!0}),Tz({ids:c?.map(e=>e.id)??[],enabled:u,rootMargin:`-20% 0px -50% 0px`,threshold:[0,.25,.5,.75],onChange:p}),u){let e=c.map(e=>({id:e.id,label:e.label,action:{type:`scroll`,sectionId:e.id}}));return(0,W.jsxs)(`div`,{className:G(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,W.jsx)(JR,{activations:e,activeSection:f,variant:`top-fixed`,deps:{navigate:()=>{},setQueryParam:()=>{},scrollToSection:e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-64;window.scrollTo({top:e,behavior:`smooth`})}}}}),(0,W.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,W.jsx)(`div`,{id:e.id,"data-section-id":e.id,className:`py-12 lg:py-16 px-6 lg:px-10 border-b border-border/30`,children:e.content},e.id);return e.runtimeFactory?(0,W.jsx)(xz,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,W.jsx)(`div`,{className:G(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,W.jsxs)(`div`,{className:G(Cz,Sz),children:[(0,W.jsx)(wz,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,W.jsx)(`div`,{className:`flex-1`,children:i})]})})}var Dz=`[data-page-sticky-boundary="true"]`,Oz=0;function kz(e,t=Oz){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(Dz)).reduce((e,t)=>{let n=t.getBoundingClientRect();return n.height<=0||n.bottom<=0?e:Math.max(e,n.bottom)},0);return n>0?n+t:e}function Az(e,t=Oz){let[n,r]=(0,U.useState)(e);return(0,U.useEffect)(()=>{let n=0,i=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>r(kz(e,t)))};return i(),window.addEventListener(`scroll`,i,{passive:!0}),window.addEventListener(`resize`,i),()=>{cancelAnimationFrame(n),window.removeEventListener(`scroll`,i),window.removeEventListener(`resize`,i)}},[e,t]),n}function jz({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,W.jsxs)(`div`,{"data-testid":a,className:G(`sticky z-10 flex items-center gap-2 border-y border-border/60 bg-card/95 px-6 py-2 shadow-[0_1px_2px_rgba(0,0,0,0.03)] backdrop-blur`,o),style:{top:`${e}px`},children:[n,(0,W.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,W.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var Mz=(0,U.createContext)(null),Nz=(0,U.createContext)(null);function Pz({children:e}){let[t,n]=(0,U.useState)(null);return(0,W.jsx)(Nz.Provider,{value:n,children:(0,W.jsx)(Mz.Provider,{value:t,children:e})})}function Fz({className:e}){let t=(0,U.useContext)(Nz);return(0,W.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function Iz(){return(0,U.useContext)(Mz)}function Lz({editor:e,title:t,subtitle:n,titleTestId:r,actions:i,timerOverlay:a,reviewOverlay:o,isTimerOpen:s=!1,isReviewOpen:c=!1,onCloseTimer:l,onCloseReview:u,className:d}){return(0,W.jsxs)(`div`,{className:G(`relative flex w-full min-h-screen justify-start items-start`,d),children:[(0,W.jsxs)(`div`,{className:G(Cz,Sz),children:[(0,W.jsx)(wz,{title:t,subtitle:n,titleTestId:r,actions:i}),(0,W.jsx)(`main`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),s&&a&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,W.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,W.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,W.jsx)(`button`,{onClick:l,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:a})]})}),c&&o&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,W.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,W.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,W.jsx)(`button`,{onClick:u,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:o})]})})]})}function Rz(e){return e.map(e=>{let t=e.action,n=e.secondaryAction?.action,r={kind:`link`,id:e.id,label:e.label};return n&&n.type===`call`&&(r.onRun=n.handler,r.runIcon=e.secondaryRunIcon??`play`),t.type===`route`?{...r,to:t.to}:t.type===`scroll`?{...r,sectionId:t.sectionId}:t.type===`call`?{...r,onRun:t.handler}:r})}var zz=U.createContext(null);function Bz(){let e=U.useContext(zz);if(!e)throw Error(`DropdownMenu components must be used inside a DropdownMenu`);return e}function Vz(){let e=U.useContext(zz);return U.useCallback(()=>{e?.setIsOpen(!1)},[e])}var Hz=({children:e,open:t,onOpenChange:n})=>{let r=U.useContext(zz),i=U.useId(),a=r?`${r.portalChain}/${i}`:i,[o,s]=U.useState(t??!1),c=U.useRef(null),[l,u]=U.useState(-1),d=U.useRef(new Map),[,f]=U.useReducer(e=>e+1,0);U.useEffect(()=>{t!==void 0&&s(t)},[t]);let p=U.useCallback(e=>{s(e),u(-1),n?.(e)},[n]),m=U.useCallback((e,t)=>{d.current.set(e,t),f()},[]),h=U.useCallback(e=>{d.current.delete(e),f()},[]),g=U.useCallback(e=>Array.from(d.current.keys()).indexOf(e),[]),_=d.current.size,v=U.useMemo(()=>({isOpen:o,setIsOpen:p,triggerRef:c,registerItem:m,unregisterItem:h,getItemIndex:g,activeIndex:l,setActiveIndex:u,itemCount:_,menuId:i,portalChain:a}),[o,p,m,h,g,l,_,i,a]);return(0,W.jsx)(zz.Provider,{value:v,children:(0,W.jsx)(`div`,{ref:c,className:`relative inline-block`,children:e})})},Uz=U.forwardRef(({className:e,children:t,asChild:n,...r},i)=>{let{isOpen:a,setIsOpen:o}=Bz(),s=e=>{e.stopPropagation(),o(!a)};return n&&U.isValidElement(t)?U.cloneElement(t,{...r,onClick:s}):(0,W.jsx)(`button`,{ref:i,className:e,onClick:s,...r,children:t})});Uz.displayName=`DropdownMenuTrigger`;var Wz=U.forwardRef(({className:e,children:t,align:n=`center`,side:r=`bottom`,...i},a)=>{let{isOpen:o,setIsOpen:s,triggerRef:c,setActiveIndex:l,itemCount:u,menuId:d,portalChain:f}=Bz(),p=U.useRef(null),m=a||p,[h,g]=U.useState({top:0,bottom:0,left:0,width:0});U.useEffect(()=>{if(!o||!c.current)return;let e=c.current.getBoundingClientRect();g({top:e.bottom+8,bottom:window.innerHeight-e.top+8,left:e.left,width:e.width})},[o,c]),U.useEffect(()=>{if(!o||u===0)return;let e=setTimeout(()=>{l(0)},0);return()=>clearTimeout(e)},[o,u,l]),U.useEffect(()=>{if(!o)return;let e=e=>{let t=e.target;if(m.current&&m.current.contains(t)||c.current&&c.current.contains(t))return;let n=t.closest?.(`[data-dropdown-chain]`)?.getAttribute(`data-dropdown-chain`);n&&n.split(`/`).includes(d)||s(!1)},t=setTimeout(()=>{document.addEventListener(`mousedown`,e)},0);return()=>{clearTimeout(t),document.removeEventListener(`mousedown`,e)}},[o,s,m,c,d]);let _=e=>{if(u!==0)switch(e.key){case`ArrowDown`:e.preventDefault(),l(e=>e<u-1?e+1:0);break;case`ArrowUp`:e.preventDefault(),l(e=>e>0?e-1:u-1);break;case`Home`:e.preventDefault(),l(0);break;case`End`:e.preventDefault(),l(u-1);break;case`Escape`:e.preventDefault(),s(!1),c.current?.querySelector(`button`)?.focus();break;case`Tab`:s(!1)}};if(!o)return null;let v={position:`fixed`,zIndex:9999};return r===`top`?v.bottom=h.bottom:v.top=h.top,n===`end`?v.right=window.innerWidth-h.left-h.width:n===`start`?v.left=h.left:(v.left=h.left+h.width/2,v.transform=`translateX(-50%)`),RS.createPortal((0,W.jsx)(`div`,{ref:m,role:`menu`,"data-dropdown-chain":f,className:G(`min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95`,e),style:v,onKeyDown:_,...i,children:t}),document.body)});Wz.displayName=`DropdownMenuContent`;var Gz=U.forwardRef(({className:e,disabled:t,inset:n,onClick:r,onKeyDown:i,...a},o)=>{let{setIsOpen:s,registerItem:c,unregisterItem:l,getItemIndex:u,activeIndex:d}=Bz(),f=U.useId(),p=U.useRef(null),m=U.useCallback(e=>{p.current=e,typeof o==`function`?o(e):o&&(o.current=e)},[o]);U.useEffect(()=>(c(f,p),()=>l(f)),[f,c,l]);let h=u(f)===d;return U.useEffect(()=>{h&&p.current?.focus()},[h]),(0,W.jsx)(`div`,{ref:m,role:`menuitem`,tabIndex:t?-1:h?0:-1,"aria-disabled":t,"data-active":h?`true`:void 0,className:G(`relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors`,`focus:bg-accent focus:text-accent-foreground`,`data-[active]:bg-accent data-[active]:text-accent-foreground`,n&&`pl-8`,t&&`pointer-events-none opacity-50`,e),onClick:e=>{t||(r?.(e),s(!1))},onKeyDown:e=>{t||(i?.(e),(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r?.(e),s(!1)))},...a})});Gz.displayName=`DropdownMenuItem`;var Kz=U.forwardRef(({className:e,inset:t,...n},r)=>(0,W.jsx)(`div`,{ref:r,className:G(`px-2 py-1.5 text-sm font-semibold`,t&&`pl-8`,e),...n}));Kz.displayName=`DropdownMenuLabel`;var qz=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`-mx-1 my-1 h-px bg-muted`,e),...t}));qz.displayName=`DropdownMenuSeparator`;function Jz({className:e,children:t,...n}){return(0,W.jsx)(`div`,{className:G(`px-2 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,e),...n,children:t})}var Yz=[{label:`Past 1 week`,value:`last 1w`},{label:`Past 2 weeks`,value:`last 2w`},{label:`Past 4 weeks`,value:`last 4w`},{label:`Past 8 weeks`,value:`last 8w`},{label:`Past 12 weeks`,value:`last 12w`},{label:`Past 1 year`,value:`last 52w`},{label:`All time`,value:`all`}],Xz=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function Zz(e,t){return new Date(e,t+1,0).getDate()}function Qz(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function $z(e,t){let n=X(e);if(n.error)return e;if(!t||t===`all`)return dh({...n,window:void 0});let r=X(`:note ${t}`);return r.error||r.family!==`find`||!r.window?e:dh({...n,window:r.window})}function eB(e){let t=X(e);return t.error||t.family===`pipeline`?null:`window`in t?t.window??null:null}function tB({query:e,onQueryChange:t,highlightDates:n=new Set,className:r}){let i=(0,U.useMemo)(()=>eB(e),[e]),[a,o]=(0,U.useState)(null),[s,c]=(0,U.useState)(()=>new Date),l=s.getFullYear(),u=s.getMonth(),d=(0,U.useMemo)(()=>i?i.kind===`relative`?`last ${i.size}${i.unit}`:i.end?`from ${i.start} to ${i.end}`:`from ${i.start}`:`All time`,[i]),f=(0,U.useMemo)(()=>{if(!i)return null;if(i.kind===`range`)return{start:i.start,end:i.end??i.start};let e=new Date,t=new Date;return i.unit===`d`?t.setDate(e.getDate()-i.size):t.setDate(e.getDate()-i.size*7),{start:PN(t),end:PN(e)}},[i]),p=(0,U.useMemo)(()=>{let e=Zz(l,u),t=Qz(l,u),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[l,u]),m=n=>{if(!a)o(n),t($z(e,`from ${n} to ${n}`));else{let[r,i]=a<=n?[a,n]:[n,a];o(null),t($z(e,`from ${r} to ${i}`))}},h=e=>{e.stopPropagation(),c(new Date(l,u-1,1))},g=e=>{e.stopPropagation(),c(new Date(l,u+1,1))},_=s.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),v=PN(new Date);return(0,W.jsxs)(`div`,{className:G(`relative inline-flex items-center`,r),children:[(0,W.jsxs)(Hz,{children:[(0,W.jsx)(Uz,{asChild:!0,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`wql-window-picker-trigger`,className:`flex h-9 items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,W.jsx)(zt,{className:`size-3.5 text-muted-foreground`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`font-mono text-xs`,children:d}),(0,W.jsx)(Cn,{className:`size-3 text-muted-foreground`,"aria-hidden":`true`})]})}),(0,W.jsxs)(Wz,{align:`end`,className:`w-72 p-3`,children:[(0,W.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-1 border-b border-border/60 pb-2`,children:Yz.map(n=>{let r=n.value===`all`?!i:i?.kind===`relative`&&`last ${i.size}${i.unit}`===n.value;return(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-window-preset-${n.value}`,onClick:()=>{o(null),t($z(e,n.value))},className:G(`rounded-md px-2 py-1 text-[11px] font-medium transition-colors`,r?`bg-primary text-primary-foreground`:`bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground`),children:n.label},n.value)})}),(0,W.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:h,"data-testid":`wql-calendar-prev-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,W.jsx)(_t,{className:`size-4`})}),(0,W.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:_}),(0,W.jsx)(`button`,{type:`button`,onClick:g,"data-testid":`wql-calendar-next-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,W.jsx)(Qt,{className:`size-4`})})]}),(0,W.jsx)(`div`,{className:`mb-1 grid grid-cols-7 gap-1`,children:Xz.map(e=>(0,W.jsx)(`div`,{className:`text-center text-[10px] font-medium text-muted-foreground`,children:e},e))}),(0,W.jsx)(`div`,{className:`grid grid-cols-7 gap-1`,"data-testid":`wql-calendar-grid`,children:p.map((e,t)=>{if(e===null)return(0,W.jsx)(`div`,{className:`size-8`},`empty-${t}`);let r=`${l}-${String(u+1).padStart(2,`0`)}-${String(e).padStart(2,`0`)}`,i=f&&r>=f.start&&r<=f.end,o=f&&r===f.start||a===r,s=f&&r===f.end,c=r===v,d=n.has(r);return(0,W.jsxs)(`button`,{type:`button`,"data-testid":`wql-calendar-day-${r}`,onClick:()=>m(r),className:G(`relative flex size-8 items-center justify-center rounded-md text-xs transition-colors`,o||s?`bg-primary font-bold text-primary-foreground`:i?`bg-primary/15 font-semibold text-primary`:c?`border border-primary font-semibold text-primary`:`text-foreground hover:bg-muted`),children:[(0,W.jsx)(`span`,{children:e}),d&&!o&&!s&&(0,W.jsx)(`span`,{className:`absolute bottom-0.5 size-1 rounded-full bg-primary`})]},r)})}),a&&(0,W.jsxs)(`div`,{className:`mt-2 text-center text-[10px] text-muted-foreground`,children:[`Select second date to complete range (starting from `,a,`)`]})]})]}),i&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-window-picker-clear`,onClick:()=>{o(null),t($z(e,null))},title:`Clear time window`,"aria-label":`Clear time window`,className:`ml-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,W.jsx)(we,{className:`size-3.5`})})]})}function nB({onOpen:e}){let t=Vz();return(0,W.jsxs)(K,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{t(),e()},"data-testid":`query-settings-trigger`,className:`w-full justify-start gap-2 rounded-lg text-xs`,children:[(0,W.jsx)(_n,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`truncate`,children:`Query settings`})]})}function rB(e){switch(e.kind){case`note`:case`post`:return`note`;case`session`:return`session`;case`result`:return`result`;case`segment`:case`event`:return`segment`;case`effort`:return`effort`;default:return`note`}}var iB=[{id:`title`,label:`Title`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`tags`,label:`Tags`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.tags??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)},{id:`excerpt`,label:`Text Excerpt`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.preview?.join(` `)||e.detail||``,formatValue:e=>String(e??``)},{id:`catalog`,label:`Catalog Source`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.sourceCatalog,formatValue:e=>String(e??``)},{id:`date`,label:`Date`,level:`note`,defaultVisible:!0,align:`right`,getValue:e=>e.date,formatValue:e=>String(e??``)}],aB={note:iB,session:[{id:`title`,label:`Title`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`protocol`,label:`Protocol`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.dataType||e.subtitle||``,formatValue:e=>String(e??``)},{id:`movements`,label:`Movements`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.detail||``,formatValue:e=>String(e??``)},{id:`targetDuration`,label:`Target Duration`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:bR(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`sessionLoad`,label:`Session Load`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``}],result:[{id:`title`,label:`Title`,level:`result`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`elapsedTime`,label:`Elapsed Time`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:bR(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`totalTonnage`,label:`Total Tonnage`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`tis`,label:`TIS Score`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.tis,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`prBadges`,label:`PR Badges`,level:`result`,defaultVisible:!0,align:`center`,getValue:e=>e.detail&&/\bPR\b/.test(e.detail)?`PR`:``,formatValue:e=>String(e??``)}],segment:[{id:`splitDuration`,label:`Split Duration`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:bR(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`roundIndex`,label:`Round/Lap Index`,level:`segment`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`reps`,label:`Reps`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.reps,formatValue:e=>e==null?``:String(e)},{id:`load`,label:`Load`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`pacingTier`,label:`Pacing / HR Tier`,level:`segment`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier||e.execution?.effortSlug||``,formatValue:e=>String(e??``)}],effort:[{id:`label`,label:`Label`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.label||e.title,formatValue:e=>String(e??``)},{id:`canonicalSlug`,label:`Canonical Slug`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.slug||e.id,formatValue:e=>String(e??``)},{id:`discipline`,label:`Discipline`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.discipline??``,formatValue:e=>String(e??``)},{id:`met`,label:`MET Score`,level:`effort`,defaultVisible:!0,align:`right`,getValue:e=>e.effort?.met,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`intensityTier`,label:`Intensity Tier`,level:`effort`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier??``,formatValue:e=>String(e??``)},{id:`aliases`,label:`Aliases`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.aliases??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)}]};function oB(e){return aB[e]??iB}function sB(e){return oB(e).filter(e=>e.defaultVisible).map(e=>e.id)}var cB=[{id:`cards`,label:`Cards`,icon:ye},{id:`rows`,label:`Rows`,icon:le},{id:`feed`,label:`Feed`,icon:Xn}];function lB({streamControls:e}){return(0,W.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":`l3-stream-controls`,children:[e.onOpenQuerySettings&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`This page`}),(0,W.jsx)(nB,{onOpen:e.onOpenQuerySettings})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date window`}),(0,W.jsx)(tB,{query:e.query,onQueryChange:e.onQueryChange,className:`w-full justify-between`})]}),e.availableGroupDims.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Group by`}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-groupby-options`,children:e.availableGroupDims.map(t=>{let n=e.groupDims.some(e=>e.toLowerCase()===t.id.toLowerCase());return(0,W.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-groupby-${t.id}`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleGroupDim(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,W.jsx)(`span`,{children:t.label})]},t.id)})})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Layout`}),(0,W.jsx)(`div`,{className:`grid grid-cols-3 gap-1`,"data-testid":`l3-layout-options`,children:cB.map(t=>{let n=t.icon,r=e.settings.layout===t.id;return(0,W.jsxs)(`button`,{type:`button`,"aria-pressed":r,onClick:()=>e.onLayoutChange(t.id),"data-testid":`l3-layout-${t.id}`,className:`flex min-h-8 items-center justify-center gap-1 rounded-md border px-1.5 py-1 text-[11px] font-medium transition-colors ${r?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[(0,W.jsx)(n,{"aria-hidden":!0,className:`size-3`}),t.label]},t.id)})})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Fields`}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-field-options`,children:oB(e.level).map(t=>{let n=e.settings.visibleFields.includes(t.id);return(0,W.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-field-${t.id}`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleField(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,W.jsx)(`span`,{children:t.label})]},t.id)})})]})]})}function uB({spec:e,pageAction:t}){let{l3Items:n,streamControls:r}=lM(),i=FR(e),a=(0,U.useMemo)(()=>Rz(n),[n]),o=IR();return i.length===0&&a.length===0&&!r&&!t?null:(0,W.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[r&&(0,W.jsx)(`div`,{className:`pb-3 border-b border-border/50`,children:(0,W.jsx)(lB,{streamControls:r})}),i.length>0&&(0,W.jsx)(RR,{entries:i,activeId:o}),a.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-col`,children:[(0,W.jsx)(`div`,{className:`px-2 pb-1 pt-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,W.jsx)(RR,{entries:a,activeId:o})]}),t&&(0,W.jsx)(`div`,{className:`pt-2 border-t border-border/50`,children:t})]})}var dB=1023;function fB(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function pB(e,t){if(e===`query:new`)return``;let n=e=>{let n=`/${e}`;for(let r of Object.keys(t))if(r===e||r.endsWith(n))return r;return null},r=e=>{let r=n(e);return r===null?null:ox(t[r])};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i=e;if(e.startsWith(`wods/examples/`))i=`markdown/canvas/`+e.replace(/^wods\/examples\//,``);else if(e.startsWith(`wods/`))i=`markdown/canvas/`+e.replace(/^wods\//,``);else if(e.startsWith(`collections/`))i=`markdown/collections/`+e.replace(/^collections\//,``);else if(e.startsWith(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;let n=r(`markdown/collections/`+e);if(n!==null)return n;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function mB(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function hB(e){let t=new Map,n=null;for(let r of e)mB(r)&&(n=r),t.set(r.id,n);return t}function gB(){let[e,t]=(0,U.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${dB}px)`).matches);return(0,U.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${dB}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var _B=`wodwiki:fabAlignment`,vB=[{id:`left`,label:`Bottom left`,description:`Left-handed — search and page actions float near your left thumb`},{id:`right`,label:`Bottom right`,description:`Right-handed — search and page actions float near your right thumb`}];function yB(){try{return bB(localStorage.getItem(_B))}catch{return}}function bB(e){return e===`right`||e===`left`?e:void 0}var xB=typeof window>`u`?void 0:yB();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===_B&&(xB=bB(e.newValue))});function SB(e){xB=e;try{e===`right`?localStorage.removeItem(_B):localStorage.setItem(_B,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:_B,newValue:e}))}function CB(){let[e,t]=(0,U.useState)(()=>xB??`right`);return(0,U.useEffect)(()=>{let e=e=>{e.key===_B&&t(bB(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,SB]}function wB({onOpen:e}){return(0,W.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,"data-testid":`search-fab`,className:G(`size-14 rounded-full flex items-center justify-center`,`bg-primary text-primary-foreground shadow-lg`,`hover:bg-primary/90 active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:(0,W.jsx)(en,{className:`size-6`})})}var TB=(0,U.createContext)(null),EB=(0,U.createContext)(!1),DB=(0,U.createContext)(null);function OB(){return(0,U.useContext)(TB)!==null}function kB({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,U.useContext)(TB),o=(0,U.useContext)(EB),s=gB(),c=(0,U.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=(0,W.jsx)(EB.Provider,{value:!0,children:n});return(0,U.useEffect)(()=>{if(!(!l&&!u))return a.register({id:c,primary:e,navbar:t,children:d,label:r??`Page options`,fallback:i}),()=>a.unregister(c)},[l,u,a,c,e,d,r,i]),i||a&&s&&!o?null:(0,W.jsx)(EB.Provider,{value:!0,children:(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function AB({onSearch:e,children:t}){let[n,r]=(0,U.useState)([]),i=(0,U.useCallback)(e=>r(t=>[...t.filter(t=>t.id!==e.id),e]),[]),a=(0,U.useCallback)(e=>r(t=>t.filter(t=>t.id!==e)),[]),o=(0,U.useMemo)(()=>({register:i,unregister:a}),[i,a]),s=(0,U.useMemo)(()=>{for(let e=n.length-1;e>=0;--e)if(!n[e].fallback)return n[e].navbar??null;return null},[n]);return(0,W.jsx)(TB.Provider,{value:o,children:(0,W.jsxs)(DB.Provider,{value:s,children:[t,(0,W.jsx)(MB,{registrations:n,onSearch:e})]})})}function jB(){let e=(0,U.useContext)(DB);return e?(0,W.jsx)(W.Fragment,{children:e}):null}function MB({registrations:e,onSearch:t}){let n=gB(),[r]=CB(),i=BS(),[a,o]=(0,U.useState)(!1),s=(0,U.useRef)(null),c=Xt(),[l,u]=(0,U.useState)(!1),d=(0,U.useRef)(0),f=i.offsetBottom>0,p=(0,U.useRef)(null),m=(0,U.useRef)(null),h=(0,U.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),g=(0,U.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]);(0,U.useEffect)(()=>{o(!1),u(!1),d.current=window.scrollY},[c.pathname]),(0,U.useEffect)(()=>{if(!n)return;let e=()=>{let e=window.scrollY;if(e<=0||f||a){d.current=e,u(!1);return}let t=e-d.current;Math.abs(t)<8||(d.current=e,u(t>0))};return window.addEventListener(`scroll`,e,{passive:!0}),()=>window.removeEventListener(`scroll`,e)},[n,f,a]),(0,U.useLayoutEffect)(()=>{a&&s.current?.focus()},[a]);let[_,v]=(0,U.useState)({active:0,global:0});(0,U.useLayoutEffect)(()=>{let e=p.current?.childElementCount??0,t=m.current?.childElementCount??0;v(n=>n.active===e&&n.global===t?n:{active:e,global:t})},[h,g]);let y=_.active>0||_.global>0;return!n||!t&&!h&&!g?null:(0,W.jsxs)(`div`,{"data-testid":`actions-dock`,className:G(`lg:hidden fixed z-40 flex flex-col items-center gap-2`,`transition-[transform,visibility] duration-200 ease-out`,r===`left`?`left-4 items-start`:`right-4 items-end`,l&&!a&&!f&&`translate-y-[calc(100%+2rem)] invisible pointer-events-none`),style:{bottom:`calc(1rem + var(--thumb-dock-lift, 0px) + ${i.offsetBottom}px + env(safe-area-inset-bottom))`},children:[(0,W.jsxs)(`div`,{className:`relative z-40 flex flex-col items-center gap-2`,children:[h?.primary&&(0,W.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:h.primary}),t&&(0,W.jsx)(wB,{onOpen:()=>{o(!1),t()}})]}),a&&y&&(0,W.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 cursor-default`,onClick:()=>o(!1)}),(0,W.jsxs)(`div`,{ref:s,role:`dialog`,"aria-label":h?.label??g?.label??`Page options`,tabIndex:-1,hidden:!a||!y,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),o(!1))},className:G(`relative z-40 flex w-60 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/5 outline-none`,`[&_button]:min-h-11 [&_button]:min-w-11`),style:{maxHeight:`calc(${i.height===null?`100dvh`:`${i.height}px`} - 6rem - env(safe-area-inset-bottom))`},children:[(0,W.jsx)(`div`,{ref:p,className:`contents`,children:h?.children}),_.active>0&&_.global>0&&(0,W.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,W.jsx)(`div`,{ref:m,className:`contents`,children:g?.children})]}),y&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-label":h?.label??g?.label??`Page options`,"aria-expanded":a,"data-testid":`actions-overflow`,className:G(`relative z-40 flex size-12 items-center justify-center rounded-full`,`bg-card text-foreground shadow-lg ring-1 ring-foreground/10`,`hover:bg-muted active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:a?(0,W.jsx)(Le,{className:`size-6`}):(0,W.jsx)(he,{className:`size-6`})})]})}function NB(){return(0,W.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,W.jsx)(`path`,{d:`M2 6.75C2 6.33579 2.33579 6 2.75 6H17.25C17.6642 6 18 6.33579 18 6.75C18 7.16421 17.6642 7.5 17.25 7.5H2.75C2.33579 7.5 2 7.16421 2 6.75ZM2 13.25C2 12.8358 2.33579 12.5 2.75 12.5H17.25C17.6642 12.5 18 12.8358 18 13.25C18 13.6642 17.6642 14 17.25 14H2.75C2.33579 14 2 13.6642 2 13.25Z`})})}function PB(){return(0,W.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,W.jsx)(`path`,{d:`M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z`})})}function FB(){let{tree:e,navState:t,contextNav:n}=lM(),r=Xt(),i=KN();return!e.find(e=>e.id===t.activeL1Id)?.applyFooter||n?.pathname===r.pathname?null:(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,W.jsx)(`button`,{type:`button`,onClick:i,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})}function IB({open:e,close:t,onSearch:n,onCreate:r,children:i}){return(0,W.jsxs)(F,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,W.jsx)(d,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,W.jsx)(Xe,{transition:!0,className:`fixed inset-y-0 left-0 w-full transition duration-300 ease-out data-closed:-translate-x-full`,children:(0,W.jsx)(GN,{close:t,children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,W.jsx)(`div`,{className:`flex h-full w-14 shrink-0 flex-col items-center border-r border-zinc-950/5 bg-background/72 py-3 dark:border-white/5 [&_a]:size-11 [&_button]:size-11`,children:(0,W.jsx)(qR,{onSearch:()=>{t(),n?.()},onCreate:r?()=>{t(),r()}:void 0})}),(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,W.jsx)(`div`,{className:`flex items-center px-4 pt-3`,children:(0,W.jsx)(ie,{as:HI,"aria-label":`Close navigation`,children:(0,W.jsx)(PB,{})})}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i}),(0,W.jsx)(FB,{})]})]})})})]})}function LB({open:e,close:t,children:n}){return(0,W.jsxs)(F,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,W.jsx)(d,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,W.jsx)(Xe,{transition:!0,className:`fixed inset-y-0 right-0 w-full transition duration-300 ease-out data-closed:translate-x-full`,children:(0,W.jsx)(GN,{close:t,children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-card`,children:[(0,W.jsx)(`div`,{className:`flex items-center justify-end px-4 pt-3`,children:(0,W.jsx)(ie,{as:HI,"aria-label":`Close page options`,children:(0,W.jsx)(PB,{})})}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:n}),(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,W.jsx)(`button`,{type:`button`,onClick:t,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})]})})})]})}function RB({navbar:e,sidebar:t,onSearch:n,onCreate:r,secondary:i,pageAction:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,U.useState)(!1),[u,d]=(0,U.useState)(!1),f=(0,U.useRef)(null),[p,m]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>m(t=>{let n=e.childElementCount>0;return t===n?t:n}),n=new MutationObserver(t);return n.observe(e,{childList:!0,subtree:!0}),t(),()=>n.disconnect()},[]);let{streamControls:h}=lM(),g=(0,U.useMemo)(()=>{let e=X(h?.query??``);return!e.error&&bm(e)&&e.filters.length>0},[h?.query]);return(0,W.jsx)(Pz,{children:(0,W.jsx)(AB,{onSearch:n,children:(0,W.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,W.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,W.jsxs)(`nav`,{"aria-label":`Main`,className:`hidden lg:flex`,children:[(0,W.jsx)(`div`,{className:`w-14 shrink-0 sticky top-0 h-svh flex flex-col items-center border-r border-zinc-950/5 dark:border-white/5 bg-background/72 backdrop-blur-sm z-40 py-3`,children:(0,W.jsx)(qR,{onSearch:n??(()=>{}),onCreate:r})}),(0,W.jsx)(`div`,{className:G(`w-60 shrink-0 sticky top-0 self-start h-svh min-h-0 overflow-hidden border-r border-zinc-950/5 dark:border-white/5 bg-background/72 backdrop-blur-sm flex flex-col`,o&&`lg:hidden`),children:t})]}),(0,W.jsx)(IB,{open:c,close:()=>l(!1),onSearch:n,onCreate:r,children:t}),(0,W.jsxs)(`div`,{className:`flex flex-1 flex-col min-w-0 xl:max-w-[984px] 2xl:max-w-none`,children:[(0,W.jsxs)(`header`,{"data-page-sticky-boundary":`true`,className:`lg:hidden sticky top-0 z-20 flex items-center px-2 sm:px-4 bg-card`,children:[(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsx)(HI,{onClick:()=>l(!0),"aria-label":`Open navigation`,children:(0,W.jsx)(NB,{})})}),(0,W.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),r&&(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsx)(HI,{onClick:r,"aria-label":`New journal note`,children:(0,W.jsx)(Dn,{className:`size-5`})})}),p&&(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsx)(HI,{onClick:()=>d(!0),"aria-label":`Open page options`,children:(0,W.jsxs)(`span`,{className:`relative inline-flex`,children:[(0,W.jsx)(_n,{className:`size-5`}),g&&(0,W.jsx)(`span`,{"data-testid":`drawer-filters-active`,className:`absolute -top-1 -right-1 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`})]})})})]}),(0,W.jsxs)(`main`,{className:`flex flex-1 flex-col lg:min-w-0`,children:[(0,W.jsx)(`div`,{className:`grow w-full max-lg:pb-48 lg:overflow-visible`,children:s}),(0,W.jsx)(zB,{})]})]}),(0,W.jsx)(`aside`,{className:`hidden 2xl:flex w-60 shrink-0 sticky top-0 h-svh flex-col overflow-y-auto bg-background/72 backdrop-blur-sm`,children:(0,W.jsx)(`div`,{ref:f,className:`contents`,children:(0,W.jsx)(uB,{spec:i,pageAction:a})})}),(0,W.jsx)(LB,{open:u,close:()=>d(!1),children:(0,W.jsx)(uB,{spec:i,pageAction:a})})]})})})})}function zB(){let e=(0,U.useRef)(null),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=e.current;if(!t)return;let r=new ResizeObserver(e=>{let t=Math.round(e[0]?.contentRect.height??0);n(e=>e===t?e:t)});r.observe(t,{box:`content-box`});let i=Math.round(t.getBoundingClientRect().height);return n(e=>e===i?e:i),()=>r.disconnect()},[]),(0,U.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${t}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[t]),(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:G(`lg:hidden fixed inset-x-0 bottom-0 z-30`,t>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,W.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,W.jsx)(Fz,{className:`flex w-full min-w-0`})})}),(0,W.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:t}})]})}function BB(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function VB(e){return String(sx(tx(e).meta,`search`)??``).toLowerCase()===`hidden`}function HB(e){let t=sx(tx(e).meta,`date`);if(typeof t!=`string`||!/^\d{4}-\d{2}-\d{2}$/.test(t))return;let n=new Date(`${t}T12:00:00Z`);return Number.isFinite(n.getTime())&&n.toISOString().slice(0,10)===t?n.getTime():void 0}function UB(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=sx(tx(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():CD(r),category:BB(n),content:i,date:HB(i),searchHidden:VB(i)}})}function WB(){let e=GD();return(0,U.useMemo)(()=>e?UB(e):[],[e])}var GB={};function KB(e){if(!(`payload`in e))return;let t=e.payload;if(!t||typeof t!=`object`)return;let n=t;return n.targetDate??n.updatedAt}function qB(e,t){let{canvasPage:n,workoutItems:r,recentResults:i,selectWorkout:a}=t;if(n){let t=/^\/(?:c|collections)\//.test(e),i=t?e.split(`/`).pop()??null:null;if(e===`/`)return[];let o=[],s=e.startsWith(`/guide/`);return n.sections.filter(e=>e.level>1).forEach(e=>{if(o.push({id:e.id,label:e.heading,type:`heading`}),!s){let t=uI(e).split(`
101
+ `),n=0;t.forEach((t,r)=>{let i=t.trim().match(/^```(time|log)(:\w+)?\s*$/);if(i){let t=i[1];n++,o.push({id:`${e.id}-${t}-${r+1}`,label:`Workout ${n}`,type:t})}})}}),t&&i&&(o.push({id:`collection-workouts`,label:`Explore`,type:`heading`}),r.filter(e=>e.category===i&&e.name.toLowerCase()!==`readme`).forEach(e=>{o.push({id:`workout-${e.id}`,label:e.name,type:`time`,onRun:()=>a(e),runIcon:`link`})})),o}if(e===`/journal`){let e=new Set;return i.forEach(t=>{let n=new Date(t.createdAt).getTime();Number.isFinite(n)&&e.add(PN(new Date(n)))}),r.forEach(t=>{let n=KB(t);n&&Number.isFinite(new Date(n).getTime())&&e.add(PN(new Date(n)))}),Array.from(e).sort().reverse().slice(0,10).map(e=>({id:e,label:VO(new Date(e+`T00:00:00`)),type:`heading`}))}return[]}var JB=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function YB(e){return JB.test(e)}function XB(e){try{return decodeURIComponent(e)}catch{return null}}function ZB(e){if(!LN(e))return!1;let t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return!1;let n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return n.getUTCFullYear()===Number(t[1])&&n.getUTCMonth()===Number(t[2])-1&&n.getUTCDate()===Number(t[3])}function QB(e){let t=e.length>1?e.replace(/\/+$/,``):e;if(t===`/journal`)return{kind:`index`};if(!t.startsWith(`/journal/`))return{kind:`invalid`};let n=t.slice(9).split(`/`).map(XB);if(n.some(e=>e==null))return{kind:`invalid`};let r=n;if(r.length===1){let e=r[0];return ZB(e)?{kind:`date`,journalDate:e}:JB.test(e)?{kind:`uuid-alias`,noteId:e}:e?{kind:`slug-alias`,slug:e}:{kind:`invalid`}}if(r.length===2){let[e,t]=r;if(ZB(e)&&JB.test(t))return{kind:`note`,journalDate:e,noteId:t}}return{kind:`invalid`}}var $B=`# My Workout Notebook
102
+
103
+ Welcome to the **WOD.WIKI** playground.
104
+ This editor uses **Whiteboard Script**, a markdown-based language for defining workouts.
105
+
106
+ ## Getting Started
107
+ 1. Hover over a code block below.
108
+ 2. Click **Run** to start the interactive timer.
109
+ 3. Track your progress with checkboxes and metrics.
110
+
111
+ ## Example Workout
112
+ \`\`\`time
113
+ Timer 12:00
114
+ - 10 Pushups
115
+ - 10 Situps
116
+ - 10 Squats
117
+ - [ ] 200m Run { intensity: 80% }
118
+ \`\`\`
119
+
120
+ ## Advanced: Repeaters
121
+ \`\`\`time
122
+ 3x
123
+ - 10 Kettlebell Swings (24kg)
124
+ - 5 Burpees
125
+ - 30s Rest
126
+ \`\`\`
127
+ `;function eV(e,t){let{name:n,id:r}=t,i=iN(e),a=r||(e.startsWith(`/note/playground/`)?n:void 0),o=QB(e),s=![`index`,`invalid`].includes(o.kind),c=o.kind===`date`?o.journalDate:o.kind===`note`||o.kind===`uuid-alias`?o.noteId:o.kind===`slug-alias`?o.slug:void 0,l=sN(e),u=l?null:cN(e),d=e.match(/^\/(?:notes|note)\/([^/]+)$/),f=d!=null,p=d?decodeURIComponent(d[1]):void 0,m=null,h=e.match(/^\/(?:c|collections)\/([^/]+)\/([^/]+)$/);if(h){let e=decodeURIComponent(h[1]),t=decodeURIComponent(h[2]);if(YB(t)){if(!f)return{isPlaygroundRoute:i,effectivePlaygroundId:a,isJournalEntryRoute:s,journalEntryId:c,isNoteByIdRoute:!0,noteById:t,collectionDate:null,feedItemMatch:l,feedDetailMatch:u}}else{let n=LN(t);n&&(m={slug:e,date:n.dateKey})}}return{isPlaygroundRoute:i,effectivePlaygroundId:a,isJournalEntryRoute:s,journalEntryId:c,isNoteByIdRoute:f,noteById:p,collectionDate:m,feedItemMatch:l,feedDetailMatch:u}}function tV(e,t,n,r,i){let{category:a,name:o,collection:s,workout:c}=n;if(e.isPlaygroundRoute)return{name:`Playground`,content:``,category:`playground`};if(e.isNoteByIdRoute&&e.noteById)return{name:`Note`,content:``,category:`note`};if(e.collectionDate)return{name:e.collectionDate.date,content:``,category:e.collectionDate.slug};if(e.isJournalEntryRoute&&e.journalEntryId)return{name:e.journalEntryId,content:``,category:`journal`};if(t.startsWith(`/effort/`)||t.startsWith(`/e/`)){let e=t.startsWith(`/e/`)?`/e/`:`/effort/`;return{name:decodeURIComponent(t.slice(e.length).split(`/`)[0]??`Effort`),content:``,category:`effort`}}if(t.startsWith(`/equipment/`))return{name:decodeURIComponent(t.slice(11).split(`/`)[0]??`Equipment`),content:``,category:`equipment`};if(e.feedItemMatch)return{name:decodeURIComponent(e.feedItemMatch[2]),content:``,category:`feed`};if(e.feedDetailMatch)return{name:decodeURIComponent(e.feedDetailMatch),content:``,category:`feed`};if(xM(t)===`/tags`)return{name:`Tags`,content:``,category:`tags`};if(t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)){let e=t.startsWith(`/d/`)?t.slice(3):t.split(`/`)[2];return{name:decodeURIComponent(e??`Dashboard`),content:``,category:`dashboard`}}if(t.startsWith(`/session/`))return{name:decodeURIComponent(t.split(`/`)[2]??`Sessions`),content:``,category:`sessions`};if(i)return{name:i.sections[0]?.heading??`Canvas`,content:``,category:`canvas`};let l={"/":`Home`,"/results":`Results`,"/results/segments":`Segments`,"/dashboard":`Dashboards`,"/dashboards":`Dashboards`,"/analytics/dashboard":`Analytics Dashboard`,"/analytics/explorer":`Metric Explorer`},u=xM(t),d=IM(u)??l[t]??l[u];if(d)return{name:d,content:``,category:`General`};if(u.startsWith(`/results/`))return{name:`Result`,content:$B,category:`Results`};if(u===`/settings`||u.startsWith(`/settings/`))return{name:`Settings`,content:$B,category:`Settings`};let f=c||o;if(!f)return{name:`Home`,content:$B,category:`General`};let p=decodeURIComponent(f),m=s||a?decodeURIComponent(s||a):`General`,h=r.find(e=>e.name===p&&e.category===m);return h?{name:h.name,content:h.content,category:h.category}:{name:p,content:$B,category:m}}function nV(e,t,n){let r=xM(t);return LM(r)?`library`:e.feedDetailMatch?`feedDetail`:e.feedItemMatch?`feedItem`:t.startsWith(`/effort/`)||t.startsWith(`/e/`)?`effortDetail`:t.startsWith(`/equipment/`)?`equipmentDetail`:t===`/analytics/explorer`?`analyticsExplorer`:t===`/dashboard`||t===`/dashboards`?`dashboardExplorer`:t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)?`dashboardView`:r===`/settings`||r.startsWith(`/settings/`)?`settings`:r===`/tags`?`tags`:n?`canvas`:e.isPlaygroundRoute&&e.effectivePlaygroundId?`playground`:e.isNoteByIdRoute&&e.noteById?`note`:e.collectionDate?`collectionDate`:e.isJournalEntryRoute&&e.journalEntryId?`journalEntry`:`workout`}function rV(e,t,n){switch(e){case`canvas`:return{wrap:`canvas`,title:n.name,subheader:/^\/(?:c|collections)\//.test(t)?`filter-collection-workouts`:void 0,actionsMode:`collection-readonly`,withIndex:!0};default:return{wrap:`bare`}}}function iV(e,t,n){let r=eV(e,t);if(!n.canvasPage&&!r.noteById){let t=e.match(/^\/p\/([^/]+)$/);t&&(r.isNoteByIdRoute=!0,r.noteById=decodeURIComponent(t[1]))}let i=tV(r,e,t,n.workoutItems,n.canvasPage),a=qB(e,n),o=nV(r,e,n.canvasPage),s=rV(o,e,i);return{...r,canvasPage:n.canvasPage,workout:i,nav:a,page:o,shell:s}}function aV(e=20){let[t,n]=(0,U.useState)([]),{pathname:r}=Xt(),i=(0,U.useCallback)(()=>{Z.getRecentSessions(e).then(n).catch(()=>{})},[e]);return(0,U.useEffect)(()=>{i()},[r,i]),t}function oV(){let e=ht();return(0,U.useCallback)(t=>{t.name===`Home`?e($.home):e(GM(t.category??`General`,t.name))},[e])}function sV(){let e=xn(),{pathname:t}=Xt(),n=WB(),r=BI(t),i=aV(),a=oV();return(0,U.useMemo)(()=>iV(t,e,{workoutItems:n,canvasPage:r,recentResults:i,selectWorkout:a}),[t,e,n,r,i,a])}function cV(e,t,n,r){let i=e===`upload`?`Uploading`:`Downloading`,a=n??`data`,o=r?.chunkId?` - ${r.chunkId} (${r.phase})`:``;return t>1?`${i} ${a} (${t} syncs)${o}`:`${i} ${a}${o}`}function lV(){let e=(0,U.useSyncExternalStore)(Vb,Bb);return e.uploading===0&&e.downloading===0?null:(0,W.jsxs)(`div`,{role:`status`,"data-testid":`sync-activity-indicators`,className:`flex items-center gap-1 text-muted-foreground`,children:[e.downloading>0&&(0,W.jsxs)(`span`,{className:`flex items-center gap-1`,"aria-label":cV(`download`,e.downloading,e.label,e.activeProgress),title:cV(`download`,e.downloading,e.label,e.activeProgress),children:[(0,W.jsx)(A,{className:`size-3.5 motion-safe:animate-spin`,"aria-hidden":`true`}),e.downloading>1&&(0,W.jsx)(`span`,{className:`text-[10px] tabular-nums`,children:e.downloading})]}),e.uploading>0&&(0,W.jsxs)(`span`,{className:`flex items-center gap-1`,"aria-label":cV(`upload`,e.uploading,e.label),title:cV(`upload`,e.uploading,e.label),children:[(0,W.jsx)(vr,{className:`size-3.5 motion-safe:animate-spin`,"aria-hidden":`true`}),e.uploading>1&&(0,W.jsx)(`span`,{className:`text-[10px] tabular-nums`,children:e.uploading})]}),e.activeProgress&&(0,W.jsxs)(`span`,{"data-testid":`sync-granular-progress`,className:`text-[11px] font-mono text-muted-foreground truncate max-w-[160px] hidden sm:inline`,title:`${e.activeProgress.sourceLabel}: ${e.activeProgress.phase} ${e.activeProgress.chunkId??``}`,children:[e.activeProgress.chunkId,e.activeProgress.totalRecords!==void 0&&e.activeProgress.completedRecords!==void 0&&` (${e.activeProgress.completedRecords+1}/${e.activeProgress.totalRecords})`]})]})}var uV=0,dV=null,fV=0;function pV(e,t){let n=[];e.added>0&&n.push(`${e.added.toLocaleString()} new ${e.added===1?`record`:`records`}`),e.updated>0&&n.push(`${e.updated.toLocaleString()} updated`),Q({title:`${e.source} sync complete`,description:n.length>0?`${n.join(`, `)} — feeds can be refreshed anytime.`:`Nothing new — feeds can be refreshed anytime.`,action:(0,W.jsx)(Uj,{altText:`Open notebooks`,onClick:()=>t(`/catalogs`),children:`Open notebooks`})})}function mV(){let e=ht();return(0,U.useEffect)(()=>{let t=()=>{let t=hj();!t||t.id<=fV||(fV=t.id,t.updates.length&&Q({title:`Notebook updates`,description:t.updates.map(e=>`${e.label}: ${e.state===`updated`?`updated`:e.state===`error`?`sync failed`:`update available`}`).join(`; `),action:(0,W.jsx)(Uj,{altText:`Manage notebook updates`,onClick:()=>e(`${$.catalogs}?manage=1`),children:`Review updates`})}))};return t(),gj(t)},[e]),(0,U.useEffect)(()=>{let t=t=>{if(t.error||(dV=null),t.result&&t.result.id>uV&&(uV=t.result.id,pV(t.result,e)),t.error&&t.error!==dV){dV=t.error;let n=t.error.toLowerCase(),r=/turso|database|token|libsql/.test(n)?$.settingsStorage:/seed|feed|source|manifest|chunk/.test(n)?$.settingsSync:$.settings;Q({title:`Sync failed`,description:t.error,variant:`destructive`,action:(0,W.jsx)(Uj,{altText:`Open settings`,onClick:()=>e(r),children:`Settings`})})}};return t(Bb()),Vb(()=>t(Bb()))},[e]),null}var hV=t({usePaletteStore:()=>gV}),gV=Lt((e,t)=>({isOpen:!1,request:null,_resolve:null,open(n){let{_resolve:r}=t();return r&&e({_resolve:null}),new Promise(t=>{e({isOpen:!0,request:n,_resolve:t})})},_select(n){let{_resolve:r}=t();e({_resolve:null}),r?.({dismissed:!1,item:n}),setTimeout(()=>{t()._resolve||e({isOpen:!1,request:null})},0)},_dismiss(){let{_resolve:n}=t();e({isOpen:!1,request:null,_resolve:null}),n?.({dismissed:!0})}}));function _V(e,t){if(!t)return!0;let n=t.toLowerCase();return!!(e.label.toLowerCase().includes(n)||e.subtitle?.toLowerCase().includes(n)||e.keywords?.some(e=>e.toLowerCase().includes(n)))}function vV(e){let{items:t,defaultActiveId:n,multi:r=!1,onSelect:i}=e,[a,o]=(0,U.useState)(n??null),[s,c]=(0,U.useState)(new Set),[l,u]=(0,U.useState)(``),d=(0,U.useRef)(null);(0,U.useEffect)(()=>{n!==void 0&&o(n)},[n]);let f=(0,U.useMemo)(()=>l?t.filter(e=>_V(e,l)):t,[t,l]),p=(0,U.useMemo)(()=>{let e=new Map;for(let t of f){let n=t.group??``;e.has(n)||e.set(n,[]),e.get(n).push(t)}return e},[f]),m=(0,U.useCallback)((e,t)=>{c(n=>{let i=new Set(n);if(r&&t?.shift&&d.current){let t=f.findIndex(e=>e.id===d.current),n=f.findIndex(t=>t.id===e);if(t!==-1&&n!==-1){let[e,r]=t<n?[t,n]:[n,t];f.slice(e,r+1).forEach(e=>i.add(e.id))}}else r&&t?.ctrl?i.has(e)?i.delete(e):i.add(e):(i.clear(),i.add(e));return i}),d.current=e},[r,f]),h=(0,U.useCallback)(()=>{c(new Set),d.current=null},[]),g=(0,U.useCallback)(e=>{o(e.id),m(e.id),i?.(e)},[i,m]);return{visibleItems:f,groups:p,activeId:a,setActiveId:o,selectedIds:s,toggleSelected:m,clearSelection:h,query:l,setQuery:u,onKeyDown:(0,U.useCallback)(e=>{if(!f.length)return;let t=f.findIndex(e=>e.id===a);if(e.key===`ArrowDown`){e.preventDefault();let n=f[Math.min(t+1,f.length-1)];o(n.id)}else if(e.key===`ArrowUp`){e.preventDefault();let n=f[Math.max(t-1,0)];o(n.id)}else if(e.key===`Enter`){e.preventDefault();let t=f.find(e=>e.id===a);t&&g(t)}else e.key===`Escape`&&h()},[f,a,g,h]),selectItem:g}}function yV(e){return e===`meta`?`⌘`:e===`shift`?`⇧`:e===`alt`?`⌥`:e}function bV({tokens:e,delimiter:t}){return(0,W.jsx)(`span`,{className:`flex items-center gap-0.5 ml-auto shrink-0`,children:e.map((e,n)=>(0,W.jsxs)(`span`,{className:`contents`,children:[n>0&&t?(0,W.jsx)(`span`,{"aria-hidden":`true`,className:`px-0.5 text-[10px] font-mono text-zinc-400 dark:text-zinc-500`,children:t}):null,(0,W.jsx)(`kbd`,{className:`inline-flex items-center rounded border border-zinc-300 bg-zinc-100 px-1 py-0.5 text-[10px] font-mono text-zinc-500 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,children:yV(e)})]},`shortcut-${n}-${e}`))})}function xV({item:e,ctx:t}){let n=t.actions.find(e=>e.isPrimary),r=t.actions.filter(e=>!e.isPrimary);return(0,W.jsxs)(`div`,{role:`option`,"aria-selected":t.isSelected,className:G(`flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer select-none`,`text-sm transition-colors`,t.isActive||t.isSelected?`bg-primary/10 text-primary`:`hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-700 dark:text-zinc-300`,e.isDisabled&&`opacity-40 pointer-events-none`,e.depth&&e.depth>0?`pl-${Math.min(e.depth*4+3,16)}`:``),onClick:e.isDisabled?void 0:t.onSelect,children:[e.icon&&(0,W.jsx)(`span`,{className:`shrink-0 text-zinc-400 dark:text-zinc-500 w-4 h-4 flex items-center justify-center`,children:e.icon}),(0,W.jsxs)(`span`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,W.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:e.label}),e.subtitle&&(0,W.jsx)(`span`,{className:`truncate text-xs text-zinc-500 dark:text-zinc-400 leading-tight mt-0.5`,children:e.subtitle})]}),e.badge!==void 0&&(0,W.jsx)(`span`,{className:`shrink-0 rounded-full bg-zinc-200 dark:bg-zinc-700 px-1.5 py-0.5 text-[10px] font-medium text-zinc-600 dark:text-zinc-300`,children:e.badge}),e.shortcut&&e.shortcut.length>0&&(0,W.jsx)(bV,{tokens:e.shortcut}),r.length>0&&(0,W.jsx)(`span`,{className:`flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-1`,children:r.map(e=>(0,W.jsx)(`button`,{title:e.label,className:`rounded p-0.5 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-400 hover:text-zinc-600`,onClick:n=>{n.stopPropagation(),t.executeAction(e.action)},children:e.icon??e.label},e.id))}),n&&(0,W.jsx)(`button`,{title:n.label,className:`shrink-0 rounded px-2 py-1 text-xs bg-primary text-primary-foreground hover:bg-primary/90 transition-colors`,onClick:e=>{e.stopPropagation(),t.executeAction(n.action)},children:n.icon??n.label})]})}function SV({items:e,query:t,onQueryChange:n,onSelect:r,isOpen:i,onClose:a,header:o,searchRow:s,footer:c,filterResults:l=!0,placeholder:u=`Search…`,actions:d,renderItem:f,mobileClose:p,emptyState:m,className:h}){let g=(0,U.useRef)(null),_=(0,U.useRef)(null),v=ht(),[y,b]=zn(),x=(0,U.useMemo)(()=>({navigate:(e,t)=>v(e,t),setQueryParam:(e,t)=>{let n=new URLSearchParams(y);Object.entries(e).forEach(([e,t])=>{t===null?n.delete(e):n.set(e,t)}),b(n,{replace:t})}}),[v,y,b]),S=(0,U.useCallback)(e=>eF(e,x),[x]),C=(0,U.useCallback)(e=>{let t=[...e.actions??[],...d?.(e)??[]].find(e=>e.isPrimary);t?S(t.action):r(e)},[d,r,S]),w=vV({items:e,onSelect:C});return(0,U.useEffect)(()=>{i&&!s&&setTimeout(()=>g.current?.focus(),0)},[i,s]),(0,U.useEffect)(()=>{w.setQuery(l?t:``)},[t,l]),(0,U.useEffect)(()=>{if(w.activeId){for(let e of _.current?.querySelectorAll(`[data-item-id]`)??[])if(e.dataset.itemId===w.activeId){e.scrollIntoView?.({block:`nearest`});break}}},[w.activeId]),i?(0,W.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:G(`flex flex-col overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-700 dark:bg-zinc-900`,h),onKeyDown:e=>{e.key===`Escape`&&a()},children:[(0,W.jsx)(`div`,{onKeyDown:e=>{if(e.key===`Escape`){a();return}if(e.key===`Enter`&&!e.defaultPrevented&&w.visibleItems.length>0){e.preventDefault();let t=w.visibleItems.find(e=>e.id===w.activeId)??w.visibleItems[0];C(t);return}e.key===`ArrowDown`&&!e.defaultPrevented&&w.visibleItems.length>0&&(e.preventDefault(),w.setActiveId(w.visibleItems[0].id),_.current?.focus())},children:s??(0,W.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 dark:border-zinc-700`,children:[(0,W.jsx)(Tt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,W.jsx)(`input`,{ref:g,type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:u,"data-testid":`palette-search-input`,className:`flex-1 bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground`}),p&&(0,W.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close`,"data-testid":`palette-cancel`,className:`-mr-1 rounded-md p-1.5 text-muted-foreground hover:text-foreground sm:hidden`,children:(0,W.jsx)(we,{className:`h-4 w-4`})}),(0,W.jsx)(`kbd`,{className:`hidden rounded border border-zinc-200 px-1.5 py-0.5 text-[10px] text-zinc-400 sm:inline dark:border-zinc-600`,children:`esc`})]})}),o,(0,W.jsx)(`div`,{ref:_,role:`listbox`,"aria-label":`Results`,"aria-activedescendant":w.activeId??void 0,tabIndex:-1,onKeyDown:e=>{if(e.key===`Escape`){a();return}w.onKeyDown(e)},className:`min-h-0 flex-1 overflow-y-auto p-1 outline-none`,children:w.visibleItems.length===0?m??(t?(0,W.jsxs)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:[`No results found for`,` `,(0,W.jsxs)(`span`,{className:`font-medium text-zinc-600 dark:text-zinc-300`,children:[`“`,t,`”`]})]}):(0,W.jsx)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`No results`})):Array.from(w.groups.entries()).map(([e,t])=>(0,W.jsxs)(`div`,{className:`mb-1`,children:[e&&(0,W.jsx)(`div`,{className:`px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500`,children:e}),t.map(e=>{let t=[...e.actions??[],...d?.(e)??[]],n={isSelected:w.selectedIds.has(e.id),isActive:w.activeId===e.id,depth:e.depth??0,actions:t,onSelect:()=>w.selectItem(e),executeAction:S};return(0,W.jsx)(`div`,{id:e.id,"data-item-id":e.id,className:`group`,onMouseEnter:()=>w.setActiveId(e.id),children:f?f(e,n):(0,W.jsx)(xV,{item:e,ctx:n})},e.id)})]},e))}),c]}):null}var CV=150,wV=.66,TV=.92;function EV(){let[e,t]=(0,U.useState)(()=>typeof window>`u`||window.matchMedia(`(min-width: 1024px)`).matches);return(0,U.useEffect)(()=>{let e=window.matchMedia(`(min-width: 1024px)`),n=()=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function DV(e){let t=e.trim();return t?!X(t).error||t.startsWith(`:`)&&!/^:\w+\{text:[^}]*\}$/.test(t):!1}function OV(e){return{id:e.id,label:e.label,subtitle:e.sublabel,group:e.category,keywords:[e.label,e.category??``],payload:e}}var kV=()=>{let{isOpen:e,request:t,_select:n,_dismiss:r}=gV(),[i,a]=(0,U.useState)(``),o=(0,U.useRef)(``),s=(0,U.useRef)(),[c,l]=(0,U.useState)({valid:!0}),u=(0,U.useRef)(c),d=EV(),[f,p]=(0,U.useState)(),m=f?f===`wql`:DV(i),h=(0,U.useCallback)(e=>{o.current=e,a(e);let t=X(e);!t.error&&bm(t)&&(s.current=e)},[]),g=(0,U.useCallback)(e=>{u.current=e,l(e)},[]),[_,v]=(0,U.useState)([]),[y,b]=(0,U.useState)(!1),x=(0,U.useRef)(0),S=(0,U.useRef)(t),C=(0,U.useRef)(0);S.current!==t&&(S.current=t,C.current+=1);let w=ht();(0,U.useEffect)(()=>{if(!e)return;w(window.location.pathname+window.location.search+window.location.hash,{state:{...history.state?.usr??{},paletteClose:!0}});let t=()=>r();return window.addEventListener(`popstate`,t),()=>{window.removeEventListener(`popstate`,t),history.state?.usr?.paletteClose&&w(-1)}},[e,r,w]);let T=t?.wql,[E,D]=(0,U.useState)(!1),O=BS(),k=O.height?`${Math.round(O.height*wV)}px`:`66dvh`,A=O.height?`${Math.round(O.height*TV)}px`:`92dvh`;(0,U.useEffect)(()=>{if(e&&t){let e=t.wql?t.wql.initialQuery??``:t.initialQuery??``;o.current=e,a(e);let n=X(e);s.current=!n.error&&bm(n)?e:void 0;let r=t.wql?n.error:void 0,i=r?{valid:!1,error:r}:{valid:!0};u.current=i,l(i),p(void 0),v([]),b(!1),D(!1)}},[e,t]),(0,U.useEffect)(()=>{if(!e||!t)return;if(t.wql&&m&&!c.valid){x.current+=1,b(!1);return}let n=++x.current;b(!0);let r=setTimeout(()=>{(async()=>{try{let e=await Promise.all(t.sources.map(e=>Promise.resolve(s.current?e.search(i,{scopeWql:s.current}):e.search(i)).then(t=>t.map(t=>({...OV(t),group:t.category??e.label})))));if(n!==x.current)return;v(e.flat())}catch(e){console.error(`[PaletteShell] search error`,e),n===x.current&&v([])}finally{n===x.current&&b(!1)}})()},CV);return()=>clearTimeout(r)},[i,c.valid,m,e,t]);let j=(0,U.useCallback)(e=>{n(e.payload)},[n]),M=(0,U.useCallback)(e=>{if(!T?.onApply)return;let t=e??o.current;X(t).error||(T.onApply(t),r())},[T,r]),N=y?(0,W.jsx)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`Searching…`}):i?(0,W.jsxs)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:[`No results for `,(0,W.jsxs)(`span`,{className:`font-medium text-foreground/60`,children:[`“`,i,`”`]})]}):(0,W.jsx)(`div`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`Start typing to search`}),P=T?(0,W.jsxs)(`div`,{className:`border-b border-border/80 px-3 py-2`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsx)(`button`,{type:`button`,"data-testid":`palette-mode`,"aria-pressed":m,"aria-label":m?`WQL mode. Press to switch to Find`:`Find mode. Press to switch to WQL`,onClick:()=>p(m?`find`:`wql`),className:`mb-2 rounded-full border px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-wider transition-colors ${m?`border-primary/40 bg-primary/10 text-primary`:`border-border bg-muted text-muted-foreground hover:text-foreground`}`,children:m?`WQL`:`Find`}),T.settings&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`palette-settings`,"aria-expanded":E,"aria-label":T.settings.label??`Query settings`,onClick:()=>D(e=>!e),className:`mb-2 ml-auto grid size-7 place-items-center rounded-md border border-border/70 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,W.jsx)(_n,{className:`size-3.5`,"aria-hidden":`true`})})]}),(0,W.jsx)(`div`,{"data-testid":`palette-composer`,className:m?void 0:`[&_[role=alert]]:hidden [&_[data-testid=wql-composer-pending]]:hidden`,children:(0,W.jsx)(aw,{query:i,onQueryChange:h,onValidationChange:g,showDiagnostics:m&&(T.showDiagnostics??!0),execute:T.execute,preferredChoices:T.preferredChoices,customSlots:T.customSlots,diagnosticsPosition:`top`,onSubmit:T.onApply?M:void 0,autoFocus:d,placeholder:`Search or edit WQL…`},C.current)}),T.settings&&E&&(0,W.jsx)(`div`,{className:`mt-2 border-t border-border/80 pt-2`,"data-testid":`palette-settings-panel`,children:T.settings.panel})]}):void 0,F=T?(0,W.jsxs)(`div`,{className:`flex items-center gap-2 border-t border-border/80 px-3 pt-2`,style:{paddingBottom:`max(0.5rem, env(safe-area-inset-bottom))`},children:[m&&!c.valid&&(0,W.jsx)(`span`,{"data-testid":`palette-stale`,className:`text-[11px] font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400`,children:`Stale — fix the query`}),(0,W.jsx)(`div`,{className:`flex-1`}),(0,W.jsx)(`button`,{type:`button`,onClick:r,"data-testid":`palette-cancel`,className:`min-h-12 rounded-md border border-border bg-background px-4 py-2 text-xs font-semibold text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:`Cancel`}),T.onApply&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>M(),disabled:!c.valid,"data-testid":`palette-apply-query`,className:`min-h-12 rounded-md bg-primary px-4 py-2 text-xs font-semibold text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50`,children:`Apply query`})]}):void 0,I=(0,U.useCallback)(e=>{e||r()},[r]);return(0,W.jsx)(mt,{open:e,onOpenChange:I,children:(0,W.jsxs)(Jn,{children:[(0,W.jsx)(sn,{className:`fixed inset-0 z-50 bg-black/50 backdrop-blur-sm`}),(0,W.jsxs)(Rn,{className:`fixed inset-x-0 z-50 mx-auto flex w-full flex-col outline-none max-lg:bottom-0 max-lg:top-auto max-lg:rounded-t-2xl max-lg:max-h-[var(--palette-max-h)] max-lg:min-h-[var(--palette-min-h)] lg:top-[10%] lg:max-h-[80vh] lg:rounded-xl ${T?`max-w-2xl`:`max-w-xl`}`,style:{"--palette-min-h":k,"--palette-max-h":A},children:[(0,W.jsx)(Ot,{className:`sr-only`,children:`Command Palette`}),(0,W.jsx)(Ct,{className:`sr-only`,children:`Search and navigate. Press Escape to close.`}),(0,W.jsx)(SV,{className:`min-h-0 flex-1 border-border bg-card dark:bg-card`,items:_,query:i,onQueryChange:h,onSelect:j,isOpen:!0,onClose:r,mobileClose:!0,placeholder:t?.placeholder??`Search…`,searchRow:P,footer:F,filterResults:!T,header:t?.header,emptyState:N})]})]})})},AV=[{id:`amrap`,label:`AMRAP`,terms:[`amrap`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=amrap`},{id:`emom`,label:`EMOM`,terms:[`emom`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=emom`},{id:`tabata`,label:`Tabata`,terms:[`tabata`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=tabata-intervals`},{id:`rest`,label:`Rest`,terms:[`rest`,`:*`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=required-rest`},{id:`duration`,label:`Duration`,terms:[`duration`,`5:00`],route:`/guide/protocols`,sublabel:`Timer behaviors`,gridRoute:`/guide/protocols?h=countdown-countup`},{id:`ladder`,label:`Ladder`,terms:[`ladder`,`21-15-9`],route:`/guide/structure`,sublabel:`Rounds & structure`,gridRoute:`/guide/structure?h=rep-schemes`},{id:`rounds`,label:`Rounds`,terms:[`rounds`],route:`/guide/structure?h=rounds`,sublabel:`Rounds & structure`,gridRoute:`/guide/structure?h=rounds`},{id:`supersets`,label:`Supersets`,terms:[`supersets`],route:`/guide/structure?h=nesting`,sublabel:`Rounds & structure`,gridRoute:`/guide/structure?h=nesting`},{id:`actual`,label:`Actual result`,terms:[`actual`,`:?`],route:`/guide/metrics`,sublabel:`Capture & feedback`,gridRoute:`/guide/metrics?h=capture`},{id:`load-prompt`,label:`Load prompt`,terms:[`load prompt`,`?lb`,`225lb`,`load`],route:`/guide/metrics`,sublabel:`Capture & feedback`,gridRoute:`/guide/metrics?h=capture`},{id:`metrics`,label:`Metrics`,terms:[`metrics`,`reps`,`effort`,`discipline`],route:`/guide/metrics?h=planned-vs-recorded`,sublabel:`Planned vs recorded`,gridRoute:`/guide/metrics?h=planned-vs-recorded`},{id:`palette`,label:`Command palette`,terms:[`palette`,`⌘/`],route:`/guide/start?h=reference`,sublabel:`Syntax reference`,gridRoute:`/guide/start?h=reference`}];Object.fromEntries(AV.map(e=>[e.id,e]));function jV(){return{id:`constructs`,label:`Reference`,search:e=>{let t=e.toLowerCase().trim();return t?AV.filter(e=>{let n=e.label.toLowerCase();return n.includes(t)||t.includes(n)?!0:e.terms.some(e=>{let n=e.toLowerCase();return n.includes(t)||t.includes(n)})}).map(e=>({id:`construct:${e.id}`,label:e.label,sublabel:e.sublabel,category:`Reference`,type:`route`,payload:{route:e.route}})):[]}}}function MV(e,t){return`${e}/${t}`}function NV(e){let t=e.indexOf(`/`);return t<0?e:e.slice(0,t)}function PV(e){return e.slug??e.id}function FV(e){let t=PV(e);return{id:e.id,slug:e.slug,category:NV(t),name:e.title||t,content:e.rawContent??``,noteBlocks:e.blocks,sourceRevision:e.sourceRevision,updatedAt:e.updatedAt??Date.now(),type:e.type,sourceId:e.sourceId}}var IV=new YO,LV={pageId:MV,async getPage(e){let t=await IV.getEntry(e);return t?FV(t):void 0},async savePage(e){let t=await IV.getEntry(e.id);return t?(await IV.updateEntry(t.id,{rawContent:e.content,expectedSourceRevision:e.sourceRevision,blocks:e.noteBlocks,title:e.name,slug:e.slug}),t.id):(await IV.saveEntry({id:e.id,slug:e.slug,title:e.name,rawContent:e.content,blocks:e.noteBlocks,tags:[],targetDate:e.updatedAt,type:`playground`})).id},async addPage(e){if(await IV.getEntry(e.id))throw new DOMException(`Page already exists: ${e.id}`,`ConstraintError`);return this.savePage(e)},async getAllPages(){return(await IV.getEntries()).map(FV)},async getPagesByCategory(e){return(await IV.getEntries()).filter(t=>NV(PV(t))===e).map(FV)},async deletePage(e){await IV.deleteEntry(e)},async clearAll(){let e=await IV.getEntries();await Promise.all(e.filter(e=>e.id.includes(`/`)).map(e=>IV.deleteEntry(e.id)))}};function RV(e){return{id:`canvas-routes`,label:`Pages`,search:t=>{let n=t.toLowerCase();return e.filter(e=>{let t=e.page.sections[0]?.heading??e.route;return!n||t.toLowerCase().includes(n)||e.route.toLowerCase().includes(n)}).slice(0,5).map(e=>{let t=e.page.sections[0]?.heading??e.route;return{id:`route:${e.route}`,label:t,sublabel:e.route,category:`Pages`,type:`route`,payload:{route:e.route}}})}}}function zV(e){let t=[],n=/```(time|log)(:\w+)?\r?\n([\s\S]*?)```/gi,r,i=0;for(;(r=n.exec(e))!==null;){let e=r[1].toLowerCase(),n=r[3],a=n.split(`
128
+ `).find(e=>e.trim())?.trim()??`(empty block)`;t.push({index:i++,script:n,preview:a,dialect:e})}return t}function BV(e){return wD(`feeds`,e).map(e=>({id:e.id,name:e.name,readme:e.readme,categories:e.categories,description:e.description,image:e.image,items:e.items.map(({id:e,name:t,content:n,path:r,date:i})=>({id:e,name:t,content:n,feedDate:i??``,path:r})).sort((e,t)=>t.feedDate.localeCompare(e.feedDate))})).sort((e,t)=>e.name.localeCompare(t.name))}var VV=null,HV=[];async function UV(){let e=await VD();return VV!==e&&(VV=e,HV=BV(e)),HV}function WV(){return new Date().toISOString().slice(0,10)}function GV(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(Date.UTC(t,n-1,r)).toLocaleDateString(`en`,{year:`numeric`,month:`short`,day:`numeric`,timeZone:`UTC`})}var KV=[{value:`blank`,label:`Blank`},{value:`template`,label:`Template`},{value:`source`,label:`Source`}],qV=`h-11 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`;function JV({open:e,onOpenChange:t,defaultDate:n,defaultMode:r=`blank`,onCreated:i}){let[a,o]=(0,U.useState)(r),[s,c]=(0,U.useState)(()=>FN()),[l,u]=(0,U.useState)(``),[d,f]=(0,U.useState)(!1),[p,m]=(0,U.useState)(null),[h,g]=(0,U.useState)(null),[_,v]=(0,U.useState)(null),[y,b]=(0,U.useState)(null),[x,S]=(0,U.useState)(null),C=(0,U.useRef)(0),w=(0,U.useRef)(0),T=(0,U.useRef)(!1),[E,D]=(0,U.useState)(``),[O,k]=(0,U.useState)(``),[A,j]=(0,U.useState)(``);(0,U.useEffect)(()=>{e&&(C.current++,w.current++,o(r),c(n&&LN(n)?n:FN()),f(!1),m(null),D(``),k(``),j(``),g(null),v(null),b(null),S(null))},[e,n]);let M=()=>{let e=++C.current;g(null),v(null),DN.listNotes({kind:`template`}).then(t=>{C.current===e&&g(t)}).catch(()=>{C.current===e&&v(`Could not load templates.`)})},N=()=>{let e=++w.current;b(null),S(null),Promise.all([OD(),UV(),Z.getAllNotes()]).then(([t,n,r])=>{if(w.current!==e)return;let i={};for(let e of r)e.sourcePath&&(i[e.sourcePath]=e.id);b({collections:t,feeds:n,sourceIdByPath:i})}).catch(()=>{w.current===e&&S(`Could not load collections and feeds.`)})};(0,U.useEffect)(()=>{e&&(a===`template`&&h===null&&!_&&M(),a===`source`&&y===null&&!x&&N())},[e,a,h,_,y,x]);let P=(0,U.useMemo)(()=>h?.find(e=>e.id===E)??null,[h,E]),F=(0,U.useMemo)(()=>{if(!y||!O)return null;let e=O.indexOf(`:`);if(e<0)return null;let t=O.slice(0,e),n=O.slice(e+1);if(t===`collection`){let e=y.collections.find(e=>e.id===n);return e?{kind:`collection`,group:e}:null}if(t===`feed`){let e=y.feeds.find(e=>e.id===n);return e?{kind:`feed`,group:e}:null}return null},[y,O]),I=F?F.group.items.find(e=>e.path===A)??null:null,L=LN(s),R=s!==``&&!L,ee=`Journal — ${GV(L?.dateKey??FN())}`,te=a===`template`?P===null:a===`source`&&I===null;return(0,W.jsx)(HS,{open:e,onClose:()=>{T.current||t(!1)},title:`New journal note`,description:`Add a note to a day in your journal.`,presentation:`sheet`,footer:(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(K,{type:`button`,variant:`outline`,size:`lg`,onClick:()=>t(!1),disabled:d,children:`Cancel`}),(0,W.jsx)(K,{type:`submit`,form:`create-journal-note-form`,size:`lg`,disabled:!L||te||d,children:d?`Creating…`:`Create`})]}),children:(0,W.jsxs)(`form`,{id:`create-journal-note-form`,onSubmit:async e=>{e.preventDefault();let n=LN(s);if(!n||T.current||te)return;let r;if(a===`template`&&P)r={journalDate:n.dateKey,title:l.trim()||P.title||ee,rawContent:P.rawContent,tags:P.tags,sourceId:P.id,type:`journal`};else if(a===`source`&&I&&F&&y){let e=y.sourceIdByPath[I.path];if(!e){m(`No stored source note matches this item. Your input is kept — pick another item or use Blank.`);return}r={journalDate:n.dateKey,title:l.trim()||I.name,rawContent:I.content,tags:[],sourceId:e,type:`journal`}}else r={journalDate:n.dateKey,title:l.trim()||ee,rawContent:``,tags:[],type:`journal`};T.current=!0,f(!0),m(null);try{let e=await BN.create(r);i?.(e),t(!1)}catch{m(`Could not create the note. Your input is kept — try again.`)}finally{T.current=!1,f(!1)}},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,W.jsx)(`div`,{role:`group`,"aria-label":`Start from`,className:`grid grid-cols-3 gap-1.5`,children:KV.map(e=>(0,W.jsx)(`button`,{type:`button`,"aria-pressed":a===e.value,onClick:()=>o(e.value),disabled:d,className:`min-h-11 rounded-md border px-2 text-sm font-medium transition-colors `+(a===e.value?`border-primary bg-primary/10 text-primary`:`border-border text-muted-foreground hover:bg-muted/60`),children:e.label},e.value))}),a===`template`&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`journal-create-template`,className:`text-sm font-medium`,children:`Template`}),_?(0,W.jsxs)(`div`,{className:`flex min-h-11 items-center justify-between gap-2`,children:[(0,W.jsx)(`p`,{className:`text-sm text-destructive`,children:_}),(0,W.jsx)(K,{type:`button`,variant:`ghost`,size:`sm`,onClick:M,children:`Retry`})]}):h===null?(0,W.jsx)(`p`,{className:`flex min-h-11 items-center text-sm text-muted-foreground`,children:`Loading templates…`}):h.length===0?(0,W.jsx)(`p`,{className:`flex min-h-11 items-center text-sm text-muted-foreground`,children:`No templates available. Choose Blank or Source.`}):(0,W.jsxs)(`select`,{id:`journal-create-template`,value:E,onChange:e=>D(e.target.value),disabled:d,className:qV,children:[(0,W.jsx)(`option`,{value:``,children:`Choose a template…`}),h.map(e=>(0,W.jsx)(`option`,{value:e.id,children:e.title||e.id},e.id))]})]}),a===`source`&&(0,W.jsx)(`div`,{className:`flex flex-col gap-3`,children:x?(0,W.jsxs)(`div`,{className:`flex min-h-11 items-center justify-between gap-2`,children:[(0,W.jsx)(`p`,{className:`text-sm text-destructive`,children:x}),(0,W.jsx)(K,{type:`button`,variant:`ghost`,size:`sm`,onClick:N,children:`Retry`})]}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`journal-create-source-group`,className:`text-sm font-medium`,children:`Feed`}),(0,W.jsxs)(`select`,{id:`journal-create-source-group`,value:O,onChange:e=>{k(e.target.value),j(``)},disabled:y===null||d,className:qV,children:[(0,W.jsx)(`option`,{value:``,children:y===null?`Loading…`:`Choose a feed…`}),y&&y.collections.length>0&&(0,W.jsx)(`optgroup`,{label:`Feeds`,children:y.collections.map(e=>(0,W.jsx)(`option`,{value:`collection:${e.id}`,children:e.name},e.id))}),y&&y.feeds.length>0&&(0,W.jsx)(`optgroup`,{label:`Feeds`,children:y.feeds.map(e=>(0,W.jsx)(`option`,{value:`feed:${e.id}`,children:e.name},e.id))})]})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`journal-create-source-item`,className:`text-sm font-medium`,children:`Item`}),(0,W.jsxs)(`select`,{id:`journal-create-source-item`,value:A,onChange:e=>j(e.target.value),disabled:!F||d,className:qV,children:[(0,W.jsx)(`option`,{value:``,children:F?`Choose an item…`:`Choose a feed first`}),F?.group.items.map(e=>(0,W.jsx)(`option`,{value:e.path,children:`feedDate`in e?`${e.name} — ${e.feedDate}`:e.name},e.path))]})]})]})}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`journal-create-date`,className:`text-sm font-medium`,children:`Date`}),(0,W.jsx)(`input`,{id:`journal-create-date`,type:`date`,value:s,onChange:e=>c(e.target.value),disabled:d,"aria-invalid":R||void 0,className:qV}),R&&(0,W.jsx)(`p`,{className:`text-sm text-destructive`,children:`Enter a valid date (YYYY-MM-DD).`})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`label`,{htmlFor:`journal-create-title`,className:`text-sm font-medium`,children:[`Title `,(0,W.jsx)(`span`,{className:`text-xs font-normal text-muted-foreground`,children:`(optional)`})]}),(0,W.jsx)(`input`,{id:`journal-create-title`,type:`text`,value:l,onChange:e=>u(e.target.value),placeholder:ee,disabled:d,className:qV})]}),p&&(0,W.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p})]})})}function YV(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function XV(e){let t=(()=>{switch(e.kind){case`note`:{if(e.sourceCatalog===`guides`)return e.pageSlug?`/p/${YV(e.pageSlug)}`:`/${YV(e.sourceItem.replace(/^\//,``))}`;if(e.sourceCatalog===`playground`)return`/playground/${encodeURIComponent(e.sourceItem)}`;let t=/^markdown\/dashboards\/(.+)\.md$/.exec(e.sourcePath??``);if(t?.[1])return`/d/${YV(t[1])}`;let n=/^markdown\/efforts\/[^/]+\/(.+)\.md$/.exec(e.sourcePath??``);return n?.[1]?`/e/${YV(n[1])}`:e.pageSlug?`/p/${YV(e.pageSlug)}`:VM(e.id)}case`session`:return e.sourceItem?`/c/${encodeURIComponent(e.sourceCatalog)}/${encodeURIComponent(e.sourceItem)}`:`/c/${encodeURIComponent(e.sourceCatalog)}`;case`dashboard`:return e.sourceCatalog===`dashboards`&&e.sourceItem?`/d/${YV(e.sourceItem)}`:VM(e.id);case`equipment`:{let t=e.sourceItem??e.id,n=t.startsWith(`equipment/`)?t.slice(10):t,r=/^(?:uuid-|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$)/i.test(n);return n&&!r?`/equipment/${YV(n)}`:VM(e.id)}case`post`:{let t=e.date??``;return`/feeds/${encodeURIComponent(e.sourceCatalog)}/${encodeURIComponent(t)}/${encodeURIComponent(e.sourceItem)}`}case`effort`:return`/e/${encodeURIComponent(e.effort?.slug??e.id)}`;case`result`:return JM(e.id);case`segment`:case`event`:return JM(e.execution?.resultId??(e.sourceCatalog===`results`?e.sourceItem:e.id));default:return`/`}})();return e.block?`${t}#${encodeURIComponent(e.block.blockId)}`:t}function ZV(e){return e.sourceCatalog===`playground`||e.sourceId===`playground`}function QV(e){return e.kind===`session`&&!e.sourceItem?`/feeds?q=${encodeURIComponent(`:notebook{notebook:${e.sourceCatalog}}`)}`:null}function $V(e){return e.blockContentId?$M({q:e.blockContentId}):null}function eH(e){return!!(e.kind===`note`||e.kind===`post`||(e.kind===`result`||e.kind===`segment`)&&e.execution?.noteId)}var tH=20,nH=`:note{source:journal,feeds} by {date}`,rH={note:`Journal`,session:`Feeds`,post:`Feeds`,effort:`Efforts`,result:`Results`,segment:`Segments`,event:`Events`,dashboard:`Dashboards`,equipment:`Equipment`};function iH(e){return{id:`entry:${e.id}`,label:e.title,sublabel:e.subtitle??e.date??void 0,category:rH[e.kind],type:`entry`,payload:e}}function aH(e,t){let n=e.filters.filter(e=>!(e.key===`text`&&!e.negate));return t&&n.push({key:`text`,negate:!1,values:[{value:t,wildcard:!1}]}),dh({...e,filters:n})}function oH(){return{id:`wql-search`,label:`Search`,search:async(e,t)=>{if(!X(e).error)return(await MR(e)).slice(0,tH).map(iH);if(e.trimStart().startsWith(`:`))return[];let n=e.trim(),r=(n.startsWith(`"`)&&n.endsWith(`"`)&&n.length>1?n.slice(1,-1):n).replaceAll(`"`,``),i=X(t?.scopeWql??lH());return i.error||!bm(i)?[]:(await MR(aH(i,r))).slice(0,tH).map(iH)}}}function sH(e){let t=X(e);return bm(t)&&!t.error?t.filters.filter(e=>e.key===`text`&&!e.negate).flatMap(e=>e.values.map(e=>e.value)).join(` `):e.replace(/^:\w+/,` `).replace(/\bin\s+\w+/g,` `).replace(/\blast\s+\w+/g,` `).replace(/\bwhere\b/g,` `).replace(/[{()}]/g,` `).replace(/\b\w+:/g,` `).replace(/\s+/g,` `).trim()}function cH(e){return{id:`${e.id}:wql-text`,label:e.label,search:t=>e.search(sH(t))}}function lH(){return UP(`/palette`).defaultWql??`:note{source:journal,feeds} by {date}`}function uH(){return UP(`/palette`).typeOptions??[]}var dH=e=>bm(e)?$L.runFind(e):$L.runQuery(e.raw);function fH(e,t){if(e.type===`route`){let n=e.payload;t(n.route)}else if(e.type===`entry`){let n=e.payload;t(XV(n))}}var pH=new Set([`syntax`]),mH=new Set([`journal`,`playground`,`canvas`,`syntax`]),hH=`$CURSOR`;function gH(e){let t=e.indexOf(hH);return t===-1?{content:e,cursorOffset:e.length}:{content:e.slice(0,t)+e.slice(t+7),cursorOffset:t}}function _H(){let e=typeof window<`u`?window.history.state?.idx:void 0;return typeof e==`number`&&e>0}function vH(e){let t=e.split(`
129
+ `),n=[],r=0,i=0,a=new Map,o=e=>{let t=(a.get(e)??0)+1;return a.set(e,t),t===1?e:`${e}-${t}`},s=e=>{for(let n=e+1;n<t.length;n++){let e=t[n];if(e.trim()==="```")break;let r=e.match(/^title:\s*(.+)$/);if(r)return r[1].trim().replace(/^["']|["']$/g,``)}};for(let e=0;e<t.length;e++){let a=t[e],c=a.match(/^(#{1,6})\s+(.*)$/);if(c){let e=c[2].trim(),t,r=e.match(/(\d{1,2}:\d{2})/);r&&(t=r[1],e=e.replace(t,``).replace(/\s+/g,` `).trim(),e||=t);let i=o(e.toLowerCase().replace(/[^\w]+/g,`-`));n.push({id:i,label:e,type:`heading`,timestamp:t});continue}let l=a.trim().match(/^```(time|log|query|widget)(:[-\w]+)?\s*$/);if(l){let t=l[1];t===`query`?(i++,n.push({id:`query-line-${e+1}`,label:s(e)??`Query ${i}`,type:`query`})):t===`widget`?n.push({id:`widget-line-${e+1}`,label:(l[2]??``).slice(1)||`Widget`,type:`widget`}):(r++,n.push({id:`${t}-line-${e+1}`,label:`Workout ${r}`,type:t}))}}return n}function yH(e){return e.map(e=>({id:e.id,label:e.label,level:3,action:e.onRun&&e.runIcon===`link`?{type:`call`,handler:e.onRun}:{type:`scroll`,sectionId:e.id},secondaryAction:e.onRun?{id:e.id+(e.runIcon===`edit`?`-edit`:`-run`),label:e.runIcon===`edit`?`Edit`:`Run`,icon:e.runIcon===`edit`?o:e.runIcon===`link`?l:rn,action:{type:`call`,handler:e.onRun}}:void 0,secondaryRunIcon:e.runIcon}))}function bH(e){let{setL3Items:t,registerScrollFn:n,dispatch:r}=lM(),i=(0,U.useRef)(null),a=(0,U.useCallback)(e=>{i.current=e},[]),o=(0,U.useCallback)(e=>{if(!e)return;let t=(e=>{let t=document.getElementById(e);if(t||(t=document.querySelector(`[data-section-id="${e}"]`),t))return t;let n=e.split(`:`);for(let e of n)if(e&&(t=document.getElementById(e)??document.querySelector(`[data-section-id="${e}"]`),t))return t;return null})(e);if(t){let e=t.style.scrollMarginTop,n=window.innerWidth<1024,r=!!document.querySelector(`.lg\\:hidden.sticky`),i=`96px`;n&&(i=r?`calc(50vh + 40px)`:`75px`),t.style.scrollMarginTop=i,t.scrollIntoView({behavior:`smooth`,block:`start`}),requestAnimationFrame(()=>{t.style.scrollMarginTop=e});return}if(i.current){let t=i.current,n=t.state.doc.toString().split(`
130
+ `),r=-1,a=e.match(/^(?:workout|time|log|query|widget)-line-(\d+)$/);if(a)r=Number(a[1])-1;else{let i=(t.state.field(Aw,!1)?.sections??[]).find(t=>!!(t.id===e||e.includes(`:${t.id}:`)||e.endsWith(`:${t.id}`)));r=i?i.startLine:n.findIndex(t=>{let n=t.match(/^(#{1,6})\s+(.*)$/);if(n){let t=n[2].trim(),r=t.match(/(\d{1,2}:\d{2})/);if(r){let e=r[1];t=t.replace(e,``).replace(/\s+/g,` `).trim(),t||=e}return t.toLowerCase().replace(/[^\w]+/g,`-`)===e}return!1})}if(r>=0&&r<n.length){let e=t.state.doc.line(r+1).from;t.dispatch({selection:{anchor:e,head:e},effects:[Er.scrollIntoView(e,{y:`start`,yMargin:20})]});let n=t.dom.parentElement;if(n&&window.innerWidth>=1024){let e=n.getBoundingClientRect().top+window.scrollY-120;window.scrollTo({top:e,behavior:`smooth`})}}}},[]);return(0,U.useEffect)(()=>{n(o)},[o,n]),(0,U.useEffect)(()=>{if(e.length===0)return;let t=new IntersectionObserver(e=>{let t=null,n=-1;e.forEach(e=>{e.isIntersecting&&e.intersectionRatio>n&&(n=e.intersectionRatio,t=e.target.id)}),t&&r({type:`SET_ACTIVE_L3`,id:t})},{rootMargin:`-10% 0px -50% 0px`,threshold:[0,.25,.5,1]});return e.forEach(e=>{let n=document.getElementById(e.id);n&&t.observe(n)}),()=>t.disconnect()},[e,r]),(0,U.useEffect)(()=>{e.length!==0&&t(yH(e))},[e,t]),{handleViewCreated:a,scrollToSection:o}}var xH=(e,t)=>!e||!Array.isArray(e)?0:e.reduce((e,n)=>{if(`started`in n){let r=n.started,i=n.ended??t;return e+Math.max(0,i-r)}let r=n.start instanceof Date?n.start.getTime():n.start||0,i=n.stop?n.stop instanceof Date?n.stop.getTime():n.stop:t;return e+Math.max(0,i-r)},0),SH=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/60),i=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},CH=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},wH=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.abs(e),r=Math.floor(n/60),i=Math.floor(n%60);return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},TH=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.abs(e),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=Math.floor(n%60);return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},EH=e=>e==null||!Number.isFinite(e)?`--:--`:Math.floor(Math.abs(e)/1e3)>=3600?CH(e):SH(e),DH=500,OH=900,kH=560;function AH(e,t){let n=e<DH,r=e>=OH,i=!n;return{width:e,height:t,isCompact:n,isWide:i,isFull:r,isShort:t>0&&t<kH,mode:r?`full`:i?`wide`:`compact`}}var jH=AH(800,600),MH=(0,U.createContext)(jH);function NH(){return(0,U.useContext)(MH)}var PH=({children:e})=>{let t=(0,U.useRef)(null),[n,r]=(0,U.useState)(jH),i=(0,U.useCallback)(e=>{let t=e[0];if(!t)return;let n=t.contentRect.width,i=t.contentRect.height;r(e=>{let t=AH(n,i);return e.mode===t.mode&&Math.abs(e.width-n)<2&&Math.abs(e.height-i)<2?e:t})},[]);return(0,U.useEffect)(()=>{let e=t.current;if(!e)return;let n=new ResizeObserver(i);return n.observe(e),()=>n.disconnect()},[i]),(0,W.jsx)(`div`,{ref:t,className:`h-full w-full`,children:(0,W.jsx)(MH.Provider,{value:n,children:e})})},FH={WORKBENCH_ROOT:`workbench-root`,WORKBENCH_HEADER:`workbench-header`,WORKBENCH_RESET_BUTTON:`workbench-reset`,WORKBENCH_DOWNLOAD_BUTTON:`workbench-download`,TAB_PLAN:`tab-plan`,TAB_TRACK:`tab-track`,TAB_REVIEW:`tab-review`,TRACKER_PANEL:`tracker-panel`,TRACKER_NEXT_BUTTON:`tracker-next`,TRACKER_CURRENT_BLOCK_LABEL:`tracker-current-block`,TRACKER_ROUND_INDICATOR:`tracker-round`,TRACKER_REP_INDICATOR:`tracker-reps`,TRACKER_COMPLETION_BANNER:`tracker-completion`,TIMER_DISPLAY:`timer-display`,TIMER_VALUE:`timer-value`,TIMER_NEXT_BLOCK:`timer-next-block`,TIMER_STOP_SESSION:`timer-stop-session`,TIMER_PLAY_PAUSE:`timer-play-pause`,TIMER_UP_NEXT_CAPTION:`timer-up-next-caption`,TIMER_SURFACE_MINIMAL:`timer-surface-minimal`,TIMER_SURFACE_GENERAL:`timer-surface-general`,TIMER_METRIC_PROMPTS:`timer-metric-prompts`,FOCUSED_DIALOG_CLOSE:`focused-dialog-close`,CLOCK_COMMAND_BOARD:`clock-command-board`,CLOCK_REP_COUNTER:`clock-rep-counter`,CLOCK_REP_VALUE:`clock-rep-value`,CLOCK_REP_MINUS:`clock-rep-minus`,CLOCK_REP_PLUS:`clock-rep-plus`,CLOCK_REP_SELECT:`clock-rep-select`,CLOCK_VALUES_BUTTON:`clock-values-button`,CLOCK_DRAFT_CHIP:`clock-draft-chip`,CLOCK_LEGEND:`clock-legend`,CLOCK_KEY_MODE_TOGGLE:`clock-key-mode-toggle`,CLOCK_KEY_CHECK_BUTTON:`clock-key-check-button`,CLOCK_KEY_CHECK_DIALOG:`clock-key-check-dialog`,CLOCK_STOP_CONFIRM:`clock-stop-confirm`,CLOCK_STOP_CONFIRM_ACCEPT:`clock-stop-confirm-accept`,CLOCK_STOP_CONFIRM_CANCEL:`clock-stop-confirm-cancel`,CLOCK_ENTRY_OVERLAY:`clock-entry-overlay`,CLOCK_ERROR:`clock-error`,REVIEW_PANEL:`review-panel`,REVIEW_RESULTS_TABLE:`review-results-table`,REVIEW_METRIC_ROW:`review-metric-row`,REVIEW_TOTAL_TIME:`review-total-time`,EDITOR_PANEL:`editor-panel`,EDITOR_CONTENT:`editor-content`,EDITOR_START_WORKOUT:`editor-start-workout`,TESTBENCH_ROOT:`testbench-root`,TESTBENCH_NEXT_BUTTON:`testbench-next`,TESTBENCH_RUNTIME_STACK:`testbench-runtime-stack`,TESTBENCH_MEMORY:`testbench-memory`,TESTBENCH_SCRIPT_EDITOR:`testbench-script-editor`,EFFORTS_CATALOG_ROOT:`efforts-catalog-root`,EFFORTS_CATALOG_SEARCH:`efforts-catalog-search`,EFFORTS_CATALOG_CREATE_BTN:`efforts-catalog-create-btn`,EFFORTS_CATALOG_EMPTY_STATE:`efforts-catalog-empty-state`,EFFORTS_LOADING:`efforts-loading`,EFFORT_DETAIL_ROOT:`effort-detail-root`,EFFORT_DETAIL_LABEL:`effort-detail-label`,EFFORT_DETAIL_ALIASES:`effort-detail-aliases`,EFFORT_DETAIL_ATTRIBUTES:`effort-detail-attributes`,EFFORT_DETAIL_SOURCE:`effort-detail-source`,EFFORT_DETAIL_EDIT_BTN:`effort-detail-edit-btn`,EFFORT_DETAIL_CLONE_BTN:`effort-detail-clone-btn`,EFFORT_DETAIL_SAVE_BTN:`effort-detail-save-btn`,EFFORT_DETAIL_CANCEL_BTN:`effort-detail-cancel-btn`,EFFORT_DETAIL_DELETE_BTN:`effort-detail-delete-btn`,EFFORT_DETAIL_NOTEBOOK_EDITOR:`effort-detail-notebook-editor`,EFFORT_DETAIL_ANALYTICS_PLACEHOLDER:`effort-detail-analytics-placeholder`,EFFORT_NOT_FOUND:`effort-not-found`,EFFORT_NOT_FOUND_CREATE_BTN:`effort-not-found-create-btn`,EFFORT_NOT_FOUND_ALIAS_BTN:`effort-not-found-alias-btn`,EFFORT_NOT_FOUND_ALIAS_SELECT:`effort-not-found-alias-select`,EFFORT_NOT_FOUND_ALIAS_CONFIRM:`effort-not-found-alias-confirm`,EFFORTS_NAV_ORIGIN_FILTER:`efforts-nav-origin-filter`,EFFORTS_NAV_DISCIPLINE_FILTER:`efforts-nav-discipline-filter`,EFFORTS_NAV_RECENT_WORKOUTS:`efforts-nav-recent-workouts`,EFFORTS_NAV_RECENT_WORKOUT_ITEM:`efforts-nav-recent-workout-item`,EQUIPMENT_DETAIL_ROOT:`equipment-detail-root`,EQUIPMENT_DETAIL_LABEL:`equipment-detail-label`,EQUIPMENT_DETAIL_SOURCE:`equipment-detail-source`,EQUIPMENT_DETAIL_CLONE_BTN:`equipment-detail-clone-btn`,EQUIPMENT_DETAIL_NOTEBOOK_EDITOR:`equipment-detail-notebook-editor`,EQUIPMENT_NOT_FOUND:`equipment-not-found`,EQUIPMENT_NOT_FOUND_CREATE_BTN:`equipment-not-found-create-btn`,EQUIPMENT_CREATE_BTN:`equipment-create-btn`,EQUIPMENT_LOAD_ERROR:`equipment-load-error`,COMMAND_PALETTE_TRIGGER:`command-palette-trigger`,COMMAND_PALETTE_INPUT:`command-palette-input`,COMMAND_PALETTE_RESULTS:`command-palette-results`},IH=SH;function LH(e,t,n=0){let r=e>0?e:800,i=t?Math.min(Math.max(r*.14,56),72,r*.3):Math.min(Math.max(r*.18,128),320,r*.3);return Math.round(n>0?Math.min(i,Math.max(44,n-(t?180:n<560?240:400))):i)}var RH=({children:e})=>{let t=(0,U.useRef)(null),n=(0,U.useRef)(null),[r,i]=(0,U.useState)(1);return(0,U.useLayoutEffect)(()=>{let e=t.current,r=n.current;if(!e||!r)return;let a=()=>{let t=Math.min(1,e.clientWidth/Math.max(r.scrollWidth,1),e.clientHeight/Math.max(r.scrollHeight,1));i(Number.isFinite(t)?Math.max(0,t):0)};a();let o=new ResizeObserver(a);return o.observe(e),o.observe(r),()=>o.disconnect()},[]),(0,W.jsx)(`div`,{ref:t,className:`flex h-full min-h-0 w-full items-center justify-center`,children:(0,W.jsx)(`div`,{ref:n,className:`shrink-0 text-center`,style:{transform:`scale(${r})`,transformOrigin:`center center`},children:e})})},zH=({onStart:e,onPause:t,onStop:n,onNext:r,isRunning:i,isPaused:a=!1,disableNext:o,primaryTimer:s,compact:c=!1,subLabel:l,subLabels:u,secondaryTimers:d,timerStates:f,getFocusProps:p,enableGestures:m=!0,skipFlash:h=!1,skipFlashKey:g=0})=>{let{width:_,height:v,isShort:y}=NH(),b=null;try{b=DA()}catch{}let x=v>0&&v<200,S=c||y||x,C=(0,U.useMemo)(()=>LH(_,c,v),[_,v,c]),w=(0,U.useCallback)(()=>{b?.playClick(),e()},[b,e]),T=(0,U.useCallback)(()=>{b?.playClick(),t()},[b,t]),E=(0,U.useCallback)(()=>{b?.playClick(),n()},[b,n]),D=o??a,O=a?`Continue`:i?`Pause`:`Start`,k=(0,U.useCallback)(()=>{D||(b?.playClick(),r())},[b,D,r]),A=(0,U.useRef)(null),j=(0,U.useRef)(null),M=e=>{j.current=null,A.current=e.targetTouches[0].clientX},N=e=>{j.current=e.targetTouches[0].clientX},P=(0,U.useCallback)(()=>{if(!m||!A.current||!j.current)return;let e=A.current-j.current,t=e>50,n=e<-50,r=document.activeElement;if(!(r&&(r.tagName===`INPUT`||r.tagName===`TEXTAREA`||r.isContentEditable))){if(t){if(D)return;console.log(`Swipe Left -> Next`),k()}else n&&(console.log(`Swipe Right -> Stop`),E())}A.current=null,j.current=null},[m,k,E,D]),F=s,I=(0,U.useMemo)(()=>{if(F)return f&&f.has(F.ownerId)?f.get(F.ownerId):{elapsed:F.accumulatedMs||0,duration:F.durationMs,format:F.format}},[F,f]),L=(0,U.useMemo)(()=>I?I.format===`down`&&I.duration?Math.max(0,I.duration-I.elapsed):I.elapsed:0,[I]),R=(0,U.useMemo)(()=>!d||d.length===0?[]:d.map(e=>{let t=f?.get(e.ownerId),n=t?.elapsed??e.accumulatedMs??0,r=t?.duration??e.durationMs,i=t?.format??e.format??`up`,a=i===`down`&&r?Math.max(0,r-n):n;return{id:e.id,ownerId:e.ownerId,label:e.label||`Timer`,displayMs:a,format:i}}),[d,f]);return(0,W.jsxs)(`div`,{className:`flex w-full flex-1 ${x?`flex-row items-stretch gap-2 min-h-[80px]`:`flex-col ${S?c?`min-h-[136px]`:`min-h-[112px]`:`min-h-[192px]`} ${c?``:S?`gap-2`:`gap-4`}`}`,onTouchStart:M,onTouchMove:N,onTouchEnd:P,children:[(0,W.jsx)(`style`,{children:`
131
+ @keyframes skip-flash-fade {
132
+ 0% { opacity: 1; transform: translateY(0); }
133
+ 70% { opacity: 1; transform: translateY(-4px); }
134
+ 100% { opacity: 0; transform: translateY(-8px); }
135
+ }
136
+ .animate-skip-flash {
137
+ }
138
+ `}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col items-center justify-center overflow-hidden ${S?`px-4 py-1`:`p-4`} ${x?`min-w-0`:``}`,children:(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center relative w-full ${S?`h-full`:`min-h-0 gap-2.5`}`,children:[h&&(0,W.jsx)(`div`,{className:`animate-skip-flash absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap bg-signal-caution text-white dark:text-white text-sm font-semibold px-4 py-1.5 rounded-full shadow-lg pointer-events-none z-20`,role:`status`,"aria-live":`polite`,children:`Timer can't be skipped!`},g),(0,W.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${S?`h-8 min-h-0 shrink mb-1`:`h-[76px] shrink-0`}`,children:(0,W.jsxs)(RH,{children:[s?.label&&(0,W.jsx)(`h2`,{className:`font-semibold text-foreground tracking-tight ${S?`text-lg`:`text-3xl lg:text-4xl`}`,children:s.label}),u&&u.length>0&&(0,W.jsx)(`div`,{className:`${S?`mt-1 space-y-0.5`:`mt-2 space-y-1`}`,children:u.map((e,t)=>(0,W.jsx)(`p`,{className:`text-muted-foreground ${S?`text-xs`:`text-lg lg:text-xl`}`,children:e},t))}),u===void 0&&l&&(0,W.jsx)(`p`,{className:`text-muted-foreground ${S?`mt-1 text-xs`:`mt-2 text-lg lg:text-xl`}`,children:l})]})}),(0,W.jsx)(`div`,{className:`relative flex w-full items-center justify-center ${S?`min-h-12 flex-1`:`min-h-12`}`,children:(0,W.jsx)(`button`,{onClick:a?w:i?T:w,...p?p(`timer-main`):{},className:`tv-focusable relative z-10 flex w-full items-center justify-center focus:outline-none focus-visible:outline-2 focus-visible:outline-ring group ${S?`min-h-[48px] py-1`:`min-h-[48px]`}`,title:O,children:(0,W.jsx)(RH,{children:(0,W.jsx)(`span`,{className:`block font-mono font-bold tracking-tighter text-foreground tabular-nums leading-none`,style:{fontSize:`${C}px`},role:`timer`,"aria-live":`polite`,"aria-atomic":`true`,children:IH(L)})})})}),(0,W.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${S?`mt-1 h-6 min-h-0 shrink`:`h-8 shrink-0`}`,children:(0,W.jsx)(`div`,{className:`flex items-center justify-center gap-2 ${S?`flex-wrap`:`gap-4`}`,children:R.map((e,t)=>(0,W.jsxs)(`div`,{...p?p(`secondary-timer-${t}`):{},className:`tv-focusable flex items-center gap-2 rounded-lg border bg-muted/40 text-muted-foreground ${S?`px-2.5 py-1.5 text-xs`:`px-4 py-2 text-sm`}`,title:e.label,role:`timer`,"aria-label":`${e.label} ${IH(e.displayMs)}`,"aria-atomic":`true`,children:[(0,W.jsx)(Ze,{className:`shrink-0 ${S?`w-3 h-3`:`w-4 h-4`}`}),(0,W.jsx)(`span`,{className:`font-medium truncate max-w-[120px]`,children:e.label}),(0,W.jsx)(`span`,{className:`font-mono font-semibold tabular-nums`,children:IH(e.displayMs)})]},e.id))})})]})}),(0,W.jsxs)(`div`,{className:`flex flex-shrink-0 items-center justify-center flex-wrap ${x?`gap-3 px-2 py-1`:c?`px-4 py-3 bg-background border-t border-border gap-3`:S?`gap-6 px-2 py-1`:`gap-8 px-2 pb-8`}`,children:[(0,W.jsxs)(`div`,{className:`flex flex-col items-center ${S?`gap-1`:`gap-2`}`,children:[(0,W.jsx)(`button`,{onClick:E,...p?p(`btn-stop`):{},className:`tv-focusable group flex items-center justify-center rounded-full border transition-all active:scale-95 ${S?`w-12 h-12 bg-muted border-border`:`w-16 h-16 bg-surface-container-low border-outline-variant hover:bg-surface-variant shadow-sm`}`,title:`Stop Session`,"data-testid":FH.TIMER_STOP_SESSION,children:(0,W.jsx)(tt,{className:`${S?`w-5 h-5`:`w-7 h-7`} text-foreground group-hover:text-destructive transition-colors`})}),!S&&(0,W.jsx)(`span`,{className:`font-mono text-[10px] font-medium uppercase tracking-widest text-muted-foreground`,children:`Stop`})]}),(0,W.jsxs)(`div`,{className:`flex flex-col items-center ${S?`gap-1`:`gap-2`}`,children:[(0,W.jsx)(`button`,{onClick:a?w:i?T:w,...p?p(`btn-pause`):{},className:`tv-focusable group flex items-center justify-center rounded-full transition-all active:scale-95 ${S?`w-12 h-12 bg-primary text-primary-foreground shadow-lg shadow-primary/20`:`w-20 h-20 bg-surface-container-low border border-outline-variant hover:bg-surface-variant shadow-sm`}`,title:O,"data-testid":FH.TIMER_PLAY_PAUSE,children:a?(0,W.jsx)(pn,{className:`${S?`w-6 h-6 text-primary-foreground ml-0.5`:`w-8 h-8 text-foreground ml-1`}`}):i?(0,W.jsx)(dt,{className:`${S?`w-6 h-6 text-primary-foreground`:`w-8 h-8 text-foreground`}`}):(0,W.jsx)(pn,{className:`${S?`w-6 h-6 text-primary-foreground ml-0.5`:`w-8 h-8 text-foreground ml-1`}`})}),!S&&(0,W.jsx)(`span`,{className:`font-mono text-[10px] font-medium uppercase tracking-widest text-muted-foreground`,children:O})]}),c?(0,W.jsxs)(`button`,{onClick:k,disabled:D,"aria-disabled":D?`true`:void 0,...p?p(`btn-next`):{},className:`tv-focusable ${x?`h-12 flex-none px-3`:`flex-1 h-14`} rounded-2xl flex items-center justify-center gap-2 transition-transform shadow-lg ${D?`bg-muted text-muted-foreground cursor-not-allowed opacity-60`:`bg-primary text-primary-foreground shadow-primary/20 active:scale-[0.98]`}`,title:`Next Block`,"data-testid":FH.TIMER_NEXT_BLOCK,children:[(0,W.jsx)(`span`,{className:`text-base font-bold tracking-widest uppercase`,children:`Next`}),(0,W.jsx)(Fn,{className:`w-5 h-5`})]}):(0,W.jsx)(`div`,{className:`flex flex-col items-center gap-2`,children:(0,W.jsxs)(`button`,{onClick:k,disabled:D,"aria-disabled":D?`true`:void 0,...p?p(`btn-next`):{},className:`tv-focusable flex flex-col items-center justify-center gap-1 rounded-full transition-all shadow-xl ${S?`w-12 h-12`:`w-20 h-20`} ${D?`bg-muted text-muted-foreground cursor-not-allowed opacity-60`:`bg-primary-container text-on-primary-container hover:bg-primary hover:text-primary-foreground active:scale-90`}`,title:`Next Block`,"data-testid":FH.TIMER_NEXT_BLOCK,children:[(0,W.jsx)(Fn,{className:`font-bold ${S?`w-5 h-5`:`w-6 h-6`}`}),!S&&(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-widest leading-none`,children:`Next`})]})})]})]})},BH={time:`bg-metric-time/15 border-metric-time/40 text-metric-time`,rep:`bg-metric-rep/15 border-metric-rep/40 text-metric-rep`,effort:`bg-metric-effort/15 border-metric-effort/40 text-metric-effort`,distance:`bg-metric-distance/15 border-metric-distance/40 text-metric-distance`,rounds:`bg-metric-rounds/15 border-metric-rounds/40 text-metric-rounds`,action:`bg-metric-action/15 border-metric-action/40 text-metric-action`,increment:`bg-metric-rounds/10 border-metric-rounds/35 text-metric-rounds`,lap:`bg-metric-rep/10 border-metric-rep/35 text-metric-rep`,text:`bg-muted border-border text-muted-foreground`,resistance:`bg-metric-resistance/15 border-metric-resistance/40 text-metric-resistance`,duration:`bg-metric-time/10 border-metric-time/30 text-metric-time`,spans:`bg-metric-distance/10 border-metric-distance/30 text-metric-distance`,elapsed:`bg-metric-time/12 border-metric-time/28 text-metric-time`,total:`bg-muted border-border text-foreground`,"system-time":`bg-muted/60 border-border/60 text-muted-foreground`,metric:`bg-metric-effort/10 border-metric-effort/30 text-metric-effort`,custom:`bg-muted/70 border-muted-foreground/30 text-muted-foreground`,calculated:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,rest:`bg-muted/70 border-muted-foreground/30 text-muted-foreground`,volume:`bg-metric-rep/12 border-metric-rep/35 text-metric-rep`,load:`bg-metric-resistance/12 border-metric-resistance/35 text-metric-resistance`,"session-load":`bg-metric-resistance/12 border-metric-resistance/35 text-metric-resistance`,intensity:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,work:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,rir:`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,"session-rpe":`bg-metric-effort/12 border-metric-effort/35 text-metric-effort`,"met-score":`bg-metric-distance/12 border-metric-distance/35 text-metric-distance`,tis:`bg-metric-action/12 border-metric-action/35 text-metric-action`,"current-round":`bg-metric-rounds/10 border-metric-rounds/30 text-metric-rounds`,label:`bg-muted border-border text-muted-foreground`,system:`bg-muted/60 border-border/60 text-muted-foreground`,sound:`bg-muted/50 border-border/50 text-muted-foreground`,group:`bg-muted/50 border-border/50 text-muted-foreground`};function VH(e,t){return e.toLowerCase()!==`effort`||!t?!1:t.trim().toLowerCase()===`rest`}function HH(e,t){let n=`bg-gray-200 border-gray-300 text-gray-800 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-100`;return VH(e,t)?BH.rest??n:BH[e.toLowerCase()]??n}var UH={time:`⏱️`,duration:`⏱️`,rounds:`🔄`,resistance:`💪`,weight:`💪`,distance:`📏`,action:`▶️`,rest:`⏸️`,effort:`🏃`,increment:`↕️`,text:`📝`,elapsed:`⏱️`,spans:`📊`,total:`🕐`,"system-time":`🖥️`,metric:`📈`,volume:`🏋️`,intensity:`⚡`,load:`⚖️`,work:`🔥`,rir:`🔋`,"session-rpe":`😓`,"session-load":`📊`,"met-score":`🫀`,tis:`📈`,calculated:`🧮`,custom:`✳️`,"current-round":`🔄`,label:`🏷️`,system:`⚙️`,sound:`🔊`,group:`🔀`,lap:`🏁`};function WH(e,t){return VH(e,t)?UH.rest:UH[e.toLowerCase()]||null}var GH=new Set([`duration`,`time`,`elapsed`,`total`,`spans`]);function KH(e,t){let n=e.toLowerCase().replace(/[^a-z0-9]/g,``),r={reps:`rep`,rep:`rep`,distance:`distance`,rounds:`rounds`,round:`rounds`,currentround:`current-round`,action:`action`,increment:`increment`,lap:`lap`,text:`text`,resistance:`resistance`,weight:`resistance`,duration:`duration`,spans:`spans`,elapsed:`elapsed`,total:`total`,totaltime:`total`,systemtime:`system-time`,label:`label`,system:`system`,sound:`sound`,group:`group`};if(r[n])return r[n];if(n.includes(`rir`))return`rir`;if(n.includes(`sessionrpe`)||n===`rpe`)return`session-rpe`;if(n.includes(`sessionload`))return`session-load`;if(n.includes(`metscore`)||n===`met`)return`met-score`;if(n===`tis`)return`tis`;if(n.includes(`calculated`)||n.includes(`calc`))return`calculated`;if(n.includes(`custom`))return`custom`;if(n.includes(`volume`))return`volume`;if(n.includes(`intensity`))return`intensity`;if(n.includes(`load`))return`load`;if(n.includes(`work`)||n.includes(`energy`)||n.includes(`calorie`))return`work`;if(n.includes(`set`))return`metric`;if(t){let e=t.toLowerCase();if(e===`reps`||e===`rep`)return`rep`;if(e===`km`||e===`m`||e===`mi`||e===`ft`||e===`yd`)return`distance`;if(e===`lb`||e===`kg`||e===`lbs`||e===`pood`)return`resistance`;if(e===`min`||e===`sec`||e===`ms`||e===`h`)return`duration`;if(e===`kcal`||e===`cal`)return`work`;if(e===`round`||e===`rounds`)return`rounds`;if(e===`sets`||e===`set`)return`metric`}return`metric`}function qH(e,t,n){if(e==null)return`—`;if(typeof e==`string`)return e;if(typeof e!=`number`||!Number.isFinite(e))return String(e);if(GH.has(t)){let t=n?.toLowerCase();return EH(t===`sec`||t===`s`?e*1e3:t===`min`||t===`m`?e*60*1e3:t===`h`||t===`hr`?e*60*60*1e3:e)}return Number.isInteger(e)?String(e):e.toFixed(1)}var JH=({className:e})=>{let t=sz(),n={};for(let e of t){let t=e.metrics;for(let e=0;e+1<t.length;e+=2){let r=t[e],i=t[e+1];if(r&&i){let e=r.image??String(r.value);n[e]={value:i.value,unit:i.unit}}}}let r=Object.entries(n);return r.length>0?(0,W.jsxs)(`div`,{className:G(`flex h-14 flex-shrink-0 flex-wrap items-center justify-center gap-2 overflow-hidden px-4`,e),children:[r.map(([e,t])=>{let n=KH(e,t.unit),r=HH(n),i=WH(n),a=qH(t.value,n,t.unit);return(0,W.jsxs)(`div`,{className:G(`flex flex-col items-center backdrop-blur-md border rounded-xl px-3 py-1.5 shadow-sm ring-1 ring-black/5 dark:ring-white/5 group transition-colors`,r),children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 opacity-70`,children:[i&&(0,W.jsx)(`span`,{className:`text-[10px] leading-none`,"aria-hidden":`true`,children:i}),(0,W.jsx)(`span`,{className:`text-[8px] font-black uppercase tracking-tighter group-hover:opacity-100 transition-opacity`,children:go(e)})]}),(0,W.jsxs)(`div`,{className:`flex items-baseline gap-0.5`,children:[(0,W.jsx)(`span`,{className:`text-sm font-black tabular-nums tracking-tight`,children:a}),t.unit&&!GH.has(n)&&(0,W.jsx)(`span`,{className:`text-[9px] font-bold opacity-60 uppercase`,children:t.unit})]})]},`bubble-${e}`)}),(0,W.jsx)(`div`,{className:`self-center bg-primary/10 border border-primary/20 rounded-full p-1.5 shadow-inner opacity-40 hover:opacity-100 transition-opacity cursor-help`,title:`Session Aggregates`,children:(0,W.jsx)(Zt,{className:`h-3 w-3 text-primary`})})]}):(0,W.jsx)(`div`,{className:G(`h-14 shrink-0`,e),"aria-hidden":`true`})},YH=e=>{let t=az(),n=DL(e=>e.viewMode),r=DL(e=>e.execution.status),[i,a]=U.useState(0),[o,s]=U.useState(!1),c=U.useRef(null);U.useEffect(()=>{if(!t)return;let e=t.eventBus.on(`timer:skip-attempt`,()=>{a(e=>e+1),s(!0),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>s(!1),3e3)},`ui-flash`);return()=>{e(),c.current&&clearTimeout(c.current)}},[t]);let l=fz(),u=pz(),d=dz(),f=mz(),p=hz(),m=p?.find(e=>e.block.blockType===`Rounds`),h=nz(m?.block),[g,_]=U.useState(Gl()),v=(0,U.useMemo)(()=>d.some(e=>e.timer.spans.some(e=>e.ended===void 0)),[d]);U.useEffect(()=>{if(!v)return;let e,t=()=>{_(Gl()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[v]);let y=(0,U.useMemo)(()=>l?xH(l.timer.spans,g):0,[l,g]),b=(0,U.useMemo)(()=>{let e=new Map;for(let t of d){let n=t.block.key.toString(),r=xH(t.timer.spans,g);e.set(n,{elapsed:r,duration:t.timer.durationMs,format:t.timer.direction})}return e},[d,g]),x=(0,U.useMemo)(()=>{if(!l)return;let e=l.block.key.toString();return{id:`timer-${e}`,ownerId:e,timerMemoryId:``,label:l.timer.label,format:l.timer.direction,durationMs:l.timer.durationMs,role:l.isPinned?`primary`:`auto`}},[l]),S=(0,U.useMemo)(()=>u.map(e=>{let t=e.block.key.toString();return{id:`timer-${t}`,ownerId:t,timerMemoryId:``,label:e.timer.label,format:e.timer.direction,durationMs:e.timer.durationMs,role:e.isPinned?`primary`:`auto`}}),[u]),C=(0,U.useMemo)(()=>f.filter(e=>e.visible&&e.enabled&&e.eventName).map(e=>({id:e.id,name:e.label,eventName:e.eventName,ownerId:``,displayLabel:e.label,isPinned:e.isPinned})),[f]),w=l?l.block.key.toString():void 0,{mainLabel:T,subLabel:E,activeTimerEntry:D,activeElapsed:O}=(0,U.useMemo)(()=>{let e=p?.find(e=>e.isLeaf),t=e?.label,n=p?.find(e=>e.block.blockType===`Rounds`),r=h?.label??n?.label,i=e?d.find(t=>t.block.key.toString()===e.block.key.toString()):void 0,a=i?xH(i.timer.spans,g):0;if(l&&l.isPinned){let e=xH(l.timer.spans,g),n=r||l.timer.label;return{mainLabel:n,subLabel:n===t?void 0:t,activeTimerEntry:l,activeElapsed:e}}return r&&r!==t?{mainLabel:r,subLabel:t,activeTimerEntry:i||l,activeElapsed:i?a:y}:{mainLabel:t||l?.timer.label||`Timer`,subLabel:void 0,activeTimerEntry:i||l,activeElapsed:i?a:y}},[l,p,d,g,y,h]),k=(0,U.useMemo)(()=>{let e=p?.find(e=>e.isLeaf);if(!e)return E?[E]:void 0;if(e.displayRows&&e.displayRows.length>1){let t=e.displayRows.map(e=>jo.presentGroup([...e],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()).filter(Boolean);if(t.length>0)return t}return E?[E]:void 0},[p,E]),A=(0,U.useMemo)(()=>{if(D){let e=D.block.key.toString();return{id:`timer-${e}`,ownerId:e,timerMemoryId:``,label:T,format:D.timer.direction,durationMs:D.timer.durationMs,role:D.isPinned?`primary`:`auto`,accumulatedMs:O}}if(x)return{...x,label:T,accumulatedMs:O}},[x,D,T,O]);return(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2`,children:[(0,W.jsx)(`div`,{className:`min-h-0 shrink overflow-y-auto pb-2`,children:(0,W.jsx)(JH,{})}),(0,W.jsx)(zH,{elapsedMs:O,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,actions:C.length>0?C:void 0,skipFlash:o,skipFlashKey:i,onAction:(n,r)=>{switch(t.handle({name:n,timestamp:new Date,data:r}),n){case`timer:pause`:e.onPause?.();break;case`timer:resume`:case`timer:start`:e.onStart?.();break;case`workout:stop`:e.onStop?.()}},isRunning:v||r===`running`,isPaused:r===`paused`,disableNext:r===`paused`||e.canNext===!1,primaryTimer:A,subLabel:E,subLabels:k,secondaryTimers:S,stackItems:p,compact:e.compact,focusedBlockId:w,timerStates:b,enableGestures:n===`track`,getFocusProps:e.getFocusProps})]})},XH=e=>{let t=DL(e=>e.viewMode);return e.enableDisplayStack?(0,W.jsx)(YH,{...e}):(0,W.jsx)(zH,{elapsedMs:e.elapsedMs,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isRunning:e.isRunning,isPaused:e.isPaused,disableNext:e.disableNext,compact:e.compact,enableGestures:t===`track`,getFocusProps:e.getFocusProps})},ZH=SH,QH=()=>{let e=null;try{e=DA()}catch{}return e},$H=({model:e})=>e.skipFlash?(0,W.jsx)(`div`,{className:`timer-surface-flash absolute -top-2 left-1/2 z-20 -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-full bg-signal-caution px-4 py-1.5 text-sm font-semibold text-white shadow-lg pointer-events-none`,role:`status`,"aria-live":`polite`,children:`Timer can't be skipped!`},e.skipFlashKey):null,eU=({model:e,onStart:t,onPause:n,size:r,showChips:i,getFocusProps:a})=>{let o=QH(),c=(0,U.useCallback)(()=>{o?.playClick(),t()},[o,t]),l=(0,U.useCallback)(()=>{o?.playClick(),n()},[o,n]),{isRunning:u,isPaused:d}=e,f=d?`Continue`:u?`Pause`:`Start`,p=d?c:u?l:c,m=r===`tv`;return(0,W.jsxs)(`div`,{className:`relative flex min-h-0 w-full flex-1 flex-col items-center justify-center overflow-hidden text-center`,children:[(0,W.jsx)(`style`,{children:`
139
+ @keyframes timer-surface-flash-fade {
140
+ 0% { opacity: 1; transform: translate(-50%, -100%) translateY(0); }
141
+ 70% { opacity: 1; transform: translate(-50%, -100%) translateY(-4px); }
142
+ 100% { opacity: 0; transform: translate(-50%, -100%) translateY(-8px); }
143
+ }
144
+ .timer-surface-flash {
145
+ animation: timer-surface-flash-fade 3s ease-out forwards;
146
+ }
147
+ @media (prefers-reduced-motion: reduce) {
148
+ .timer-surface-flash { animation: none; }
149
+ }
150
+ `}),(0,W.jsx)($H,{model:e}),(0,W.jsxs)(`div`,{className:`flex min-h-0 w-full flex-col items-center justify-center ${m?`gap-[1.2cqw]`:`gap-2.5`}`,children:[(0,W.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${m?`h-[8.6cqw]`:`h-[76px]`}`,children:(0,W.jsxs)(RH,{children:[(0,W.jsx)(`h2`,{className:`font-semibold tracking-tight text-foreground ${m?`text-[3.4cqw]`:`text-xl`}`,children:e.mainLabel}),e.subLabels&&e.subLabels.length>0&&(0,W.jsx)(`div`,{className:`${m?`mt-[0.6cqw] space-y-[0.4cqw]`:`mt-1 space-y-0.5`}`,children:e.subLabels.map((e,t)=>(0,W.jsx)(`p`,{className:`text-muted-foreground ${m?`text-[2cqw]`:`text-[13.5px]`}`,children:e},t))})]})}),(0,W.jsx)(`button`,{onClick:p,...a?a(`timer-main`):{},className:`tv-focusable group relative z-10 flex min-h-[48px] w-full items-center justify-center focus:outline-none`,title:f,children:(0,W.jsx)(RH,{children:(0,W.jsx)(`span`,{className:`block font-mono font-bold leading-none tracking-tighter text-foreground tabular-nums ${m?`text-[13cqw]`:`text-[21cqw]`}`,role:`timer`,"aria-live":`polite`,"aria-atomic":`true`,children:ZH(e.displayMs)})})}),(0,W.jsx)(`div`,{className:`flex w-full items-center justify-center overflow-hidden ${m?`h-[4.4cqw]`:`h-8`}`,children:i&&(0,W.jsxs)(`div`,{className:`flex items-center justify-center ${m?`gap-[1cqw]`:`gap-2`}`,children:[e.secondaryTimers.map(e=>(0,W.jsxs)(`div`,{className:`flex items-center gap-[0.6em] rounded-lg border border-border bg-muted/40 text-muted-foreground ${m?`px-[1.4cqw] py-[0.8cqw] text-[1.7cqw]`:`px-2.5 py-1.5 text-xs`}`,role:`timer`,"aria-label":`${e.label} ${ZH(e.displayMs)}`,"aria-atomic":`true`,children:[(0,W.jsx)(Ze,{className:`shrink-0 ${m?`w-[1.8cqw] h-[1.8cqw]`:`w-3 h-3`}`}),(0,W.jsx)(`span`,{className:`max-w-[10em] truncate font-medium`,children:e.label}),(0,W.jsx)(`span`,{className:`font-mono font-semibold tabular-nums`,children:ZH(e.displayMs)})]},e.id)),e.roundLabel&&(0,W.jsxs)(`div`,{className:`flex items-center gap-[0.6em] rounded-lg border border-border bg-muted/40 text-muted-foreground ${m?`px-[1.4cqw] py-[0.8cqw] text-[1.7cqw]`:`px-2.5 py-1.5 text-xs`}`,"aria-label":e.roundLabel,children:[(0,W.jsx)(s,{className:`shrink-0 text-metric-rounds ${m?`w-[1.8cqw] h-[1.8cqw]`:`w-3 h-3`}`}),(0,W.jsx)(`span`,{className:`font-medium`,children:e.roundLabel})]})]})})]})]})},tU=({model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:a,getFocusProps:o})=>{let s=QH(),{isRunning:c,isPaused:l,isNextDisabled:u}=e,d=l?`Continue`:c?`Pause`:`Start`,f=(0,U.useCallback)(()=>{s?.playClick(),t()},[s,t]),p=(0,U.useCallback)(()=>{s?.playClick(),n()},[s,n]),m=(0,U.useCallback)(()=>{s?.playClick(),r()},[s,r]),h=(0,U.useCallback)(()=>{u||(s?.playClick(),i())},[s,u,i]),g=a===`tv`,_=(0,W.jsx)(`button`,{onClick:m,...o?o(`btn-stop`):{},className:`tv-focusable group flex shrink-0 items-center justify-center rounded-full border border-border bg-muted transition-all active:scale-95 ${g?`h-[6cqw] w-[6cqw]`:`h-12 w-12`}`,title:`Stop Session`,"data-testid":FH.TIMER_STOP_SESSION,children:(0,W.jsx)(tt,{className:`text-foreground transition-colors group-hover:text-destructive ${g?`h-[2.2cqw] w-[2.2cqw]`:`h-[17px] w-[17px]`}`})}),v=(0,W.jsx)(`button`,{onClick:l?f:c?p:f,...o?o(`btn-pause`):{},className:`tv-focusable flex shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/20 transition-all active:scale-95 ${g?`h-[7cqw] w-[7cqw]`:`h-[54px] w-[54px]`}`,title:d,"data-testid":FH.TIMER_PLAY_PAUSE,children:l?(0,W.jsx)(pn,{className:`${g?`ml-[0.3cqw] h-[2.8cqw] w-[2.8cqw]`:`ml-0.5 h-[22px] w-[22px]`}`}):c?(0,W.jsx)(dt,{className:g?`h-[2.8cqw] w-[2.8cqw]`:`h-[22px] w-[22px]`}):(0,W.jsx)(pn,{className:`${g?`ml-[0.3cqw] h-[2.8cqw] w-[2.8cqw]`:`ml-0.5 h-[22px] w-[22px]`}`})}),y=(0,W.jsxs)(`button`,{onClick:h,disabled:u,"aria-disabled":u?`true`:void 0,...o?o(`btn-next`):{},className:`tv-focusable flex shrink-0 items-center justify-center gap-2 bg-primary font-bold uppercase tracking-[0.12em] text-primary-foreground shadow-lg shadow-primary/20 transition-all active:scale-[0.98] disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground disabled:shadow-none ${g?`h-[7cqw] rounded-[1.4cqw] px-[4cqw] text-[2.2cqw]`:`h-[54px] w-full rounded-2xl text-[15px]`}`,title:`Next Block`,"data-testid":FH.TIMER_NEXT_BLOCK,children:[(0,W.jsx)(`span`,{children:`Next`}),(0,W.jsx)(Fn,{className:g?`h-[2.4cqw] w-[2.4cqw]`:`h-5 w-5`})]}),b=(0,W.jsx)(`p`,{className:`truncate text-muted-foreground ${g?`pl-[0.4cqw] text-[1.8cqw]`:`pl-1 text-xs`}`,"data-testid":FH.TIMER_UP_NEXT_CAPTION,children:e.upNext&&(0,W.jsxs)(W.Fragment,{children:[`Up next: `,(0,W.jsx)(`b`,{className:`font-semibold text-foreground`,children:e.upNext})]})});return(0,W.jsxs)(`div`,{className:g?`flex items-end justify-center gap-[2cqw]`:`flex items-end gap-3`,children:[_,!g&&v,(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-col ${g?`items-start gap-[1cqw]`:`flex-1 items-stretch gap-2`}`,children:[b,g?(0,W.jsxs)(`div`,{className:`flex items-center gap-[1.6cqw]`,children:[v,y]}):y]})]})};function nU(e,t,n,r){let i=(0,U.useRef)(null),a=(0,U.useRef)(null),o=(0,U.useRef)({onNext:e,onStop:t,isNextDisabled:r});return o.current={onNext:e,onStop:t,isNextDisabled:r},{onTouchStart:(0,U.useCallback)(e=>{a.current=null,i.current=e.targetTouches[0].clientX},[]),onTouchMove:(0,U.useCallback)(e=>{a.current=e.targetTouches[0].clientX},[]),onTouchEnd:(0,U.useCallback)(()=>{let{onNext:e,onStop:t,isNextDisabled:r}=o.current;if(!n||!i.current||!a.current)return;let s=i.current-a.current,c=document.activeElement;c&&(c.tagName===`INPUT`||c.tagName===`TEXTAREA`||c.isContentEditable)||(s>50?r||e():s<-50&&t()),i.current=null,a.current=null},[n])}}var rU=({sessionElapsedMs:e,roundCurrent:t,roundTotal:n})=>{let r=t!==void 0&&n!==void 0&&n>0;return(0,W.jsxs)(`div`,{className:`flex h-11 shrink-0 items-center justify-between border-b border-border px-4`,"data-testid":`timer-status-strip`,children:[(0,W.jsxs)(`span`,{className:`flex items-center gap-1.5 font-mono text-xs text-muted-foreground tabular-nums`,children:[(0,W.jsx)(Ze,{className:`h-[13px] w-[13px]`}),SH(e)]}),r&&(0,W.jsx)(`span`,{className:`flex items-center gap-[5px]`,role:`progressbar`,"aria-label":`Round ${t} of ${n}`,"aria-valuemin":1,"aria-valuemax":n,"aria-valuenow":t,children:Array.from({length:n},(e,n)=>{let r=n+1,i=r<t?`done`:r===t?`now`:`pending`;return(0,W.jsx)(`i`,{className:`block h-[7px] w-[7px] rounded-full ${i===`done`?`bg-primary/45`:i===`now`?`bg-primary`:`bg-border`}`},r)})})]})},iU=({model:e,onStart:t,onPause:n,onStop:r,onNext:i,getFocusProps:a,enableGestures:o=!0,promptRow:s})=>{let c=nU(i,r,o,e.isNextDisabled);return(0,W.jsxs)(`div`,{className:`@container flex h-full flex-col bg-background text-foreground`,onTouchStart:c.onTouchStart,onTouchMove:c.onTouchMove,onTouchEnd:c.onTouchEnd,"data-testid":FH.TIMER_SURFACE_MINIMAL,children:[(0,W.jsx)(rU,{sessionElapsedMs:e.sessionElapsedMs,roundCurrent:e.roundCurrent,roundTotal:e.roundTotal}),s&&(0,W.jsx)(`div`,{className:`shrink-0`,children:s}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col px-5 pb-3 text-center`,children:(0,W.jsx)(eU,{model:e,onStart:t,onPause:n,size:`mobile`,showChips:!1,getFocusProps:a})}),(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border p-4`,children:(0,W.jsx)(tU,{model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:`mobile`,getFocusProps:a})})]})},aU=({model:e,onStart:t,onPause:n,onStop:r,onNext:i,workoutTitle:a,promptRow:o,getFocusProps:s})=>(0,W.jsxs)(`div`,{className:`@container flex h-full flex-col bg-background p-[3cqw_4cqw] text-foreground`,"data-testid":FH.TIMER_SURFACE_GENERAL,children:[(0,W.jsxs)(`div`,{className:`flex shrink-0 items-center gap-[1.4cqw]`,children:[(0,W.jsxs)(`span`,{className:`flex items-center gap-[0.7cqw] font-mono text-[1.7cqw] text-muted-foreground tabular-nums`,children:[(0,W.jsx)(Ze,{className:`h-[1.9cqw] w-[1.9cqw]`}),`Session `,SH(e.sessionElapsedMs)]}),a&&(0,W.jsx)(`span`,{className:`text-[2cqw] font-semibold tracking-tight`,children:a}),(0,W.jsxs)(`span`,{className:`ml-auto flex items-center gap-[1.4cqw] text-muted-foreground`,children:[(0,W.jsx)(Zn,{className:`h-[2.4cqw] w-[2.4cqw]`,"aria-hidden":`true`}),(0,W.jsx)(fe,{className:`h-[2.4cqw] w-[2.4cqw]`,"aria-hidden":`true`})]})]}),o&&(0,W.jsx)(`div`,{className:`shrink-0`,children:o}),(0,W.jsx)(eU,{model:e,onStart:t,onPause:n,size:`tv`,showChips:!0,getFocusProps:s}),(0,W.jsx)(`div`,{className:`shrink-0`,children:(0,W.jsx)(tU,{model:e,onStart:t,onPause:n,onStop:r,onNext:i,size:`tv`,getFocusProps:s})})]});function oU(e){let t=az(),n=DL(e=>e.execution.status),r=fz(),i=dz(),a=hz(),o=a?.find(e=>e.block.blockType===`Rounds`),s=nz(o?.block),c=uz(),[l,u]=(0,U.useState)(0),[d,f]=(0,U.useState)(!1),p=(0,U.useRef)(null);(0,U.useEffect)(()=>{if(!t)return;let e=t.eventBus.on(`timer:skip-attempt`,()=>{u(e=>e+1),f(!0),clearTimeout(p.current),p.current=setTimeout(()=>f(!1),3e3)},`ui-flash`);return()=>{e(),clearTimeout(p.current)}},[t]);let m=i.some(e=>e.timer.spans.some(e=>e.ended===void 0)),[h,g]=(0,U.useState)(Gl());return(0,U.useEffect)(()=>{if(!m)return;let e,t=()=>{g(Gl()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[m]),{...(0,U.useMemo)(()=>{let e=a?.find(e=>e.isLeaf),t=e?.label,n=s?.label??o?.label,l=e?i.find(t=>t.block.key.toString()===e.block.key.toString()):void 0,u=r?.isPinned?r:l||r,d=(r?.isPinned?n||r.timer.label:n&&n!==t?n:t||r?.timer.label)||`Timer`,f=d===t?void 0:t,p;if(e?.displayRows&&e.displayRows.length>1){let t=e.displayRows.map(e=>jo.presentGroup([...e],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()).filter(Boolean);t.length>0&&(p=t)}p||=f?[f]:void 0;let m=0;if(u){let e=xH(u.timer.spans,h);m=u.timer.direction===`down`&&u.timer.durationMs?Math.max(0,u.timer.durationMs-e):e}let g=i.map(e=>({t:e,elapsed:xH(e.timer.spans,h)})),_=r?.isPinned?{t:r,elapsed:xH(r.timer.spans,h)}:g.reduce((e,t)=>t.elapsed>(e?.elapsed??-1)?t:e,g[0]),v=_?.elapsed??0,y=u?.block.key.toString(),b=_?.t.block.key.toString(),x=i.filter(e=>{let t=e.block.key.toString();return t!==y&&t!==b}).map(e=>{let t=xH(e.timer.spans,h);return{id:e.block.key.toString(),label:e.timer.label,displayMs:e.timer.direction===`down`&&e.timer.durationMs?Math.max(0,e.timer.durationMs-t):t}}),S=null;return c?.metrics&&(S=jo.presentGroup([...c.metrics],`timer-subtitle`).filter(e=>e.visible).map(e=>e.label).filter(Boolean).join(` `).trim()||null),{mainLabel:d,subLabels:p,displayMs:m,sessionElapsedMs:v,roundCurrent:s?.current,roundTotal:s?.total,roundLabel:s?.label,secondaryTimers:x,upNext:S}},[r,i,a,h,s,o,c]),isRunning:m||n===`running`,isPaused:e.isPaused,isNextDisabled:e.isPaused||e.canNext===!1,skipFlash:d,skipFlashKey:l}}var sU=e=>{let{isCompact:t,isFull:n}=NH(),r=oU({onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isPaused:!!e.isPaused,canNext:e.canNext});if(n)return(0,W.jsx)(XH,{elapsedMs:e.elapsedMs,hasActiveBlock:e.hasActiveBlock,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,isRunning:e.isRunning,isPaused:e.isPaused,canNext:e.canNext,onBlockHover:e.onBlockHover,onBlockClick:e.onBlockClick,enableDisplayStack:e.enableDisplayStack,getFocusProps:e.getFocusProps});let i=(0,W.jsx)(`div`,{"data-testid":FH.TIMER_METRIC_PROMPTS,className:`shrink-0 overflow-y-auto border-b border-border px-4 py-1.5`,children:(0,W.jsx)(JH,{})});return t?(0,W.jsx)(iU,{model:r,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,getFocusProps:e.getFocusProps,enableGestures:e.enableGestures,promptRow:i}):(0,W.jsx)(aU,{model:r,onStart:e.onStart,onPause:e.onPause,onStop:e.onStop,onNext:e.onNext,getFocusProps:e.getFocusProps,workoutTitle:e.workoutTitle,promptRow:i})};function cU(e){let t=e.metric.image??String(e.metric.value??``);return{...e,colorClasses:HH(e.metric.type,t),icon:WH(e.metric.type,t),originClasses:e.userEntered?`border-dashed italic ring-1 ring-offset-1 ring-primary/30`:``}}function lU(e,t){return jo.presentGroup(e,t).map(cU)}var uU=U.memo(({metrics:e,error:t,className:n=``,size:r=`normal`,filter:i})=>{let a=(0,U.useMemo)(()=>i?e.filter(e=>{let t=String(e.value||``).toLowerCase(),n=e.type.toLowerCase();if(i.nameOverrides){if(t in i.nameOverrides)return i.nameOverrides[t];if(n in i.nameOverrides)return i.nameOverrides[n]}return i.typeOverrides&&n in i.typeOverrides?i.typeOverrides[n]:!i.allowedOrigins||i.allowedOrigins.includes(e.origin||`parser`)}):e,[e,i]);if(t)return(0,W.jsx)(`div`,{className:`border border-destructive/50 rounded-lg p-4 bg-destructive/10 ${n}`,children:(0,W.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,W.jsx)(`span`,{className:`text-destructive font-bold text-lg`,children:`⚠️`}),(0,W.jsxs)(`div`,{className:`flex-1`,children:[(0,W.jsx)(`div`,{className:`font-semibold text-destructive mb-1`,children:`Parse Error`}),(0,W.jsx)(`div`,{className:`text-destructive/90 text-sm`,children:t.message}),(t.line!==void 0||t.column!==void 0)&&(0,W.jsxs)(`div`,{className:`text-destructive/80 text-xs mt-2`,children:[t.line!==void 0&&(0,W.jsxs)(`span`,{children:[`Line `,t.line]}),t.line!==void 0&&t.column!==void 0&&(0,W.jsx)(`span`,{children:`, `}),t.column!==void 0&&(0,W.jsxs)(`span`,{children:[`Column `,t.column]})]}),t.excerpt&&(0,W.jsx)(`pre`,{className:`mt-2 p-2 bg-background border border-destructive/20 rounded text-xs overflow-x-auto text-foreground`,children:t.excerpt})]})]})});if(!a||a.length===0)return(0,W.jsx)(`div`,{className:`border border-border rounded-lg p-4 bg-muted/20 text-center text-muted-foreground text-sm ${n}`,children:`No metrics to display`});let o={compact:{padding:`px-1 py-0`,text:`text-[10px] leading-tight`,icon:`text-xs`},normal:{padding:`px-2 py-0.5`,text:`text-sm`,icon:`text-base leading-none`},focused:{padding:`px-2.5 py-1`,text:`text-base`,icon:`text-lg leading-none`}}[r];return(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1 ${n}`,children:lU(a,`runtime-badge`).filter(e=>e.visible).map((e,t)=>e.renderKind===`comment`?(0,W.jsx)(`span`,{className:G(`italic text-muted-foreground select-text`,o.text),title:`COMMENT: ${e.label}`,"data-metric-type":`comment`,children:e.label},t):(0,W.jsxs)(`span`,{className:G(`inline-flex items-center gap-1 rounded font-mono border ${e.colorClasses} bg-opacity-60 shadow-sm cursor-help transition-colors hover:bg-opacity-80`,o.padding,o.text),title:e.tooltip,children:[e.icon&&(0,W.jsx)(`span`,{className:o.icon,children:e.icon}),(0,W.jsx)(`span`,{children:e.label})]},t))})});uU.displayName=`MetricVisualizer`;function dU(e){if(!e||e<0)return``;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}`:`${r}s`}var fU=({source:e,metrics:t,status:n=`pending`,depth:r=0,size:i=`normal`,filter:a,isSelected:o=!1,isHighlighted:s=!1,isLeaf:c=!1,isHeader:l=!1,label:u,showDuration:d=!1,duration:f,actions:p,metricGroups:m,onClick:h,onDoubleClick:g,onHover:_,className:v})=>{let y={compact:{indent:12,baseIndent:8,fontSize:`text-xs md:text-sm`},normal:{indent:16,baseIndent:12,fontSize:`text-sm md:text-base`},focused:{indent:20,baseIndent:16,fontSize:`text-base md:text-lg`}}[i],b=r*y.indent,x=J.from(t??(e?.getDisplayMetrics(a?{origins:a.allowedOrigins}:void 0)||[])).toArray(),S=t=>{h?.(e,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},C=t=>{t.preventDefault(),g?.(e)},w=()=>{_?.(e)},T=()=>{_?.(null)},E=u??(x.length===0?e?`Block ${e.id}`:`Block`:void 0);return(0,W.jsxs)(`div`,{className:G(`flex items-center gap-2 transition-all px-2`,l&&`font-semibold bg-muted/30`,h&&`cursor-pointer hover:bg-muted/50`,o&&`bg-primary/10`,s&&`bg-muted/40`,c&&`font-bold`,v),style:{paddingLeft:`${b+y.baseIndent}px`,minHeight:`var(--wod-preview-statement-height)`,paddingTop:`var(--wod-preview-statement-gap)`,paddingBottom:`var(--wod-preview-statement-gap)`},onClick:S,onDoubleClick:C,onMouseEnter:w,onMouseLeave:T,role:h?`button`:void 0,tabIndex:h?0:void 0,children:[(0,W.jsx)(`div`,{className:`flex-1 min-w-0`,children:m&&m.length>1?(0,W.jsx)(`div`,{className:`flex flex-col`,children:m.map(e=>jo.presentGroup([...e],`runtime-badge`).filter(e=>e.visible).map(e=>e.metric)).filter(e=>e.length>0).map((e,t,n)=>(0,W.jsx)(`div`,{className:G(t<n.length-1&&`border-b border-border/20 pb-0.5 mb-0.5`),children:(0,W.jsx)(uU,{metrics:e,size:i,filter:a,className:G(`inline-flex`,y.fontSize)})},t))}):x.length>0?(0,W.jsx)(uU,{metrics:x,size:i,filter:a,className:G(`inline-flex`,y.fontSize)}):E?(0,W.jsx)(`span`,{className:G(`text-muted-foreground`,y.fontSize),children:E}):(0,W.jsx)(`span`,{className:`text-muted-foreground/50 italic text-xs`,children:`No data`})}),d&&f!==void 0&&f>0&&(0,W.jsx)(`div`,{className:`flex-shrink-0 text-muted-foreground tabular-nums text-right min-w-[40px]`,style:{fontSize:i===`compact`?`10px`:`12px`},children:dU(f)}),p&&(0,W.jsx)(`div`,{className:`flex-shrink-0 flex items-center gap-1`,children:p})]})},pU={display:P,promote:Kn,private:m,result:Ft},mU={display:`text-green-500 dark:text-green-400`,promote:`text-blue-500 dark:text-blue-400`,private:`text-amber-500 dark:text-amber-400`,result:`text-purple-500 dark:text-purple-400`},hU={display:`bg-green-500/10 dark:bg-green-900/30`,promote:`bg-blue-500/10 dark:bg-blue-900/30`,private:`bg-amber-500/10 dark:bg-amber-900/30`,result:`bg-purple-500/10 dark:bg-purple-900/30`},gU=({visibility:e})=>{let t=pU[e];return(0,W.jsxs)(`span`,{className:G(`inline-flex items-center gap-1 text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded`,mU[e],hU[e]),title:Hl[e],children:[(0,W.jsx)(t,{className:`h-3 w-3`}),Hl[e]]})},_U=({open:e,onOpenChange:t,children:n})=>(0,W.jsx)(j,{appear:!0,show:e,as:U.Fragment,children:(0,W.jsx)(F,{as:`div`,className:`relative z-[200]`,onClose:()=>t?.(!1),children:n})}),vU=U.forwardRef(({className:e,children:t,...n},r)=>(0,W.jsx)(ce,{as:U.Fragment,enter:`ease-out duration-300`,enterFrom:`opacity-0 scale-95`,enterTo:`opacity-100 scale-100`,leave:`ease-in duration-200`,leaveFrom:`opacity-100 scale-100`,leaveTo:`opacity-0 scale-95`,children:(0,W.jsx)(`div`,{className:`fixed inset-0 overflow-y-auto`,children:(0,W.jsxs)(`div`,{className:`flex min-h-full items-center justify-center p-4 text-center`,children:[(0,W.jsx)(ce,{as:U.Fragment,enter:`ease-out duration-300`,enterFrom:`opacity-0`,enterTo:`opacity-100`,leave:`ease-in duration-200`,leaveFrom:`opacity-100`,leaveTo:`opacity-0`,children:(0,W.jsx)(`div`,{className:`fixed inset-0 bg-black/25 dark:bg-black/25`})}),(0,W.jsx)(Xe,{ref:r,className:G(`relative w-full max-w-md transform overflow-hidden rounded-2xl bg-popover text-popover-foreground p-6 text-left align-middle shadow-xl transition-all border border-border`,e),...n,children:t})]})})}));vU.displayName=`DialogContent`;var yU=({className:e,...t})=>(0,W.jsx)(`div`,{className:G(`flex flex-col space-y-1.5 text-center sm:text-left mb-4`,e),...t});yU.displayName=`DialogHeader`;var bU=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Ke,{ref:n,as:`h3`,className:G(`text-lg font-medium leading-6 text-foreground`,e),...t}));bU.displayName=`DialogTitle`;var xU=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(He,{ref:n,className:G(`text-sm text-muted-foreground`,e),...t}));xU.displayName=`DialogDescription`;var SU=[`Statements`,`Behaviors`,`Memory`],CU=({open:e,onOpenChange:t,block:n,runtime:r})=>{let[i,a]=(0,U.useState)(0),o=(0,U.useMemo)(()=>!r.script||!n.sourceIds.length?[]:r.script.getIds(n.sourceIds),[r.script,n.sourceIds]),s=(0,U.useMemo)(()=>n.behaviors.map(e=>e.constructor.name),[n.behaviors]),l=(0,U.useMemo)(()=>n.getAllMemory(),[n]);return(0,W.jsx)(_U,{open:e,onOpenChange:t,children:(0,W.jsxs)(vU,{className:`max-w-2xl max-h-[80vh] flex flex-col overflow-hidden`,children:[(0,W.jsxs)(yU,{children:[(0,W.jsx)(bU,{children:(0,W.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,W.jsx)(`span`,{children:n.label}),n.blockType&&(0,W.jsx)(`span`,{className:`text-[10px] uppercase px-1.5 py-0.5 rounded bg-primary/10 text-primary/70 font-bold tracking-wider`,children:n.blockType})]})}),(0,W.jsxs)(`div`,{className:`text-[10px] font-mono text-muted-foreground`,children:[`Key: `,n.key.toString()]})]}),(0,W.jsxs)(on,{selectedIndex:i,onChange:a,children:[(0,W.jsx)(nn,{className:`flex border-b border-border gap-0`,children:SU.map(e=>(0,W.jsx)(me,{className:({selected:e})=>G(`px-4 py-2 text-sm font-medium transition-colors outline-none`,`border-b-2 -mb-px`,e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground hover:border-border`),children:e},e))}),(0,W.jsxs)(_e,{className:`flex-1 min-h-0 overflow-y-auto mt-2`,children:[(0,W.jsx)(c,{children:(0,W.jsx)(wU,{statements:o})}),(0,W.jsx)(c,{children:(0,W.jsx)(TU,{names:s})}),(0,W.jsx)(c,{children:(0,W.jsx)(EU,{block:n,locations:l})})]})]})]})})},wU=({statements:e})=>e.length===0?(0,W.jsx)(DU,{text:`No source statements`}):(0,W.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,W.jsxs)(`div`,{className:`grid grid-cols-[60px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:`ID`}),(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:`Fragments`})]}),e.map(e=>(0,W.jsxs)(`div`,{className:`grid grid-cols-[60px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-mono text-muted-foreground tabular-nums`,children:e.id}),(0,W.jsx)(`div`,{className:`py-0.5`,children:(0,W.jsx)(fU,{metrics:e.metrics,size:`compact`})})]},e.id))]}),TU=({names:e})=>e.length===0?(0,W.jsx)(DU,{text:`No behaviors attached`}):(0,W.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,W.jsxs)(`div`,{className:`grid grid-cols-[40px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:`#`}),(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:`Behavior`})]}),e.map((e,t)=>(0,W.jsxs)(`div`,{className:`grid grid-cols-[40px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-mono text-muted-foreground tabular-nums`,children:t+1}),(0,W.jsx)(`div`,{className:`px-3 py-1.5 text-sm font-mono`,children:e})]},t))]}),EU=({locations:e})=>e.length===0?(0,W.jsx)(DU,{text:`No memory locations`}):(0,W.jsxs)(`div`,{className:`border border-border rounded-md overflow-hidden`,children:[(0,W.jsxs)(`div`,{className:`grid grid-cols-[120px_1fr] text-[10px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/40 border-b border-border`,children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:`Tag`}),(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:`Fragments`})]}),e.map((e,t)=>(0,W.jsxs)(`div`,{className:`grid grid-cols-[120px_1fr] items-center border-b border-border/50 last:border-b-0 hover:bg-muted/20 transition-colors`,children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5`,children:(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:e.tag})}),(0,W.jsx)(`div`,{className:`py-0.5`,children:(0,W.jsx)(fU,{metrics:e.metrics,size:`compact`})})]},`${e.tag}-${t}`))]}),DU=({text:e})=>(0,W.jsx)(`div`,{className:`flex items-center justify-center py-8 text-sm text-muted-foreground italic`,children:e}),OU=({block:e,isLeaf:t,debug:n})=>{let{isDebugMode:r}=Jv(),i=n??r,a=az(),{elapsed:o,isRunning:s,timeSpans:c}=gz(e.key.toString()),l=nz(e),[u,d]=(0,U.useState)([]),[f,p]=(0,U.useState)([]),[m,h]=(0,U.useState)([]),[g,_]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let t=()=>{let t=e.getMetricMemoryByVisibility(`display`);if(d(t.map(e=>e.metrics)),i){let t=e.getMetricMemoryByVisibility(`promote`);p(t.map(e=>e.metrics));let n=e.getMetricMemoryByVisibility(`private`);h(n.map(e=>e.metrics))}};t();let n=(i?[...e.getMetricMemoryByVisibility(`display`),...e.getMetricMemoryByVisibility(`promote`),...e.getMetricMemoryByVisibility(`private`)]:e.getMetricMemoryByVisibility(`display`)).map(e=>e.subscribe(()=>t()));return()=>n.forEach(e=>e())},[e,i]);let v=c.length>0,y=(e,t,n,r)=>e.length===0?null:(0,W.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[n&&(0,W.jsx)(gU,{visibility:t}),e.map((e,n)=>(0,W.jsx)(fU,{metrics:e,size:r?`normal`:`compact`,isLeaf:r},`${t}-${n}`))]}),b=!t&&l!=null,x=(0,U.useMemo)(()=>{let t=u.flatMap(e=>lU([...e],`runtime-badge`).filter(e=>e.visible)),n=e.label?.trim();return n?t.filter(e=>e.label.trim()!==n):t},[u,e.label]),S=i&&(0,W.jsx)(`button`,{onClick:()=>_(!0),className:`h-7 w-7 rounded-md flex items-center justify-center hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0`,title:`Inspect block`,children:(0,W.jsx)(Mn,{className:`h-4 w-4`})});return(0,W.jsxs)(`div`,{className:G(`relative w-full`,t?`animate-in fade-in slide-in-from-left-1 duration-300`:``),children:[(0,W.jsxs)(`div`,{className:G(`rounded-md border text-sm transition-all`,t?`bg-card shadow-sm border-primary/40 ring-1 ring-primary/15`:`bg-muted/40 border-transparent text-muted-foreground hover:bg-muted/50 hover:border-border/50`),children:[t?(0,W.jsxs)(`div`,{className:`p-3`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[e.label&&(0,W.jsx)(`span`,{className:`text-[13.5px] font-bold tracking-tight text-foreground leading-tight`,children:e.label}),e.blockType&&i&&(0,W.jsx)(`span`,{className:`text-[10px] uppercase px-1.5 py-0.5 rounded bg-primary/5 text-primary/70 font-bold tracking-wider`,children:e.blockType}),S]}),(0,W.jsxs)(`div`,{className:`flex items-center flex-wrap gap-1.5 mt-1.5 min-w-0`,children:[x.map((e,t)=>e.renderKind===`comment`?(0,W.jsx)(`span`,{className:`text-[11.5px] italic text-muted-foreground select-text`,title:e.tooltip,children:e.label},t):(0,W.jsxs)(`span`,{className:G(`inline-flex items-center gap-1 rounded-md border px-2 py-1 font-mono text-[11.5px] font-bold tabular-nums cursor-help transition-colors`,e.colorClasses),title:e.tooltip,children:[e.icon&&(0,W.jsx)(`span`,{className:`text-[11px] leading-none`,children:e.icon}),e.label]},t)),v&&(0,W.jsxs)(`div`,{className:G(`ml-auto flex items-center gap-1.5 px-2 py-1 rounded-md font-mono text-[11.5px] font-bold tabular-nums shrink-0`,s?`bg-primary/10 text-primary animate-pulse`:`bg-muted text-muted-foreground`),children:[(0,W.jsx)(Ze,{className:`h-3 w-3`}),SH(o)]})]}),i&&(0,W.jsx)(`div`,{className:`text-[10px] font-mono text-muted-foreground/60 truncate max-w-[200px] mt-1`,children:e.key.toString()})]}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,W.jsx)(`span`,{className:`text-xs font-medium tracking-tight text-muted-foreground/80 truncate`,children:b?`Round`:e.label}),b&&l?(0,W.jsxs)(`span`,{className:`font-mono text-[15px] font-bold tracking-tight text-foreground tabular-nums shrink-0 leading-none`,children:[l.current,l.total!==void 0&&(0,W.jsxs)(`span`,{className:`text-[11px] font-medium text-muted-foreground`,children:[` / `,l.total]})]}):v?(0,W.jsxs)(`span`,{className:`flex items-center gap-1.5 font-mono text-[11px] font-semibold tabular-nums text-foreground shrink-0`,children:[(0,W.jsx)(Ze,{className:`h-3 w-3`}),SH(o)]}):null,S]}),u.length>0&&(0,W.jsx)(`div`,{className:`flex flex-col gap-1 px-3 pb-2`,children:y(u,`display`,i,t)})]}),i&&(f.length>0||m.length>0)&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1 px-3 pb-2`,children:[y(f,`promote`,!0,t),y(m,`private`,!0,t)]})]}),i&&(0,W.jsx)(CU,{open:g,onOpenChange:_,block:e,runtime:a})]})};function kU(e,t,n){return e.filter(e=>e.outputType===`segment`&&t===Math.min(e.stackLevel-1,n-1))}var AU=({runtime:e,outputs:t,debug:n=!1})=>{let r=e.stack.blocks;if(r.length===0)return(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center p-8 text-muted-foreground border-2 border-dashed rounded-lg bg-muted/10`,children:[(0,W.jsx)(Re,{className:`h-8 w-8 mb-2 opacity-20`}),(0,W.jsx)(`span`,{className:`text-sm`,children:`No Active Blocks`})]});let i=(e,n)=>{let r=kU(t,e,n);if(r.length===0)return null;let i=r.reduce((e,t)=>e+(t.getMetric(q.Elapsed)?.value??0),0);return(0,W.jsxs)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground py-1 pl-2.5 border-l-2 border-border/85 ml-3 my-0.5`,children:[(0,W.jsx)(Ft,{className:`h-3 w-3 shrink-0`}),(0,W.jsxs)(`span`,{className:`font-semibold text-foreground`,children:[r.length,` completed`]}),(0,W.jsx)(`span`,{className:`w-px h-2.5 bg-border/70`}),(0,W.jsx)(st,{className:`h-3 w-3 shrink-0`}),(0,W.jsx)(`span`,{className:`font-mono font-semibold tabular-nums text-metric-time`,children:(e=>{let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`})(i)})]})},a=[...r].reverse();return(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5 relative`,children:a.map((e,t)=>{let r=t===a.length-1;return(0,W.jsxs)(U.Fragment,{children:[(0,W.jsx)(OU,{block:e,isLeaf:r,debug:n}),i(t,a.length)]},e.key.toString())})})},jU=()=>{let e=uz();return e?(0,W.jsx)(`div`,{className:`rounded-[10px] border border-dashed border-border/90 bg-muted/30 p-2.5 transition-all`,children:(0,W.jsx)(fU,{metrics:e.metrics,size:`compact`,isLeaf:!1})}):(0,W.jsxs)(`div`,{className:`flex items-center gap-3 text-sm p-3 border border-dashed rounded-lg text-muted-foreground bg-muted/10`,children:[(0,W.jsx)(Ft,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`italic`,children:`End of section`})]})},MU=U.memo(U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`rounded-lg border bg-card text-card-foreground shadow-sm`,e),...t})));MU.displayName=`Card`;var NU=U.memo(U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`flex flex-col space-y-1.5 p-6`,e),...t})));NU.displayName=`CardHeader`;var PU=U.memo(U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`h3`,{ref:n,className:G(`text-2xl font-semibold leading-none tracking-tight`,e),...t})));PU.displayName=`CardTitle`;var FU=U.memo(U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`p`,{ref:n,className:G(`text-sm text-muted-foreground`,e),...t})));FU.displayName=`CardDescription`;var IU=U.memo(U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`p-6 pt-0`,e),...t})));IU.displayName=`CardContent`;var LU=U.memo(U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`flex items-center p-6 pt-0`,e),...t})));LU.displayName=`CardFooter`;var RU=()=>{let e=az(),{outputs:t}=oz(e),{isDebugMode:n}=Jv(),{isCompact:r}=NH();return e?(0,W.jsxs)(`div`,{className:G(`h-full flex flex-col overflow-hidden bg-slate-50/50 dark:bg-slate-900/50`,r?`gap-2 p-2`:`gap-4 p-4`),children:[(0,W.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col overflow-y-auto`,children:(0,W.jsx)(AU,{runtime:e,outputs:t,debug:n})}),(0,W.jsxs)(MU,{className:`shrink-0 bg-muted/30 border-dashed`,children:[(0,W.jsx)(NU,{className:G(r?`p-2 pb-0`:`p-3 pb-0`),children:(0,W.jsx)(PU,{className:G(`font-mono font-semibold text-muted-foreground uppercase tracking-[0.14em]`,r?`text-[10px]`:`text-[11px]`),children:`Up Next`})}),(0,W.jsx)(IU,{className:G(r?`p-2`:`p-3`),children:(0,W.jsx)(jU,{runtime:e})})]})]}):null},zU=new class{state=`not-loaded`;listeners=new Map;loadPromise=null;appId=null;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){let n=this.listeners.get(e)??[];this.listeners.set(e,n.filter(e=>e!==t))}emit(e,...t){this.listeners.get(e)?.forEach(e=>e(...t))}getState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit(`state-changed`,e))}load(e){return this.loadPromise&&this.appId===e?this.loadPromise:(this.appId=e,this.loadPromise=this._load(e).catch(t=>{throw this.appId===e&&(this.loadPromise=null,this.appId=null),t}),this.loadPromise)}_load(e){return this.setState(`loading`),new Promise((t,n)=>{window.__onGCastApiAvailable=(r,i)=>{if(!r){console.warn(`[Cast SDK] Not available:`,i),this.setState(`unavailable`),n(Error(`Cast SDK unavailable`));return}try{this._initFramework(e),t()}catch(e){this.setState(`unavailable`),n(e)}};let r=`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`;if(!document.querySelector(`script[src="${r}"]`)){let e=document.createElement(`script`);e.src=r,e.onerror=()=>{this.setState(`unavailable`),n(Error(`Failed to load cast_sender.js`))},document.head.appendChild(e)}})}_initFramework(e){let{cast:t,chrome:n}=window;if(!t?.framework)throw Error(`cast.framework not found after SDK load`);let r=t.framework.CastContext.getInstance();r.setOptions({receiverApplicationId:e,autoJoinPolicy:n.cast.AutoJoinPolicy.ORIGIN_SCOPED,resumeSavedSession:!0}),r.addEventListener(t.framework.CastContextEventType.SESSION_STATE_CHANGED,e=>{let n=t.framework.SessionState;switch(e.sessionState){case n.SESSION_STARTED:case n.SESSION_RESUMED:this.setState(`session-active`),this.emit(`session-started`,r.getCurrentSession());break;case n.SESSION_ENDED:case n.NO_SESSION:this.setState(`ready`),this.emit(`session-ended`)}}),this.setState(`ready`),console.log(`[Cast SDK] Initialised with App ID:`,e)}async requestSession(){let{cast:e}=window;if(!e?.framework)throw Error(`Cast SDK not loaded`);let t=e.framework.CastContext.getInstance(),n=await t.requestSession();if(n)throw n===`cancel`?Error(`cancel`):(console.error(`[Cast SDK] requestSession() error code:`,n),Error(`Cast session request failed: ${n}`));let r=t.getCurrentSession();console.log(`[Cast SDK] requestSession() succeeded — sessionId:`,r?.getSessionId?.())}endSession(){window.cast?.framework?.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}isSessionActive(){return this.state===`session-active`}getSession(){return window.cast?.framework?.CastContext.getInstance()?.getCurrentSession()??null}},BU=`38F01E0E`,VU=(e=>!!e&&e!==`CC1AD845`)(BU);function HU(e){let t=[],n=e.VITE_CAST_STUN_URL?.trim();t.push({urls:n||`stun:stun.l.google.com:19302`});let r=e.VITE_CAST_TURN_URL?.trim();return r&&t.push({urls:r,username:e.VITE_CAST_TURN_USERNAME?.trim()||void 0,credential:e.VITE_CAST_TURN_CREDENTIAL?.trim()||void 0}),t}var UU=HU({BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,VITE_API_URL:``,VITE_BASE_PATH:``,VITE_STORAGE:`indexed-db`}),WU=`urn:x-cast:com.wodwiki`,GU=class{session;listeners=new Set;boundListener=null;constructor(e){this.session=e,this.boundListener=(e,t)=>{try{console.log(`[SenderCastSignaling] RAW incoming:`,typeof t,typeof t==`string`?t.substring(0,120):JSON.stringify(t).substring(0,120));let e=typeof t==`string`?JSON.parse(t):t;console.log(`[SenderCastSignaling] Parsed signal type:`,e.type);for(let t of this.listeners)t(e)}catch(e){console.error(`[SenderCastSignaling] Failed to parse incoming signal`,e)}},this.session.addMessageListener(WU,this.boundListener),console.log(`[SenderCastSignaling] Listening on ${WU}`),console.log(`[SenderCastSignaling] Session state: ${this.session.getSessionState?.()}`)}send(e){console.log(`[SenderCastSignaling] Sending: ${e.type}`),this.session.sendMessage(WU,e).then(()=>console.log(`[SenderCastSignaling] sendMessage(${e.type}) OK`)).catch(t=>console.error(`[SenderCastSignaling] sendMessage(${e.type}) FAILED`,t))}onSignal(e){return this.listeners.add(e),()=>this.listeners.delete(e)}dispose(){if(this.boundListener){try{this.session.removeMessageListener(WU,this.boundListener)}catch{}this.boundListener=null}this.listeners.clear()}},KU=class{role;signaling;pc;dc=null;signalUnsub=null;disposed=!1;messageHandlers=new Set;connectedHandlers=new Set;disconnectedHandlers=new Set;signalQueue=Promise.resolve();pendingIceCandidates=[];offerRetryTimer=null;offerRetryIntervalMs;localCandidateCount=0;gatheringComplete=!1;constructor(e,t,n={}){this.role=e,this.signaling=t,console.log(`[WebRtcRpcTransport:${e}] Initializing transport`),this.offerRetryIntervalMs=n.offerRetryIntervalMs??1e3,this.pc=new RTCPeerConnection({iceServers:UU}),this.pc.onicecandidate=t=>{t.candidate?(this.localCandidateCount++,console.log(`[WebRtcRpcTransport:${e}] ICE candidate (local):`,t.candidate.candidate.substring(0,60)+`...`),this.signaling.send({type:`webrtc-ice`,candidate:t.candidate.toJSON()})):(this.gatheringComplete=!0,console.log(`[WebRtcRpcTransport:${e}] ICE gathering complete (${this.localCandidateCount} candidates)`))},this.pc.onconnectionstatechange=()=>{let t=this.pc.connectionState;console.log(`[WebRtcRpcTransport:${e}] Connection state: ${t}`),(t===`disconnected`||t===`failed`||t===`closed`)&&this.notifyDisconnected()},this.pc.oniceconnectionstatechange=()=>{console.log(`[WebRtcRpcTransport:${e}] ICE connection state: ${this.pc.iceConnectionState}`)},this.pc.onsignalingstatechange=()=>{console.log(`[WebRtcRpcTransport:${e}] Signaling state: ${this.pc.signalingState}`)},this.signalUnsub=this.signaling.onSignal(e=>this.receiveSignal(e))}receiveSignal(e){console.log(`[WebRtcRpcTransport:${this.role}] Incoming signal: ${e.type}`),this.signalQueue=this.signalQueue.then(()=>this.handleSignal(e))}retransmitOffer(){return this.disposed||this.pc.signalingState!==`have-local-offer`||!this.pc.localDescription?!1:(console.log(`[WebRtcRpcTransport:${this.role}] Retransmitting offer`),this.signaling.send({type:`webrtc-offer`,sdp:this.pc.localDescription.sdp}),!0)}startOfferRetry(){this.role===`offerer`&&this.offerRetryTimer===null&&(this.offerRetryTimer=window.setInterval(()=>{this.retransmitOffer()||this.stopOfferRetry()},this.offerRetryIntervalMs))}stopOfferRetry(){this.offerRetryTimer!==null&&(window.clearInterval(this.offerRetryTimer),this.offerRetryTimer=null)}get connected(){return this.dc?.readyState===`open`}get needsClockSync(){return!0}send(e){if(!this.dc||this.dc.readyState!==`open`){console.warn(`[WebRtcRpcTransport] DataChannel not open — dropping message`);return}this.dc.send(JSON.stringify(e))}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onConnected(e){return this.connectedHandlers.add(e),()=>this.connectedHandlers.delete(e)}onDisconnected(e){return this.disconnectedHandlers.add(e),()=>this.disconnectedHandlers.delete(e)}dispose(){if(this.disposed)return;this.disposed=!0,this.stopOfferRetry(),this.signalUnsub?.(),this.signalUnsub=null;let e=this.dc?.readyState===`open`,t=[...this.disconnectedHandlers];if(this.messageHandlers.clear(),this.connectedHandlers.clear(),this.disconnectedHandlers.clear(),this.dc?.close(),this.pc.close(),this.signaling.dispose(),e)for(let e of t)e()}connect(e=15e3){if(console.log(`[WebRtcRpcTransport:${this.role}] connect() starting, timeout=${e}ms`),this.connected)return console.log(`[WebRtcRpcTransport:${this.role}] Already connected — short-circuiting`),Promise.resolve();let{promise:t,resolve:n,reject:r}=Promise.withResolvers(),i=Date.now(),a=setTimeout(()=>{this.stopOfferRetry();let t=`pcState=${this.pc.connectionState}, iceState=${this.pc.iceConnectionState}, sigState=${this.pc.signalingState}, dcState=${this.dc?.readyState??`null`}, localCandidates=${this.localCandidateCount}${this.gatheringComplete?``:` (still gathering)`}`;console.error(`[WebRtcRpcTransport:${this.role}] TIMEOUT after ${e}ms — ${t}`),r(Error(`WebRTC connect timed out after ${e}ms — ${t}`))},e),o=()=>{clearTimeout(a),this.stopOfferRetry(),console.log(`[WebRtcRpcTransport:${this.role}] DataChannel OPEN in ${Date.now()-i}ms`),this.notifyConnected(),n()};return this.role===`offerer`?(console.log(`[WebRtcRpcTransport:offerer] Creating DataChannel…`),this.dc=this.pc.createDataChannel(`wod-wiki-rpc`,{ordered:!0}),this.wireDataChannel(this.dc,o),console.log(`[WebRtcRpcTransport:offerer] Creating offer…`),this.pc.createOffer().then(e=>(console.log(`[WebRtcRpcTransport:offerer] Offer created, SDP length=${e.sdp?.length}`),this.pc.setLocalDescription(e))).then(()=>{console.log(`[WebRtcRpcTransport:offerer] Local description set — sending offer via signaling`),this.retransmitOffer(),this.startOfferRetry(),console.log(`[WebRtcRpcTransport:offerer] Offer sent — waiting for answer…`)}).catch(e=>{clearTimeout(a),console.error(`[WebRtcRpcTransport:offerer] Failed to create/set offer`,e),r(e)})):(console.log(`[WebRtcRpcTransport:answerer] Waiting for ondatachannel…`),this.pc.ondatachannel=e=>{console.log(`[WebRtcRpcTransport:answerer] Remote DataChannel received: ${e.channel.label}`),this.dc=e.channel,this.wireDataChannel(this.dc,o)}),t}wireDataChannel(e,t){e.onopen=()=>t(),e.onclose=()=>{this.disposed||this.notifyDisconnected()},e.onerror=e=>{console.error(`[WebRtcRpcTransport] DataChannel error`,e)},e.onmessage=e=>{try{let t=JSON.parse(e.data);for(let e of this.messageHandlers)e(t)}catch(e){console.error(`[WebRtcRpcTransport] Failed to parse RPC message`,e)}}}async handleSignal(e){try{switch(e.type){case`webrtc-offer`:{if(this.role!==`answerer`){console.warn(`[WebRtcRpcTransport:${this.role}] Ignoring offer (not an answerer)`);return}if(this.pc.remoteDescription?.sdp===e.sdp){console.log(`[WebRtcRpcTransport:answerer] Ignoring duplicate offer (already processed)`);return}console.log(`[WebRtcRpcTransport:answerer] Received offer, length=${e.sdp.length}`),await this.pc.setRemoteDescription({type:`offer`,sdp:e.sdp}),console.log(`[WebRtcRpcTransport:answerer] Remote description set — creating answer`);let t=await this.pc.createAnswer();console.log(`[WebRtcRpcTransport:answerer] Answer created, length=${t.sdp?.length}`),await this.pc.setLocalDescription(t),console.log(`[WebRtcRpcTransport:answerer] Local description set — sending answer via signaling`),this.signaling.send({type:`webrtc-answer`,sdp:this.pc.localDescription.sdp}),await this.processPendingIceCandidates();break}case`webrtc-answer`:if(this.role!==`offerer`){console.warn(`[WebRtcRpcTransport:${this.role}] Ignoring answer (not an offerer)`);return}if(this.pc.signalingState!==`have-local-offer`){console.log(`[WebRtcRpcTransport:offerer] Ignoring duplicate answer (already applied)`);return}console.log(`[WebRtcRpcTransport:offerer] Received answer, length=${e.sdp.length}`),await this.pc.setRemoteDescription({type:`answer`,sdp:e.sdp}),console.log(`[WebRtcRpcTransport:offerer] Remote description set — processing pending candidates…`),await this.processPendingIceCandidates();break;case`webrtc-ice`:{let t=e.candidate;this.pc.remoteDescription?(console.log(`[WebRtcRpcTransport:${this.role}] Adding remote ICE candidate`),await this.pc.addIceCandidate(t)):(console.log(`[WebRtcRpcTransport:${this.role}] Buffering candidate until remote description is set`),this.pendingIceCandidates.push(t));break}case`cast-ready`:this.role===`offerer`&&this.retransmitOffer()}}catch(e){console.error(`[WebRtcRpcTransport:${this.role}] Signal handling error`,e)}}async processPendingIceCandidates(){if(this.pendingIceCandidates.length===0)return;console.log(`[WebRtcRpcTransport:${this.role}] Processing ${this.pendingIceCandidates.length} buffered ICE candidates`);let e=[...this.pendingIceCandidates];this.pendingIceCandidates=[];for(let t of e)try{await this.pc.addIceCandidate(t),console.log(`[WebRtcRpcTransport:${this.role}] Buffered ICE candidate added OK`)}catch(e){console.error(`[WebRtcRpcTransport:${this.role}] Failed to add buffered ICE candidate`,e)}}notifyConnected(){for(let e of this.connectedHandlers)e()}notifyDisconnected(){for(let e of this.disconnectedHandlers)e()}},qU={"not-loaded":`ready`,loading:`ready`,unavailable:`unavailable`,ready:`ready`,"session-active":`session-active`},JU=class{_state;stateListeners=new Set;sdkUnsubState=null;sdkUnsubEnded=null;activeTransport=null;disposed=!1;constructor(){this._state=qU[zU.getState()],this.subscribeToSdk(),VU&&typeof window<`u`&&zU.load(BU).catch(()=>{})}get state(){return this._state}onStateChanged(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}setState(e){if(this._state!==e){this._state=e;for(let t of[...this.stateListeners])t(e)}}subscribeToSdk(){this.sdkUnsubState=zU.on(`state-changed`,e=>{let t=qU[e]??`ready`;this._state!==`session-active`&&(this._state!==`connecting`||t!==`session-active`)&&this.setState(t)}),this.sdkUnsubEnded=zU.on(`session-ended`,()=>{this.activeTransport=null,this.setState(`session-ended`)})}async startSession(){if(this.disposed)throw Error(`ChromecastBackend: startSession after dispose`);if(!VU)throw this.setState(`unavailable`),Error(`ChromecastBackend: VITE_CAST_APP_ID is not configured`);this.setState(`connecting`);let e=null;try{try{await zU.load(BU)}catch(e){throw this.setState(qU[zU.getState()]),e}if(this.disposed)throw Error(`ChromecastBackend: dispose() called during SDK load`);if(zU.getState()===`unavailable`)throw this.setState(`unavailable`),Error(`ChromecastBackend: Cast not supported in this browser`);if(await zU.requestSession(),this.disposed)throw Error(`ChromecastBackend: dispose() called during requestSession`);let t=zU.getSession();if(!t)throw Error(`ChromecastBackend: no Cast session after requestSession()`);try{await t.sendMessage(`urn:x-cast:com.wodwiki`,{type:`ping`,timestamp:Date.now()})}catch(e){cL(`ChromecastBackend`,`namespace ping failed`,e)}e=new KU(`offerer`,new GU(t)),await e.connect()}catch(t){throw e?.dispose(),!this.disposed&&this._state===`connecting`&&this.setState(`ready`),t}return this.activeTransport=e,e.onDisconnected(()=>{this._state===`session-active`&&(this.activeTransport=null,this.setState(`session-ended`))}),this.setState(`session-active`),e}async resumeSession(){if(this.disposed)throw Error(`ChromecastBackend: resumeSession after dispose`);if(this.activeTransport)return this.activeTransport;await zU.load(BU);let e=zU.getSession();if(!e)throw Error(`ChromecastBackend: no Cast session to resume`);let t=new KU(`offerer`,new GU(e));try{await t.connect()}catch(e){throw t.dispose(),e}return this.activeTransport=t,t.onDisconnected(()=>{this._state===`session-active`&&(this.activeTransport=null,this.setState(`session-ended`))}),this.setState(`session-active`),t}endSession(){try{zU.endSession()}catch{}this.activeTransport&&=(this.activeTransport.dispose(),null),this._state!==`unavailable`&&this.setState(`ready`)}dispose(){this.disposed||(this.disposed=!0,this.endSession(),this.sdkUnsubState?.(),this.sdkUnsubEnded?.(),this.sdkUnsubState=null,this.sdkUnsubEnded=null,this.stateListeners.clear())}},YU=null;function XU(){return YU||(YU=new JU,YU)}function ZU(e,t,n=0,r){let i=(0,U.useRef)(null),a=(0,U.useRef)({snapshot:e,handler:t,priority:n,keyboard:r?.keyboard===!0});a.current={snapshot:e,handler:t,priority:n,keyboard:r?.keyboard===!0},(0,U.useEffect)(()=>{let e=hW(a.current);return i.current=e,()=>{_W(e),i.current=null}},[]),(0,U.useEffect)(()=>{i.current!==null&&gW(i.current,a.current)})}function QU(){return(0,U.useSyncExternalStore)(TW,CW,CW)}function $U(){return(0,U.useSyncExternalStore)(TW,wW,wW)}var eW=[`next`,`playback`,`stop-request`,`stop-confirm`,`stop-cancel`,`values-open`,`entry-cancel`,`entry-save`,`entry-skip`,`reps-adjust`,`reps-set`,`reps-select`,`choice-select`,`ready-start`,`dismiss`];function tW(e){if(typeof e!=`object`||!e)return!1;let t=e.kind;if(typeof t!=`string`||!eW.includes(t))return!1;let n=e;switch(t){case`entry-save`:return typeof n.fieldId==`string`&&typeof n.value==`number`&&Number.isFinite(n.value);case`entry-skip`:return typeof n.fieldId==`string`;case`reps-select`:return typeof n.occurrenceId==`string`;case`reps-adjust`:return typeof n.occurrenceId==`string`&&(n.delta===1||n.delta===-1);case`reps-set`:return typeof n.occurrenceId==`string`&&typeof n.value==`number`&&Number.isSafeInteger(n.value)&&n.value>=0;case`choice-select`:return typeof n.fieldId==`string`&&typeof n.index==`number`&&Number.isInteger(n.index);default:return!0}}var nW=0;function rW(){return nW+=1,`run-${Date.now().toString(36)}-${nW}`}var iW=new Map,aW=1,oW=1,sW=new Set,cW=null,lW=null;function uW(){let e=null;for(let t of iW.values())t.snapshot!==null&&(!e||t.priority>e.priority||t.priority===e.priority&&t.seq>e.seq)&&(e=t);return e}function dW(){let e=uW(),t=e?.snapshot??null,n=(e?.id??null)!==lW,r=t!==cW;if(cW=t,lW=e?.id??null,OW(t?.entry??null),r||n)for(let e of sW)e();GW()}function fW(){return cW}function pW(e){return sW.add(e),()=>sW.delete(e)}function mW(e,t){let n=uW(),r=n?.snapshot;if(!n||!r||r.runId!==e)return!1;try{return n.handler(t)===!0}catch{return!1}}function hW(e){let t=aW++;return iW.set(t,{id:t,seq:oW++,...e}),dW(),t}function gW(e,t){let n=iW.get(e);n&&(iW.set(e,{...n,...t}),dW())}function _W(e){iW.delete(e)&&dW()}var vW=``,yW=null,bW=new Set,xW=null;function SW(){for(let e of bW)e()}function CW(){return vW}function wW(){return yW}function TW(e){return bW.add(e),()=>bW.delete(e)}function EW(e,t=null){(vW!==e||yW!==t)&&(vW=e,yW=t,SW())}function DW(e){EW(e)}function OW(e){let t=e?.fieldId??null;t!==xW&&(xW=t,EW(``))}function kW(e,t,n){if(n===`clear`)return``;if(n===`back`){let n=e===`duration`?t.replace(`:`,``).slice(0,-1):t.slice(0,-1);return e===`duration`&&n.length>2?`${n.slice(0,-2)}:${n.slice(-2)}`:n}if(e===`duration`){if(!/^\d$/.test(n))return t;let e=t.split(`:`).join(``);if(!/^\d{0,4}$/.test(e+n))return t;let r=e+n;return r.length<=2?r:`${r.slice(0,-2)}:${r.slice(-2)}`}return e===`decimal`&&n===`.`?t.includes(`.`)?t:t+`.`:e===`decimal`&&n===`-`?t:/^\d$/.test(n)?t+n:t}function AW(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:`Enter a value`};switch(t){case`integer`:{if(!/^\d+$/.test(n))return{ok:!1,error:`Whole number required`};let e=Number.parseInt(n,10);return Number.isSafeInteger(e)?{ok:!0,value:e}:{ok:!1,error:`Number too large`}}case`decimal`:{if(!/^\d*\.?\d*$/.test(n)||!/\d/.test(n))return{ok:!1,error:`Invalid number`};let e=Number.parseFloat(n);return Number.isFinite(e)?{ok:!0,value:e}:{ok:!1,error:`Invalid number`}}case`duration`:{let e=/^(\d*):(\d{0,2})$/.exec(n);if(n.includes(`:`)&&(!e||!/\d/.test(n))||!e&&!/^\d{1,4}$/.test(n))return{ok:!1,error:`Use minutes and seconds`};let t=Number(e?e[1]||`0`:n.slice(0,-2)||`0`),r=Number(e?e[2]||`0`:n.slice(-2));if(r>59)return{ok:!1,error:`Seconds must be 0–59`};let i=(t*60+r)*1e3;return Number.isSafeInteger(i)?{ok:!0,value:i}:{ok:!1,error:`Duration too large`}}case`choice`:return{ok:!1,error:`Pick an option`}}}var jW=`wodwiki.clock.keyMode`;function MW(){try{return window.localStorage.getItem(jW)===`keypad`?`keypad`:`navigation`}catch{return`navigation`}}function NW(e){try{window.localStorage.setItem(jW,e)}catch{}}var PW={Numpad0:`0`,Numpad1:`1`,Numpad2:`2`,Numpad3:`3`,Numpad4:`4`,Numpad5:`5`,Numpad6:`6`,Numpad7:`7`,Numpad8:`8`,Numpad9:`9`},FW={8:`up`,2:`down`,4:`left`,6:`right`};function IW(e,t,n){let r=t?PW[t]:void 0;if(r)return{type:`digit`,digit:r,fromNumpad:!0};switch(t){case`NumpadEnter`:return{type:`enter`,keypad:!0};case`NumpadAdd`:return{type:`plus`};case`NumpadSubtract`:return{type:`minus`};case`NumpadDecimal`:return{type:`decimal`};case`NumpadMultiply`:return{type:`values`};case`NumpadDivide`:return{type:`playback`};case`Backspace`:return{type:`backspace`}}if(e===`Enter`&&n===3)return{type:`enter`,keypad:!0};switch(e){case`ArrowUp`:return{type:`direction`,direction:`up`};case`ArrowDown`:return{type:`direction`,direction:`down`};case`ArrowLeft`:return{type:`direction`,direction:`left`};case`ArrowRight`:return{type:`direction`,direction:`right`};case`Enter`:return{type:`enter`,keypad:!1};case`MediaPlayPause`:return{type:`playback`};case`Escape`:return{type:`escape`};case`+`:return{type:`plus`};case`-`:return{type:`minus`};case`*`:return{type:`values`};case`/`:return{type:`playback`};case`.`:case`,`:return{type:`decimal`};case`Backspace`:case`Clear`:return{type:`backspace`}}return/^[0-9]$/.test(e)?{type:`digit`,digit:e,fromNumpad:!1}:{type:`other`}}function LW(e,t){if(e.keyCode===179||e.keyCode===126||e.keyCode===127)return{kind:`playback`};if(e.key===`Select`||e.key===`Accept`||e.key===`DPAD_CENTER`||e.keyCode===23)return{kind:`select`};if(e.key===`GoBack`||e.key===`BrowserBack`||e.key===`Back`||e.keyCode===4||e.keyCode===461||e.keyCode===10009)return{kind:`cancel`};let n=IW(e.key,e.code,e.location),r={entryOpen:t?.entryOpen===!0,mode:t?.mode??MW()};switch(n.type){case`digit`:{if(r.entryOpen)return{kind:`digit`,digit:n.digit};let e=FW[n.digit];return e?{kind:`direction`,direction:e}:{kind:`digit`,digit:n.digit}}case`direction`:return{kind:`direction`,direction:n.direction};case`enter`:return n.keypad?{kind:`primary`}:r.mode===`keypad`?{kind:`primary`,ambiguous:!0}:{kind:`select`};case`decimal`:return r.entryOpen?{kind:`digit`,digit:`.`}:{kind:`none`};case`plus`:return{kind:`reps-adjust`,delta:1};case`minus`:return{kind:`reps-adjust`,delta:-1};case`values`:return{kind:`values`};case`playback`:return{kind:`playback`};case`backspace`:return r.entryOpen?{kind:`back`}:{kind:`none`};case`escape`:return{kind:`cancel`};case`other`:return{kind:`none`}}}function RW(e){if(!e)return!1;let t=e.tagName;return t===`BUTTON`||t===`INPUT`||t===`SELECT`||t===`TEXTAREA`||t===`A`||e.getAttribute(`role`)===`button`||e.getAttribute(`role`)===`option`||e.isContentEditable}function zW(e){let t=document.querySelector(`[data-clock-entry]`)??document.querySelector(`[data-clock-panel]`);if(!t)return!1;let n=Array.from(t.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null||e===document.activeElement);if(n.length===0)return!1;let r=document.activeElement;if(!r||!t.contains(r)||!n.includes(r))return n[0].focus(),!0;let i=r.getBoundingClientRect(),a=i.left+i.width/2,o=i.top+i.height/2,{primary:s,sign:c}={right:{primary:`x`,sign:1},left:{primary:`x`,sign:-1},down:{primary:`y`,sign:1},up:{primary:`y`,sign:-1}}[e],l=null,u=1/0;for(let e of n){if(e===r)continue;let t=e.getBoundingClientRect(),n=t.left+t.width/2-a,i=t.top+t.height/2-o,d=s===`x`?n:i,f=s===`x`?i:n;if(d*c<=2)continue;let p=Math.abs(d)+2*Math.abs(f);p<u&&(u=p,l=e)}return l?(l.focus(),!0):!1}function BW(e,t){let n=e.entry;if(!n||n.domain===`choice`)return!1;let r=AW(vW,n.domain);return r.ok===!1?(EW(vW,r.error),!0):t({kind:`entry-save`,fieldId:n.fieldId,value:r.value})}function VW(e){let t=e;return!t||!(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable)?!1:t.closest(`[data-clock-panel]`)===null&&t.closest(`[data-clock-entry]`)===null}function HW(e){if(e.ctrlKey||e.metaKey||e.altKey||e.isComposing)return;let t=uW();if(!t||!t.keyboard)return;let n=t.snapshot;if(n===null||n.status===`completed`&&n.phase!==`review`)return;let r=e.target;if(VW(r))return;let i=n.entry;if(i!==null&&r!==null&&r.closest(`[data-clock-entry]`)!==null||document.body.dataset.clockModal!==void 0&&document.body.dataset.clockModal!==``)return;OW(i);let a=LW(e,{entryOpen:i!==null});if(a.kind===`none`)return;if(e.repeat&&a.kind!==`digit`&&a.kind!==`back`){(RW(r)||UW(e))&&e.preventDefault();return}let o=t.handler,s=!1,c=UW(e);switch(a.kind){case`primary`:if(a.ambiguous){if(RW(document.activeElement))break;let e=document.querySelector(`[data-clock-panel]`),t=document.activeElement;if(!(!t||t===document.body||e!==null&&e.contains(t)))break}if(n.stopRequested){s=o({kind:`stop-confirm`});break}if(i){s=BW(n,o);break}if(n.phase===`review`){s=o({kind:`dismiss`});break}if(n.status===`idle`&&n.phase!==`collection`){s=o({kind:`ready-start`});break}s=o({kind:`next`});break;case`playback`:s=o({kind:`playback`});break;case`direction`:s=zW(a.direction);break;case`reps-adjust`:i||(s=o({kind:`reps-adjust`,occurrenceId:n.selectedOccurrenceId??``,delta:a.delta}));break;case`values`:i||(s=o({kind:`values-open`}));break;case`cancel`:n.stopRequested?s=o({kind:`stop-cancel`}):i?s=o({kind:`entry-cancel`}):n.status===`running`||n.status===`paused`?s=o({kind:`stop-request`}):n.phase===`review`&&(s=o({kind:`dismiss`}));break;case`back`:EW(vW.slice(0,-1)),s=!0;break;case`digit`:if(i?.domain===`choice`){let e=Number.parseInt(a.digit,10)-1;i.alternatives?.[e]&&(s=o({kind:`choice-select`,fieldId:i.fieldId,index:e}));break}if(i){EW(kW(i.domain,vW,a.digit)),s=!0;break}(n.phase===`live`||n.phase===`collection`)&&/^\d{0,5}$/.test(vW+a.digit)&&(EW(vW+a.digit),s=o({kind:`values-open`}))}(s||c)&&e.preventDefault()}function UW(e){return e.code===`NumpadEnter`||e.location===3}var WW=!1;function GW(){let e=[...iW.values()].some(e=>e.keyboard);e&&!WW&&typeof window<`u`?(window.addEventListener(`keydown`,HW),WW=!0):!e&&WW&&(window.removeEventListener(`keydown`,HW),WW=!1)}function KW(e){return typeof e==`string`&&e.length>0&&e.length<=512}function qW(e){if(typeof e!=`object`||!e)return null;let t=e;return!KW(t.runId)||!tW(t.command)?null:{runId:t.runId,command:t.command}}function JW(e,t){if(!t)return null;switch(e){case`next`:return{kind:`next`};case`start`:return t.phase===`ready`?{kind:`ready-start`}:{kind:`playback`};case`pause`:return{kind:`playback`};case`stop`:return{kind:`stop-request`};case`dismiss`:return{kind:`dismiss`};default:return null}}var YW=new Set;function XW(e){return YW.add(e),()=>{YW.delete(e)}}function ZW(e){for(let t of YW)try{t(e)}catch(e){hL(`resultRecorder`,`error in listener:`,e)}}function QW(e){return{async record({resultId:t,data:n,createdAt:r}){let i=await e.finishSession(t,n,r);return ZW(i),i}}}var $W=QW(DN);function eG(e){let t=e.length>0?Math.max(...e.map(e=>e.endTime))-Math.min(...e.map(e=>e.startTime)):0,n=Math.round(t*1e3),r=[];if(n>0&&r.push({label:`Total Time`,value:SH(n)}),r.push({label:`Segments`,value:String(e.length)}),e.length>0){let t=Math.max(...e.map(e=>e.depth));e.filter(e=>e.depth===t).slice(0,4).forEach(e=>{r.push({label:e.name||`Segment`,value:SH(Math.round(e.elapsed*1e3))})})}return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:n,completedSegments:e.length,rows:r}}}function tG(e){return{type:`rpc-workbench-update`,mode:`review`,reviewData:{totalDurationMs:e.totalDurationMs,completedSegments:e.segmentCount,rows:[{label:`Total Time`,value:SH(e.totalDurationMs)},{label:`Segments`,value:String(e.segmentCount)}]}}}function nG(e,t){let n=t.filter(e=>e.type===`time`||e.type===`log`);return n.length===0&&!e?{type:`rpc-workbench-update`,mode:`idle`}:{type:`rpc-workbench-update`,mode:`preview`,previewData:{title:(e?.content??n[0]?.content??``).split(`
151
+ `)[0].trim().substring(0,60)||`Workout`,blocks:n.slice(0,8).map(e=>({id:e.id,title:(e.scriptBlock?.content??e.content).split(`
152
+ `)[0].trim().substring(0,50)||`Workout`,statementCount:e.scriptBlock?.statements?.length??0}))}}}var rG=`wod-wiki:userOutputOverrides`;function iG(e=!1){let t=DL(e=>e.userOutputOverrides),n=DL(e=>e.setUserOverride),r=DL(e=>e.clearUserOverride);return(0,U.useEffect)(()=>{if(e)try{let e=localStorage.getItem(rG);if(!e)return;let t=JSON.parse(e);for(let[e,r]of Object.entries(t))n(e,r.map(oG))}catch{}},[e,n]),(0,U.useEffect)(()=>{if(!e)return;if(t.size===0){localStorage.removeItem(rG);return}let n={};for(let[e,r]of t)n[e]=r.map(aG);localStorage.setItem(rG,JSON.stringify(n))},[t,e]),{overrides:t,setOverride:(0,U.useCallback)((e,r,i,a)=>{let o=(t.get(e)??J.empty(e)).filter(e=>e.type!==r),s={type:r,origin:`user`,value:i,image:a??String(i??``)};n(e,J.from(o,e).add(s))},[t,n]),removeOverride:(0,U.useCallback)((e,i)=>{let a=t.get(e);if(!a)return;let o=a.filter(e=>e.type!==i);o.length===0?r(e):n(e,o)},[t,n,r]),clearBlock:(0,U.useCallback)(e=>{r(e)},[r]),clearAll:(0,U.useCallback)(()=>{for(let e of t.keys())r(e)},[t,r])}}function aG(e){return{type:e.type,value:e.value,image:e.image,origin:e.origin,sourceBlockKey:e.sourceBlockKey,timestamp:e.timestamp?.toISOString()}}function oG(e){return{type:e.type,value:e.value,image:e.image,origin:e.origin??`user`,sourceBlockKey:e.sourceBlockKey,timestamp:e.timestamp?new Date(e.timestamp):void 0}}var sG=(typeof window<`u`?window.__wod_runtimeNowProvider?.():void 0)??rl,cG=new Vf(rp(),sG);function lG(e){if(e.statements?.length)return e;let t=yc({tags:BA()});return{...e,statements:t.read(e.content,e.sport).statements}}function uG(e){return cG.createRuntime(lG(e))??null}function dG(e,t){return{startTime:t.startTime??t.now.nowMs(),endTime:t.now.nowMs(),duration:t.elapsedTime,completed:t.completed,logs:e.map(fN)}}function fG(e){return e.filter(e=>e.outputType===`segment`).length}function pG(e,t){let n=new Set;for(let r of t){let t=e?.getId(r),i=t?.meta?.line??t?.line;i!==void 0&&n.add(i)}return[...n]}function mG(e){let t=e.kind===`choice`?q.Choice:String(e.metricType),n=e.kind===`value`&&e.sourceStatementId!==void 0?`:${e.sourceStatementId}`:``;return`${e.blockKey}:${t}${n}`}var hG={[q.Rep]:!0,[q.Rounds]:!0,[q.RIR]:!0,[q.SessionRPE]:!0,[q.Lap]:!0},gG={[q.Duration]:!0},_G={[q.Choice]:!0};function vG(e){let t=String(e);return hG[t]?`integer`:gG[t]?`duration`:_G[t]?`choice`:`decimal`}function yG(e,t,n){return e.kind===`choice`?{fieldId:mG(e),label:e.exerciseLabel,metricType:q.Choice,domain:`choice`,intent:`target`,required:!0,value:null,unit:``,index:t,total:n,selectedIndex:0,alternatives:e.alternatives.map((e,t)=>({label:e.image??String(e.value?.amount??e.value??t),value:t}))}:{fieldId:mG(e),label:e.exerciseLabel,metricType:String(e.metricType),domain:vG(e.metricType),intent:e.intent,required:e.intent===`target`,value:null,unit:e.unit??``,index:t,total:n}}function bG(e,t,n){let r=e?.statements[t.statementIndex];r&&zf(r,t.alternatives,n)}function xG(e,t){if(e.type===q.Duration){let n=Math.round(t),r=Math.floor(n/1e3)%60,i=Math.floor(n/6e4)%60,a=Math.floor(n/36e5)%24,o=Math.floor(n/864e5),s=e=>String(e).padStart(2,`0`),c=o>0?`${o}:${s(a)}:${s(i)}:${s(r)}`:a>0?`${a}:${s(i)}:${s(r)}`:`${i}:${s(r)}`;return{...e,origin:`user-plan`,value:n,original:n,image:c,days:o,hours:a,minutes:i,seconds:r}}if(e.type===q.Distance||e.type===q.Resistance){let n=typeof e.value==`object`&&e.value!==null&&`unit`in e.value?e.value.unit:void 0,r=e.unit??(typeof n==`string`?n:``);return{...e,origin:`user-plan`,value:{amount:t,unit:r},image:`${t} ${r}`.trim()}}return{...e,origin:`user-plan`,value:t,image:String(t)}}function SG(e,t,n,r){if(r!==`target`||!Number.isFinite(n))return!1;if(t.kind===`choice`)return!Number.isInteger(n)||n<0?!1:(bG(e,t,n),!0);if(TG[String(t.metricType)]&&n<=0||t.metricType===q.Rounds&&!Number.isInteger(n))return!1;let i=e?.statements[t.statementIndex];if(!i)return!1;let a=i.metrics.find(e=>e.type===t.metricType&&(e.origin===`hinted`||e.image===`?`));return i.metrics.remove(e=>e.type===t.metricType&&e.origin===`user-plan`),a?(i.metrics.remove(e=>e===a),i.metrics.add(xG(a,n))):i.metrics.add({type:t.metricType,origin:`user-plan`,value:n,image:String(n)}),!0}function CG(e){if(!(`context`in e))return;let t=e.context;if(!(!t||typeof t!=`object`))return t}function wG(e){let t=CG(e)?.sourceBlockKey;return typeof t==`string`&&t.length>0?t:void 0}var TG={[q.Duration]:!0,[q.Rounds]:!0};function EG(e){return!TG[String(e)]}function DG(e,t,n){let r=[];if(e.length===0&&n){for(let e=0;e<n.statements.length;e++){let i=n.statements[e],a=`stmt-${i.id}`,o=t.get(a),s=i.metrics.find(e=>e.type===q.Effort||e.type===q.Label),c=s?.value?.toString()||s?.image||`Exercise`;for(let t of i.metrics){if(t.type===q.Choice){let n=t;r.push({kind:`choice`,blockKey:a,exerciseLabel:c,alternatives:n.alternatives,selectedIndex:0,statementIndex:e});continue}if(t.origin===`hinted`||t.image===`?`){let n=o?.some(e=>e.type===t.type&&e.origin===`user`),s=i.metrics.some(e=>e.type===t.type&&e.origin===`user-plan`);!n&&!s&&r.push({kind:`value`,blockKey:a,exerciseLabel:c,metricType:t.type,hint:t.image||`?`,origin:`hinted`,intent:`target`,statementIndex:e,...t.unit?{unit:t.unit}:{},deferrable:EG(t.type)})}}}return r}for(let n of e){if(!n.metrics)continue;let e=wG(n);if(!e)continue;let i=CG(n),a=typeof i?.sourceStatementId==`number`?i.sourceStatementId:void 0,o=t.get(e);for(let t of n.metrics){let i=t.origin===`hinted`||t.image===`?`,s=t.origin===`user-plan`&&typeof t.value==`number`&&!TG[String(t.type)];if(!i&&!s)continue;let c=o?.some(e=>e.type===t.type&&e.origin===`user`),l=n.metrics.some(e=>e.type===t.type&&e.origin===`user`);if(!c&&!l){let i=n.metrics.find(e=>e.type===q.Effort||e.type===q.Label),o=i?.value?.toString()||i?.image||`Exercise`,s=e.match(/\[(\d+)\]/),c=e.match(/\[\d+\]\[(\d+)\]/);r.push({kind:`value`,blockKey:e,exerciseLabel:o,metricType:t.type,hint:t.image||`?`,origin:`hinted`,intent:`actual`,statementIndex:0,roundIndex:s?parseInt(s[1])+1:void 0,setIndex:c?parseInt(c[1])+1:void 0,sourceStatementId:a,stackLevel:n.depth,...t.unit?{unit:t.unit}:{},deferrable:EG(t.type)})}}}return r}function OG(e,t,n){let r=(0,U.useMemo)(()=>DG(e,t,n),[e,t,n]);return{collectionItems:r,totalCount:r.length,isComplete:r.length===0}}function kG(e,t){if(!Number.isFinite(t))return{ok:!1,reason:`Invalid number`};switch(e.domain){case`integer`:return Number.isSafeInteger(t)&&t>=0?{ok:!0,value:t}:{ok:!1,reason:`Whole number 0 or more required`};case`choice`:return Number.isInteger(t)&&t>=0?{ok:!0,value:t}:{ok:!1,reason:`Invalid choice`};case`duration`:case`decimal`:return t>=0?{ok:!0,value:t}:{ok:!1,reason:`Must be 0 or more`}}}function AG(e){if(e.includes(`:`)){let t=/^(\d*):(\d*)$/.exec(e);if(t)return{min:t[1]??``,sec:t[2]??``}}return{min:``,sec:e.replace(/\D/g,``)}}var jG=(e,t)=>e?e(t):{},MG=({entry:e,saving:t,error:n,onSave:r,onCancel:i,onSkip:a,skipLabel:o,onChoice:s,onDraftChange:c,draft:l,initialDraft:u,getFocusProps:d})=>{let[f,p]=(0,U.useState)(u??``),m=l??f,h=e=>{p(e),c?.(e)},[g,_]=(0,U.useState)(null),[v,y]=(0,U.useState)(e.selectedIndex??0),b=(0,U.useRef)(!1),x=(0,U.useRef)(null);(0,U.useEffect)(()=>{let e=document.activeElement;return x.current?.focus({preventScroll:!0}),()=>{e instanceof HTMLElement&&e.isConnected&&e.focus()}},[]);let S=e.alternatives??[],C=n??g,w=()=>{if(b.current||t)return;let n=e.domain===`choice`?kG(e,v):AW(m,e.domain);if(n.ok===!1){_(`error`in n?n.error:n.reason);return}_(null),b.current=!0;try{let e=r(n.value);e&&typeof e.then==`function`?e.then(()=>{b.current=!1},()=>{b.current=!1}):b.current=!1}catch{b.current=!1}},T=e=>{e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.repeat||w())},E=t=>{_(null),h(kW(e.domain,m,t))},D=t=>{if(t.defaultPrevented||t.ctrlKey||t.altKey||t.metaKey||t.nativeEvent.isComposing)return;if(t.key===`Tab`){let e=Array.from(x.current?.querySelectorAll(`button:not([disabled]), input:not([disabled])`)??[]),n=e[0],r=e.at(-1);t.shiftKey&&(document.activeElement===n||document.activeElement===x.current)?(t.preventDefault(),r?.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n?.focus()),t.stopPropagation();return}let n=LW(t,{entryOpen:!0});if(n.kind!==`none`&&n.kind!==`direction`&&n.kind!==`select`&&!(t.target instanceof HTMLInputElement&&(n.kind===`digit`&&/^[\d.,]$/.test(t.key)||t.key===`Backspace`))&&(t.preventDefault(),t.stopPropagation(),!(t.repeat&&n.kind!==`digit`&&n.kind!==`back`))){if(n.kind===`primary`)w();else if(n.kind===`cancel`)i();else if(n.kind===`back`)E(t.key===`Clear`?`clear`:`back`);else if(n.kind===`digit`){if(e.domain===`choice`){let e=Number(n.digit)-1;S[e]&&(y(e),s?.(e))}else E(n.digit)}}},O=(e,t)=>{let n=t.replace(/\D/g,``),r=AG(m);h(e===`min`?`${n}:${r.sec}`:`${r.min}:${n.slice(0,2)}`)},k=e.domain===`duration`?`0:00`:e.domain===`integer`?`0`:`0.0`,A=e.domain!==`choice`,j=[{id:`entry-digit-7`,label:`7`,key:`7`},{id:`entry-digit-8`,label:`8`,key:`8`},{id:`entry-digit-9`,label:`9`,key:`9`},{id:`entry-digit-4`,label:`4`,key:`4`},{id:`entry-digit-5`,label:`5`,key:`5`},{id:`entry-digit-6`,label:`6`,key:`6`},{id:`entry-digit-1`,label:`1`,key:`1`},{id:`entry-digit-2`,label:`2`,key:`2`},{id:`entry-digit-3`,label:`3`,key:`3`},...e.domain===`decimal`?[{id:`entry-dot`,label:`.`,key:`.`}]:[],{id:`entry-digit-0`,label:`0`,key:`0`},{id:`entry-back`,label:`⌫`,key:`back`}];return(0,U.useEffect)(()=>{y(e.selectedIndex??0)},[e.selectedIndex]),(0,W.jsxs)(`div`,{ref:x,"data-clock-entry":!0,tabIndex:-1,onKeyDown:D,className:`flex w-full flex-col items-center gap-4 outline-none`,"aria-label":`Enter ${e.label}`,children:[e.domain===`choice`?(0,W.jsx)(`div`,{className:`flex w-full flex-col gap-3`,role:`radiogroup`,"aria-label":e.label,children:S.map((e,t)=>(0,W.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":v===t,"data-testid":`entry-choice-${t}`,onClick:()=>{y(t),_(null),s?.(t)},...jG(d,`entry-choice-${t}`),className:G(`w-full rounded-xl border-2 px-6 py-4 text-lg font-bold transition-all`,v===t?`border-primary bg-primary/10 text-primary shadow-sm`:`border-border bg-background text-foreground hover:border-primary/50`),children:e.label},t))}):e.domain===`duration`?(0,W.jsxs)(`div`,{className:`flex items-center justify-center gap-2`,onKeyDown:T,children:[(0,W.jsx)(`input`,{"data-testid":`entry-min`,"aria-label":`Minutes`,inputMode:`numeric`,value:AG(m).min,onChange:e=>O(`min`,e.target.value),className:`w-24 rounded-lg border-2 border-border bg-background py-3 text-center text-3xl font-bold tabular-nums outline-none focus:border-primary`}),(0,W.jsx)(`span`,{className:`text-3xl font-bold text-muted-foreground`,children:`:`}),(0,W.jsx)(`input`,{"data-testid":`entry-sec`,"aria-label":`Seconds`,inputMode:`numeric`,value:AG(m).sec,onChange:e=>O(`sec`,e.target.value),className:`w-24 rounded-lg border-2 border-border bg-background py-3 text-center text-3xl font-bold tabular-nums outline-none focus:border-primary`})]}):(0,W.jsx)(`input`,{"data-testid":`entry-value`,"aria-label":e.label,inputMode:e.domain===`integer`?`numeric`:`decimal`,value:m,placeholder:k,onChange:e=>h(e.target.value),onKeyDown:T,className:`w-full rounded-lg border-2 border-border bg-background py-3 text-center text-2xl font-bold tabular-nums outline-none transition-all focus:border-primary focus:ring-2 focus:ring-primary/20`}),C&&(0,W.jsx)(`p`,{role:`alert`,className:`text-sm font-medium text-destructive`,children:C}),A&&(0,W.jsxs)(`div`,{className:`grid w-full max-w-[260px] grid-cols-3 gap-2`,"aria-label":`Number pad`,children:[j.map(e=>(0,W.jsx)(`button`,{type:`button`,"data-testid":e.id,onClick:()=>E(e.key),...jG(d,e.id),className:`min-h-[44px] rounded-lg border border-border bg-muted/30 text-xl font-bold tabular-nums transition-colors hover:bg-accent`,children:e.label},e.id)),(0,W.jsx)(`button`,{type:`button`,"data-testid":`entry-clear`,onClick:()=>E(`clear`),...jG(d,`entry-clear`),className:`col-span-3 min-h-[44px] rounded-lg border border-border text-xs font-bold uppercase tracking-label text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Clear`})]}),(0,W.jsxs)(`div`,{className:`flex w-full items-center justify-between gap-3`,children:[(0,W.jsx)(`button`,{type:`button`,"data-testid":`entry-cancel`,onClick:i,...jG(d,`entry-cancel`),className:`px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:`Cancel`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[a&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`entry-skip`,onClick:a,...jG(d,`entry-skip`),className:`px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:o??`Skip`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`entry-save`,onClick:w,disabled:t,...jG(d,`entry-save`),className:`flex items-center gap-2 rounded-lg bg-primary px-6 py-2 font-bold text-primary-foreground shadow-sm transition-all hover:brightness-110 disabled:opacity-50`,children:t?`Saving…`:`Save`})]})]})]})},NG=({items:e,onSave:t,onSkip:n,onStart:r,onClose:i,mode:a,runId:o,className:s})=>{let[c,l]=(0,U.useState)(new Set),[u,d]=(0,U.useState)(new Set),[f,p]=(0,U.useState)(0),[m,h]=(0,U.useState)({}),[g,_]=(0,U.useState)({}),[v,y]=(0,U.useState)(!1),[b,x]=(0,U.useState)(null),[S,C]=(0,U.useState)(!1),w=(0,U.useRef)(!1),T=(0,U.useRef)(!1);e.length>0&&(T.current=!0);let E=QU(),D=(0,U.useMemo)(()=>e.filter(e=>!c.has(mG(e))),[e,c]),O=Math.min(f,Math.max(D.length-1,0)),k=D[O],A=k?mG(k):null,j=a===`pre-run`&&D.length===0&&T.current;(0,U.useEffect)(()=>{A&&typeof E==`string`&&h(e=>e[A]===E?e:{...e,[A]:E})},[E,A]);let M=(0,U.useCallback)(e=>{h(t=>{if(!(e in t))return t;let n={...t};return delete n[e],n}),_(t=>{if(!(e in t))return t;let n={...t};return delete n[e],n}),DW(``)},[]),N=(0,U.useCallback)((e,t)=>{h(n=>({...n,[e]:t})),DW(t)},[]),P=(0,U.useCallback)(async(n,r)=>{if(w.current)return!1;let i=mG(n),a=kG(yG(n,0,e.length),r);if(!a.ok)return x(a.reason),!1;w.current=!0,y(!0),x(null);try{if(await t(n,a.value,n.intent)===!1)throw Error(`Save was rejected`)}catch(e){return x(e instanceof Error?e.message:String(e)),!1}finally{w.current=!1,y(!1)}return M(i),l(e=>new Set(e).add(i)),!0},[t,e.length,M]),F=(0,U.useCallback)(()=>{if(!k||w.current)return;let e=mG(k);a===`pre-run`&&!k.deferrable||(M(e),a===`post-run`&&n&&n(k),d(t=>new Set(t).add(e)),l(t=>new Set(t).add(e)))},[k,a,n,M]),I=(0,U.useCallback)(e=>{switch(e.kind){case`entry-save`:return!k||w.current||e.fieldId!==mG(k)?!1:(P(k,e.value),!0);case`entry-cancel`:return k?(N(mG(k),``),x(null),!0):!1;case`entry-skip`:return!k||w.current||e.fieldId!==mG(k)?!1:(F(),!0);case`choice-select`:return!k||k.kind!==`choice`||e.fieldId!==mG(k)||!Number.isInteger(e.index)||e.index<0||e.index>=k.alternatives.length?!1:(_(t=>({...t,[mG(k)]:e.index})),x(null),!0);case`ready-start`:return j?(r?.(),!0):!1;case`dismiss`:return a===`pre-run`&&!j?!1:(C(!0),i?.(),!0);default:return!1}},[k,P,F,j,r,i,a,N]);ZU((0,U.useMemo)(()=>{if(D.length===0)return j&&!S?{runId:o??`collection:pre-run`,phase:`ready`,status:`idle`,canNext:!1,canStop:!1,stopRequested:!1,reps:[],selectedOccurrenceId:null,entry:null,error:null,saving:!1}:null;let e=k?yG(k,O,D.length):null;return{runId:o??(a===`pre-run`?`collection:pre-run`:`collection:post-run`),phase:a===`pre-run`?`ready`:`collection`,status:`idle`,canNext:!1,canStop:!1,stopRequested:!1,reps:[],selectedOccurrenceId:null,entry:e&&k&&k.kind===`choice`?{...e,selectedIndex:g[e.fieldId]??0}:e,error:b,saving:v}},[D.length,k,O,a,o,g,b,v,j,S]),I,a===`pre-run`?10:20,{keyboard:!0});let L=(0,U.useCallback)(()=>{a===`pre-run`&&!j||(C(!0),i?.())},[a,j,i]);if(D.length===0)return j&&!S?(0,W.jsxs)(`div`,{className:G(`flex flex-col items-center justify-center gap-6 rounded-2xl border border-border bg-card p-8 text-center shadow-xl`,s),children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:`Ready to Start`}),(0,W.jsxs)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:[`Targets are set`,u.size>0?` — ${u.size} logged after your workout`:``,`.`]})]}),r&&(0,W.jsxs)(`button`,{type:`button`,"data-testid":`collection-start`,onClick:r,className:`flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-6 py-4 text-lg font-bold text-primary-foreground shadow-lg transition-all hover:brightness-110`,children:[`Start Workout`,(0,W.jsx)(Qt,{className:`w-5 h-5`})]})]}):null;if(!k)return null;let R=yG(k,O,D.length),ee=k.kind===`choice`?g[R.fieldId]??0:0,te=a===`post-run`||k.deferrable;return(0,W.jsxs)(`div`,{className:G(`flex flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-xl`,a===`pre-run`?`fixed inset-0 z-50 md:inset-10`:`relative`,s),children:[(0,W.jsx)(`div`,{className:`h-1 bg-muted`,children:(0,W.jsx)(`div`,{className:`h-full bg-primary transition-all duration-300`,style:{width:`${(e.length-D.length+1)/(e.length+1)*100}%`}})}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border bg-muted/10 px-6 py-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-lg font-bold tracking-tight`,children:a===`pre-run`?`Set Your Targets`:`Fill in your actuals`}),(0,W.jsxs)(`p`,{className:`text-xs uppercase tracking-label text-muted-foreground`,children:[e.length-D.length+1,` of `,e.length,` metrics`]})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,children:[O>0&&(0,W.jsxs)(`button`,{type:`button`,"data-testid":`collection-back`,onClick:()=>{p(O-1),x(null)},className:`flex items-center gap-1 px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,children:[(0,W.jsx)(_t,{className:`w-4 h-4`}),`Back`]}),i&&a===`post-run`&&(0,W.jsx)(`button`,{type:`button`,onClick:L,className:`rounded-full p-2 transition-colors hover:bg-muted`,children:(0,W.jsx)(we,{className:`w-5 h-5 text-muted-foreground`})})]})]}),(0,W.jsx)(`div`,{className:`flex flex-1 flex-col items-center justify-center w-full max-w-md mx-auto p-8`,children:(0,W.jsxs)(`div`,{className:`w-full space-y-6`,children:[(0,W.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,W.jsxs)(`div`,{className:`rounded-pill border border-metric-effort/40 bg-metric-effort/15 px-3 py-1 text-xs font-bold text-metric-effort`,children:[a===`pre-run`?`Target`:`Actual`,` · `,k.exerciseLabel]}),(k.setIndex||k.roundIndex)&&(0,W.jsxs)(`div`,{className:`text-[10px] font-bold uppercase tracking-label text-muted-foreground`,children:[k.roundIndex&&`Round ${k.roundIndex}`,k.roundIndex&&k.setIndex&&` · `,k.setIndex&&`Set ${k.setIndex}`]})]}),(0,W.jsx)(MG,{entry:k.kind===`choice`?{...R,selectedIndex:ee}:R,saving:v,error:b,onSave:e=>void P(k,e),onCancel:()=>{N(R.fieldId,``),x(null)},onSkip:te?F:void 0,skipLabel:a===`pre-run`?`Log after workout`:`Skip`,onChoice:k.kind===`choice`?e=>_(t=>({...t,[R.fieldId]:e})):void 0,onDraftChange:e=>N(R.fieldId,e),initialDraft:m[R.fieldId]??``},R.fieldId)]})}),b&&(0,W.jsxs)(`div`,{className:`flex items-center gap-2 border-t border-border bg-warning/10 px-6 py-2 text-sm text-warning`,children:[(0,W.jsx)(vn,{className:`h-4 w-4`}),(0,W.jsxs)(`span`,{role:`alert`,children:[b,` — your entry is kept.`]})]})]})};function PG(e){let t=[];for(let n of e)n.origin===`user`&&n.type===q.Rep&&typeof n.value==`number`&&t.push(n);return t}function FG(e,t,n){let r=e.getMemoryByTag(`metric:result`),i=e.getMemoryByTag(`metric:display`),a=Math.max(r.length,i.length);if(t?.sourceId!==void 0){let r=e.sourceIds.indexOf(t.sourceId);if(r!==-1)return r;if(Number.isInteger(t.sourceId)&&t.sourceId>=0&&t.sourceId<a)return t.sourceId;if(n)throw Error(`Block ${e.key.toString()} has no movement group for sourceId ${t.sourceId}`);return-1}if(a>1){if(n)throw Error(`Grouped block ${e.key.toString()} has ${a} movements — pass an occurrence sourceId instead of applying one count to every movement`);return-1}return 0}function IG(e,t,n){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Actual rep count must be a nonnegative safe integer, got ${t}`);let r=FG(e,n,!0),i={type:q.Rep,value:t,origin:`user`,image:String(t),sourceBlockKey:e.key.toString(),timestamp:new Date},a=e.getMemoryByTag(`metric:result`);if(a.length===0){let t=e.getMemoryByTag(`metric:display`);if(t.length>1){for(let n=0;n<t.length;n++)e.pushMemory(new Fl(`metric:result`,n===r?[i]:[]));return}e.pushMemory(new Fl(`metric:result`,[i]));return}let o=a[Math.min(r,a.length-1)],s=o.metrics.filter(e=>e.origin!==`user`||e.type!==q.Rep);o.update([...s,i])}function LG(e,t){let n=e.getMemoryByTag(`metric:result`);if(n.length===0)return null;let r=FG(e,t,!1);if(r===-1)return null;r=Math.min(r,n.length-1);let i=PG(n[r].metrics),a=i[i.length-1];return a?a.value:null}var RG=new Set([`Rounds`,`Group`,`AMRAP`,`EMOM`,`SessionRoot`,`Root`]),zG=new Set([`Timer`]);function BG(e){let t=[];for(let n of e.stack.blocks){let e=n.blockType??``;if(RG.has(e)||zG.has(e)||n.getMemoryByTag(`children:status`).length>0)continue;let r=n.getMemoryByTag(`metric:display`),i=n.key.toString(),a=r.length>1;for(let e of r){let o=VG(e);if(!(o!==null||e.metrics.some(e=>(e.type===q.Effort||e.type===q.Action)&&(typeof e.value==`string`||typeof e.image==`string`))))continue;let s=r.indexOf(e),c=n.sourceIds[s]??s;t.push({block:n,occurrenceId:a?`${i}:${c}`:i,label:HG(n,e),target:o})}}return t}function VG(e){let t=null;for(let n of e.metrics)n.type===q.Rep&&n.origin!==`user`&&typeof n.value==`number`&&(t=n.value);return t}function HG(e,t){if(e.getMemoryByTag(`metric:display`).length<=1)return e.label;for(let e of t.metrics)if((e.type===q.Effort||e.type===q.Action)&&typeof e.value==`string`&&e.value)return e.value;return e.label}function UG(e,t){for(let n of e.stack.blocks){let e=n.key.toString();if(t===e)return{block:n,occurrence:void 0};if(t.startsWith(`${e}:`)){let r=Number(t.slice(e.length+1));if(Number.isFinite(r))return{block:n,occurrence:{sourceId:r}}}}}function WG({runtime:e,executionStatus:t,actions:n,enabled:r=!0,saving:i=!1}){let a=(0,U.useRef)(rW()),[o,s]=(0,U.useState)(0),[c,l]=(0,U.useState)(0),[u,d]=(0,U.useState)(!1),[f,p]=(0,U.useState)(null),[m,h]=(0,U.useState)(null),[g,_]=(0,U.useState)(null),v=(0,U.useRef)({runtime:e,executionStatus:t,actions:n});v.current={runtime:e,executionStatus:t,actions:n},(0,U.useEffect)(()=>{if(e)return e.subscribeToStack(()=>s(e=>e+1))},[e]);let y=(0,U.useMemo)(()=>e?BG(e).map(t=>{let n=UG(e,t.occurrenceId);return{occurrenceId:t.occurrenceId,label:t.label,target:t.target,actual:n?LG(n.block,n.occurrence):null}}):[],[e,o,c]);(0,U.useEffect)(()=>{if(y.length===1){p(y[0].occurrenceId);return}p(e=>e!==null&&y.some(t=>t.occurrenceId===e)?e:null)},[y]),(0,U.useEffect)(()=>{y.length>0&&_(e=>e===`No rep movements`||e===`No rep movements to record`?null:e)},[y]);let b=m,x=t,S=x===`idle`?`ready`:x===`completed`?`review`:`live`,C=x===`running`||x===`idle`,w=x===`running`||x===`paused`,T=(0,U.useMemo)(()=>!r||!e?null:{runId:a.current,phase:S,status:x,canNext:C,canStop:w,stopRequested:u,reps:y,selectedOccurrenceId:f,entry:b,error:g,saving:i},[r,e,S,x,C,w,u,y,f,b,g,i]);return ZU(T,(0,U.useCallback)(e=>{let t=v.current.runtime,n=v.current.executionStatus,r=v.current.actions;if(m!==null&&[`next`,`ready-start`,`playback`,`stop-request`,`reps-select`].includes(e.kind))return!1;let i=e=>t!==null&&e!==null?UG(t,e):void 0,a=e=>{let t=y.find(t=>t.occurrenceId===e);return t?(h({fieldId:`reps:${t.occurrenceId}`,label:t.label,metricType:`reps`,domain:`integer`,intent:`actual`,required:!1,value:t.actual,unit:`reps`,index:0,total:1}),_(null),!0):(_(`Movement no longer active`),!1)};switch(e.kind){case`next`:return u?!1:n===`paused`?(_(`Paused — press play to continue first`),!1):n!==`running`&&n!==`idle`?!1:(r.next(),!0);case`ready-start`:return u||n!==`idle`?!1:(r.start(),!0);case`playback`:return u||n===`completed`?!1:(_(null),r.playback(),!0);case`stop-request`:return u||m!==null||n!==`running`&&n!==`paused`?!1:(d(!0),!0);case`stop-cancel`:return u?(d(!1),!0):!1;case`stop-confirm`:return u?(d(!1),r.stop(),!0):!1;case`values-open`:{if(m!==null||u)return!1;let e=f??(y.length===1?y[0].occurrenceId:null);return e===null?(_(y.length>1?`Select a movement first`:`No rep movements to record`),!1):a(e)}case`entry-cancel`:return m!==null&&(h(null),_(null),!0);case`entry-save`:{if(m===null||e.fieldId!==m.fieldId)return!1;if(!Number.isSafeInteger(e.value)||e.value<0)return _(`Reps must be a whole number of 0 or more`),!1;let t=i(m.fieldId.slice(5));return t?(IG(t.block,e.value,t.occurrence),l(e=>e+1),h(null),_(null),!0):(_(`Movement no longer active — draft preserved`),!1)}case`entry-skip`:return m===null||e.fieldId!==m.fieldId?!1:(h(null),_(null),!0);case`reps-adjust`:{if(m!==null||u)return!1;let t=e.occurrenceId===``?f:e.occurrenceId;if(t===null)return _(y.length>1?`Select a movement first`:`No rep movements`),!1;let n=i(t);if(!n)return!1;let r=(LG(n.block,n.occurrence)??0)+e.delta;return r<0||(IG(n.block,r,n.occurrence),l(e=>e+1),_(null),!0)}case`reps-set`:{if(m!==null||u)return!1;if(!Number.isSafeInteger(e.value)||e.value<0)return _(`Reps must be a whole number of 0 or more`),!1;let t=i(e.occurrenceId===``?f:e.occurrenceId);return t?(IG(t.block,e.value,t.occurrence),l(e=>e+1),_(null),!0):!1}case`reps-select`:return u||!y.some(t=>t.occurrenceId===e.occurrenceId)?!1:(p(e.occurrenceId),_(null),!0);case`choice-select`:return!1;case`dismiss`:return r.dismiss?(r.dismiss(),!0):!1}},[y,f,m,u]),0,{keyboard:!0}),{snapshot:T,dispatch:(0,U.useCallback)(e=>mW(a.current,e),[])}}var GG=`⏎ Select · Pad⏎ Next · 8/2/4/6 Move · +/− Reps · * Values · / Play · Esc Stop`,KG=`⏎ Next · Pad⏎ Next · 8/2/4/6 Move · +/− Reps · * Values · / Play · Esc Stop`;function qG({mode:e,className:t}){return(0,W.jsx)(`p`,{"data-testid":FH.CLOCK_LEGEND,className:`px-3 text-[10px] leading-4 text-muted-foreground ${t??``}`,children:e===`keypad`?KG:GG})}var JG=({mode:e,onModeChange:t,className:n,getFocusProps:r})=>{let[i,a]=(0,U.useState)(()=>MW()),o=e??i,s=e=>{NW(e),a(e),t?.(e)};return(0,W.jsx)(`div`,{"data-testid":FH.CLOCK_KEY_MODE_TOGGLE,role:`group`,"aria-label":`Enter key mode`,className:`inline-flex items-center rounded-full border border-border text-[10px] ${n??``}`,children:[`navigation`,`keypad`].map(e=>(0,W.jsx)(`button`,{type:`button`,"aria-pressed":o===e,onClick:()=>s(e),...r?.(`board-keymode-${e}`),className:`rounded-full px-2 py-0.5 ${o===e?`bg-foreground text-background`:`text-muted-foreground hover:text-foreground`}`,children:e===`navigation`?`Nav`:`Keypad`},e))})},YG=({open:e,onClose:t,getFocusProps:n})=>{let[r,i]=(0,U.useState)([]),a=(0,U.useRef)(null);return(0,U.useEffect)(()=>{if(!e)return;document.body.dataset.clockModal=`key-check`;let t=document.activeElement;return a.current?.focus({preventScroll:!0}),()=>{delete document.body.dataset.clockModal,t instanceof HTMLElement&&t.isConnected&&t.focus()}},[e]),(0,U.useEffect)(()=>{if(!e)return;let n=e=>{if((e.code===`NumpadEnter`||e.location===3)&&e.preventDefault(),e.key===`Escape`){e.preventDefault(),e.stopPropagation(),t();return}i(t=>{let n=t[t.length-1];return n&&n.key===e.key&&n.code===e.code&&n.location===e.location?[...t.slice(0,-1),{...n,repeat:e.repeat,count:n.count+1}]:[...t.slice(-7),{key:e.key,code:e.code,location:e.location,keyCode:e.keyCode,repeat:e.repeat,count:1}]})};return window.addEventListener(`keydown`,n,!0),()=>window.removeEventListener(`keydown`,n,!0)},[e,t]),e?(0,W.jsx)(`div`,{className:`fixed inset-0 z-[140] flex items-center justify-center bg-black/60 p-4`,children:(0,W.jsxs)(`div`,{"data-testid":FH.CLOCK_KEY_CHECK_DIALOG,role:`dialog`,"aria-modal":`true`,onKeyDown:e=>{e.key===`Tab`&&(e.preventDefault(),e.stopPropagation(),a.current?.focus())},"aria-label":`Key check`,tabIndex:-1,"data-clock-panel":!0,className:`w-full max-w-md rounded-lg border border-border bg-background p-4 shadow-xl outline-none`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:`Key check`}),(0,W.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Press keys to record delivered key / code / location / repeat. Num Lock on and off, keypad and main Enter.`}),(0,W.jsxs)(`table`,{className:`mt-3 w-full font-mono text-[11px]`,children:[(0,W.jsx)(`thead`,{children:(0,W.jsxs)(`tr`,{className:`text-left text-muted-foreground`,children:[(0,W.jsx)(`th`,{className:`pr-2 font-medium`,children:`key`}),(0,W.jsx)(`th`,{className:`pr-2 font-medium`,children:`code`}),(0,W.jsx)(`th`,{className:`pr-2 font-medium`,children:`loc`}),(0,W.jsx)(`th`,{className:`pr-2 font-medium`,children:`keyCode`}),(0,W.jsx)(`th`,{className:`font-medium`,children:`repeat`})]})}),(0,W.jsx)(`tbody`,{children:r.map((e,t)=>(0,W.jsxs)(`tr`,{className:`border-t border-border/60`,children:[(0,W.jsx)(`td`,{className:`pr-2`,children:e.key}),(0,W.jsx)(`td`,{className:`pr-2`,children:e.code}),(0,W.jsx)(`td`,{className:`pr-2`,children:e.location}),(0,W.jsxs)(`td`,{className:`pr-2`,children:[e.keyCode,`×`,e.count]}),(0,W.jsx)(`td`,{children:e.repeat?`yes`:`no`})]},t))})]}),(0,W.jsx)(`div`,{className:`mt-3 flex justify-end`,children:(0,W.jsx)(`button`,{type:`button`,ref:a,onClick:t,...n?.(`board-keycheck-close`),className:`rounded-md border border-border px-3 py-1.5 text-xs font-medium hover:bg-accent`,children:`Close`})})]})}):null},XG=({snapshot:e,dispatch:t,className:n,getFocusProps:r})=>{let i=QU(),a=$U(),[o,s]=(0,U.useState)(()=>MW()),[c,l]=(0,U.useState)(!1),u=e=>r?.(e),d=e.entry,f=(0,U.useRef)(d?.fieldId??null);U.useLayoutEffect(()=>{let e=d?.fieldId??null;r&&f.current!==e&&DW(``),f.current=e},[d?.fieldId,r]);let p=e.error??a,m=e.reps.find(t=>t.occurrenceId===e.selectedOccurrenceId)??null,h=e.reps.length>0&&(e.phase===`live`||e.phase===`collection`);return(0,W.jsxs)(`div`,{"data-testid":FH.CLOCK_COMMAND_BOARD,className:n,children:[p!==null&&(0,W.jsx)(`p`,{"data-testid":FH.CLOCK_ERROR,role:`status`,className:`px-3 pt-1 text-xs text-destructive`,children:p}),r&&e.phase===`ready`&&d===null&&(0,W.jsx)(`button`,{type:`button`,...u(`board-ready-start`),onClick:()=>t({kind:`ready-start`}),className:`rounded-xl bg-primary px-6 py-4 text-lg font-bold text-primary-foreground focus-visible:ring-2`,children:`Start Workout`}),h&&(0,W.jsxs)(`div`,{"data-testid":FH.CLOCK_REP_COUNTER,className:`flex flex-wrap items-center gap-2 px-3 py-1.5 text-sm`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Actual reps`}),(0,W.jsxs)(`span`,{"data-testid":FH.CLOCK_REP_VALUE,className:`font-mono text-sm font-semibold`,children:[m?.actual??`—`,m?.target==null?``:` / Target ${m.target}`]}),(0,W.jsx)(`button`,{type:`button`,"data-testid":FH.CLOCK_REP_MINUS,"aria-label":`Remove one rep`,className:`h-7 w-7 rounded-full border border-border text-sm hover:bg-accent`,...u(`board-reps-minus-${e.selectedOccurrenceId??``}`),onClick:()=>t({kind:`reps-adjust`,occurrenceId:e.selectedOccurrenceId??``,delta:-1}),children:`−`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":FH.CLOCK_REP_PLUS,"aria-label":`Add one rep`,className:`h-7 w-7 rounded-full border border-border text-sm hover:bg-accent`,...u(`board-reps-plus-${e.selectedOccurrenceId??``}`),onClick:()=>t({kind:`reps-adjust`,occurrenceId:e.selectedOccurrenceId??``,delta:1}),children:`+`}),i!==``&&d===null&&(0,W.jsxs)(`span`,{"data-testid":FH.CLOCK_DRAFT_CHIP,className:`rounded bg-muted px-1.5 py-0.5 font-mono text-xs`,children:[i,` `,(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`⏎ to set`})]}),e.reps.length>1&&(0,W.jsx)(`span`,{className:`flex flex-wrap items-center gap-1`,role:`group`,"aria-label":`Counted movement`,children:e.reps.map(n=>(0,W.jsx)(`button`,{type:`button`,"data-testid":`${FH.CLOCK_REP_SELECT}-${n.occurrenceId}`,"aria-pressed":n.occurrenceId===e.selectedOccurrenceId,...u(`board-reps-${n.occurrenceId}`),onClick:()=>t({kind:`reps-select`,occurrenceId:n.occurrenceId}),className:`max-w-[9rem] truncate rounded-full border px-2 py-0.5 text-[11px] ${n.occurrenceId===e.selectedOccurrenceId?`border-foreground bg-foreground text-background`:`border-border text-muted-foreground hover:bg-accent`}`,children:n.label},n.occurrenceId))}),(0,W.jsx)(`button`,{type:`button`,"data-testid":FH.CLOCK_VALUES_BUTTON,className:`ml-auto rounded-full border border-border px-2.5 py-0.5 text-[11px] hover:bg-accent`,...u(`board-values`),onClick:()=>t({kind:`values-open`}),children:`Values *`})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsx)(qG,{mode:o,className:`min-w-0 flex-1 truncate`}),(0,W.jsx)(JG,{mode:o,onModeChange:s,getFocusProps:r,className:`mr-2 shrink-0`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":FH.CLOCK_KEY_CHECK_BUTTON,className:`mr-2 shrink-0 rounded-full border border-border px-2 py-0.5 text-[10px] text-muted-foreground hover:bg-accent hover:text-foreground`,...u(`board-key-check`),onClick:()=>l(!0),children:`Keys?`})]}),d!==null&&(0,W.jsx)(`div`,{"data-testid":FH.CLOCK_ENTRY_OVERLAY,className:`fixed inset-0 z-[120] flex items-center justify-center bg-background/80 p-4`,children:(0,W.jsxs)(`div`,{"data-clock-entry":!0,role:`dialog`,"aria-modal":`true`,"aria-label":`Enter ${d.label}`,className:`w-full max-w-md rounded-lg border border-border bg-background p-4 shadow-lg`,children:[(0,W.jsx)(`p`,{className:`mb-1 text-sm font-semibold`,children:d.label}),(0,W.jsxs)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:[d.intent===`actual`?`Actual`:`Target`,` `,d.metricType,d.unit?` · ${d.unit}`:``,` · `,e.status]}),(0,W.jsx)(MG,{entry:d,saving:e.saving,error:p,draft:i,onSave:e=>{t({kind:`entry-save`,fieldId:d.fieldId,value:e})},onCancel:()=>t({kind:`entry-cancel`}),onSkip:d.required?void 0:()=>t({kind:`entry-skip`,fieldId:d.fieldId}),onChoice:e=>t({kind:`choice-select`,fieldId:d.fieldId,index:e}),onDraftChange:DW,getFocusProps:r},d.fieldId)]})}),e.stopRequested&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-[130] flex items-center justify-center bg-black/60 p-4`,children:(0,W.jsxs)(`div`,{"data-testid":FH.CLOCK_STOP_CONFIRM,role:`alertdialog`,"aria-label":`Stop workout?`,"aria-modal":`true`,className:`w-full max-w-sm rounded-lg border border-border bg-background p-4 text-center shadow-xl`,onKeyDown:e=>{if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=e.currentTarget.querySelectorAll(`button`);(document.activeElement===t[0]?t[1]:t[0])?.focus()}},children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:`Stop workout?`}),(0,W.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Partial results are saved. This cannot be undone.`}),(0,W.jsxs)(`div`,{className:`mt-4 flex justify-center gap-2`,children:[(0,W.jsx)(`button`,{type:`button`,autoFocus:!0,"data-testid":FH.CLOCK_STOP_CONFIRM_CANCEL,className:`rounded-md border border-border px-3 py-1.5 text-xs font-medium hover:bg-accent`,...u(`board-stop-cancel`),onClick:()=>t({kind:`stop-cancel`}),children:`Keep going`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":FH.CLOCK_STOP_CONFIRM_ACCEPT,className:`rounded-md bg-destructive px-3 py-1.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,...u(`board-stop-confirm`),onClick:()=>t({kind:`stop-confirm`}),children:`Stop`})]})]})}),(0,W.jsx)(YG,{open:c,onClose:()=>l(!1),getFocusProps:r})]})},ZG=({execution:e,outputCount:t,createdAt:n,handleStart:r,handleStop:i,handleNext:a,commandBoard:o,canNext:s})=>{let{isCompact:c,isFull:l}=NH();return l?(0,W.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,"data-clock-panel":!0,children:[(0,W.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex ${c?`flex-col`:`flex-row`}`,children:[(0,W.jsx)(`div`,{className:`overflow-hidden bg-secondary/10 ${c?`order-2 min-h-0 flex-[2] border-t border-border`:`min-h-0 min-w-0 w-1/3 border-r border-border`}`,children:(0,W.jsx)(RU,{})}),(0,W.jsx)(`div`,{className:`flex flex-col overflow-y-auto bg-background ${c?`order-1 min-h-[min(280px,100%)] flex-[3]`:`min-h-0 w-2/3`}`,children:(0,W.jsx)(PH,{children:(0,W.jsx)(XH,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`,canNext:s,compact:c,enableDisplayStack:!0})})})]}),o,(0,W.jsxs)(`div`,{className:`flex h-[26px] flex-shrink-0 items-center gap-2 px-2.5 text-[10px] text-muted-foreground ${t>0?`border-t border-border bg-muted/20`:``}`,children:[t>0&&(0,W.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,W.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]}):(0,W.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden bg-background`,"data-clock-panel":!0,children:[(0,W.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:(0,W.jsx)(sU,{elapsedMs:e.elapsedTime,hasActiveBlock:!0,onStart:r,onPause:e.pause,onStop:i,onNext:a,isRunning:e.status===`running`,isPaused:e.status===`paused`,canNext:s})}),o,(0,W.jsxs)(`div`,{className:`flex h-[26px] flex-shrink-0 items-center gap-2 px-2.5 text-[10px] text-muted-foreground ${t>0?`border-t border-border bg-muted/20`:``}`,children:[t>0&&(0,W.jsx)(`span`,{className:`whitespace-nowrap`,children:`${t} ${t===1?`result`:`results`} captured`}),t>0&&n&&(0,W.jsxs)(`span`,{className:`ml-auto font-medium text-primary`,children:[`✓ `,n.toLocaleTimeString()]})]})]})},QG=({block:e,view:t,onClose:n,onComplete:r,isExpanded:i=!1,onToggleExpand:a,autoStart:o,onRuntimeReady:s,onRunStarted:c,externalPause:l,externalStop:u,adoptRuntime:d,parkOnUnmount:f,onPark:p})=>{let[m]=(0,U.useState)(()=>lG(e)),[h]=(0,U.useState)(()=>({statements:m.statements})),[g,_]=(0,U.useState)(null),[v,y]=(0,U.useState)(!1),[b,x]=(0,U.useState)(0),[S,C]=(0,U.useState)(null),[w,T]=(0,U.useState)(!1),[E,D]=(0,U.useState)(!1),O=(0,U.useRef)(!1),[k,A]=(0,U.useState)(!1),j=e.startLine+1,{overrides:M,setOverride:N}=iG(!0),{collectionItems:P}=OG([],M,h),F=(0,U.useCallback)(e=>{let n=e.subscribeToStack(n=>{if(!t)return;if(n.blocks.length===0){vE(t,[]);return}let r=n.blocks[0];r?.sourceIds?.length?vE(t,pG(e.script,r.sourceIds).map(e=>j+e)):vE(t,[])}),r=e.subscribeToOutput(e=>{(e.outputType===`segment`||e.outputType===`milestone`)&&(O.current||(O.current=!0,c?.()),x(e=>e+1))});return()=>{n(),r(),t&&vE(t,[])}},[t,j,c]),I=(0,U.useRef)(!1);(0,U.useEffect)(()=>()=>{I.current=!0},[]),(0,U.useEffect)(()=>{if(d||!w&&(P.length>0||oe.current))return;let e=uG(m);if(!e){A(!0);return}_(e),s?.(e);let t=F(e);return y(!0),()=>{if(t(),f&&I.current){p?.(e);return}e.dispose()}},[w,P.length,d]),(0,U.useEffect)(()=>{if(!d)return;let e=d;T(!0),_(e),s?.(e);let t=F(e);return y(!0),()=>{t(),p?.(e)}},[d]);let L=ZR(g);(0,U.useEffect)(()=>{L.status!==`idle`&&EL().getState().setExecution(L)},[L.status,L.elapsedTime,L.stepCount,L.startTime]),(0,U.useEffect)(()=>{(o||E)&&v&&L.status===`idle`&&(L.start(),D(!1))},[o,E,v,L.status,L.start]),(0,U.useEffect)(()=>{L.status===`running`&&!O.current&&(O.current=!0,c?.())},[L.status,c]),(0,U.useEffect)(()=>{l&&L.status===`running`&&L.pause()},[l,L.status,L.pause]),(0,U.useEffect)(()=>{!u||L.status===`completed`||L.status!==`running`&&L.status!==`paused`&&!O.current||re()},[u,L.status,L.stop]);let R=(0,U.useCallback)(t=>{if(!g)return;g.finalizeAnalytics();let n=dG(g.getOutputStatements(),{startTime:L.startTime??void 0,elapsedTime:L.elapsedTime,completed:t,now:g.nowProvider});r?.(e.id,n)},[e.id,L.elapsedTime,L.startTime,r,g]),[ee,te]=(0,U.useState)(()=>yA());(0,U.useEffect)(()=>bA(te),[]),(0,U.useEffect)(()=>{if(!g||!ee)return;let e=new oL(ee),t=g.subscribeToStack(t=>e.onStackSnapshot(t)),n=g.subscribeToOutput(t=>e.onOutput(t));return()=>{t(),n(),e.dispose()}},[g,ee]);let ne=(0,U.useRef)(null);(0,U.useEffect)(()=>{ne.current=null},[ee]),(0,U.useEffect)(()=>{if(L.status===`completed`){ne.current=null;return}let e=v?`active`:null;if(!(!e||e===ne.current||!ee?.connected)){ne.current=e;try{ee.send({type:`rpc-workbench-update`,mode:e})}catch{}}},[v,L.status,ee]),(0,U.useEffect)(()=>()=>{if(ne.current===`active`)try{yA()?.send({type:`rpc-workbench-update`,mode:`idle`})}catch{}},[]),(0,U.useEffect)(()=>{if(L.status===`completed`&&!S&&(C(new Date),R(!0),ee?.connected)){let e=fG(g?.getOutputStatements()||[]),t=tG({totalDurationMs:L.elapsedTime,segmentCount:e});try{ee.send(t)}catch{}}},[L.status,L.elapsedTime,S,R,ee,g]);let re=(0,U.useCallback)(()=>{let e=g?g.stack.count===0:!1;L.stop(),g?.handle({name:`abort`,timestamp:g.clock.currentDate,data:{}}),R(e)},[g,L,R]),ie=(0,U.useCallback)(()=>{re(),n()},[re,n]),ae=(0,U.useCallback)(()=>{L.start(),i||a?.()},[L,i,a]),oe=(0,U.useRef)(!1);(0,U.useEffect)(()=>{P.length>0&&(oe.current=!0)},[P.length]);let se=!w&&(P.length>0||oe.current),ce=()=>{T(!0),D(!0),i||a?.()},le=(0,U.useCallback)(()=>{L.status!==`paused`&&g?.handle(new tp(void 0,g.nowProvider))},[g,L.status]),{snapshot:z,dispatch:ue}=WG({runtime:g,executionStatus:L.status===`error`?`idle`:L.status,enabled:v&&!se&&!k&&L.status!==`error`,actions:{next:le,start:ae,playback:()=>{L.status===`running`?L.pause():L.start()},stop:ie,dismiss:n}});return(0,U.useEffect)(()=>{if(!g)return;let e=EL().getState();return e.setRuntime(g),e.setHandles({handleStart:ae,handlePause:()=>L.pause(),handleStop:ie,handleNext:le,handleStartWorkoutAction:()=>{}}),()=>{let e=EL().getState();e.runtime===g&&e.setRuntime(null)}},[g,L,ae,ie,le]),se?(0,W.jsx)(PH,{children:(0,W.jsx)(NG,{items:P,onSave:(e,t)=>{if(typeof t!=`number`)throw TypeError(`A numeric target is required`);if(!SG(h,e,t,`target`))throw Error(`Enter a valid target before starting`);e.kind===`value`&&N(e.blockKey,e.metricType,t)},onSkip:()=>{},onStart:ce,mode:`pre-run`})}):k?(0,W.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`Nothing to run`}),(0,W.jsx)(`p`,{className:`max-w-xs text-xs text-muted-foreground`,children:`This block has no workout statements yet. Add a timer or some movements, then run it again.`}),(0,W.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:`Close`})]}):!v||!g?(0,W.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Initializing…`}):(0,W.jsx)(PH,{children:(0,W.jsx)(iz,{runtime:g,children:(0,W.jsx)(ZG,{execution:L,outputCount:b,createdAt:S,handleStart:ae,handleStop:()=>{ue({kind:`stop-request`})},handleNext:le,commandBoard:z?(0,W.jsx)(XG,{snapshot:z,dispatch:ue}):null,canNext:z?.canNext})})})},$G=`wodwiki-telemetry`,eK=1,tK=`events`,nK=`wodwiki.telemetry.consent`,rK=class{events=new nk;consentListeners=new Set;storage;forwarder;idb;sink;load;dbPromise;_consent;setForwarder(e){this.forwarder=e}constructor(e={}){this.storage=e.storage??(globalThis.localStorage===void 0?void 0:globalThis.localStorage),this.forwarder=e.forwarder,this.idb=e.sink?void 0:e.idb??(typeof indexedDB<`u`?indexedDB:void 0),this.sink=e.sink,this.load=e.load,this._consent=this.storage?.getItem(nK)!==`denied`}get consent(){return this._consent}setConsent(e){if(this._consent!==e){this._consent=e;try{this.storage?.setItem(nK,e?`granted`:`denied`)}catch{}this.consentListeners.forEach(t=>t(e))}}subscribeConsent(e){return this.consentListeners.add(e),()=>this.consentListeners.delete(e)}record(e,t){let n={name:e,payload:t,at:Date.now()};if(this.persist(n).catch(e=>console.error(`[TelemetryService] persist failed:`,e)),this.events.emit(n),this._consent&&this.forwarder)try{this.forwarder(n)}catch(e){console.error(`[TelemetryService] forwarder error:`,e)}}async list(){if(this.load)return this.load();let e=await this.open();if(!e)return[];let{promise:t,resolve:n,reject:r}=Promise.withResolvers(),i=e.transaction(tK,`readonly`).objectStore(tK).getAll();return i.onsuccess=()=>n(i.result.map(({name:e,payload:t,at:n})=>({name:e,payload:t,at:n}))),i.onerror=()=>r(i.error),t}async persist(e){if(this.sink){await this.sink(e);return}let t=await this.open();if(!t)return;let{promise:n,resolve:r,reject:i}=Promise.withResolvers(),a=t.transaction(tK,`readwrite`);return a.objectStore(tK).add(e),a.oncomplete=()=>r(),a.onerror=()=>i(a.error),n}open(){return this.idb?(this.dbPromise??=this.openDatabase(),this.dbPromise):Promise.resolve(null)}async openDatabase(){let{promise:e,resolve:t,reject:n}=Promise.withResolvers(),r=this.idb.open($G,eK);return r.onupgradeneeded=()=>{let e=r.result;if(!e.objectStoreNames.contains(tK)){let t=e.createObjectStore(tK,{keyPath:`id`,autoIncrement:!0});t.createIndex(`by-name`,`name`),t.createIndex(`by-at`,`at`)}},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),e.catch(e=>(console.error(`[TelemetryService] open failed:`,e),null))}},iK;function aK(){let e=Date.now(),t=iK===void 0?0:e-iK;return iK=e,t}var oK=ik?new rK({sink:e=>pk(`telemetry:${crypto.randomUUID()}`,{name:e.name,payload:e.payload,at:e.at}),load:async()=>(await fk(`telemetry:`)).map(e=>e.value).sort((e,t)=>e.at-t.at)}):new rK,sK={demoOpened:`home:demo_opened`,demoRun:`home:demo_run`,demoEdited:`home:demo_edited`,libraryOpened:`home:library_opened`,feedsOpened:`home:feeds_opened`,noteCreated:`home:note_created`,lessonStarted:`home:lesson_started`,cheatsheetOpened:`home:cheatsheet_opened`,behaviorsOpened:`home:behaviors_opened`,analyticsGuideOpened:`home:analytics_guide_opened`,explorerOpened:`home:explorer_opened`,dashboardViewed:`home:dashboard_viewed`,effortsOpened:`home:efforts_opened`,referenceOpened:`home:reference_opened`,chapterHeroViewed:`home:chapter_hero_viewed`,chapterExampleRun:`home:chapter_example_run`,chapterGuideClicked:`home:chapter_guide_clicked`,hostedInterestClicked:`home:hosted_interest_clicked`,hostedSurveyOpened:`home:hosted_survey_opened`};function cK(){let e=(0,U.useSyncExternalStore)(e=>oK.subscribeConsent(e),()=>oK.consent);return{track:(0,U.useCallback)((e,t)=>oK.record(e,t),[]),consent:e,setConsent:(0,U.useCallback)(e=>oK.setConsent(e),[])}}var lK=[25,50,75,90];function uK(e,t=lK){let n=(0,U.useRef)(new Set);(0,U.useEffect)(()=>{if(!e||typeof window>`u`)return;n.current.clear();let r=()=>{let r=document.documentElement.scrollHeight-window.innerHeight;if(r<=0)return;let i=Math.round(window.scrollY/r*100);for(let r of t)i>=r&&!n.current.has(r)&&(n.current.add(r),oK.record(`scroll`,{percent_scrolled:r,page_path:e}))};return window.addEventListener(`scroll`,r,{passive:!0}),r(),()=>{window.removeEventListener(`scroll`,r)}},[e,t])}var dK=`playground`;function fK(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`entry`}function pK({persistence:e,pages:t,now:n=Date.now}){async function r(t,r,i,a){return(await e.createNote({id:w(),title:r,rawContent:i,targetDate:n(),type:`playground`,slug:t,sourceId:a??dK})).id}async function i(e,r,i,a){await t.savePage({id:e.id,slug:r,category:`playground`,name:i,content:a,sourceRevision:e.sourceRevision,updatedAt:n()})}return{async createPage(e,a){let o=ny(n()),s=MV(`playground`,o),c=await t.getPage(s);return c?(await i(c,c.slug??s,c.name||o,e),o):(await r(s,o,e,a?.sourcePath),o)},async ensureEntry(e,a={}){if(!a.reuseKey){let t=ny(n()),i=MV(`playground`,t);return{noteId:await r(i,t,e),routeId:i}}let o=fK(a.reuseKey),s=MV(`playground`,o),c=await t.getPage(s);if(c&&c.type===`playground`)return await i(c,c.slug??s,c.name||o,e),{noteId:c.id,routeId:s};if(c){console.warn(`[playground-intake] reuse key '${o}' resolves to a non-playground note (${c.id}); minting a fresh entry instead of overwriting it.`);let t=`${o}-${ny(n())}`,i=MV(`playground`,t);return{noteId:await r(i,a.title??t,e),routeId:i}}return{noteId:await r(s,a.title??o,e),routeId:s}},async snapshotEntry(e,i){let a=ny(n()),o=[fK(i.pageTitle),i.sectionTitle?fK(i.sectionTitle):null,a].filter(Boolean).join(`-`),s=MV(`playground`,o);for(let e=2;await t.getPage(s);e+=1)s=MV(`playground`,`${o}-${e}`);let c=[i.pageTitle,i.sectionTitle,a].filter(Boolean).join(` `);return{noteId:await r(s,c,e),routeId:s}},moveToJournal(t,n){return e.mutateNote({id:t},{metadata:{journalDate:n,type:`journal`,sourceId:null,slug:null}})}}}var mK=pK({persistence:DN,pages:LV});function hK(e,t){return mK.createPage(e,t)}function gK(e,t){return mK.ensureEntry(e,t)}function _K(e,t){return mK.moveToJournal(e,t)}function vK({intake:e=mK,recorder:t=$W,persistence:n=DN}={}){let[r,i]=(0,U.useState)(null),[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(null),l=(0,U.useRef)(null),u=(0,U.useRef)(!1),d=(0,U.useRef)(null),f=(0,U.useRef)(null),p=(0,U.useRef)(null),m=(0,U.useCallback)(async(t,r,a)=>{if(f.current)throw Error(`A workout is already starting.`);if(l.current&&!u.current)throw Error(`A workout is already running.`);if(d.current)throw Error(`Previous workout results are not saved yet.`);let s=(async()=>{let s=await e.snapshotEntry(t,{pageTitle:a.pageTitle,sectionTitle:a.sectionTitle}),f=await n.getNote(s.noteId);if(!f.blocks||f.sourceRevision===void 0)throw Error(`The saved workout map is unavailable.`);let p=Object.values(f.blocks).filter(e=>e.kind===`wod`).sort((e,t)=>e.from-t.from),m=t.split(`
153
+ `).slice(0,r.startLine).join(`
154
+ `).length+ +(r.startLine>0),h=p.find(e=>e.from===m);if(!h)throw Error(`The selected workout occurrence is not in the saved note.`);let g=w(),_=await yL({noteId:s.noteId,rawContent:f.rawContent,blocks:f.blocks,expectedSourceRevision:f.sourceRevision},{...r,id:h.id},g,`playground`,n),v={noteId:s.noteId,resultId:g,block:_.block};return l.current=v,u.current=!1,o(!1),d.current=null,c(null),i(v),v})();f.current=s;try{return await s}finally{f.current===s&&(f.current=null)}},[e,n]),h=(0,U.useCallback)(async(e,n)=>{if(f.current)try{await f.current}catch{}let r=l.current;if(!r||u.current)return;if(p.current)return p.current;let i=d.current??{results:e,completed:n},a=(async()=>{d.current=i,c(d.current);try{await t.record({runBlock:r.block,blockId:r.block.id,noteId:r.noteId,resultId:r.resultId,data:i.results,createdAt:i.results.endTime??Date.now(),origin:`playground`})}finally{p.current===a&&(p.current=null)}u.current=!0,o(!0),d.current=null,c(null)})();return p.current=a,a},[t]),g=(0,U.useCallback)(async()=>{if(f.current)try{await f.current}catch{}p.current&&await p.current},[]);return{run:r,recorded:a,pendingResults:s,start:m,finalize:h,reset:(0,U.useCallback)(async(t,n)=>{if(await g(),l.current&&!u.current&&n.results&&await h(n.results,!1),d.current)throw Error(`Previous workout results are not saved yet.`);await e.snapshotEntry(t,{pageTitle:n.pageTitle,sectionTitle:n.sectionTitle}),l.current=null,u.current=!1,o(!1),d.current=null,c(null),i(null)},[g,h,e]),end:(0,U.useCallback)(async e=>{if(await g(),l.current&&!u.current&&e&&await h(e,!1),d.current)throw Error(`Previous workout results are not saved yet.`);l.current=null,u.current=!1,o(!1),d.current=null,c(null),i(null)},[g,h])}}function yK({title:e,getBlock:t,getContent:n}){let r=vK(),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(null),[c,l]=(0,U.useState)(!1),u=(0,U.useRef)(!1),d=(0,U.useRef)(0),f=(0,U.useRef)(null),p=(0,U.useRef)(null);(0,U.useEffect)(()=>()=>{d.current+=1},[]);let m=(0,U.useCallback)(async e=>{let t=++d.current;try{await r.end(e?.results)}catch(e){t===d.current&&Q({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try stopping again.`,variant:`destructive`});return}t===d.current&&a(null)},[r]),h=(0,U.useCallback)(async(i,o)=>{let c=i??t();if(!c||u.current)return;u.current=!0;let l=++d.current;try{let t=await r.start(o??n(),c,{pageTitle:e??`Playground`});if(l!==d.current)return;s(null),a({kind:`timer`,block:t.block,results:null})}catch(e){l===d.current&&Q({title:`Could not save playground workout`,description:e instanceof Error?e.message:`The workout was not started. Please try again.`,variant:`destructive`})}finally{u.current=!1}},[r,e,t,n]),g=(0,U.useCallback)(async t=>{let i=d.current;try{await r.finalize(t,t.completed??!1)}catch(e){i===d.current&&Q({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try completing again.`,variant:`destructive`});return}if(i===d.current&&(s(t),a(null),f.current)){let t=f.current;f.current=null,l(!1);let i=p.current??{doc:n(),meta:{pageTitle:e??`Playground`}};p.current=null;try{await r.reset(i.doc,i.meta)}catch(e){Q({title:`Could not save reset snapshot`,description:e instanceof Error?e.message:`Your partial results are kept — try resetting again.`,variant:`destructive`})}finally{t()}}},[r,n,e]),_=(0,U.useCallback)(async t=>{let a=t??n(),o={pageTitle:e??`Playground`};try{if(r.run&&!r.recorded&&i){if(r.pendingResults)return await r.finalize(r.pendingResults.results,!1),await r.reset(a,o),!0;p.current={doc:a,meta:o},l(!0);let e=Promise.withResolvers();return f.current=e.resolve,await e.promise,!0}return await r.reset(a,o),!0}catch(e){return Q({title:`Could not save workout results`,description:e instanceof Error?e.message:`Your results are kept — try resetting again.`,variant:`destructive`}),!1}},[r,n,e,i]);return{fullscreen:i,startRun:h,closeRun:m,completedResults:o,runState:(0,U.useMemo)(()=>({isReconnect:!1,onReconnect:()=>{},onRun:()=>{h()}}),[h]),handleWorkoutComplete:g,run:r.run,recorded:r.recorded,pendingResults:r.pendingResults,resetRequested:c,resetRun:_}}function bK({initialSource:e,initialSourceKey:t,contentOverride:n}){let[r,i]=(0,U.useState)(e),[a,o]=(0,U.useState)(1),[s,c]=(0,U.useState)(!1),[l,u]=(0,U.useState)(t),[d,f]=(0,U.useState)(e),p=(0,U.useRef)(e),m=(0,U.useRef)(null),h=(0,U.useRef)(new Map([[t,{original:e,current:e}]])),g=(0,U.useRef)(void 0),_=(0,U.useCallback)(()=>{requestAnimationFrame(()=>m.current?.focus())},[]),v=(0,U.useCallback)((e,t=e)=>{let n=h.current.get(t),r=n?.current??e,a=n?.original??e;if(n||h.current.set(t,{original:e,current:e}),u(t),f(a),_(),r===p.current){c(!1);return}clearTimeout(g.current),c(!0),o(0),g.current=setTimeout(()=>{p.current=r,i(r),o(1),c(!1),g.current=void 0,_()},180)},[_]),y=(0,U.useCallback)(e=>{i(e),p.current=e;let t=h.current.get(l)??{original:d,current:d};h.current.set(l,{...t,current:e})},[d,l]),b=(0,U.useCallback)(()=>{let e=h.current.get(l)?.original??d;h.current.set(l,{original:e,current:e}),p.current=e,i(e),f(e),_()},[d,l,_]),x=(0,U.useCallback)(e=>{m.current=e},[]),S=(0,U.useCallback)(()=>p.current,[]),C=(0,U.useRef)(void 0);return(0,U.useEffect)(()=>{n&&n!==C.current&&(C.current=n,v(n,`content-override:${n}`))},[n,v]),{editorSource:r,editorOpacity:a,isEditorLoading:s,activeSourceKey:l,activeOriginalSource:d,swapSource:v,handleEditorChange:y,resetActiveSource:b,setEditorView:x,getSource:S}}var xK=`wodwiki.quests.v1`;function SK(){try{let e=window.localStorage.getItem(xK);if(!e)return{};let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch(e){console.error(`Failed to read quest progress:`,e)}return{}}function CK(e){try{window.localStorage.setItem(xK,JSON.stringify(e))}catch(e){console.error(`Failed to write quest progress:`,e)}}function wK(e){return SK()[e]??{}}function TK(e,t){let n=SK();n[e]=t,CK(n),window.dispatchEvent(new StorageEvent(`storage`,{key:xK}))}function EK(e,t){let n=wK(e);n[t]||(n[t]=!0,TK(e,n))}function DK(e,t){let n=wK(e);n[t]=!n[t],TK(e,n)}function OK(e,t){let[n,r]=(0,U.useState)(()=>wK(e));(0,U.useEffect)(()=>{let t=t=>{t.key===`wodwiki.quests.v1`&&r(wK(e))};return window.addEventListener(`storage`,t),()=>window.removeEventListener(`storage`,t)},[e]);let i=(0,U.useCallback)(t=>{EK(e,t),r(wK(e))},[e]),a=(0,U.useCallback)(t=>{DK(e,t),r(wK(e))},[e]),o=t.map(e=>({...e,isCompleted:!!n[e.id]})),s=t.length,c=o.filter(e=>e.isCompleted).length;return{quests:o,stepsComplete:c,totalSteps:s,isComplete:s>0&&c===s,markComplete:i,toggleQuest:a}}function kK({pageRoute:e,quests:t,completedResults:n,enabled:r=!0}){let{markComplete:i}=OK(e,t),a=(0,U.useRef)(new Set),o=t.map(e=>e.id).join(`|`);(0,U.useEffect)(()=>{a.current.clear()},[e,o]);let s=t.filter(e=>e.validation?.type===`workout-complete`);return(0,U.useEffect)(()=>{if(!(!r||!n)&&n.completed===!0)for(let e of s)a.current.has(e.id)||(i(e.id),a.current.add(e.id))},[r,n,s,i]),{questIds:s.map(e=>e.id)}}function AK({pageRoute:e,quests:t,initialSource:n,currentSource:r,enabled:i=!0}){let{markComplete:a}=OK(e,t),o=t.some(e=>e.id===`qs-arrive`),s=t.some(e=>e.id===`qs-edit`),c=(0,U.useRef)(n);c.current=n;let l=(0,U.useRef)(r);l.current=r,(0,U.useEffect)(()=>{!i||!o||a(`qs-arrive`)},[i,o,a]),(0,U.useEffect)(()=>{if(!i||!s)return;let e=c.current.trim(),t=l.current.trim();t!==e&&t.length>0&&a(`qs-edit`)},[i,s,r,a])}function jK(e){let[t,n]=(0,U.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(e).matches);return(0,U.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e),r=e=>n(e.matches);return t.addEventListener?(t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)):(t.addListener(r),()=>t.removeListener(r))},[e]),t}var MK=(0,U.createContext)(null);function NK(){return(0,U.useContext)(MK)}function PK({title:e,subtitle:t,children:n,onReset:r,headerActions:i,className:a}){let o=NK();return(0,W.jsxs)(`div`,{className:G(`flex flex-col w-full h-full rounded-2xl lg:rounded-3xl border border-border shadow-2xl bg-background`,a),children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2.5 bg-muted/20 border-b border-border/60 shrink-0 rounded-t-2xl lg:rounded-t-3xl`,children:[(0,W.jsxs)(`div`,{className:`flex gap-1.5`,children:[r?(0,W.jsx)(`button`,{onClick:r,title:`Reset`,className:`size-2.5 rounded-full bg-red-500 hover:bg-red-400 transition-colors cursor-pointer ring-1 ring-red-500/40 hover:ring-red-400/60`}):(0,W.jsx)(`div`,{className:`size-2.5 rounded-full bg-red-500/30`}),(0,W.jsx)(`div`,{className:`size-2.5 rounded-full bg-amber-500/30`}),(0,W.jsx)(`div`,{className:`size-2.5 rounded-full bg-emerald-500/30`})]}),(0,W.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[o?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`flex min-w-0 flex-1 justify-end`,children:o.status}),o.pips]}):(0,W.jsxs)(`span`,{className:`text-[9px] font-black text-muted-foreground uppercase tracking-[0.2em]`,children:[e,t&&(0,W.jsxs)(`span`,{className:`ml-1.5 font-medium normal-case tracking-normal text-muted-foreground/50`,children:[`· `,t]})]}),i,r&&(0,W.jsxs)(`button`,{onClick:r,className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[10px] font-black uppercase tracking-wider text-destructive-foreground bg-destructive/80 hover:bg-destructive border border-destructive/40 shadow-sm transition-all`,children:[(0,W.jsx)(At,{className:`size-3`}),`Reset`]})]})]}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden rounded-b-2xl lg:rounded-b-3xl`,children:n})]})}function FK(){return sT.of(async()=>{let[e,t,n]=await Promise.all([Z.getAllTagTypes(),Z.getAllTags(),WK()]);return{types:e.map(e=>e.name),tags:t,efforts:n.efforts.map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[]})),equipment:n.equipment.map(e=>({slug:e.slug,label:e.label,aliases:e.aliases??[]}))}})}var IK=null;function LK(e,t,n){return XV(e===`effort`?{id:t,kind:`effort`,sourceCatalog:`efforts`,sourceItem:t,title:n,date:null,effort:{slug:t,label:n}}:{id:t,kind:`equipment`,sourceCatalog:`equipment`,sourceItem:t,title:n,date:null})}function RK(e){return`/tags?tag=${encodeURIComponent(e)}`}function zK(e){return{resolve:(t,n)=>e.resolve(t,n),resolveEffort:t=>e.resolveEffort(t),resolveEquipment:t=>e.resolveEquipment(t),openHref:(e,t)=>e===`tag`?RK(t):LK(e,t,t),createHref:e=>e===`effort`?`/e/new?mode=create`:e===`equipment`?`/equipment/new?mode=create`:`/tags`}}function BK(e){return JSON.stringify([e.efforts.map(e=>[e.slug,e.label,e.aliases??[],e.equipment??[]]),e.equipment.map(e=>[e.slug,e.label,e.aliases??[]])])}function VK(){let e=vD(),t=QA();if(!e.isInitialized()||!t.isInitialized())return null;let n={efforts:[...e.list()],equipment:[...t.list()]},r=BK(n);if(!IK||IK.signature!==r){let e=hc(n);IK={index:e,provider:zK(e),signature:r}}return IK.provider}function HK(){return VK(),IK?.index??null}function UK(){let e=Vr.fromClass(class{view;channel=null;onSeed=()=>{this.view.dispatch({effects:lT.of(null)})};constructor(e){this.view=e,typeof BroadcastChannel<`u`&&(this.channel=new BroadcastChannel(av),this.channel.onmessage=this.onSeed)}destroy(){this.channel?.close()}});return[cT.of(VK),e]}async function WK(){return{efforts:[...vD().list()],equipment:[...QA().list()]}}function GK(e){let{meta:t}=E_(e),n=t[`metrics.effort`],r=typeof n==`string`&&n.trim()?n.trim():void 0,i=t[`metrics.equipment`],a=(Array.isArray(i)?i:[i]).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim());return{...r?{effort:r}:{},...a.length>0?{equipment:a}:{}}}function KK(e,t){return{id:`reference:${e}`,label:e===`effort`?`Effort`:`Equipment`,search:async n=>{let r=await WK(),i=e===`effort`?r.efforts:r.equipment,a=(t?i.filter(e=>t.includes(e.slug)):i).map(t=>({id:t.slug,label:`${t.label} (${t.slug})`,category:e===`effort`?`Effort`:`Equipment`,type:`statement-part`,payload:t.slug}));if(!n)return a;let o=n.toLowerCase();return a.filter(e=>e.label.toLowerCase().includes(o))}}}function qK(e){let t=e.trimEnd();if(!t.endsWith(`}`))return null;let n=0;for(let e=t.length-1;e>=0&&n<24;e--){if(t[e]!==`{`)continue;n++;let r=t.slice(e);try{return JSON.parse(r),{json:r,from:e,to:e+r.length}}catch{}}return null}function JK(e){let t=qK(e);if(!t)return{equipment:[],jsonFrom:-1,jsonTo:-1,malformed:!1,hasInvalidEntries:!1};let n;try{n=JSON.parse(t.json)}catch{return{equipment:[],jsonFrom:t.from,jsonTo:t.to,malformed:!0,hasInvalidEntries:!1}}let r=!1,i,a=[];if(typeof n==`object`&&n){let e=n;if(e.effort!==void 0&&(typeof e.effort==`string`&&e.effort.trim()?i=e.effort.trim():r=!0),e.equipment!==void 0){let t=Array.isArray(e.equipment)?e.equipment:[e.equipment];for(let e of t)typeof e==`string`&&e.trim()?a.push(e.trim()):r=!0}}else r=!0;return{effort:i,equipment:a,jsonFrom:t.from,jsonTo:t.to,malformed:!1,hasInvalidEntries:r}}function YK(e,t){let n=JK(e);if(n.malformed||n.hasInvalidEntries)return e;let r=n.jsonFrom>=0?e.slice(0,n.jsonFrom).trimEnd():e.trimEnd(),i={};if(n.jsonFrom>=0)try{i=JSON.parse(e.slice(n.jsonFrom,n.jsonTo))}catch{return e}return t.effort!==void 0&&(t.effort===null?delete i.effort:i.effort=t.effort),t.equipment!==void 0&&(t.equipment.length===0?delete i.equipment:i.equipment=t.equipment),Object.keys(i).length===0?r:`${r} ${JSON.stringify(i)}`}function XK(e,t){return t||(e.current||=new EN,e.current)}function ZK(e,t){return Er.domEventHandlers({drop:(n,r)=>{let i=n.dataTransfer?.files;if(!i||i.length===0)return!1;n.preventDefault();let a=r.posAtCoords({x:n.clientX,y:n.clientY});return a!==null&&(Array.from(i).forEach(async n=>{let i=w(),o=new FileReader;o.onload=async()=>{let s=o.result;if(e)try{await t.mutateNote(e,{attachments:{add:[{id:i,file:new File([s],n.name,{type:n.type})}]}})}catch(e){mL(`NoteEditor`,`Attachment persist skipped:`,e)}let c=`\n${n.type.startsWith(`image/`)?`!`:``}[${n.name}](${i})\n`;r.dispatch({changes:{from:a,insert:c},selection:{anchor:a+c.length}})},o.readAsArrayBuffer(n)}),!0)}})}function QK(e){let t=e?.split(`:`,1)[0];return t===`time`||t===`log`?bc:null}var $K=Xr.define(),eq=Vr.fromClass(class{unsubscribes;constructor(e){let t=()=>e.dispatch({effects:[$K.of(null)]});this.unsubscribes=[WA(t),hD(t),YA(t)]}update(e){}destroy(){for(let e of this.unsubscribes)e()}}),tq={[q.Duration]:`cm-metric-underline-duration`,[q.Rep]:`cm-metric-underline-rep`,[q.Effort]:`cm-metric-underline-effort`,[q.Rounds]:`cm-metric-underline-rounds`,[q.Distance]:`cm-metric-underline-distance`,[q.Resistance]:`cm-metric-underline-resistance`,[q.Action]:`cm-metric-underline-action`,[q.Equipment]:`cm-metric-underline-equipment`};function nq(e){return e?.soundProfileId?`cm-tag-reference-sound`:`cm-tag-reference`}function rq(e,t){if(e.contentFrom===void 0||e.contentTo===void 0)return null;let n=t.doc.sliceString(e.contentFrom,e.contentTo);if(!n.trim())return null;try{let r=HK(),i=BA();return r?yc({references:r,defaults:GK(t.doc.toString()),tags:i}).read(n,e.sport).statements:yc({tags:i}).read(n,e.sport).statements}catch{return null}}function iq(e,t,n,r){let i=[];for(let a of e){if(a.contentFrom===void 0||a.contentTo===void 0)continue;let e=rq(a,r);if(e)for(let o of e){let e=a.startLine+(o.meta?.line??0),s=t===a&&e===n;for(let e of o.metrics){let t=ba(e.metadata),n=typeof e.type==`string`&&e.type.startsWith(`tag.`);if(t&&!n)continue;let c=e.type===q.Choice?e.alternatives[0]?.type:e.type,l=n?nq(t):tq[c];if(!l)continue;let u=o.metricMeta?.get(e);if(!u)continue;let d=a.contentFrom+u.startOffset,f=a.contentFrom+u.endOffset;if(!Number.isFinite(d)||!Number.isFinite(f)||d>=f||d<0||f>r.doc.length)continue;let p=s?l:`${l}-dim`;i.push(Br.mark({class:p}).range(d,f))}}}return i.sort((e,t)=>e.from-t.from),Br.set(i)}function aq(e){let{sections:t}=e.field(Aw),{head:n}=e.selection.main,r=e.doc.lineAt(n).number,i=t.filter(e=>e.type===`time`||e.type===`log`),a=i.find(e=>r>=e.startLine+1&&r<e.endLine)??null,o=null,s=null,c=-1,l=null;if(a){let t=e.doc.line(r);l=rq(a,e);let i=r-a.startLine;c=l?.findIndex(e=>e.meta?.line===i&&e.metrics.some(t=>{let r=e.metricMeta.get(t),i=n-(a.contentFrom??0);return r&&i>=r.startOffset&&i<=r.endOffset}))??-1,c<0&&(c=l?.findIndex(e=>e.meta?.line===i)??-1),s=c>=0&&l?l[c]:null,o={sectionId:a.id,section:a,statement:s,statementIndex:c,cursorLine:r,docLine:r,lineFrom:t.from,lineTo:t.to,focusedMetric:null,focusedMetricIndex:-1,allStatements:l??[]}}let u=null,d=-1;if(a&&s&&a.contentFrom!==void 0)for(let e=0;e<s.metrics.length;e++){let t=s.metrics[e];if(t.type===q.Sound||t.type===q.System)continue;let r=s.metricMeta?.get(t);if(!r)continue;let i=a.contentFrom+r.startOffset,o=a.contentFrom+r.endOffset;if(n>=i&&n<=o){u=t,d=e;break}}o&&(o.focusedMetric=u,o.focusedMetricIndex=d);let f=iq(i,a,r,e);return{focus:o,decos:f}}var oq=si.define({create(e){return aq(e)},update(e,t){return t.effects.some(e=>e.is(lT)||e.is($K))?aq(t.state):!t.docChanged&&t.startState.selection.eq(t.state.selection)?e:aq(t.state)},provide:e=>Er.decorations.from(e,e=>e.decos)});function sq(e){try{return e.field(oq).focus}catch{return null}}function cq(e,t){let n=sq(e.state);if(!n)return!1;if(!n.statement)return!0;let{section:r}=n,i=r.contentFrom??0,{head:a}=e.state.selection.main,o=rq(r,e.state)??[],s=[];for(let e of o)for(let t of e.metrics){if(t.type===q.Sound||t.type===q.System)continue;let n=e.metricMeta?.get(t);n&&s.push({from:i+n.startOffset,to:i+n.endOffset})}if(s.sort((e,t)=>e.from-t.from),s.length===0)return!0;let c;return c=t===1?s.find(e=>e.from>a):[...s].reverse().find(e=>e.from<a),c&&e.dispatch({selection:{anchor:c.from}}),!0}var lq=fi.high(yr.of([{key:`Ctrl-ArrowRight`,run:e=>cq(e,1)},{key:`Ctrl-ArrowLeft`,run:e=>cq(e,-1)}])),uq=[oq,Er.baseTheme({".cm-metric-underline-duration":{borderBottom:`2px solid hsl(var(--metric-time))`,color:`hsl(var(--metric-time))`},".cm-metric-underline-rep":{borderBottom:`2px solid hsl(var(--metric-rep))`,color:`hsl(var(--metric-rep))`},".cm-metric-underline-effort":{borderBottom:`2px solid hsl(var(--metric-effort))`,color:`hsl(var(--metric-effort))`},".cm-metric-underline-rounds":{borderBottom:`2px solid hsl(var(--metric-rounds))`,color:`hsl(var(--metric-rounds))`},".cm-metric-underline-distance":{borderBottom:`2px solid hsl(var(--metric-distance))`,color:`hsl(var(--metric-distance))`},".cm-metric-underline-resistance":{borderBottom:`2px solid hsl(var(--metric-resistance))`,color:`hsl(var(--metric-resistance))`},".cm-metric-underline-action":{borderBottom:`2px solid hsl(var(--metric-action))`,color:`hsl(var(--metric-action))`},".cm-metric-underline-equipment":{borderBottom:`2px solid hsl(var(--metric-equipment))`,color:`hsl(var(--metric-equipment))`},".cm-metric-underline-duration-dim":{borderBottom:`2px solid hsl(var(--metric-time) / 0.2)`,color:`hsl(var(--metric-time))`},".cm-metric-underline-rep-dim":{borderBottom:`2px solid hsl(var(--metric-rep) / 0.2)`,color:`hsl(var(--metric-rep))`},".cm-metric-underline-effort-dim":{borderBottom:`2px solid hsl(var(--metric-effort) / 0.2)`,color:`hsl(var(--metric-effort))`},".cm-metric-underline-rounds-dim":{borderBottom:`2px solid hsl(var(--metric-rounds) / 0.2)`,color:`hsl(var(--metric-rounds))`},".cm-metric-underline-distance-dim":{borderBottom:`2px solid hsl(var(--metric-distance) / 0.2)`,color:`hsl(var(--metric-distance))`},".cm-metric-underline-resistance-dim":{borderBottom:`2px solid hsl(var(--metric-resistance) / 0.2)`,color:`hsl(var(--metric-resistance))`},".cm-metric-underline-action-dim":{borderBottom:`2px solid hsl(var(--metric-action) / 0.2)`,color:`hsl(var(--metric-action))`},".cm-metric-underline-equipment-dim":{borderBottom:`2px solid hsl(var(--metric-equipment) / 0.2)`,color:`hsl(var(--metric-equipment))`},".cm-tag-reference":{color:`hsl(var(--primary))`,backgroundColor:`hsl(var(--primary) / 0.08)`,borderRadius:`3px`,padding:`0 2px`},".cm-tag-reference-dim":{color:`hsl(var(--primary) / 0.55)`},".cm-tag-reference-sound":{color:`hsl(var(--metric-action))`,backgroundColor:`hsl(var(--metric-action) / 0.12)`,borderRadius:`3px`,padding:`0 2px`},".cm-tag-reference-sound-dim":{color:`hsl(var(--metric-action) / 0.55)`}}),lq,eq],dq={frontmatter:120,code:60,widget:220,embed:180},fq={frontmatter:280,code:140,widget:220,embed:280},pq=({view:e,widths:t,activeSectionId:n,renderSlot:r,cursorLine:i})=>{let a=(0,U.useRef)(null),o=(0,U.useRef)(null),[s,c]=(0,U.useState)(()=>e?.plugin(Jw)?.rects??[]),[l,u]=(0,U.useState)(0),[d,f]=(0,U.useState)({left:0,right:0}),[p,m]=(0,U.useState)(()=>e?.plugin(Jw)?.docVersion??0),[h,g]=(0,U.useState)(void 0),[_,v]=(0,U.useState)(void 0);(0,U.useEffect)(()=>{if(!e)return;let t=()=>{let t=e.contentDOM.offsetLeft,n=e.scrollDOM.offsetWidth-e.scrollDOM.clientWidth;f({left:t,right:n})};t();let n=new ResizeObserver(t);return n.observe(e.dom),()=>n.disconnect()},[e]),(0,U.useEffect)(()=>{if(!e)return;let t=e.plugin(Jw);if(t)return t.addListener((e,t)=>{c(e),m(t)})},[e]),(0,U.useEffect)(()=>{if(!e)return;let t=e.scrollDOM,n=null,r=()=>{let e=t.scrollTop;o.current&&(o.current.style.transform=`translateY(${-e}px)`),n===null&&(n=requestAnimationFrame(()=>{n=null,u(t.scrollTop)}))},i=t.scrollTop;return o.current&&(o.current.style.transform=`translateY(${-i}px)`),u(i),t.addEventListener(`scroll`,r,{passive:!0}),()=>{n!==null&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,r)}},[e]),(0,U.useEffect)(()=>{if(!e)return;let t=e.scrollDOM,n={current:void 0},r=r=>{let i=t.getBoundingClientRect();if(r.clientY<i.top||r.clientY>i.bottom||r.clientX<i.left||r.clientX>i.right){n.current!==void 0&&(n.current=void 0,g(void 0));return}try{let t=e.posAtCoords({x:r.clientX,y:r.clientY});if(t==null){n.current!==void 0&&(n.current=void 0,g(void 0));return}let i=e.state.doc.lineAt(t).number;i!==n.current&&(n.current=i,g(i))}catch{n.current!==void 0&&(n.current=void 0,g(void 0))}},i=()=>{n.current!==void 0&&(n.current=void 0,g(void 0))};return document.addEventListener(`mousemove`,r,{passive:!0}),t.addEventListener(`mouseleave`,i),()=>{document.removeEventListener(`mousemove`,r),t.removeEventListener(`mouseleave`,i)}},[e]);let y=(s.length>0?s:e?.plugin(Jw)?.rects??[]).filter(e=>{let n=t.get(e.sectionId);return n&&n.effectiveWidth>0});return!e||y.length===0?null:(0,W.jsx)(`div`,{ref:a,className:`overlay-track`,style:{position:`absolute`,top:0,left:d.left,right:d.right,bottom:0,pointerEvents:`none`,overflow:`visible`,zIndex:10},children:(0,W.jsx)(`div`,{ref:o,style:{position:`relative`,willChange:`transform`},children:y.map(a=>{let o=t.get(a.sectionId),s=a.sectionId===n,c=_===a.sectionId,u,d;if(a.type===`time`||a.type===`log`)u=a.top,d=a.height;else{let t=(s?fq:dq)[a.type]??0;if(d=a.type===`widget`?t:Math.max(a.height,t),s){let t=a.top+a.height/2;if(i!==void 0)try{let n=e.state.doc.lines,r=Math.max(1,Math.min(i,n)),o=e.state.doc.line(r).from,s=e.lineBlockAt(o),c=s.top+s.height/2;c>=a.top&&c<=a.top+a.height&&(t=c)}catch{}let n=t-d/2;u=Math.max(a.top,Math.min(n,a.top+a.height-d))}else u=a.top}let f=Math.max(0,l-a.top),m=Math.min(f,Math.max(0,a.height-28)),g;if(a.type===`time`||a.type===`log`){let t=s?i:h;if(t!==void 0)try{let n=Math.max(1,Math.min(t,e.state.doc.lines)),r=e.lineBlockAt(e.state.doc.line(n).from),i=r.top+r.height/2;i>=a.top&&i<=a.top+a.height&&(g=i)}catch{}}return(0,W.jsx)(`div`,{className:`overlay-slot ${s?`overlay-slot-active`:``}`,style:{position:`absolute`,top:u,right:0,width:`${o.effectiveWidth}%`,height:d,pointerEvents:a.type===`time`||a.type===`log`?`none`:`auto`,transition:`width 150ms ease`,overflow:`visible`},onClick:a.type!==`time`&&a.type!==`log`?t=>{if(t.target.closest(`button,a,input,select,textarea,[role=button]`))return;let n=e.posAtCoords({x:t.clientX,y:t.clientY});n!=null&&(e.dispatch({selection:{anchor:n}}),e.focus())}:void 0,onMouseEnter:()=>v(a.sectionId),onMouseLeave:()=>v(void 0),children:r?.({sectionId:a.sectionId,sectionType:a.type,rect:a,widthPercent:o.effectiveWidth,isActive:s,view:e,docVersion:p,widgetName:a.widgetName,hoverLine:h,stickyTopOffset:m,isPanelHovered:c,lineDocY:g})},a.sectionId)})})})},mq={time:{active:35,inactive:20},log:{active:35,inactive:20},frontmatter:{active:35,inactive:100},markdown:{active:0,inactive:0},code:{active:30,inactive:0},widget:{active:100,inactive:100},embed:{active:35,inactive:100}};function hq(e,t=mq){if(e.userOverride!==void 0)return Math.max(0,Math.min(100,e.userOverride));let n=t[e.sectionType];return n?e.isActive?n.active:n.inactive:0}function gq(e,t){switch(t.type){case`SET_SECTION_WIDTH`:return{...e,sectionOverrides:{...e.sectionOverrides,[t.sectionId]:t.width}};case`SET_TYPE_WIDTH`:return{...e,typeOverrides:{...e.typeOverrides,[t.sectionType]:t.width}};case`CLEAR_SECTION_OVERRIDE`:{let{[t.sectionId]:n,...r}=e.sectionOverrides;return{...e,sectionOverrides:r}}case`CLEAR_TYPE_OVERRIDE`:{let{[t.sectionType]:n,...r}=e.typeOverrides;return{...e,typeOverrides:r}}default:return e}}var _q={typeOverrides:{},sectionOverrides:{}};function vq(e,t,n=mq){let[r,i]=(0,U.useReducer)(gq,_q);return{widths:(0,U.useMemo)(()=>{let i=new Map;for(let a of e){let e=a.id===t,o=r.sectionOverrides[a.id],s=r.typeOverrides[a.type],c=o??s,l=hq({sectionType:a.type,isActive:e,userOverride:c},n);i.set(a.id,{effectiveWidth:l,isUserOverridden:c!==void 0})}return i},[e,t,r,n]),setSectionWidth:(0,U.useCallback)((e,t)=>i({type:`SET_SECTION_WIDTH`,sectionId:e,width:t}),[]),setTypeWidth:(0,U.useCallback)((e,t)=>i({type:`SET_TYPE_WIDTH`,sectionType:e,width:t}),[]),clearSectionOverride:(0,U.useCallback)(e=>i({type:`CLEAR_SECTION_OVERRIDE`,sectionId:e}),[])}}function yq(e,t){let{sections:n}=e.state.field(Aw);return n.find(e=>e.id===t)}function bq(e,t){return t.contentFrom===void 0||t.contentTo===void 0?``:e.state.doc.sliceString(t.contentFrom,t.contentTo)}var xq=({props:e,isActive:t})=>{let n=e.source_url||e.website||``,r=e.title||e.label||`Link`,i=!t;return(0,W.jsxs)(`div`,{className:G(`h-full w-full flex flex-col bg-popover/90 backdrop-blur-sm border-l border-border overflow-auto`,i?`p-2`:`p-3`),children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[(0,W.jsx)(`span`,{className:`rounded bg-blue-500/10 dark:bg-blue-900/30 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-blue-500 dark:text-blue-400`,children:`Link`}),(0,W.jsx)(`span`,{className:`truncate text-xs font-medium`,children:r})]}),(0,W.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`mb-2 truncate text-[10px] text-blue-400 dark:text-blue-300 hover:underline`,title:n,children:n}),!i&&(0,W.jsx)(`div`,{className:`rounded-md border border-border/70 bg-background/70 p-2 text-[11px] text-muted-foreground`,children:`External link preview. Click the URL above to open in a new tab.`})]})},Sq=({sectionId:e,section:t,view:n,isActive:r})=>{let i=(0,U.useMemo)(()=>t||yq(n,e),[n,e,t]),a=i?bq(n,i):``,o=(0,U.useMemo)(()=>fx(a),[a]);if(!i)return null;if(i.type===`embed`&&i.embed){let{type:e,url:t,label:n}=i.embed;if(e===`youtube`){let e=px(t);if(e)return(0,W.jsx)(Cq,{videoId:e,title:n,isActive:r})}return(0,W.jsxs)(`div`,{className:`h-full w-full flex flex-col bg-popover/90 backdrop-blur-sm border-l border-border p-3 overflow-auto`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-mono px-1.5 py-0.5 rounded bg-blue-500/10 dark:bg-blue-900/30 text-blue-500 dark:text-blue-400 uppercase font-bold`,children:i.embed.isImage?`IMAGE`:`LINK`}),(0,W.jsx)(`span`,{className:`text-xs font-medium truncate`,children:n||`Untitled`})]}),(0,W.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mb-3`,children:t}),i.embed.isImage&&(0,W.jsx)(`img`,{src:t,alt:n,className:`w-full h-auto rounded border border-border shadow-sm bg-muted/20`})]})}let s=(o.type||``).toLowerCase(),c=o.url||o.link||``;if(s===`youtube`){let e=px(c);if(e)return(0,W.jsx)(Cq,{videoId:e,title:o.title||`YouTube Video`,isActive:r})}return o.source_url||o.website||s===`strava`?(0,W.jsx)(xq,{props:o,isActive:r}):null},Cq=({videoId:e,title:t,isActive:n})=>(0,W.jsxs)(`div`,{className:G(`h-full w-full flex flex-col`,n?`bg-popover/90 backdrop-blur-sm border-l border-border`:`bg-black dark:bg-black`),children:[(0,W.jsx)(`div`,{className:`relative flex-1 min-h-0`,children:(0,W.jsx)(`iframe`,{className:`absolute inset-0 w-full h-full border-0`,src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(e)}`,title:t,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0,loading:`lazy`})}),n&&t&&t!==`YouTube Video`&&(0,W.jsx)(`div`,{className:`px-3 py-1.5 text-xs text-muted-foreground truncate border-t border-border bg-popover/90`,children:t})]});function wq(e,t,n,r){let[i,a]=(0,U.useState)([]),[o,s]=(0,U.useState)(!0),c=DL(e=>e.currentEntry),l=DL(e=>e.getNote),u=n??c?.extendedResults;return(0,U.useEffect)(()=>{if(!e||!t){a([]),s(!1);return}let n=!1;async function r(){if(Array.isArray(u)){let r=u.filter(n=>n.noteId===e&&n.blockId===t);if(r.length>0&&!n){a(r.sort((e,t)=>t.createdAt-e.createdAt)),s(!1);return}}if(typeof l!=`function`){n||(a([]),s(!1));return}try{let r=await l(e,{projection:`history-detail`,resultSelection:{mode:`all-for-section`,blockId:t}});n||a((r?.extendedResults??[]).sort((e,t)=>t.createdAt-e.createdAt))}catch{n||a([])}finally{n||s(!1)}}return r(),()=>{n=!0}},[e,t,u,l,r]),{results:i,loading:o}}function Tq(e){let t=e.metrics?.find(e=>e.type===q.Elapsed);return t?.value!==void 0&&typeof t.value==`number`?t.value:0}function Eq(e,t){let n=[],r=0;for(let i of e){let e=(i.data?.logs??[]).filter(e=>e.outputType===`segment`&&(e.line??e.sourceStatementId)===t),a=e.reduce((e,t)=>Math.max(e,t.stackLevel),0),o=e.filter(e=>e.stackLevel===a);if(o.length===0)continue;let s=o.reduce((e,t)=>e+Tq(t),0);r+=o.length,n.push({createdAt:i.createdAt,hitCount:o.length,elapsedMs:s})}return{lineNumber:t,resultCount:n.length,totalHits:r,entries:n}}function Dq(e,t){return(0,U.useMemo)(()=>{if(t===void 0||e.length===0)return null;let n=Eq(e,t);return n.resultCount>0?n:null},[e,t])}function Oq(e,t){if(t){t(e.action,e);return}e.action.type===`call`&&e.action.handler()}var kq=({primary:e,secondary:t,size:n=`default`,variant:r=`default`,className:i,labelClassName:a,onAction:o})=>{let s=e.icon,c=t.icon,l=r===`primary`,u=n===`xs`?`h-11 min-w-11 justify-center px-0 sm:h-auto sm:min-h-[44px] sm:min-w-0 sm:px-2 sm:py-0.5 sm:justify-start`:n===`sm`?`min-h-[44px] px-2.5 py-1.5`:`min-h-[44px] px-3 py-2`,d=n===`xs`?`h-11 w-11 px-0 sm:h-auto sm:min-h-[44px] sm:min-w-[44px] sm:w-auto sm:px-1.5 sm:py-0.5`:n===`sm`?`min-h-[44px] min-w-[44px] px-2 py-1.5`:`min-h-[44px] min-w-[44px] px-2.5 py-2`,f=n===`xs`?`h-11 min-w-11 justify-center px-0 sm:h-auto sm:min-h-[44px] sm:min-w-0 sm:pl-5 sm:pr-4 sm:py-2 sm:justify-start`:`min-h-[44px] pl-5 pr-4 py-2`,p=n===`xs`?`h-11 w-11 px-0 sm:h-auto sm:min-h-[44px] sm:min-w-[44px] sm:w-auto sm:px-3 sm:py-2`:`min-h-[44px] min-w-[44px] px-3 py-2`;return(0,W.jsxs)(`div`,{className:G(`inline-flex items-stretch overflow-hidden`,l?`rounded-full shadow-lg shadow-primary/25`:`rounded-lg border border-border/70 bg-muted shadow-sm hover:shadow-md transition-shadow`,n===`xs`?`text-[10px]`:n===`sm`?`text-[11px]`:`text-xs`,i),children:[(0,W.jsxs)(`button`,{type:`button`,title:e.label,"aria-label":e.label,onClick:()=>Oq(e,o),className:G(`flex items-center gap-2 transition-colors active:scale-95`,n===`xs`&&`gap-0 sm:gap-2`,l?G(`bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest`,f):G(`hover:bg-accent hover:text-accent-foreground text-muted-foreground font-medium`,u)),children:[s&&(0,W.jsx)(s,{className:G(`shrink-0`,l?`size-4 fill-current sm:size-3`:`size-4 sm:h-4 sm:w-4`)}),(0,W.jsx)(`span`,{className:a,children:e.label})]}),(0,W.jsx)(`div`,{className:G(`self-stretch`,l?`w-px bg-primary-foreground/20 my-2 sm:my-1`:`w-px bg-border/60`)}),(0,W.jsx)(`button`,{type:`button`,title:t.label,"aria-label":t.label,onClick:()=>Oq(t,o),className:G(`flex items-center justify-center transition-colors active:scale-95`,l?G(`bg-primary text-primary-foreground hover:bg-primary/90`,p):G(`hover:bg-accent hover:text-accent-foreground text-muted-foreground`,d)),children:c?(0,W.jsx)(c,{className:G(`shrink-0`,l?`size-4 sm:size-3.5`:`size-4 sm:h-4 sm:w-4`)}):(0,W.jsx)(`span`,{className:`sr-only`,children:t.label})})]})},Aq=new vc;function jq(e,t){let{sections:n}=e.state.field(Aw);return n.find(e=>e.id===t)??null}function Mq(e,t){if(t.contentFrom===void 0||t.contentTo===void 0)return[];let n=e.state.doc.sliceString(t.contentFrom,t.contentTo);if(!n.trim())return[];try{return Aq.read(n,t.sport).statements}catch{return[]}}function Nq(e,t,n){if(!e.length)return null;let r=n-t.startLine;return e.find(e=>e.meta?.line===r)??null}function Pq(e){if(!Number.isFinite(e)||e<=0)return`--:--`;let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`:`${r}:${i.toString().padStart(2,`0`)}`}var Fq={[q.Duration]:{label:`Timer`,icon:`⏱`,color:`bg-metric-time/10 text-metric-time`},[q.Rep]:{label:`Reps`,icon:`✕`,color:`bg-metric-rep/10 text-metric-rep`},[q.Effort]:{label:`Exercise`,icon:`🏋`,color:`bg-metric-effort/10 text-metric-effort`},[q.Rounds]:{label:`Rounds`,icon:`↻`,color:`bg-metric-rounds/10 text-metric-rounds`},[q.Distance]:{label:`Distance`,icon:`📏`,color:`bg-metric-distance/10 text-metric-distance`},[q.Resistance]:{label:`Weight`,icon:`⚖`,color:`bg-metric-resistance/10 text-metric-resistance`},[q.Action]:{label:`Action`,icon:`⚡`,color:`bg-metric-action/10 text-metric-action`}};function Iq(e){return e.metrics.filter(e=>e.type!==q.Sound&&e.type!==q.System).map(e=>{let t=Fq[e.type],n=e.image??(e.value===void 0?`—`:String(e.value));return{label:t?.label??String(e.type),value:n,icon:t?.icon??`•`,color:t?.color??`bg-muted text-muted-foreground`}})}var Lq=({summary:e})=>{let t=e.entries.slice(0,3);return(0,W.jsxs)(`div`,{className:`px-3 py-2 border-t border-border/30 bg-muted/20`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1.5`,children:[(0,W.jsx)(ze,{className:`h-3 w-3 text-muted-foreground`}),(0,W.jsx)(`span`,{className:`text-[10px] font-semibold text-muted-foreground uppercase tracking-wider`,children:`History`}),(0,W.jsxs)(`span`,{className:`ml-auto text-[10px] text-muted-foreground`,children:[e.totalHits,`× across `,e.resultCount,` run`,e.resultCount===1?``:`s`]})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t.map(e=>(0,W.jsxs)(`div`,{className:`flex items-center gap-1 px-1.5 py-0.5 rounded bg-background/60 border border-border/40 text-[10px]`,children:[(0,W.jsx)(`span`,{className:`font-mono font-medium text-foreground`,children:Pq(e.elapsedMs)}),e.hitCount>1&&(0,W.jsxs)(`span`,{className:`text-muted-foreground`,children:[`×`,e.hitCount]}),(0,W.jsx)(`span`,{className:`text-muted-foreground/60`,children:BO(new Date(e.createdAt))})]},e.createdAt)),e.entries.length>3&&(0,W.jsxs)(`span`,{className:`text-[10px] text-muted-foreground self-center`,children:[`+`,e.entries.length-3,` more`]})]})]})};function Rq(e,t){let n=t.contentFrom!==void 0&&t.contentTo!==void 0?e.state.doc.sliceString(t.contentFrom,t.contentTo):``,r=t.type===`time`||t.type===`log`?t.type:`time`;return{id:t.id,contentId:t.contentId,dialect:r,sport:t.sport,startLine:t.startLine-1,endLine:t.endLine-1,content:n,state:`idle`,version:1,createdAt:Date.now(),widgetIds:{}}}function zq(e){return function({className:t}){return U.isValidElement(e)?U.cloneElement(e,{className:G(e.props.className,t)}):(0,W.jsx)(`span`,{className:G(`flex items-center`,t),children:e})}}var Bq=({cmd:e,block:t})=>{let[n,r]=(0,U.useState)(!1),i=(0,U.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),a=(0,U.useMemo)(()=>zq(e.icon),[e.icon]),o=(0,U.useMemo)(()=>zq(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),s=(0,U.useMemo)(()=>({id:e.id,label:e.label,icon:a,action:{type:`call`,handler:()=>e.onClick(t)}}),[e,t,a]),c=(0,U.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:o,action:{type:`call`,handler:i}}),[e.id,o,i]),l=(0,U.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);return e.onSplitClick?(0,W.jsx)(`div`,{onClick:l,onMouseDown:l,onPointerDown:l,children:(0,W.jsx)(kq,{primary:s,secondary:c,size:`xs`,variant:e.primary?`primary`:`default`,className:`rounded-full sm:rounded-sm`,labelClassName:`sr-only sm:not-sr-only sm:inline`})}):(0,W.jsxs)(K,{variant:e.primary?`default`:`secondary`,className:G(`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`),title:e.label,"aria-label":e.label,onClick:n=>{l(n),e.onClick(t)},onMouseDown:l,onPointerDown:l,children:[(0,W.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:e.icon}),(0,W.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})},Vq=({commands:e,section:t,view:n,compact:r})=>{if(!e.length)return null;let i=Rq(n,t);return r?(0,W.jsx)(`div`,{className:`flex flex-row items-center gap-1 p-0 sm:p-1.5`,children:e.map(e=>(0,W.jsx)(Bq,{cmd:e,block:i},e.id))}):(0,W.jsx)(`div`,{className:`flex items-center gap-1.5 p-2 border-t border-border/50 flex-wrap`,children:e.map(e=>(0,W.jsx)(Bq,{cmd:e,block:i},e.id))})},Hq=({noteId:e,sectionId:t,view:n,isActive:r,cursorLine:i,hoverLine:a,stickyTopOffset:o,isPanelHovered:s,lineDocY:c,rect:l,docVersion:u,commands:d,extendedResults:f})=>{let p=e||n.state.noteId||`current`,m=(0,U.useMemo)(()=>jq(n,t),[n,t,u]),{results:h}=wq(p,t,f,m?.contentId),g=(0,U.useMemo)(()=>m?Mq(n,m):[],[n,m?.id,u]),_=U.useRef(null),v=m&&a!==void 0&&a>=m.startLine&&a<=m.endLine;v&&a!==void 0&&(_.current=a);let y=v?a:s?_.current??null:null,b=r?i:y??i,x=!(m&&(b===m.startLine||b===m.endLine))&&(r||y!==null),S=(0,U.useMemo)(()=>m&&x?Nq(g,m,b):null,[m,b,x,g]),C=(0,U.useMemo)(()=>S?g.filter(e=>e.meta?.line===S.meta.line).flatMap(Iq):[],[S,g]),w=Dq(h,S?.meta?.line);if(!m)return null;let T=S?.meta?.raw??``,E=b-m.startLine,D=typeof window<`u`&&window.matchMedia(`(max-width: 639px)`).matches?44:28,O;if(c!==void 0){let e=c-l.top-100,t=o+D+4,n=l.height-200;O=Math.max(t,Math.min(e,Math.max(t,n)))}else O=o+D+4;return(0,W.jsxs)(`div`,{className:`relative w-full h-full`,style:{pointerEvents:`none`},children:[(0,W.jsx)(`div`,{className:`absolute inset-x-0 flex items-center justify-end gap-1 px-2 pointer-events-auto
155
+ bg-background/70 backdrop-blur-sm border-l border-b border-border/40 rounded-bl-md`,style:{top:o,height:D},children:(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[h.length>0&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2 py-0.5 rounded-sm text-[10px] font-medium bg-primary/10 text-primary border border-primary/20 shadow-sm`,children:[(0,W.jsx)(Se,{className:`h-3 w-3`}),(0,W.jsx)(`span`,{children:h.length})]}),(0,W.jsx)(`div`,{className:`h-3 w-[1px] bg-border/40 mx-0.5`})]}),(0,W.jsx)(Vq,{commands:d,section:m,view:n,compact:!0})]})}),x&&(0,W.jsxs)(`div`,{className:`absolute inset-x-0 flex flex-col bg-popover/95 backdrop-blur-md
156
+ border border-border/80 shadow-xl rounded-lg overflow-hidden pointer-events-auto`,style:{top:O,maxHeight:200},children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border/50 shrink-0`,children:[(0,W.jsx)(`span`,{className:`text-[11px] font-mono px-2 py-0.5 rounded bg-metric-time/10 text-metric-time uppercase tracking-wider font-semibold`,children:m.type}),(0,W.jsxs)(`div`,{className:`flex items-center min-w-0 gap-2`,children:[(0,W.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`L`,E]}),(0,W.jsx)(`span`,{className:`text-muted-foreground/40`,children:`·`}),(0,W.jsx)(`span`,{className:`text-xs font-mono text-foreground/90 truncate font-medium`,title:T,children:T||(0,W.jsx)(`span`,{className:`italic text-muted-foreground`,children:`—`})})]})]}),(0,W.jsx)(`div`,{className:`px-3 py-2.5 min-h-0 overflow-auto`,children:C.length>0?(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:C.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2 py-1 rounded-md text-sm font-semibold ${e.color}`,title:e.label,children:[(0,W.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,W.jsx)(`span`,{className:`font-mono tracking-tight`,children:e.value})]},t))}):(0,W.jsx)(`span`,{className:`text-xs italic text-muted-foreground`,children:`No metrics on this line`})}),w&&(0,W.jsx)(Lq,{summary:w}),(0,W.jsx)(`div`,{className:`border-t border-border/40 shrink-0`,children:(0,W.jsx)(Vq,{commands:d,section:m,view:n})})]})]})},Uq=({sectionId:e,widgetName:t,view:n,registry:r,docVersion:i})=>{let{rawContent:a,config:o}=(0,U.useMemo)(()=>{let t=n.state.field(Aw).sections.find(t=>t.id===e),r=t?.contentFrom!==void 0&&t?.contentTo!==void 0?n.state.doc.sliceString(t.contentFrom,t.contentTo).trim():``,i={};if(r)try{i=JSON.parse(r)}catch{}return{rawContent:r,config:i}},[n,e,i]),s=r.get(t);return s?(0,W.jsx)(`div`,{className:`h-full w-full overflow-hidden rounded-l-md border-l border-border bg-background shadow-sm`,children:(0,W.jsx)(s,{config:o,rawContent:a,sectionId:e})}):(0,W.jsxs)(`div`,{className:`flex h-full w-full items-center justify-center rounded-l-md border-l border-border bg-muted/60 p-4 text-xs text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,t]}),(0,W.jsx)(`span`,{className:`ml-2 opacity-60`,children:`— not registered`})]})};function Wq(e,t,n,r,i){switch(t.type){case`fixed-field`:return Gq(e,t);case`metric-type`:return Kq(e,t);case`derived`:return qq(e,t,n,r,i);case`fallback`:return Jq(e,t,n,r,i);default:return}}function Gq(e,t){return e[t.field]}function Kq(e,t){return e.cells.get(t.metricType)}function qq(e,t,n,r,i){let a=new Map;if(t.dependencies&&r)for(let o of t.dependencies){if(i?.includes(o))throw Error(`Circular dependency detected in column '${o}': ${(i??[]).join(` -> `)} -> ${o}`);let t=r.get(o);if(t){let s=Wq(e,t.source,n,r,[...i??[],o]);a.set(o,s)}}let o={...n,allRows:n?.allRows??[e],rowIndex:n?.rowIndex??0,columnDef:n?.columnDef??{id:`unknown`,label:``,source:t,format:{type:`text`}},dependencies:a,...t.context};return t.compute(e,o)}function Jq(e,t,n,r,i){return Yq(e,t,n,r,i)}function Yq(e,t,n,r,i){if(!(!t.sources||t.sources.length===0))switch(t.semantics){case`first-present`:return Xq(e,t.sources,n,r,i);case`all-present-joined`:return Zq(e,t.sources,t.joinString,n,r,i);case`all-present-combined`:return Qq(e,t.sources,n,r,i);default:return}}function Xq(e,t,n,r,i){for(let a of t){let t=Wq(e,a,n,r,i);if(t!=null)return t}}function Zq(e,t,n,r,i,a){let o=[];for(let n of t){let t=Wq(e,n,r,i,a);if(t==null)return;o.push(t)}let s=n??` `;return o.map(e=>eJ(e)).join(s)}function Qq(e,t,n,r,i){let a=[];for(let o of t){let t=Wq(e,o,n,r,i);if(t==null)return;a.push(t)}return a}function $q(e){if(e==null)return``;let t=Array.isArray(e)?e:e instanceof J?e.toArray():[];if(t.length===0)return``;let n=t[0];if(typeof n==`object`&&n){if(`image`in n&&typeof n.image==`string`)return n.image;if(`value`in n&&n.value!==void 0)return String(n.value)}return String(n)}function eJ(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`&&`metrics`in e){let t=$q(e.metrics);if(t.length>0)return t}return String(e)}function tJ(e,t,n,r){if(!t.sort)return``;let i=Wq(e,t.source,n,r);return(t.sort.type===`custom`?typeof i==`number`||typeof i==`string`?i:String(i??``):t.sort.extractor(i))??``}function nJ(e,t){if(typeof e==`number`&&typeof t==`number`)return Number.isNaN(e)&&Number.isNaN(t)?0:Number.isNaN(e)?1:Number.isNaN(t)?-1:e-t;let n=String(e??``),r=String(t??``),i=parseFloat(n),a=parseFloat(r);return!Number.isNaN(i)&&!Number.isNaN(a)&&n===String(i)&&r===String(a)?i-a:n.localeCompare(r)}function rJ(e,t,n,r){if(!t.graph)return;let i=Wq(e,t.source,n,r);return t.graph.extractor(i)}function iJ(e,t,n,r){if(!t.filter)return``;let i=Wq(e,t.source,n,r);return t.filter.extractor(i)??``}function aJ(e,t,n,r,i){if(!n||n.trim().length===0||!t.filter)return!0;let a=iJ(e,t,r,i),o=t.filter.caseInsensitive===!1?n.trim():n.trim().toLowerCase(),s=t.filter.caseInsensitive===!1?a:a.toLowerCase();return t.filter.matcher?t.filter.matcher(s,o):s.includes(o)}var oJ=({metric:e})=>{let t=e.origin===`hinted`||e.image===`?`,n=(0,U.useMemo)(()=>cU(jo.present(e,`review-grid-cell`)),[e]);return(0,W.jsxs)(`span`,{className:[`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium border transition-all`,t?`bg-warning/10 border-warning/40 text-warning animate-pulse-opacity`:`${n.colorClasses} ${n.originClasses}`].join(` `),title:t?`Missing value - click to fill`:n.tooltip,children:[t&&(0,W.jsx)(`span`,{className:`mr-0.5 text-[10px]`,children:`◉`}),n.label,n.userEntered&&!t&&(0,W.jsx)(`span`,{className:`text-[10px] opacity-70 ml-0.5`,children:`👤`})]})},sJ=({columnDef:e,row:t,allRows:n,rowIndex:r,indent:i=0,onDoubleClick:a,className:o,style:s,definitionMap:c})=>{let l=(0,U.useRef)(null),u=(0,U.useMemo)(()=>{if(!(!n||r===void 0))return{allRows:n,rowIndex:r,columnDef:e,dependencies:new Map}},[n,r,e]),d=(0,U.useMemo)(()=>Wq(t,e.source,u,c),[t,e.source,u,c]),f=e.source.type===`metric-type`,p=(0,U.useCallback)(n=>{if(n.stopPropagation(),f&&a&&l.current){let n=l.current.getBoundingClientRect();a(t.sourceBlockKey,e.source.metricType,n)}},[f,e.source,t.sourceBlockKey,a]),m=(0,U.useMemo)(()=>cJ(d,e.format,i,t),[d,e.format,i,t]);return(0,W.jsx)(`td`,{ref:l,className:G(`py-1 px-2`,f&&`cursor-cell`,o),style:s,onDoubleClick:p,children:m})};function cJ(e,t,n,r){if(e==null)return(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[xJ(n),(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]});switch(t.type){case`text`:return lJ(e,t,n);case`time`:return uJ(e,t);case`number`:return dJ(e,t);case`badge`:return fJ(e,t);case`pill`:return pJ(e,t);case`combined`:return hJ(e,t,n);case`custom`:return _J(e,t,r);default:return yJ(e,n)}}function lJ(e,t,n){let r=t.transform?t.transform(e):SJ(e);return(0,W.jsxs)(`span`,{className:G(`inline-flex items-center gap-1`,t.className),children:[xJ(n),r]})}function uJ(e,t){let n=CJ(e);if(n==null||!Number.isFinite(n))return(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r;switch(t.style){case`long`:r=TH(n);break;case`precise`:r=`${n.toFixed(2)}s`;break;default:r=wH(n)}return t.transform&&(r=t.transform(r)),(0,W.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:r})}function dJ(e,t){let n=CJ(e);if(n==null||!Number.isFinite(n))return(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r=t.decimals??0,i=n.toFixed(r)+(t.unit??``);return t.transform?(0,W.jsx)(`span`,{children:t.transform(i)}):(0,W.jsx)(`span`,{children:i})}function fJ(e,t){let n=t.styleResolver(e),r=t.textResolver(e);return(0,W.jsxs)(`span`,{className:G(`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium`,n.className),title:n.title,children:[n.icon&&(0,W.jsx)(`span`,{className:`mr-0.5`,children:n.icon}),r]})}function pJ(e,t){let n=t.transform?t.transform(e):SJ(e),r=t.backgroundColor??`bg-muted`,i=t.borderRadius??`rounded`;return(0,W.jsx)(`span`,{className:G(`inline-block px-1.5 py-0.5 text-xs font-medium`,r,i),children:n})}var mJ={primary:`text-sm font-semibold text-foreground`,secondary:`text-xs text-muted-foreground`,tertiary:`text-[11px] text-muted-foreground opacity-80`};function hJ(e,t,n,r){let[i,a,o]=Array.isArray(e)?e:[e],s=i===void 0?null:gJ(i,t.primaryFormat??{type:`text`},r,`primary`),c=a===void 0?null:gJ(a,t.secondaryFormat??{type:`text`},r,`secondary`),l=o===void 0?null:gJ(o,t.tertiaryFormat??{type:`text`},r,`tertiary`),u=t.layout===`horizontal`;return(0,W.jsxs)(`div`,{className:G(`inline-flex`,u?`flex-row items-center gap-1`:`flex-col items-start gap-0.5`,t.containerClassName),children:[xJ(n),s,c&&(0,W.jsxs)(W.Fragment,{children:[u&&t.separator&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),c]}),l&&(0,W.jsxs)(W.Fragment,{children:[u&&t.separator&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),l]})]})}function gJ(e,t,n,r){let i=cJ(e,t,0,n);return r?(0,W.jsx)(`span`,{className:G(`inline-flex items-center`,mJ[r]),children:i}):i}function _J(e,t,n){let r=n?{...t.context,row:n}:t.context;return t.render(e,r)}function vJ(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function yJ(e,t){return e?.metrics?bJ(e,t):(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[xJ(t),SJ(e)]})}function bJ(e,t){let n=vJ(e);return n.length===0?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[xJ(t),(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]}):(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1 items-center`,children:[xJ(t),n.map((e,t)=>(0,W.jsx)(oJ,{metric:e},t))]})}function xJ(e){return e<=0?null:(0,W.jsx)(`div`,{className:`flex-shrink-0 mr-1 border-l-2 border-muted h-4`,style:{width:`${e*1.25}rem`,marginLeft:`2px`}})}function SJ(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);let t=vJ(e);if(t.length>0){let e=t[0];if(e?.image)return e.image;if(e?.value!==void 0)return String(e.value)}return String(e)}function CJ(e){if(e==null)return;if(typeof e==`number`)return e;if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}let t=vJ(e);if(t.length>0&&typeof t[0]?.value==`number`)return t[0].value}var wJ=e=>e;function TJ(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function EJ(e){let t=TJ(e);if(t.length===0)return;let n=t[0];return typeof n?.value==`number`?n.value:n?.image?n.image:String(n?.value??``)}function DJ(e){let t=TJ(e);for(let e of t)if(typeof e?.value==`number`)return e.value}function OJ(e){return TJ(e).map(e=>e.image??String(e.value??``)).join(`, `)}function kJ(e){return e==null?``:Array.isArray(e)?e.map(e=>kJ(e)).filter(Boolean).join(` — `):typeof e==`string`?e:typeof e==`number`?String(e):OJ(e)}function AJ(e){switch(e){case q.Duration:case q.Rep:case q.Distance:case q.Rounds:case q.Resistance:case q.Increment:case q.Metric:case q.Volume:case q.Intensity:case q.Load:case q.Work:case q.CurrentRound:case q.Calculated:return!0;default:return!1}}function jJ(e){switch(e){case q.Duration:return`s`;case q.Rep:return`reps`;case q.Distance:return`m`;case q.Rounds:return`rounds`;case q.Resistance:return`kg`;case q.Increment:return`Δ`;case q.Calculated:case q.Custom:return``;default:return``}}function MJ(e,t){let n=go(e),r=WH(e)??void 0,i=t?.graphable??AJ(e);return{id:e,label:n,icon:r,source:{type:`metric-type`,metricType:e},format:{type:`custom`,render:e=>bJ(e,0)},sort:AJ(e)?{type:`numeric`,extractor:e=>DJ(e)}:{type:`text`,extractor:e=>{let t=EJ(e);return t===void 0?void 0:String(t)}},graph:i?{extractor:e=>DJ(e),axisLabel:n,unit:jJ(e)}:void 0,filter:{extractor:e=>OJ(e),caseInsensitive:!0},meta:{defaultVisible:t?.defaultVisible??!0,debugOnly:t?.debugOnly,tags:[e]}}}function NJ(e){switch(e){case`segment`:return`bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-200`;case`milestone`:return`bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-200`;case`system`:return`bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400`;case`event`:return`bg-purple-100 text-purple-800 dark:bg-purple-900/50 dark:text-purple-200`;case`group`:return`bg-indigo-100 text-indigo-800 dark:bg-indigo-900/50 dark:text-indigo-200`;case`load`:return`bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-200`;case`compiler`:return`bg-pink-100 text-pink-800 dark:bg-pink-900/50 dark:text-pink-200`;default:return`bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300`}}function PJ(e,t){if(!e||e.length===0)return``;let n=e=>wH(e);if(t===0)return n(e[0].started);let r=n(e[0].started),i=e[e.length-1];if(i.ended===void 0)return r;let a=n(i.ended);return r===a?r:`${r} — ${a}`}function FJ(e,t=!0){if(e===void 0||e===0)return``;let n=new Date(e),r=n.getHours().toString().padStart(2,`0`),i=n.getMinutes().toString().padStart(2,`0`),a=n.getSeconds().toString().padStart(2,`0`);return t?`${r}:${i}:${a}.${n.getMilliseconds().toString().padStart(3,`0`)}`:`${r}:${i}:${a}`}function IJ({value:e}){let t=e.match(/^(-?)(\d+)(:\d{2})(?::\d{2})?(\.\d+)?$/);if(!t)return(0,W.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:e});let[,n,r,i,a,o]=t,s=i.slice(1);return(0,W.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap inline-flex items-baseline`,children:[n&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:n}),(0,W.jsx)(`span`,{className:`font-semibold text-foreground`,children:r}),(0,W.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`:`,s]}),a&&(0,W.jsx)(`span`,{className:`text-muted-foreground/40`,children:a}),o&&(0,W.jsx)(`span`,{className:`text-muted-foreground/30 text-[10px]`,children:o})]})}function LJ({elapsed:e,duration:t}){let n=wH(e);return(0,W.jsxs)(`span`,{className:`inline-flex items-baseline gap-0.5`,children:[(0,W.jsx)(IJ,{value:n}),t!==void 0&&t>0&&t!==e&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`text-muted-foreground/40 mx-0.5`,children:`/`}),(0,W.jsx)(`span`,{className:`opacity-60`,children:(0,W.jsx)(IJ,{value:wH(t)})})]})]})}var RJ={id:`#`,label:`#`,source:{type:`derived`,compute:e=>({index:e.index,outputType:e.outputType,sourceBlockKey:e.sourceBlockKey})},format:{type:`custom`,render:e=>{let{index:t,outputType:n,sourceBlockKey:r}=e??{};return(0,W.jsx)(`span`,{className:G(`font-mono text-[11px] w-8 text-right inline-block`,NJ(n)),title:`Type: ${n}\nBlock: ${r}`,children:t})}},sort:{type:`numeric`,extractor:e=>wJ(e)?.index||0},meta:{tags:[`layout`],defaultVisible:!0,width:`40px`,resizable:!1}},zJ={id:`timestamp`,label:`Timestamp`,source:{type:`fixed-field`,field:`absoluteStartTime`},format:{type:`custom`,render:(e,t)=>{let n=e,r=wJ(t)?.hideMs!==!1;return(0,W.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-24 whitespace-nowrap`,children:FJ(n,r)})},context:{hideMs:!1}},sort:{type:`numeric`,extractor:e=>wJ(e)?.absoluteStartTime??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},BJ={id:`spans`,label:`Time`,source:{type:`derived`,compute:e=>({spans:e.spans,duration:e.duration})},format:{type:`custom`,render:e=>{let{spans:t,duration:n}=e??{};return(0,W.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-40 whitespace-nowrap`,children:PJ(t,n)})}},sort:{type:`numeric`,extractor:e=>(wJ(e)?.spans)?.[0]?.started??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},VJ={id:`timeSpan`,label:`Time`,source:{type:`derived`,compute:e=>({timestamp:e.absoluteStartTime,elapsed:e.elapsed,duration:e.duration})},format:{type:`custom`,render:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{};return n===void 0?(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`}):(0,W.jsxs)(`div`,{className:`flex flex-col items-start gap-0 leading-tight`,children:[t!==void 0&&t>0&&(0,W.jsx)(`span`,{className:`text-muted-foreground/50 font-mono text-[10px] whitespace-nowrap`,children:FJ(t,!1)}),(0,W.jsx)(LJ,{elapsed:n,duration:r})]})}},sort:{type:`numeric`,extractor:e=>wJ(e)?.elapsed??0},graph:{extractor:e=>wJ(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`},filter:{extractor:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{},i=[];return t!==void 0&&t>0&&i.push(FJ(t,!1)),n!==void 0&&i.push(wH(n)),r!==void 0&&r>0&&r!==n&&i.push(wH(r)),i.join(` `)},caseInsensitive:!0},meta:{tags:[`timing`,`compound`],defaultVisible:!0,width:`100px`,subsumes:[`duration`,`elapsedTotal`]}},HJ={id:`blockKey`,label:`Block`,source:{type:`fixed-field`,field:`sourceBlockKey`},format:{type:`text`,className:`truncate max-w-[160px] text-sm`},sort:{type:`text`,extractor:e=>wJ(e)?.sourceBlockKey??``},filter:{extractor:e=>wJ(e)?.sourceBlockKey??``,caseInsensitive:!0},meta:{tags:[`layout`],defaultVisible:!1}},UJ={id:`outputType`,label:`Type`,source:{type:`fixed-field`,field:`outputType`},format:{type:`custom`,render:e=>{let t=String(e??``);return(0,W.jsx)(`span`,{className:G(`text-xs px-1.5 py-0.5 rounded font-medium`,NJ(t)),children:t})}},sort:{type:`text`,extractor:e=>wJ(e)?.outputType??``},filter:{extractor:e=>wJ(e)?.outputType??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1}},WJ={id:`stackLevel`,label:`Depth`,source:{type:`fixed-field`,field:`stackLevel`},format:{type:`text`,className:`text-muted-foreground font-mono text-xs text-center w-12`},sort:{type:`numeric`,extractor:e=>wJ(e)?.stackLevel??0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},GJ={id:`elapsedTotal`,label:`Elapsed`,source:{type:`derived`,compute:e=>({elapsed:e.elapsed,total:e.total})},format:{type:`custom`,render:e=>{let{elapsed:t,total:n}=e??{};if(t===void 0||n===void 0)return``;let r=t===n?wH(t):`${wH(t)} / ${wH(n)}`;return(0,W.jsx)(`span`,{className:`text-foreground font-mono text-xs text-right w-32 whitespace-nowrap`,children:r})}},sort:{type:`numeric`,extractor:e=>wJ(e)?.elapsed??0},graph:{extractor:e=>wJ(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`,color:`#14b8a6`},meta:{tags:[`timing`],defaultVisible:!1}},KJ={id:`completionReason`,label:`Reason`,source:{type:`fixed-field`,field:`completionReason`},format:{type:`text`,className:`text-muted-foreground text-xs truncate max-w-[120px]`},sort:{type:`text`,extractor:e=>wJ(e)?.completionReason??``},filter:{extractor:e=>wJ(e)?.completionReason??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},qJ=MJ(q.Effort,{defaultVisible:!1}),JJ=MJ(q.Duration,{debugOnly:!0}),YJ=MJ(q.Rep),XJ=MJ(q.Rounds,{defaultVisible:!1}),ZJ=MJ(q.Distance),QJ=MJ(q.Resistance),$J=MJ(q.Action),eY=MJ(q.Increment),tY=MJ(q.Metric),nY=MJ(q.Calculated),rY=MJ(q.Custom,{defaultVisible:!1}),iY=MJ(q.Group,{defaultVisible:!1}),aY=MJ(q.System,{defaultVisible:!1}),oY=MJ(q.Label,{defaultVisible:!1}),sY=MJ(q.Text),cY=MJ(q.CurrentRound,{defaultVisible:!1}),lY=MJ(q.Volume),uY=MJ(q.Intensity),dY=MJ(q.Load),fY=MJ(q.Work),pY=[RJ,VJ,zJ,BJ,HJ,UJ,WJ,GJ,KJ,{id:`exercise`,label:`Exercise`,icon:WH(q.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`fallback`,semantics:`all-present-combined`,sources:[{type:`metric-type`,metricType:q.Effort},{type:`metric-type`,metricType:q.Text}]},{type:`metric-type`,metricType:q.Text},{type:`metric-type`,metricType:q.Label},{type:`metric-type`,metricType:q.Effort}]},format:{type:`combined`,layout:`vertical`,primaryFormat:{type:`text`,className:`font-medium text-foreground`},secondaryFormat:{type:`text`,className:`text-muted-foreground text-xs`},containerClassName:`items-start`},sort:{type:`text`,extractor:e=>kJ(e)},filter:{extractor:e=>kJ(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`grouping`,`fallback`,`descriptor`],subsumes:[`effort`,`text`,`label`]}},{id:`descriptor`,label:`Descriptor`,icon:WH(q.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:q.Effort},{type:`metric-type`,metricType:q.Label},{type:`metric-type`,metricType:q.Rounds},{type:`metric-type`,metricType:q.CurrentRound}]},format:{type:`custom`,render:e=>bJ(e,0)},sort:{type:`text`,extractor:e=>kJ(e)},filter:{extractor:e=>kJ(e),caseInsensitive:!0},meta:{defaultVisible:!0,subsumes:[`effort`,`label`,`rounds`,`current-round`]}},qJ,sY,oY,JJ,{id:`pace`,label:`Pace`,icon:`⏱️`,source:{type:`derived`,dependencies:[`distance`,`duration`],compute:(e,t)=>{let n=DJ(t.dependencies.get(`distance`)),r=DJ(t.dependencies.get(`duration`));if(!(!n||!r))return n/r}},format:{type:`custom`,render:e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`});let t=1e3/e;return(0,W.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:[wH(t),`/km`]})}},sort:{type:`numeric`,extractor:e=>typeof e==`number`?e:void 0},graph:{extractor:e=>typeof e==`number`?e:void 0,axisLabel:`Pace`,unit:`m/s`},filter:{extractor:e=>typeof e!=`number`||!Number.isFinite(e)||e<=0?``:`${wH(1e3/e)}/km`,caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`endurance`,`derived`]}},YJ,XJ,ZJ,QJ,$J,eY,tY,nY,rY,cY,lY,uY,{id:`loadFocus`,label:`Load`,icon:WH(q.Load)??WH(q.Resistance)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:q.Load},{type:`metric-type`,metricType:q.Resistance}]},format:{type:`custom`,render:e=>bJ(e,0)},sort:{type:`numeric`,extractor:e=>DJ(e)},graph:{extractor:e=>DJ(e),axisLabel:`Load`,unit:`kg`},filter:{extractor:e=>OJ(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`strength`,`fallback`]}},dY,fY,iY,aY],mY={outputTypes:[`segment`,`milestone`,`group`,`analytics`]},hY={definitions:pY,presets:{default:{label:`Default`,filters:mY,visibleColumnIds:[`#`,`timeSpan`,`descriptor`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`]},debug:{label:`Debug`,filters:{},visibleColumnIds:[`#`,`timeSpan`,`timestamp`,`spans`,`blockKey`,`outputType`,`stackLevel`,`descriptor`,`duration`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`,`group`,`system`,`elapsedTotal`,`completionReason`]},strength:{label:`Strength`,filters:mY,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`rep`,`loadFocus`,`volume`,`intensity`,`load`,`work`,`elapsedTotal`]},endurance:{label:`Endurance`,filters:mY,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`distance`,`duration`,`pace`,`rounds`,`increment`,`work`,`elapsedTotal`]}},defaultPreset:`default`},gY=new class{config;definitionMap;constructor(e){this.config=e,this.definitionMap=new Map(e.definitions.map(e=>[e.id,e]))}getVisibleColumns(e){return this.getOrderedCandidates(e).filter(t=>this.computeVisibility(t.id,e))}getAvailableColumns(e){let t=new Set(this.getVisibleColumns(e).map(e=>e.id));return this.config.definitions.filter(n=>!t.has(n.id)&&this.isColumnAvailable(n,e))}getGraphableColumns(e){return this.getVisibleColumns(e).filter(e=>e.graph!==void 0)}getGraphTaggedColumns(e){let t=e.graphTaggedColumnIds;return!t||t.size===0?[]:this.getVisibleColumns(e).filter(e=>t.has(e.id))}isColumnVisible(e,t){return this.getDefinition(e)?this.computeVisibility(e,t):!1}getDefinition(e){return this.definitionMap.get(e)}getPreset(e){return this.config.presets[e]??this.config.presets[this.config.defaultPreset]}getAllDefinitions(){return this.config.definitions}get definitions(){return this.definitionMap}resolveColumnValue(e,t,n,r){let i=this.getDefinition(t);if(!i)return;let a={allRows:n,rowIndex:r??n.findIndex(t=>t.id===e.id),columnDef:i,dependencies:new Map};return Wq(e,i.source,a,this.definitionMap)}getOrderedCandidates(e){let t=this.getPreset(e.activePresetId),n=[],r=new Set,i=e=>{if(r.has(e))return;let t=this.getDefinition(e);t&&(n.push(t),r.add(e))};for(let e of t.visibleColumnIds)i(e);for(let e of this.config.definitions)i(e.id);if(e.addedColumnIds)for(let t of e.addedColumnIds)i(t);return n}computeVisibility(e,t,n){if(t.visibilityOverrides&&e in t.visibilityOverrides)return t.visibilityOverrides[e];if(t.addedColumnIds?.has(e))return!0;let r=this.getDefinition(e);if(!r||r.meta?.debugOnly&&!t.isDebugMode||!n&&this.isColumnSubsumed(e,t))return!1;let i=this.getPreset(t.activePresetId).visibleColumnIds.includes(e),a=this.hasDataInRows(r,t.rows);switch(r.source.type){case`fixed-field`:return i;case`derived`:return i;case`metric-type`:return a;case`fallback`:return i&&a;default:return i}}isColumnSubsumed(e,t){for(let n of this.config.definitions)if(n.meta?.subsumes?.length&&this.getPreset(t.activePresetId).visibleColumnIds.includes(n.id)&&n.meta.subsumes.includes(e))return!0;return!1}isColumnAvailable(e,t){return e.meta?.debugOnly&&!t.isDebugMode?!1:this.getPreset(t.activePresetId).visibleColumnIds.includes(e.id)?!this.computeVisibility(e.id,t):e.source.type===`fixed-field`||e.source.type===`derived`||this.hasDataInRows(e,t.rows)}hasDataInRows(e,t){if(t.length===0)return!1;switch(e.source.type){case`fixed-field`:return!0;case`metric-type`:{let{metricType:n}=e.source;return t.some(e=>e.cells.has(n))}case`derived`:return!0;case`fallback`:{let{sources:n}=e.source;return t.some(e=>n.some(t=>this.sourceHasDataInRow(t,e)))}default:return!0}}sourceHasDataInRow(e,t){switch(e.type){case`fixed-field`:return t[e.field]!==void 0&&t[e.field]!==null;case`metric-type`:return t.cells.has(e.metricType);case`derived`:return!0;case`fallback`:return e.sources.some(e=>this.sourceHasDataInRow(e,t));default:return!1}}}(hY);function _Y(e){let{segments:t,userOutputOverrides:n,presetId:r,isDebugMode:i,sortConfigs:a,filterOverrides:o,graphTaggedColumns:s,extraMetricTypes:c,columnVisibilityOverrides:l,addedColumnIds:u}=e,d=(0,U.useMemo)(()=>vY(t,n),[t,n]),f=(0,U.useMemo)(()=>{let e=new Set(u??[]);for(let t of c??[])e.add(t);return e},[u,c]),p=(0,U.useMemo)(()=>({rows:d,activePresetId:r,isDebugMode:i,graphTaggedColumnIds:s,visibilityOverrides:l,addedColumnIds:f}),[d,r,i,s,l,f]),m=(0,U.useMemo)(()=>gY.getVisibleColumns(p),[p]),h=(0,U.useMemo)(()=>gY.getAvailableColumns(p),[p]),g=(0,U.useMemo)(()=>({...gY.getPreset(r).filters??{},...o}),[r,o]);return{rows:(0,U.useMemo)(()=>SY(xY(d,g,m,gY.definitions),a,m,gY.definitions),[d,g,a,m]),visibleColumns:m,availableColumns:h,graphTaggedColumnIds:(0,U.useMemo)(()=>Array.from(s??[]),[s])}}function vY(e,t){return e.map((e,n)=>{let r=new Map;if(e.metrics)for(let t of e.metrics)bY(r,t);let i=yY(e),a=i?t.get(i):void 0;if(a)for(let e of a)bY(r,e);for(let[,e]of r)e.hasUserOverride=e.metrics.some(e=>e.origin===`user`);let o=e.context?.outputType??e.type;return{id:e.id,index:n+1,sourceBlockKey:i??`segment-${e.id}`,sourceStatementId:e.context?.sourceStatementId,outputType:o,stackLevel:e.depth,absoluteStartTime:e.absoluteStartTime,duration:e.duration,elapsed:e.elapsed,total:e.total,spans:e.spans?[...e.spans]:[],completionReason:e.context?.completionReason,cells:r}})}function yY(e){let t=e.context;return t?.sourceBlockKey?t.sourceBlockKey:e.name}function bY(e,t){let n=t.type;if(n===q.Sound)return;let r=e.get(n);r?e.set(n,{metrics:r.metrics.clone().add(t),hasUserOverride:r.hasUserOverride}):e.set(n,{metrics:J.empty(n).add(t),hasUserOverride:!1})}function xY(e,t,n,r){let i=e;if(t.outputTypes&&t.outputTypes.length>0){let e=new Set(t.outputTypes);i=i.filter(t=>e.has(t.outputType))}if(t.origins&&t.origins.length>0){let e=new Set(t.origins);i=i.filter(t=>{for(let[,n]of t.cells)if(n.metrics.some(t=>t.origin&&e.has(t.origin)))return!0;return!1})}if(t.searchText&&t.searchText.trim().length>0){let a=t.searchText.trim().toLowerCase();i=i.filter(t=>{for(let i of n)if(i.filter&&iJ(t,i,{allRows:e,rowIndex:e.indexOf(t),columnDef:i,dependencies:new Map},r).toLowerCase().includes(a))return!0;return!1})}if(t.columnFilters)for(let[a,o]of Object.entries(t.columnFilters)){if(!o||o.trim().length===0)continue;let t=n.find(e=>e.id===a);t&&(i=i.filter(n=>{let i={allRows:e,rowIndex:e.indexOf(n),columnDef:t,dependencies:new Map};return aJ(n,t,o,i,r)}))}return i}function SY(e,t,n,r){if(t.length===0)return e;let i=[...e];return i.sort((i,a)=>{for(let o of t){let t=n.find(e=>e.id===o.columnId);if(!t||!t.sort)continue;let s={allRows:e,rowIndex:e.indexOf(i),columnDef:t,dependencies:new Map},c={allRows:e,rowIndex:e.indexOf(a),columnDef:t,dependencies:new Map},l=nJ(tJ(i,t,s,r),tJ(a,t,c,r));if(l!==0)return o.direction===`asc`?l:-l}return i.index-a.index}),i}function CY(e,t){return{id:e,label:t.label,filters:t.filters??{},visibleColumns:[...t.visibleColumnIds],isDefault:e===hY.defaultPreset}}var wY=Object.fromEntries(Object.entries(hY.presets).map(([e,t])=>[e,CY(e,t)])),TY=wY.default;wY.debug,wY.strength,wY.endurance;function EY(e){return wY[e]??TY}var DY=({activePreset:e,onPresetChange:t,searchText:n,onSearchChange:r,showFilters:i,onToggleFilters:a,totalRows:o,visibleRows:s})=>(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2 border-b border-border bg-muted/10 dark:bg-muted/5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,W.jsx)(`label`,{className:`text-xs text-muted-foreground font-medium`,children:`View:`}),(0,W.jsx)(`select`,{className:`text-xs rounded border border-border bg-background text-foreground px-1.5 py-1 focus:outline-none focus:ring-1 focus:ring-primary/40`,value:e.id,onChange:e=>t(e.target.value),children:Object.values(wY).map(e=>(0,W.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,W.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,W.jsx)(`div`,{className:`flex items-center flex-1 max-w-md`,children:(0,W.jsxs)(`div`,{className:`flex w-full group`,children:[(0,W.jsx)(`input`,{type:`text`,className:`flex-1 px-2.5 py-1 text-xs rounded-l border border-r-0 border-border bg-background text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-primary/40 focus:z-10`,placeholder:`Filter results…`,value:n,onChange:e=>r(e.target.value)}),(0,W.jsxs)(`button`,{className:`px-2.5 py-1 text-xs rounded-r border border-border bg-muted/30 text-muted-foreground hover:bg-muted/50 hover:text-foreground transition-colors flex items-center gap-1.5 border-l-0`,title:`Filter results`,children:[(0,W.jsx)(`span`,{children:`🔍`}),(0,W.jsx)(`span`,{className:`font-medium`,children:`Search`})]})]})}),(0,W.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,W.jsx)(`button`,{className:[`text-xs px-2 py-1 rounded border transition-colors`,i?`bg-primary/10 border-primary/30 text-primary`:`bg-muted/30 border-border text-muted-foreground hover:text-foreground`].join(` `),onClick:a,title:i?`Hide column filters`:`Show column filters`,children:`🔽 Filters`}),(0,W.jsx)(`div`,{className:`ml-auto text-xs text-muted-foreground tabular-nums`,children:s===o?`${o} rows`:`${s} / ${o} rows`})]}),OY={"#":`40px`,exercise:`180px`,text:`160px`,notes:`160px`,completionReason:`160px`,rep:`72px`,rounds:`72px`,"current-round":`72px`,duration:`96px`,distance:`96px`,resistance:`96px`,load:`96px`,volume:`96px`,intensity:`96px`,metric:`96px`,work:`96px`,elapsedTotal:`96px`,action:`96px`,increment:`96px`,timestamp:`96px`,spans:`96px`,blockKey:`180px`,outputType:`96px`,stackLevel:`72px`,elapsed:`96px`},kY=`48px`;function AY(e){return e.meta?.width??OY[e.id]??`96px`}function jY(){return kY}var MY=({columns:e,sortConfigs:t,onSort:n,onToggleGraph:r,showFilters:i,columnFilters:a,onColumnFilterChange:o,availableToAdd:s,onAddColumn:c,graphTaggedColumnIds:l})=>(0,W.jsxs)(`thead`,{className:`bg-muted/50 dark:bg-muted/30 sticky top-0 z-10`,children:[(0,W.jsxs)(`tr`,{className:`border-b border-border`,children:[e.map(e=>(0,W.jsx)(NY,{column:e,sortConfig:t.find(t=>t.columnId===e.id),onSort:n,onToggleGraph:r,isGraphed:l?.has(e.id)??!1},e.id)),c&&(0,W.jsx)(`th`,{className:`py-2 px-1`,style:{minWidth:jY()},children:(0,W.jsx)(IY,{availableToAdd:s??[],onAddColumn:c})})]}),i&&(0,W.jsxs)(`tr`,{className:`border-b border-border/50 bg-muted/20 dark:bg-muted/10`,children:[e.map(e=>(0,W.jsx)(FY,{column:e,value:a[e.id]??``,onChange:o},e.id)),c&&(0,W.jsx)(`th`,{className:`py-1 px-1`,style:{minWidth:jY()}})]})]}),NY=({column:e,sortConfig:t,onSort:n,onToggleGraph:r,isGraphed:i})=>{let a=e.sort!==void 0,o=e.graph!==void 0,s=(0,U.useCallback)(t=>{a&&n(e.id,t.shiftKey)},[e.id,a,n]),c=(0,U.useCallback)(t=>{t.stopPropagation(),r(e.id)},[e.id,r]);return(0,W.jsx)(`th`,{className:[`py-1.5 px-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap select-none`,a?`cursor-pointer hover:text-foreground transition-colors`:``].join(` `),style:{minWidth:AY(e)},onClick:s,children:(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.icon&&(0,W.jsx)(`span`,{className:`text-sm`,children:e.icon}),(0,W.jsx)(`span`,{children:e.label}),t&&(0,W.jsx)(PY,{direction:t.direction}),o&&(0,W.jsx)(`button`,{className:[`ml-auto text-sm opacity-40 hover:opacity-100 transition-opacity`,i?`opacity-100 text-primary`:``].join(` `),onClick:c,title:i?`Remove from graph`:`Add to graph`,children:`📊`})]})})},PY=({direction:e})=>(0,W.jsx)(`span`,{className:`text-primary text-[10px] ml-0.5`,children:e===`asc`?`▲`:`▼`}),FY=({column:e,value:t,onChange:n})=>e.filter?(0,W.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:AY(e)},children:(0,W.jsx)(`input`,{type:`text`,className:`w-full px-1.5 py-0.5 text-xs rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/40`,placeholder:`Filter…`,value:t,onChange:t=>n(e.id,t.target.value)})}):(0,W.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:AY(e)}}),IY=({availableToAdd:e,onAddColumn:t})=>{let[n,r]=(0,U.useState)(!1),i=(0,U.useRef)(null),a=(0,U.useRef)(null);return(0,U.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&a.current&&!a.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]),e.length===0?null:(0,W.jsxs)(`div`,{className:`relative flex items-center justify-center`,children:[(0,W.jsx)(`button`,{ref:a,title:`Add metric column`,onClick:e=>{e.stopPropagation(),r(e=>!e)},className:[`flex items-center justify-center w-5 h-5 rounded text-[11px] font-bold transition-all`,`text-muted-foreground hover:text-foreground hover:bg-primary/10 hover:border-primary/40`,`border border-dashed border-muted-foreground/40`,n?`bg-primary/10 border-primary/40 text-foreground`:``].join(` `),children:`+`}),n&&(0,W.jsxs)(`div`,{ref:i,className:`absolute right-0 top-full mt-1 z-50 min-w-[160px] max-h-64 overflow-y-auto
157
+ bg-popover border border-border rounded-md shadow-xl py-1`,onClick:e=>e.stopPropagation(),children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider border-b border-border/50 mb-1`,children:`Add metric column`}),e.map(e=>{let n=WH(e)??`•`,i=jo.columnLabel(e);return(0,W.jsxs)(`button`,{onClick:()=>{t(e),r(!1)},className:`w-full flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-muted text-foreground transition-colors`,children:[(0,W.jsx)(`span`,{className:`text-sm w-4 text-center`,children:n}),(0,W.jsx)(`span`,{children:i})]},e)})]})]})},LY=({row:e,allRows:t,rowIndex:n,columns:r,isSelected:i,onSelect:a,isHovered:o,onHover:s,onCellDoubleClick:c})=>{let l=t=>{a(e.id,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},u=e.outputType===`group`;return(0,W.jsx)(`tr`,{className:G(`border-b border-border transition-colors cursor-pointer`,u?`bg-muted/50 font-bold`:``,i?`bg-accent dark:bg-accent/20`:o?`bg-muted/50 dark:bg-muted/40`:`hover:bg-muted/30 dark:hover:bg-muted/20`),onClick:l,onMouseEnter:()=>s(e.sourceBlockKey),onMouseLeave:()=>s(null),children:r.map(r=>{let i=r.source.type===`metric-type`&&r.source.metricType===q.Effort;return(0,W.jsx)(sJ,{columnDef:r,row:e,allRows:t,rowIndex:n,indent:i?e.stackLevel:0,onDoubleClick:c,style:{minWidth:AY(r)}},r.id)})})};function RY(e){let{rows:t,columns:n,graphTaggedColumnIds:r,definitionMap:i}=e,a=(0,U.useMemo)(()=>zY(r,n),[r,n]),o=(0,U.useMemo)(()=>BY(t,r,n,i),[t,r,n,i]);return{data:o,graphConfigs:a,hasData:a.length>0&&o.length>0}}function zY(e,t){let n=[];for(let r of e){let e=t.find(e=>e.id===r);e&&n.push({id:r,label:e.label,unit:WY(e),color:VY(e),dataKey:r,icon:e.icon})}return n}function BY(e,t,n,r){return t.length===0?[]:e.map((i,a)=>{let o={index:i.index,label:i.sourceBlockKey};for(let s of t){let t=n.find(e=>e.id===s);if(!t||!t.graph){o[s]=0;continue}o[s]=rJ(i,t,{allRows:e,rowIndex:a,columnDef:t,dependencies:new Map},r)??0}return o})}function VY(e){if(e.graph?.color)return e.graph.color;let t=HY(e);return t?UY[t]??`#888888`:`#888888`}function HY(e){if(e.source.type===`metric-type`)return e.source.metricType}var UY={[q.Time]:`#3b82f6`,[q.Rep]:`#22c55e`,[q.Effort]:`#eab308`,[q.Distance]:`#14b8a6`,[q.Rounds]:`#a855f7`,[q.Resistance]:`#ef4444`,[q.Increment]:`#6366f1`,[q.Action]:`#ec4899`};function WY(e){if(e.graph?.unit)return e.graph.unit;let t=HY(e);if(!t)return``;switch(t){case q.Time:return`ms`;case q.Rep:return`reps`;case q.Distance:return`m`;case q.Rounds:return`rounds`;case q.Resistance:return`kg`;case q.Increment:return`Δ`;default:return``}}var GY=({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r,onSelectRow:i})=>{let[a,o]=(0,U.useState)(!1),{data:s,graphConfigs:c,hasData:l}=RY({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r}),u=(0,U.useCallback)(t=>{if(!t?.activePayload?.[0])return;let n=t.activePayload[0].payload,r=e.find(e=>e.index===n.index);r&&i&&i(r.id)},[e,i]);return n.length===0?null:(0,W.jsxs)(`div`,{className:`border-b border-border bg-background`,children:[(0,W.jsxs)(`button`,{className:`w-full flex items-center justify-between px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/20 transition-colors`,onClick:()=>o(e=>!e),children:[(0,W.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,W.jsx)(`span`,{children:`📊`}),(0,W.jsxs)(`span`,{children:[`Graph — `,c.map(e=>e.label).join(`, `)]})]}),(0,W.jsx)(`span`,{className:`text-[10px]`,children:a?`▼`:`▲`})]}),!a&&(0,W.jsx)(`div`,{className:`px-3 pb-3`,children:l?(0,W.jsx)(`div`,{className:`w-full bg-muted/30 rounded-lg border border-border p-2`,style:{height:220},children:(0,W.jsx)(Ln,{width:`100%`,height:`100%`,children:(0,W.jsxs)(kn,{data:s,onClick:u,children:[(0,W.jsx)(Te,{strokeDasharray:`3 3`,stroke:`hsl(var(--border))`,vertical:!1}),(0,W.jsx)(nt,{dataKey:`index`,stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},label:{value:`Row #`,position:`insideBottom`,offset:-5,fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,W.jsx)(ne,{stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},domain:[`auto`,`auto`]}),(0,W.jsx)(qn,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},labelFormatter:e=>`Row ${e}`,formatter:(e,t)=>{let n=c.find(e=>e.dataKey===t);return[`${typeof e==`number`?e.toLocaleString():e}${n?.unit?` ${n.unit}`:``}`,n?.label??t]}}),(0,W.jsx)(yn,{verticalAlign:`top`,height:24,wrapperStyle:{fontSize:`11px`}}),c.map(e=>(0,W.jsx)(ot,{type:`monotone`,dataKey:e.dataKey,name:e.label,stroke:e.color,strokeWidth:2,dot:{r:3,fill:e.color},activeDot:{r:5,stroke:e.color,strokeWidth:2}},e.id))]})})}):(0,W.jsx)(`div`,{className:`h-32 flex items-center justify-center text-sm text-muted-foreground`,children:`No numeric data available for the tagged columns.`})})]})},KY=({isOpen:e,blockKey:t,metricType:n,existingFragments:r,existingUserValue:i,anchorRect:a,onSave:o,onRemove:s,onClose:c})=>{let[l,u]=(0,U.useState)(``),d=(0,U.useRef)(null),f=(0,U.useRef)(null);(0,U.useEffect)(()=>{e&&(u(i===void 0?``:String(i)),setTimeout(()=>d.current?.focus(),0))},[e,i]),(0,U.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&c()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,c]),(0,U.useEffect)(()=>{if(!e)return;let t=e=>{f.current&&!f.current.contains(e.target)&&c()},n=setTimeout(()=>{document.addEventListener(`mousedown`,t)},100);return()=>{clearTimeout(n),document.removeEventListener(`mousedown`,t)}},[e,c]);let p=(0,U.useCallback)(()=>{if(l.trim()===``)return;let e=Number(l.trim()),r=!isNaN(e)&&l.trim()!==``?e:l.trim();o(t,n,r,String(r)),c()},[l,t,n,o,c]),m=(0,U.useCallback)(()=>{s(t,n),c()},[t,n,s,c]),h=(0,U.useCallback)(e=>{e.key===`Enter`&&(e.preventDefault(),p())},[p]);if(!e)return null;let g=WH(n),_=HH(n),v=i!==void 0,y=r.filter(e=>e.origin!==`user`),b=a?{position:`fixed`,top:a.bottom+4,left:Math.max(8,Math.min(a.left,window.innerWidth-280)),zIndex:50}:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,zIndex:50};return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`fixed inset-0 bg-black/20 dark:bg-black/40 z-40`}),(0,W.jsxs)(`div`,{ref:f,className:`w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-lg`,style:b,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[g&&(0,W.jsx)(`span`,{className:`text-sm`,children:g}),(0,W.jsx)(`span`,{className:`text-sm font-medium capitalize`,children:n}),(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground ml-auto truncate max-w-[100px]`,title:t,children:t})]}),y.length>0&&(0,W.jsxs)(`div`,{className:`px-3 py-1.5 border-b border-border/50 bg-muted/10`,children:[(0,W.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1 uppercase tracking-wider`,children:`Current`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:y.map((e,t)=>(0,W.jsx)(`span`,{className:`inline-flex items-center px-1.5 py-0.5 rounded text-xs border ${_}`,children:e.image??String(e.value??e.type)},t))})]}),(0,W.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,W.jsx)(`label`,{className:`text-[10px] text-muted-foreground uppercase tracking-wider mb-1 block`,children:v?`Update override`:`Enter value`}),(0,W.jsx)(`input`,{ref:d,type:`text`,className:`w-full px-2 py-1.5 text-sm rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/40`,placeholder:`Enter ${n} value…`,value:l,onChange:e=>u(e.target.value),onKeyDown:h})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-t border-border/50`,children:[(0,W.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors`,onClick:c,children:`Cancel`}),v&&(0,W.jsx)(`button`,{className:`px-2 py-1 text-xs rounded border border-destructive/30 text-destructive hover:bg-destructive/10 transition-colors`,onClick:m,title:`Remove user override`,children:`Clear`}),(0,W.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50`,onClick:p,disabled:l.trim()===``,children:`Save`})]})]})]})},qY=({segments:e,selectedSegmentIds:t,onSelectSegment:n,userOutputOverrides:r=new Map,gridViewPreset:i=`default`,onPresetChange:a,hoveredBlockKey:o,onHoverBlockKey:s})=>{let{isDebugMode:c}=Jv(),[l,u]=(0,U.useState)([]),[d,f]=(0,U.useState)(``),[p,m]=(0,U.useState)({}),[h,g]=(0,U.useState)(!1),[_,v]=(0,U.useState)(new Set),[y,b]=(0,U.useState)({}),[x,S]=(0,U.useState)(new Set),{overrides:C,setOverride:w,removeOverride:T}=iG(!0),[E,D]=(0,U.useState)({isOpen:!1,blockKey:``,type:`Time`,anchorRect:null,existingFragments:[]}),O=(0,U.useMemo)(()=>{let e=new Map;for(let[t,n]of r)e.set(t,n instanceof J?n:J.from(n,t));for(let[t,n]of C)e.set(t,n);return e},[r,C]),k=c?`debug`:i,A=(0,U.useMemo)(()=>EY(k),[k]),{rows:j,visibleColumns:M,availableColumns:N,graphTaggedColumnIds:P}=_Y({segments:e,userOutputOverrides:O,presetId:k,isDebugMode:c,sortConfigs:l,filterOverrides:(0,U.useMemo)(()=>({searchText:d||void 0,columnFilters:Object.keys(p).length>0?p:void 0}),[d,p]),graphTaggedColumns:_,extraMetricTypes:x,columnVisibilityOverrides:y,addedColumnIds:x}),F=M,I=e.length,L=(0,U.useMemo)(()=>j.map(e=>e.id),[j]),R=(0,U.useCallback)((e,t)=>{u(n=>{let r=n.find(t=>t.columnId===e);return t?r?r.direction===`asc`?n.map(t=>t.columnId===e?{...t,direction:`desc`}:t):n.filter(t=>t.columnId!==e):[...n,{columnId:e,direction:`asc`}]:r?r.direction===`asc`?[{columnId:e,direction:`desc`}]:[]:[{columnId:e,direction:`asc`}]})},[]),ee=(0,U.useCallback)(e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),te=(0,U.useCallback)((e,t)=>{m(n=>{if(!t){let t={...n};return delete t[e],t}return{...n,[e]:t}})},[]),ne=(0,U.useCallback)(e=>{b({}),m({}),f(``),a?.(e)},[a]),re=(0,U.useCallback)(e=>{S(t=>{let n=new Set(t);return n.add(e),n})},[]),ie=(0,U.useMemo)(()=>N.filter(e=>e.source.type===`metric-type`).map(e=>e.source.metricType),[N]),ae=(0,U.useCallback)((e,t)=>{n(e,t,L)},[n,L]),oe=(0,U.useCallback)(e=>{s?.(e)},[s]),se=(0,U.useCallback)(e=>{n(e,{ctrlKey:!1,shiftKey:!1},L)},[n,L]),ce=(0,U.useCallback)((e,t,n)=>{let r=(j.find(t=>t.sourceBlockKey===e)?.cells.get(t))?.metrics.toArray()??[],i=r.find(e=>e.origin===`user`),a=i?.value==null?void 0:String(i.value);D({isOpen:!0,blockKey:e,type:t,anchorRect:n,existingFragments:r,existingUserValue:a})},[j]),le=(0,U.useCallback)((e,t,n,r)=>{w(e,t,n,r),D(e=>({...e,isOpen:!1}))},[w]),z=(0,U.useCallback)(()=>{T(E.blockKey,E.type),D(e=>({...e,isOpen:!1}))},[E.blockKey,E.type,T]),ue=(0,U.useCallback)(()=>{D(e=>({...e,isOpen:!1}))},[]);return(0,W.jsxs)(`div`,{className:`h-full flex flex-col bg-background`,children:[(0,W.jsx)(DY,{activePreset:A,onPresetChange:ne,searchText:d,onSearchChange:f,showFilters:h,onToggleFilters:()=>g(e=>!e),totalRows:I,visibleRows:j.length}),(0,W.jsx)(GY,{rows:j,columns:M,graphTaggedColumnIds:P,selectedIds:t,onSelectRow:se}),(0,W.jsx)(`div`,{className:`flex-1 overflow-auto`,children:(0,W.jsxs)(`table`,{className:`text-left text-sm border-collapse min-w-[700px]`,children:[(0,W.jsx)(MY,{columns:F,sortConfigs:l,onSort:R,onToggleGraph:ee,showFilters:h,columnFilters:p,onColumnFilterChange:te,availableToAdd:ie,onAddColumn:re,graphTaggedColumnIds:_}),(0,W.jsx)(`tbody`,{className:`divide-y divide-border`,children:j.length===0?(0,W.jsx)(`tr`,{children:(0,W.jsx)(`td`,{colSpan:F.length,className:`py-8 text-center text-muted-foreground text-sm`,children:e.length===0?`Finish or stop the timer — results land here`:`No rows match the current filters.`})}):j.map((e,n)=>(0,W.jsx)(LY,{row:e,allRows:j,rowIndex:n,columns:F,isSelected:t.has(e.id),onSelect:ae,isHovered:o===e.sourceBlockKey,onHover:oe,onCellDoubleClick:ce},e.id))})]})}),(0,W.jsx)(KY,{isOpen:E.isOpen,blockKey:E.blockKey,metricType:E.type,existingFragments:E.existingFragments,existingUserValue:E.existingUserValue,anchorRect:E.anchorRect??void 0,onSave:le,onRemove:z,onClose:ue}),(0,W.jsxs)(`div`,{className:`px-3 py-1.5 border-t border-border bg-muted/10 text-xs text-muted-foreground flex items-center justify-between`,children:[(0,W.jsx)(`span`,{children:t.size>0?`${t.size} selected`:`Click a row to select`}),(0,W.jsxs)(`span`,{className:`tabular-nums`,children:[j.length,` / `,I,` rows`]})]})]})};Yt();var JY=({title:e,onClose:t,children:n,closeButtonClassName:r,floatingClose:i=!1,variant:a=`default`,actions:o,closeLabel:s})=>{(0,U.useEffect)(()=>(document.body.style.overflow=`hidden`,()=>{document.body.style.overflow=``}),[]);let c=U.useRef(null);(0,U.useEffect)(()=>{let e=document.activeElement;return c.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[]);let l=e=>{if(e.key!==`Tab`||!c.current)return;let t=Array.from(c.current.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(t.length===0){e.preventDefault();return}let n=document.activeElement,r=t[0],i=t[t.length-1];e.shiftKey&&(n===r||n===c.current||!c.current.contains(n))?(e.preventDefault(),i.focus()):!e.shiftKey&&n===i&&(e.preventDefault(),r.focus())},u=a===`minimal`,d=(0,W.jsx)(`button`,{onClick:t,className:r??`rounded-pill transition-colors shadow-[rgba(0,0,0,0.06)_0px_1px_2px] ${u?`bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground`:`bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground`} ${s?`flex h-11 min-w-[44px] items-center justify-center px-4 text-sm font-medium hover:text-foreground`:`p-2`}`,title:s??`Close`,"data-testid":FH.FOCUSED_DIALOG_CLOSE,children:s??(0,W.jsx)(we,{className:`h-5 w-5`})});return RS.createPortal((0,W.jsxs)(`div`,{ref:c,onKeyDown:l,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e??`Workout`,className:`fixed inset-0 z-[100] flex flex-col bg-background text-foreground outline-none animate-in fade-in duration-200`,children:[i||u&&!e?(0,W.jsxs)(`div`,{className:`absolute top-4 right-4 z-[110] flex items-center gap-2`,children:[o,d]}):e?(0,W.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border ${u?`bg-muted/10`:`bg-muted/30`} shrink-0`,children:[(0,W.jsx)(`h2`,{className:`text-lg ${u?`font-black tracking-tight uppercase text-[11px] text-muted-foreground`:`font-semibold`}`,children:e}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[o,d]})]}):null,(0,W.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:n})]}),document.body)},YY=(0,U.createContext)({updateFromSegments:()=>{},clear:()=>{}}),XY=({children:e,chromecastSubscription:t=null})=>(0,W.jsx)(YY.Provider,{value:{updateFromSegments:(e,n,r)=>{t&&t.sendAnalyticsSummary([],n,r)},clear:()=>{}},children:e}),ZY=new class{resolve(e){let t=this.resolveMode(e);return t===`active`?{type:`rpc-workbench-update`,mode:`active`}:t===`review`?eG(e.analyticsSegments):nG(e.selectedBlock,e.documentItems)}resolveMode(e){return e.viewMode===`track`?e.runtime&&(e.executionStatus===`running`||e.executionStatus===`paused`)?`active`:e.analyticsSegments.length>0?`review`:e.runtime?`active`:`preview`:e.viewMode===`review`&&e.analyticsSegments.length>0?`review`:`preview`}};function QY(){if(!(`wakeLock`in navigator))return;let e=navigator.wakeLock;if(!(typeof e!=`object`||!e||!(`request`in e)))return e}function $Y(e){let t=(0,U.useRef)(null);(0,U.useEffect)(()=>{let n=QY();if(!n||!e)return;let r=!1,i=async()=>{if(document.visibilityState===`visible`)try{let e=await n.request(`screen`);if(r){e.release();return}t.current=e,e.addEventListener(`release`,()=>{t.current===e&&(t.current=null)})}catch{}},a=()=>{document.visibilityState===`visible`&&!t.current&&i()};return i(),document.addEventListener(`visibilitychange`,a),()=>{r=!0,document.removeEventListener(`visibilitychange`,a);let e=t.current;t.current=null,e&&!e.released&&e.release()}},[e])}function eX(e){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let{code:t,description:n}=e;if(t!==void 0||n!==void 0)return[t===void 0?null:String(t),n?String(n):null].filter(e=>e!==null).join(`: `)||`unknown`;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}var tX=``,nX=null,rX=()=>{let e=XU(),[t,n]=(0,U.useState)(e.state),[r,i]=(0,U.useState)(!1);$Y(r);let[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(null),[l,u]=(0,U.useState)(null),d=(0,U.useRef)(null),p=dL,m=(0,U.useRef)(p.getActiveHandle()),h=(0,U.useRef)(!1),g=(0,U.useCallback)(e=>{let t=m.current;m.current=null,t&&p.dispose(e),vA(null),u(null),c(null),i(!1)},[p]),_=(0,U.useCallback)(async e=>{if(!h.current){h.current=!0;try{let t=yz.getState().subscriptionManager,n=p.connect(e,t);m.current=n,u(n),c(n.subscription),i(!0),vA(n.transport),n.eventProvider.onEvent(e=>{if(e.name===`clock-command`){let t=qW(e.data);if(!t){console.warn(`[CastButtonRpc] Dropped malformed clock-command payload`);return}mW(t.runId,t.command)||console.warn(`[CastButtonRpc] Clock command rejected by authority:`,t.command.kind);return}let t=fW(),n=JW(e.name,t);n&&t&&!mW(t.runId,n)&&console.warn(`[CastButtonRpc] Legacy receiver event rejected by authority:`,e.name)});let r=yz.getState(),a=ZY.resolve({viewMode:r.viewMode,executionStatus:r.execution.status,runtime:r.runtime,analyticsSegments:r.analyticsSegments,selectedBlock:r.selectedBlock,documentItems:r.documentItems});n.pushInitialWorkbench(a)}finally{h.current=!1}}},[p]),v=(0,U.useRef)(!1),y=(0,U.useCallback)(async()=>{if(p.isConnected&&p.getActiveHandle()){let e=p.getActiveHandle();m.current=e,u(e),c(e.subscription),i(!0);return}if(!(m.current||v.current)&&typeof e.resumeSession==`function`){v.current=!0;try{let t=await e.resumeSession();await _(t)}catch(t){console.warn(`[CastButtonRpc] Session resume failed:`,eX(t)),g(!1),e.endSession()}finally{v.current=!1}}},[e,_,g,p]);(0,U.useEffect)(()=>e.onStateChanged(e=>{n(e),e===`session-active`?(i(!0),y()):e===`ready`||e===`unavailable`?i(!1):e===`session-ended`&&g(!1)}),[e,g,y]),(0,U.useEffect)(()=>{if(p.isConnected&&p.getActiveHandle()){let e=p.getActiveHandle();m.current=e,u(e),c(e.subscription),i(!0)}else e.state===`session-active`&&y()},[e,p]),(0,U.useEffect)(()=>{let e=l?.transport;if(!e)return;let t=()=>{let t=fW(),n=JSON.stringify(t);if(n!==tX||e!==nX){tX=n,nX=e;try{e.send({type:`rpc-clock-snapshot`,snapshot:t})}catch{}}};return t(),pW(t)},[l]),(0,U.useEffect)(()=>{let e=()=>{p.sendDisposeSignal()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[p]),(0,U.useEffect)(()=>{let t=d.current;if(!t)return;let n=async()=>{if(b.current===`session-active`){if(x.current)return;o(!0);try{g(!0),e.endSession()}finally{setTimeout(()=>o(!1),2e3)}return}try{let t=await e.startSession();i(!0),await _(t)}catch(e){let t=eX(e);t===`cancel`||t.includes(`cancel`)?console.log(`[CastButtonRpc] Cast request canceled or gesture expired`):console.error(`[CastButtonRpc] Cast failed:`,t),g(!1)}};return t.addEventListener(`click`,n),()=>t.removeEventListener(`click`,n)},[e,_,g]);let b=(0,U.useRef)(t);b.current=t;let x=(0,U.useRef)(a);x.current=a;let S=t===`unavailable`,C=t===`ready`,w=t===`session-active`,T=t===`connecting`,E=r&&w,D=T,O=D||a,k=C||w;return S?(0,W.jsx)(K,{variant:`ghost`,size:`icon`,disabled:!0,className:`opacity-20 cursor-not-allowed`,children:(0,W.jsx)(Zn,{className:`h-5 w-5`})}):(0,W.jsx)(CA,{transport:l?.transport??null,children:(0,W.jsx)(XY,{chromecastSubscription:s,children:(0,W.jsx)(K,{ref:d,variant:`ghost`,size:`icon`,disabled:O,onClick:()=>{},className:G(`transition-all`,E&&`text-signal-positive ring-2 ring-signal-positive/30`,D&&`animate-pulse text-signal-caution`,!k&&`opacity-50`),"aria-label":E?`Stop casting`:`Cast to TV`,title:E?`Stop casting`:D?`Connecting...`:`Cast to TV`,children:E?(0,W.jsx)(f,{className:`h-5 w-5`}):(0,W.jsx)(Zn,{className:`h-5 w-5`})})})})};function iX(){let{isEnabled:e,toggleAudio:t}=DA();return(0,W.jsxs)(K,{variant:`ghost`,size:`icon`,onClick:t,className:`h-9 w-9 text-muted-foreground hover:text-foreground`,title:e?`Mute audio`:`Enable audio`,children:[e?(0,W.jsx)(fe,{className:`h-[1.2rem] w-[1.2rem]`}):(0,W.jsx)(te,{className:`h-[1.2rem] w-[1.2rem]`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Toggle audio`})]})}async function aX(e,t={}){let{resultId:n,occurrence:r,metric:i}=e;if(!n||typeof n!=`string`)throw TypeError(`captureMetricCorrection: resultId is required`);if(!r?.blockKey||typeof r.blockKey!=`string`)throw TypeError(`captureMetricCorrection: occurrence.blockKey is required`);if(!i||typeof i.image!=`string`||i.image.length===0)throw TypeError(`captureMetricCorrection: metric.image is required`);if(typeof i.value!=`number`||!Number.isFinite(i.value))throw RangeError(`captureMetricCorrection: metric.value must be finite, got ${i.value}`);if(i.type===q.Rep&&(!Number.isSafeInteger(i.value)||i.value<0))throw RangeError(`captureMetricCorrection: rep corrections must be nonnegative safe integers, got ${i.value}`);let a=t.storage??Z,o=t.persistence??new EN(a);if(!await a.getSessionById(n)||await a.withTransaction([`events`],async e=>{let t=(await e.getEventsByResult(n)).filter(e=>e.grain===`event`&&e.outputType===`segment`&&e.sourceBlockKey===r.blockKey&&(r.sourceStatementId===void 0||e.sourceStatementId===r.sourceStatementId)&&(r.stackLevel===void 0||e.stackLevel===r.stackLevel));if(t.length===0)return`not-found`;if(t.length>1)throw Error(`captureMetricCorrection: ambiguous occurrence ${r.blockKey} in result ${n} — ${t.length} segments match; pass sourceStatementId/stackLevel`);let a=t[0],o=[...a.metrics.filter(e=>e.origin!==`user`||e.type!==i.type),{type:i.type,value:i.value,image:i.image,origin:`user`,timestamp:new Date}],s=a.timeSpan?.started??a.timestamp,c={...a,metrics:o,...a.metricTemporal?{metricTemporal:o.map(()=>({temporalKind:`instant`,instant:s}))}:{}};return await e.appendEvents([c]),`captured`})===`not-found`)return`not-found`;try{return await o.rederiveResultAnalytics(n),`captured`}catch(e){if(e instanceof sb&&e.code===`BLOCK_REVISION_NOT_FOUND`)return`captured-no-rederive`;throw e}}var oX=new Map,sX=({block:e,prepareRun:t,view:n,onClose:r,onCompleteWorkout:i,resultId:a,autoStart:o,onRuntimeReady:s,onRunStarted:c,externalStop:l,adoptRuntime:u,parkOnUnmount:d,onPark:f})=>{let[p,m]=(0,U.useState)(t?null:e),[h,g]=(0,U.useState)(null),_=(0,U.useRef)(!1),v=(0,U.useCallback)(async()=>{if(!(!t||_.current)){_.current=!0,g(null);try{m(await t())}catch(e){g(e instanceof Error?e.message:String(e))}finally{_.current=!1}}},[t]);(0,U.useEffect)(()=>{v()},[v]);let[y,b]=(0,U.useState)(null),[x,S]=(0,U.useState)(new Set),{isDebugMode:C}=Jv(),w=(0,U.useRef)(Date.now()),T=(0,U.useRef)(typeof document<`u`?document.title:`Wod.Wiki`),E=(0,U.useRef)(null);(0,U.useEffect)(()=>{let t=e.label||e.id,n=y!==null,r=n?`Wod.Wiki - Workout Complete${t?`: `+t:``}`:`Wod.Wiki - Workout Timer${t?`: `+t:``}`,i=n?`/workout/review`:`/workout/timer`;document.title=r,E.current!==i&&(E.current=i,window.gtag?.(`event`,`page_view`,{page_title:r,page_path:i,page_location:typeof window<`u`?window.location.href:i,engagement_time_msec:aK()}));let a=oK.consent;n?a&&window.gtag?.(`event`,`runtime_dialog_review`,{workout_label:t,block_type:e.blockType}):(oK.record(`runtime:dialog_loaded`,{workout_label:t,block_type:e.blockType}),a&&window.gtag?.(`event`,`runtime_dialog_loaded`,{workout_label:t,block_type:e.blockType}))},[e.id,e.label,e.blockType,y]),(0,U.useEffect)(()=>{let t=T.current,n=e.label||e.id;return()=>{let e=Date.now()-w.current;e>=1e3&&window.gtag?.(`event`,`runtime_dialog_closed`,{workout_label:n,duration_seconds:Math.round(e/1e3),engagement_time_msec:e}),typeof document<`u`&&(document.title=t)}},[e.id,e.label]);let D=(0,U.useRef)(!1),O=(0,U.useRef)(!1),k=(0,U.useRef)(!1),[A,j]=(0,U.useState)(!1),[M,N]=(0,U.useState)(!1),P=(0,U.useRef)(!1),F=(0,U.useRef)(!1),I=(0,U.useRef)(null),[L,R]=(0,U.useState)(`idle`),[ee,te]=(0,U.useState)(null),[ne,re]=(0,U.useState)(!1),{collectionItems:ie}=OG(y??[],oX,null),[ae,oe]=(0,U.useState)(new Set),[se,ce]=(0,U.useState)(new Set),[le,z]=(0,U.useState)(!1),ue=(0,U.useMemo)(()=>ie.filter(e=>{let t=mG(e);return!ae.has(t)&&!se.has(t)}),[ie,ae,se]),de=y!==null&&!!a&&ue.length>0&&!le,fe=(0,U.useCallback)(async(e,t)=>{if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid value`);if(e.kind!==`value`)throw Error(`Unsupported entry`);if(!a)throw Error(`The saved run is unavailable.`);if(await aX({resultId:a,occurrence:{blockKey:e.blockKey,...e.sourceStatementId===void 0?{}:{sourceStatementId:e.sourceStatementId},...e.stackLevel===void 0?{}:{stackLevel:e.stackLevel}},metric:{type:e.metricType,value:t,image:String(t)}})===`not-found`)throw Error(`This result entry could not be found — retry or skip.`);let{segments:n}=JI(kg(await Z.getEventsByResult(a)).map(e=>fN(new ga(e))));b(n),oe(t=>new Set(t).add(mG(e)))},[a]),B=(0,U.useCallback)(e=>{ce(t=>new Set(t).add(mG(e)))},[]),pe=(0,U.useMemo)(()=>y===null||de?null:{runId:a?`result:${a}`:`review`,phase:`review`,status:`idle`,canNext:!1,canStop:!1,stopRequested:!1,reps:[],selectedOccurrenceId:null,entry:null,error:null,saving:!1},[y,de,a]),me=async()=>{let e=I.current;if(!e||P.current)return;P.current=!0,F.current=!1,R(`saving`),te(null);let t;try{t=i?.(e.blockId,e.results),await t}catch(e){F.current=!0,te(e instanceof Error?e.message:String(e)),R(`error`),P.current=!1;return}P.current=!1,R(`idle`),re(!0);let{results:n}=e;if(n.logs&&n.logs.length>0)try{let{segments:e}=JI(n.logs,n.startTime);b(e)}catch{b([])}else n.completed?b([]):k.current&&r()},he=(0,U.useCallback)(()=>{D.current=!0,c?.()},[c]),ge=()=>{if(P.current||F.current){k.current=!0;return}if(y!==null||O.current||!D.current){r();return}if(!A&&!l){N(!0);return}k.current=!0,j(!0)},_e=()=>{N(!1),k.current=!0,j(!0)},ve=(0,U.useRef)(ge);ve.current=ge,ZU(pe,(0,U.useCallback)(e=>e.kind===`dismiss`&&(ve.current(),!0),[]),20,{keyboard:!0});let ye=(e,t)=>{O.current||(O.current=!0,I.current={blockId:e,results:t},me())},be=(e,t,n)=>{S(r=>{let i=new Set(r);if(t?.ctrlKey)i.has(e)?i.delete(e):i.add(e);else if(t?.shiftKey&&n){let t=Array.from(r).pop();if(t!==void 0){let r=n.indexOf(t),a=n.indexOf(e);if(r!==-1&&a!==-1){let e=Math.min(r,a),t=Math.max(r,a);for(let r=e;r<=t;r++)i.add(n[r])}else i.add(e)}else i.add(e)}else i.clear(),i.add(e);return i})},xe=L===`idle`?null:(0,W.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3 border-b border-border bg-muted/20 px-6 py-2 text-sm`,children:[L===`saving`&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Saving…`}),L===`error`&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`span`,{role:`alert`,className:`text-destructive`,children:[`Save failed`,ee?` — ${ee}`:``]}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>void me(),className:`rounded-pill border border-border px-3 py-1 text-xs font-medium text-foreground transition-colors hover:bg-accent`,children:`Retry save`})]})]});return p?y===null?(0,W.jsx)(JY,{onClose:ge,title:`Workout`,closeLabel:`Exit`,actions:(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`button`,{type:`button`,onClick:ge,title:`Stop Session`,className:`flex h-11 min-w-[44px] items-center justify-center rounded-pill bg-muted/50 px-4 text-sm font-medium text-muted-foreground shadow-[rgba(0,0,0,0.06)_0px_1px_2px] transition-colors hover:bg-muted hover:text-foreground`,children:`Stop`}),(0,W.jsx)(rX,{}),(0,W.jsx)(iX,{})]}),children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[xe,h?(0,W.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,W.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,h]}),(0,W.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:()=>void v(),children:`Retry starting workout`})]}):p?null:(0,W.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`p-4`,children:`Saving workout before starting…`}),(0,W.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,W.jsx)(QG,{block:p,view:n,onClose:ge,onComplete:ye,isExpanded:!0,autoStart:o,onRuntimeReady:s,onRunStarted:he,externalStop:l||A,adoptRuntime:u,parkOnUnmount:d,onPark:f})}),M&&(0,W.jsx)(JY,{title:`Stop workout?`,onClose:()=>N(!1),closeLabel:`Keep going`,actions:void 0,children:(0,W.jsxs)(`div`,{className:`space-y-4 p-6`,children:[(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The run stops now and your partial results are kept.`}),(0,W.jsxs)(`div`,{className:`flex items-center justify-end gap-3`,children:[(0,W.jsx)(`button`,{type:`button`,"data-testid":`stop-cancel`,onClick:()=>N(!1),className:`rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-accent`,children:`Keep going`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`stop-confirm`,onClick:_e,className:`rounded-lg bg-destructive px-4 py-2 text-sm font-bold text-destructive-foreground transition-colors hover:brightness-110`,children:`Stop — keep partial results`})]})]})})]})}):(0,W.jsx)(JY,{title:`Workout Complete`,onClose:ge,actions:(0,W.jsxs)(W.Fragment,{children:[ne&&(0,W.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Saved ✓`}),(0,W.jsx)(rX,{}),(0,W.jsx)(iX,{})]}),children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[xe,(0,W.jsx)(`div`,{className:`min-h-0 flex-1`,children:de?(0,W.jsx)(NG,{mode:`post-run`,items:ue,onSave:fe,onSkip:B,onClose:()=>z(!0),runId:a?`result:${a}`:void 0,className:`mx-auto max-w-md`}):(0,W.jsx)(qY,{runtime:null,segments:y,selectedSegmentIds:x,onSelectSegment:be,groups:[],gridViewPreset:C?`debug`:`default`})})]})}):(0,W.jsx)(JY,{title:`Starting workout`,onClose:r,children:h?(0,W.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,W.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,h,` Your draft is kept.`]}),(0,W.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 focus-visible:ring-2`,onClick:()=>void v(),children:`Retry start`})]}):(0,W.jsx)(`p`,{role:`status`,className:`p-6`,children:`Saving workout before starting…`})})},cX={play:!0,"add-to-today":!0,schedule:!0},lX=`log`;function uX(e,t){return e.filter(e=>e.id===lX?t===`log`:!cX[e.id]||t===`run`)}function dX(e,t){let n=t.contentFrom!==void 0&&t.contentTo!==void 0?e.state.doc.sliceString(t.contentFrom,t.contentTo):``,r=t.type===`time`||t.type===`log`?t.type:`time`;return{id:t.id,contentId:t.contentId,dialect:r,sport:t.sport,startLine:t.startLine-1,endLine:t.endLine-1,content:n,state:`idle`,version:1,createdAt:Date.now(),widgetIds:{}}}function fX(e){return function({className:t}){return U.isValidElement(e)?U.cloneElement(e,{className:G(e.props.className,t)}):(0,W.jsx)(`span`,{className:G(`flex items-center`,t),children:e})}}var pX=({cmd:e,block:t})=>{let[n,r]=(0,U.useState)(!1),[i,a]=(0,U.useState)(!1),o=(0,U.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),s=(0,U.useCallback)(async()=>{i||(await e.onClick(t),e.successIcon&&(a(!0),setTimeout(()=>a(!1),1500)))},[e,t,i]),c=(0,U.useMemo)(()=>fX(i?e.successIcon??e.icon:e.icon),[e.icon,e.successIcon,i]),l=(0,U.useMemo)(()=>fX(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),u=(0,U.useMemo)(()=>({id:e.id,label:e.label,icon:c,action:{type:`call`,handler:()=>s()}}),[e.id,e.label,c,s]),d=(0,U.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:l,action:{type:`call`,handler:o}}),[e.id,l,o]),f=(0,U.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);if(!e.onSplitClick){let t=i?e.successIcon??e.icon:e.icon;return(0,W.jsxs)(K,{variant:e.primary?`default`:`secondary`,className:G(e.iconOnly?`h-11 w-11 rounded-full p-0 sm:h-auto sm:min-h-[44px] sm:min-w-[44px] sm:w-auto sm:rounded-sm sm:px-1.5 sm:py-0.5 text-[10px] font-medium shadow-sm`:`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`,i&&`text-emerald-600 bg-emerald-500/15 dark:text-emerald-400 dark:bg-emerald-500/20 border-emerald-500/30`),title:e.label,"aria-label":e.label,"data-testid":e.id===`run`?FH.EDITOR_START_WORKOUT:void 0,onClick:e=>{f(e),s()},onMouseDown:f,onPointerDown:f,children:[(0,W.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:t}),!e.iconOnly&&(0,W.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})}return(0,W.jsx)(`div`,{onClick:f,onMouseDown:f,onPointerDown:f,children:(0,W.jsx)(kq,{primary:u,secondary:d,size:`xs`,variant:e.primary?`primary`:`default`,className:`rounded-full sm:rounded-sm`,labelClassName:`sr-only sm:not-sr-only sm:inline`})})},mX=({view:e,commands:t})=>{let[n,r]=(0,U.useState)(()=>e?.plugin(Jw)?.rects??[]),[i,a]=(0,U.useState)(0);(0,U.useEffect)(()=>{if(!e)return;let t=e.plugin(Jw);t&&(r([...t.rects]),t.addListener(e=>r([...e])))},[e]),(0,U.useEffect)(()=>{if(!e)return;let t=e.scrollDOM,n=null,r=()=>{n===null&&(n=requestAnimationFrame(()=>{n=null,a(t.scrollTop)}))};return t.addEventListener(`scroll`,r,{passive:!0}),a(t.scrollTop),()=>{n!==null&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,r)}},[e]);let o=e?e.plugin(Jw):null,s=(n.length>0?n:o?.rects??[]).filter(e=>e.type===`time`||e.type===`log`);if(s.length===0)return null;let{sections:c}=e.state.field(Aw),l=new Map(c.map(e=>[e.id,e]));return(0,W.jsx)(W.Fragment,{children:s.map(n=>{let r=l.get(n.sectionId);if(!r)return null;let a=dX(e,r),o=uX(t,Ca(r.type));return o.length===0?null:(0,W.jsx)(`div`,{className:`absolute right-1 z-10 flex items-end gap-1 pointer-events-auto`,style:{top:n.top-i,height:n.firstLineHeight},children:o.map(e=>(0,W.jsx)(pX,{cmd:e,block:a},e.id))},n.sectionId)})})},hX=({sections:e,isRuntimeActive:t,editorState:n,onSelectBlock:r})=>{let i=SA(),a=(0,U.useRef)(``);return(0,U.useEffect)(()=>{if(!i?.connected||t||!n)return;let r=e.filter(e=>e.type===`time`).map(e=>{let t=e.contentFrom!==void 0&&e.contentTo!==void 0?n.doc.sliceString(e.contentFrom,e.contentTo):``,r=t.split(`
158
+ `).filter(e=>e.trim().length>0),i=r.slice(0,3).join(`
159
+ `),a=t.match(/^(\d{1,2}:\d{2}(?::\d{2})?)/m)?.[1],o=r[0]?.substring(0,60)||`Workout`,s=e.type===`time`||e.type===`log`?e.type:`time`;return{id:e.id,title:o,statementCount:r.length,contentPreview:i,timerHint:a,dialect:s}}),o={type:`rpc-workbench-update`,mode:r.length>0?`preview`:`idle`,previewData:r.length>0?{title:r[0].title,blocks:r}:void 0},s=JSON.stringify(o);if(s!==a.current){a.current=s;try{i.send(o)}catch{}}},[i,e,t,n]),(0,U.useEffect)(()=>{i?.connected||(a.current=``)},[i]),(0,U.useEffect)(()=>{t||(a.current=``)},[t]),(0,U.useEffect)(()=>{if(!(!i?.connected||!r||!n))return i.onMessage(t=>{if(t.type!==`rpc-event`||t.name!==`select-block`)return;let{index:i,blockId:a}=t.data??{},o=e.filter(e=>e.type===`time`),s=a?o.find(e=>e.id===a):o[i??0];if(!s||!n)return;let c=s.contentFrom!==void 0&&s.contentTo!==void 0?n.doc.sliceString(s.contentFrom,s.contentTo):``;r({id:s.id,dialect:s.type===`time`||s.type===`log`?s.type:`time`,sport:s.sport,startLine:s.startLine-1,endLine:s.endLine-1,content:c,state:`idle`,version:1,createdAt:Date.now(),widgetIds:{}})})},[i,e,n,r,t]),null},gX={[q.Duration]:{label:`Timer`,icon:`⏱`,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[q.Rep]:{label:`Reps`,icon:`✕`,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[q.Effort]:{label:`Exercise`,icon:`🏋`,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[q.Rounds]:{label:`Rounds`,icon:`↻`,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[q.Distance]:{label:`Distance`,icon:`📏`,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[q.Resistance]:{label:`Weight`,icon:`⚖`,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[q.Equipment]:{label:`Equipment`,icon:`🧰`,textClass:`text-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border/50`},[q.Action]:{label:`Action`,icon:`⚡`,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[q.Label]:{label:`Label`,icon:`🏷`,textClass:`text-muted-foreground`,bgClass:`bg-muted/30`,borderClass:`border-border/40`}},_X={[q.Rep]:`reps`,[q.Effort]:`movement`,[q.Resistance]:`weight`},vX=({metric:e,tooltip:t,isFocused:n,onClick:r})=>{let i=gX[e.type],a=e.type===q.Hint,o=e.image??(e.value===void 0?``:String(e.value)),s=i?.label??String(e.type);return(0,W.jsxs)(`span`,{title:t,onClick:r,className:G(`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium`,`pointer-events-auto transition-opacity hover:opacity-80`,i?.bgClass??`bg-muted/30`,i?.textClass??`text-muted-foreground`,i?.borderClass??`border-border/40`,r&&`cursor-pointer`,n&&`font-bold shadow-sm`),children:[(0,W.jsx)(`span`,{children:a?e.icon:i?.icon??`•`}),!a&&(0,W.jsx)(`span`,{children:s}),!a&&o&&(0,W.jsx)(`span`,{className:`font-semibold`,children:o})]})};function yX(e){let t=fa(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function bX(e,t){try{let n=e.coordsAtPos(t);if(!n)return null;let r=e.dom?.getBoundingClientRect?.()??{top:0,left:0},i=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:0};return{top:n.bottom-r.top,left:i.left-r.left,width:i.width}}catch{return null}}var xX=({view:e,cursorVersion:t,getCursorFocusState:n})=>{let[r,i]=(0,U.useState)(null),[a,o]=(0,U.useState)(null),s=(0,U.useRef)(null),c=(0,U.useCallback)(()=>{if(!e){o(null),i(null);return}let t=(n??sq)(e.state);o(t),i(t?bX(e,t.lineFrom):null)},[e,n]);if((0,U.useEffect)(()=>{c()},[c,t]),(0,U.useEffect)(()=>{if(!e)return;let t=()=>c();return window.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t,!0),()=>{window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t,!0)}},[e,c]),!r||!a?.section)return null;let l=a.allStatements?.filter(e=>e.meta?.line===a.cursorLine-a.section.startLine)??(a.statement?[a.statement]:[]),u=l.flatMap(e=>e.metrics.toArray()).filter(e=>e.type!==q.Sound&&e.type!==q.System&&!(e.type===q.Hint&&!e.icon)),d=lU(u,`runtime-badge`),f=l.flatMap(e=>e.metrics.toArray()),p=[],m=[],h=[];for(let e of f){let t=yX(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;p.includes(t)||(p.push(t),m.push(e))}h.push(...t.diagnostics)}let g=[];for(let e of f){let t=ba(e.metadata);t&&(g.some(e=>e.slug===t.slug)||g.push(t))}let _=typeof e?.state?.facet==`function`?e.state.facet(cT)?.()??null:null,v=typeof e?.state?.doc?.sliceString==`function`?JK(e.state.doc.sliceString(a.lineFrom,a.lineTo)):null,y=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&v?.equipment.includes(e.token)?`equipment`:`effort`,b=e=>typeof e==`string`&&e.trim()?e:null,x=async t=>{if(!e)return;let n=e.state.doc.sliceString(a.lineFrom,a.lineTo),r=gV.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort…`,sources:[KK(`effort`)]});if(t.dismissed)return;let i=b(t.item.payload);if(!i)return;e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:YK(n,{effort:i})}});return}let i=[...v?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)…`:`Set equipment…`,sources:[KK(`equipment`)]});if(e.dismissed)break;let t=b(e.item.payload);t&&!i.includes(t)&&i.push(t)}((v?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:YK(n,{equipment:i})}})},S=async()=>{if(!e)return;let t=e.state.doc.sliceString(a.lineFrom,a.lineTo),n=gV.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)…`,sources:[KK(`effort`)]});i.dismissed||(r=b(i.item.payload)??void 0);let o=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)…`,sources:[KK(`equipment`)]});if(e.dismissed)break;let t=b(e.item.payload);t&&!o.includes(t)&&o.push(t)}!r&&o.length===0||e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:YK(t,{effort:r,equipment:o})}})},C=async t=>{if(!e||!t.token)return;let n=y(t),r=await gV.getState().open({placeholder:`Replace “${t.token}”…`,sources:[KK(n,t.candidates)]});if(r.dismissed)return;let i=b(r.item.payload);if(!i)return;let o=e.state.doc.sliceString(a.lineFrom,a.lineTo).indexOf(t.token);o<0||e.dispatch({changes:{from:a.lineFrom+o,to:a.lineFrom+o+t.token.length,insert:i}})},w=t=>{let n=_X[t.type];if(!n||!e)return;let r=t.type===q.Effort?`effort`:t.type===q.Equipment?`equipment`:null;if(r&&v?.jsonFrom!==void 0&&v.jsonFrom>=0){x(r);return}wt(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-BVI_QsJW.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([2,1,0])).then(({runStatementBuilderFlow:t})=>{t(a,e,n)})};return(0,W.jsxs)(`div`,{ref:s,className:G(`cm-metric-inline-panel`,`absolute z-50 pointer-events-none`,`flex items-center gap-2 px-3 h-[28px]`,`bg-background/90 backdrop-blur-sm`,`border-l border-r border-border/50`,`transition-opacity duration-100`),style:{top:r.top,left:r.left,width:r.width,maxWidth:r.width},"aria-live":`polite`,"aria-label":`Metric inline panel`,children:[u.length>0?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-medium shrink-0 select-none`,children:`Metrics:`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[u.map((e,t)=>(0,W.jsx)(vX,{metric:e,tooltip:e.type===q.Hint?String(e.value??``):d[t]?.tooltip,isFocused:a.focusedMetric===e,onClick:_X[e.type]?()=>w(e):void 0},`${e.type}-${t}`)),m.map(e=>(0,W.jsxs)(`span`,{title:`${e.kind===`effort`?`Effort`:`Equipment`} · click to change source`,onClick:()=>void x(e.kind),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium cursor-pointer hover:opacity-80 bg-muted/40 text-foreground border-border/50`,children:[(0,W.jsx)(`span`,{children:e.kind===`effort`?`🏋`:`🧰`}),(0,W.jsx)(`span`,{className:`font-semibold`,children:e.label}),_&&(0,W.jsx)(`a`,{href:_.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`${e.kind}:${e.slug}`)),g.map(e=>(0,W.jsxs)(`span`,{title:e.soundProfileId?`Tag ${e.label} · names the ${e.soundProfileId} sound profile`:`Tag ${e.label}`,className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium bg-muted/40 text-foreground border-border/50`,children:[(0,W.jsx)(`span`,{children:`#`}),(0,W.jsx)(`span`,{className:`font-semibold font-mono`,children:e.label}),_&&(0,W.jsx)(`a`,{href:_.openHref(`tag`,e.slug),title:`Open the ${e.label} tag`,"aria-label":`Open the ${e.label} tag`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`tag:${e.slug}`)),v?.malformed&&(0,W.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:`Reference JSON on this line does not parse — fix it in the raw text.`,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,W.jsx)(`span`,{children:`⚠`}),(0,W.jsx)(`span`,{children:`Malformed reference JSON`})]}),h.map((e,t)=>{let n=y(e);return(0,W.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,W.jsx)(`span`,{children:`⚠`}),(0,W.jsx)(`span`,{children:e.token??e.reason}),(0,W.jsx)(`button`,{type:`button`,className:`underline cursor-pointer`,onClick:()=>void C(e),children:`Select existing`}),_&&(0,W.jsx)(`a`,{href:_.createHref(n),className:`underline hover:text-foreground`,children:`Create page`})]},`${e.reason}-${t}`)}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void S(),className:`pointer-events-auto inline-flex items-center px-1.5 py-0.5 rounded border border-dashed border-border/60 text-[10px] text-muted-foreground hover:text-foreground hover:border-primary/50 cursor-pointer`,children:`+ Metric`})]})]}):(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground/50 italic select-none`,children:`No metrics on this line`}),(0,W.jsx)(`span`,{className:`ml-auto text-[9px] text-muted-foreground/40 shrink-0 select-none`,children:`Ctrl+↑↓ · adjust value`})]})},SX=new ui,CX=new ui,wX=new ui;async function TX(e){let t=new TextEncoder().encode(e);if(typeof CompressionStream<`u`)try{let e=new CompressionStream(`gzip`),n=e.writable.getWriter(),r=e.readable.getReader();n.write(t),n.close();let i=[];for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t)}let a=i.reduce((e,t)=>e+t.length,0),o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.length;return btoa(String.fromCharCode(...o)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}catch{}return btoa(String.fromCharCode(...t)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}async function EX(e){let t=await TX(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function DX(e){let t=await TX(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${yb()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var OX=({noteId:e,noteBlocks:t,sourceRevision:n=0,onIdentityChange:r,onSaved:i,beforeRun:a,onSaveRequest:o,onCommitChange:s,value:c,onChange:l,onDocUpdate:u,onCursorPositionChange:d,onBlur:f,theme:p=`vs`,readonly:m=!1,className:h=``,onStartWorkout:g,onCompleteWorkout:_,onBlocksChange:v,onAddToPlan:y,notePersistence:b,onViewCreated:x,mode:S=`edit`,lineWrapping:C=!0,showLineNumbers:T=!0,enablePreview:E=!0,showFrontmatter:D=!0,enableLinting:O=!0,enableOverlay:k=!1,commands:A,hideDefaultCommands:j=!1,enableInlineRuntime:M=!0,extensions:N,widgetComponents:P,activeSectionId:F,scrollToSectionId:I,results:L,placeholder:R})=>{let ee=(0,U.useRef)(null),te=(0,U.useRef)(null),ne=(0,U.useRef)(null),re=(0,U.useRef)(``);(0,U.useEffect)(()=>{let e=async e=>{if(e.view!==te.current||!kX(e.state,e.pos))return null;let t=e.state.doc.lineAt(e.pos),n=t.text.slice(0,e.pos-t.from).match(/^([a-zA-Z][\w.-]*)$/),r=AX(e.state,e.pos);if(!n&&!r)return null;let[i,a]=await Promise.all([Z.getAllTagTypes().catch(()=>[]),Z.getAllTags().catch(()=>[])]);if(n)return{from:t.from,options:i.map(e=>({label:e.name,detail:`Tag Type (${e.label})`,type:`property`,apply:`${e.name}:\n - `})),validFor:(e,t,n,r)=>/^[a-zA-Z][\w.-]*$/.test(e)&&kX(r,n)};if(!r)return null;let{propertyKey:o,from:s}=r,c={"metrics.effort":`effort`,"metrics.equipment":`equipment`,equipment:`equipment`}[o.toLowerCase()];if(c){let e=await WK();return{from:s,options:(c===`effort`?e.efforts:e.equipment).map(e=>({label:`${e.label} (${e.slug})`,detail:c===`effort`?`Effort`:`Equipment`,type:`constant`,apply:e.slug})),validFor:(e,t,n,r)=>{let i=AX(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}}let l=i.find(e=>e.name.toLowerCase()===o.toLowerCase());if(!l)return null;let u=a.filter(e=>e.type?.toLowerCase()===l.name.toLowerCase());return u.length===0?null:{from:s,options:u.map(e=>({label:e.label,detail:l.label,type:`constant`})),validFor:(e,t,n,r)=>{let i=AX(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}};return Ww(e),()=>{Gw(e)}},[]);let ie=p===`dark`||p===`vs-dark`,ae=XK(ne,b),[oe,se]=(0,U.useState)(null),[ce,le]=(0,U.useState)([]),[z,ue]=(0,U.useState)(1),[de,fe]=(0,U.useState)(0),B=F??oe,pe=vq(ce,B),[me,he]=(0,U.useState)(null),[ge,_e]=(0,U.useState)(null),[ve,ye]=(0,U.useState)(null),[be,xe]=(0,U.useState)(!1),Se=(0,U.useRef)(null),Ce=(0,U.useRef)(!1),we=(0,U.useRef)(n??0);(0,U.useEffect)(()=>{we.current=n??0},[n]);let[Te,Ee]=(0,U.useState)(null),De=(0,U.useRef)(null),Oe=(0,U.useCallback)(async(t,n=!1)=>{let r=te.current;if(!(!r||Ce.current)){Ce.current=!0,Ee(null);try{let o=await a?.();typeof o==`number`&&(we.current=o);let s=r.state.field(Aw),c=await yL({noteId:e??w(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:we.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,w(),e?void 0:`playground`,ae);Se.current=c,De.current=null,we.current=c.note.sourceRevision,r.dispatch({effects:Sw.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),xe(n),_e(c.block),ye(c.session.id)}catch(e){Ee(e instanceof Error?e.message:String(e))}finally{Ce.current=!1}}},[e,ae,i,a]),ke=(0,U.useCallback)(()=>{_e(null),ye(null),xe(!1)},[]),Ae=(0,U.useCallback)(e=>{M&&Oe(e,!0)},[M,Oe]),je=(0,U.useRef)(null),Me=(0,U.useCallback)((e,t)=>{let n=je.current,r=n!==null&&n.results===t,i=Se.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(De.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&te.current){let t=te.current,n=TE(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[Er.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(je.current={results:t,resultId:a,runBlock:o});let s;try{s=QW(ae).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,data:t,createdAt:t.endTime}).then(()=>_?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{je.current?.results===t&&(je.current=null),De.current=a},()=>{}),s},[l,_,ae]),Ne=(0,U.useMemo)(()=>{if(j)return[];if(A&&A.length>0)return A;let e=[];return M?e.push({id:`run`,label:`Run`,icon:(0,W.jsx)(pn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:Oe}):g&&e.push({id:`run`,label:`Run`,icon:(0,W.jsx)(pn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:g}),e.push({id:`playground`,label:`Playground`,icon:(0,W.jsx)(Ve,{className:`h-3 w-3`}),splitIcon:(0,W.jsx)(An,{className:`h-3 w-3`}),splitSuccessIcon:(0,W.jsx)(Vn,{className:`h-3 w-3`}),onClick:e=>{EX(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await DX(e.content);await navigator.clipboard.writeText(t)}}),y&&e.push({id:`plan`,label:`Plan`,icon:(0,W.jsx)(En,{className:`h-3 w-3`}),onClick:y}),e},[A,g,y,M,j,Oe]),Pe=(0,U.useMemo)(()=>hi({codeLanguages:QK}),[]),Fe=(0,U.useMemo)(()=>[...T?[Qr(),Hr()]:[],Wr(),pi(),kr(),mi(),...C?[Er.lineWrapping]:[],ri.allowMultipleSelections.of(!0),Dr(),Ti(),Ur(),yi(),fi.highest(yr.of([{key:`Tab`,run:e=>Rr(e.state)!==null&&(Ei(e),!0)},{key:`Enter`,run:e=>{let t=e.state.selection.main,n=AX(e.state,t.head),r=e.state.doc.lineAt(t.head);return!t.empty||n?.value.trim()!==``||r.text.slice(t.head-r.from).trim()?!1:(xr(e),ei(e))}}])),yr.of([...Lr,...$r,...li,...ci,...wi,...di,ti,{key:`Mod-s`,run:()=>(o?.(),!0)},{key:`Ctrl-.`,run:e=>{let t=sq(e.state);if(!t?.focusedMetric)return!1;let n=t.focusedMetric.type;return!new Set([`duration`,`rep`,`rounds`,`distance`,`resistance`]).has(n)&&(wt(()=>Promise.resolve().then(()=>hV).then(()=>{wt(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-BVI_QsJW.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([2,1,0])).then(({runStatementBuilderFlow:n})=>{n(t,e)}).catch(()=>{gV.getState().open({placeholder:`Modify metric…`,sources:[]})})}),void 0),!0)}}]),jE,Aw,yw.of({blocks:t??Na(c,{sourceRevision:Math.max(1,n),registeredWidgets:P?[...P.keys()]:Da}),sourceRevision:Math.max(1,n),rawContent:c}),bw.of(P?[...P.keys()]:Da),jw,uT.of(D),...E||!D?[LT]:[],...E?[rT,oT,FK(),UK(),eE,JT(),dE]:[],...O?[Iw]:[],Kw,Hw,Vw,...k?[ME]:[],Jw,vw,uq,..._E,mw,...P&&P.size>0?[uD(P)]:[],BE({executor:$L,onResultSaved:XW,readOnly:m,noteHref:e=>XV(`blockContentId`in e||`dataType`in e?vR(e):fR(e))}),ZK(e,ae),Er.domEventHandlers({blur:()=>(f?.(),!1)}),Er.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(Aw);r?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision}),l(t.rawContent),u?.(e),MX(e.state,v,re),e.transactions.some(e=>e.isUserEvent(`input`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||s?.()}if(e.selectionSet||e.docChanged){fe(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Rr(e.startState)!==null&&Rr(e.state)===null&&AX(e.state,e.state.selection.main.head)?.value===``&&queueMicrotask(()=>{e.view.state===e.state&&ii(e.view)});let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);d?.(n.number,t-n.from+1);let r=Nw(e.state);se(r?.id??null),ue(n.number);let{sections:i}=e.state.field(Aw);le(i)}}),ri.readOnly.of(m),Er.editable.of(!m),...R?[bi(R)]:[]],[l,d,f,u,v,r,m,o,s,T,C,E,D,O,k,e,ae,P,R]);return(0,U.useEffect)(()=>{let e=ee.current;if(!e)return;let t=ri.create({doc:c,extensions:[...Fe,SX.of(pw(ie)),CX.of(Pe),wX.of([]),...N??[]]}),n=new Er({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{n.hasFocus&&i?.scale===1&&i.height<window.innerHeight&&n.dispatch({effects:Er.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})})})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),te.current=n,he(n),e.__codemirrorView=n,x?.(n);let{sections:s}=n.state.field(Aw);le(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;ue(l);let u=Nw(n.state);se(u?.id??null);let d=n.state.field(Aw);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),MX(n.state,v,re),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,he(null),n.destroy()}},[]),(0,U.useEffect)(()=>{let e=te.current;if(!e)return;let r=e.state.field(Aw);c===r.rawContent?t&&n!==r.sourceRevision&&e.dispatch({effects:Sw.of({blocks:t,sourceRevision:n})}):e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},...t?{effects:Cw.of({rawContent:c,blocks:t,sourceRevision:n})}:{}})},[c,t,n]),(0,U.useEffect)(()=>{te.current&&te.current.dispatch({effects:SX.reconfigure(pw(ie))})},[ie]),(0,U.useEffect)(()=>{if(te.current){let e=[];te.current.dispatch({effects:[Xr.reconfigure.of([...Fe,SX.of(pw(ie)),CX.of(Pe),wX.of(e),...N??[]])]})}},[Fe,N,S,ie,Pe]),(0,U.useEffect)(()=>{m||te.current?.focus()},[m]),(0,U.useEffect)(()=>{if(I&&te.current){let e=te.current,t=e.state.doc.toString().split(`
160
+ `),n=-1,r=I.match(/-line-(\d+)$/);if(n=r?parseInt(r[1],10)-1:t.findIndex(e=>{let t=e.match(/^(#{1,6})\s+(.*)$/);if(t){let e=t[2].trim(),n=e.match(/(\d{1,2}:\d{2})/);if(n){let t=n[1];e=e.replace(t,``).replace(/\s+/g,` `).trim(),e||=t}return e.toLowerCase().replace(/[^\w]+/g,`-`)===I}return!1}),n>=0&&n<t.length){let t=e.state.doc.line(n+1).from;e.dispatch({selection:{anchor:t,head:t},effects:[Er.scrollIntoView(t,{y:`start`,yMargin:20})]})}}},[I]),(0,W.jsxs)(`div`,{ref:ee,className:`cm-note-editor relative w-full min-w-0 ${h}`,children:[k&&(0,W.jsx)(pq,{view:me??te.current,widths:pe.widths,activeSectionId:B,renderSlot:t=>{if(!D&&t.sectionType===`frontmatter`)return null;if(t.sectionType===`time`||t.sectionType===`log`)return(0,W.jsx)(Hq,{noteId:e,sectionId:t.sectionId,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,cursorLine:z,docVersion:t.docVersion,commands:Ne,extendedResults:L,hoverLine:t.hoverLine,stickyTopOffset:t.stickyTopOffset,isPanelHovered:t.isPanelHovered,lineDocY:t.lineDocY,rect:t.rect});if(t.sectionType===`frontmatter`||t.sectionType===`embed`){let{sections:e}=t.view.state.field(Aw),n=e.find(e=>e.id===t.sectionId);return(0,W.jsx)(Sq,{sectionId:t.sectionId,section:n,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,docVersion:t.docVersion})}return t.sectionType===`widget`&&t.widgetName?(0,W.jsx)(Uq,{sectionId:t.sectionId,widgetName:t.widgetName,view:t.view,registry:P??new Map,docVersion:t.docVersion}):(0,W.jsx)(`div`,{className:`h-full w-full bg-popover/80 backdrop-blur-sm border-l border-border rounded-l-md p-2 text-xs text-muted-foreground`,children:(0,W.jsx)(`div`,{className:`font-medium text-foreground`,children:t.sectionType})})},cursorLine:z}),Te&&(0,W.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[`Workout not started. `,Te,` Your draft is kept.`]}),!k&&Ne.length>0&&(0,W.jsx)(mX,{view:me??te.current,commands:Ne}),(0,W.jsx)(xX,{view:me??te.current,cursorVersion:de}),ge&&te.current&&(0,W.jsx)(sX,{block:ge,view:me??te.current,onClose:ke,onCompleteWorkout:Me,resultId:ve??void 0,autoStart:be}),(0,W.jsx)(hX,{sections:ce,isRuntimeActive:ge!==null,editorState:(me??te.current)?.state??null,onSelectBlock:Ae})]})};function kX(e,t){let n=e.doc.lineAt(t);if(n.number===1||e.doc.line(1).text.trim()!==`---`)return!1;for(let t=2;t<=n.number;t++)if(/^(---|\.\.\.)\s*$/.test(e.doc.line(t).text))return!1;return!0}function AX(e,t){if(!kX(e,t))return null;let n=e.doc.lineAt(t),r=n.text.slice(0,t-n.from),i=r.match(/^([a-zA-Z][\w.-]*)\s*:\s*(.*)$/);if(i)return{propertyKey:i[1],from:t-i[2].length,value:i[2]};let a=r.match(/^\s*-\s*(.*)$/);if(!a)return null;for(let r=n.number-1;r>1;r--){let n=e.doc.line(r).text.match(/^([a-zA-Z][\w.-]*)\s*:/);if(n)return{propertyKey:n[1],from:t-a[1].length,value:a[1]}}return null}function jX(e,t){if(e.type!==`time`&&e.type!==`log`)return null;let n=e.contentFrom!==void 0&&e.contentTo!==void 0?t.doc.sliceString(e.contentFrom,e.contentTo):``,r=[];try{n.trim()&&(r=yc({tags:BA()}).read(n,e.sport).statements??[])}catch{}return{id:e.id,contentId:e.contentId,dialect:e.type,sport:e.sport,startLine:e.startLine-1,endLine:e.endLine-1,content:n,statements:r,state:`idle`,version:t.field(Aw).noteBlocks[e.id]?.version??1,createdAt:Date.now(),widgetIds:{}}}function MX(e,t,n){if(!t)return;let r=e.field(Aw).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>jX(t,e)).filter(e=>e!==null),i=JSON.stringify(r.map(e=>({id:e.id,startLine:e.startLine,endLine:e.endLine,content:e.content})));i!==n.current&&(n.current=i,t(r))}function NX({title:e,subtitle:t,doc:n,onDocChange:r,noteId:i,onBlocksChange:a,theme:o,readonly:s=!1,showLineNumbers:c=!1,enableOverlay:l=!1,enableInlineRuntime:u=!1,enablePreview:d=!0,showFrontmatter:f=!1,enableLinting:p=!0,commands:m,hideDefaultCommands:h,onViewCreated:g,onReset:_,run:v,headerActions:y,subheader:b,children:x,className:S,editorClassName:C,bodyRef:w}){let T=(0,U.useRef)([]),E=(0,U.useCallback)(e=>{T.current=e,a?.(e)},[a]),D=(0,U.useCallback)(()=>{v?.onRun(n,T.current[0]??null)},[v,n]),O=(0,W.jsxs)(W.Fragment,{children:[y,v&&(0,W.jsxs)(`button`,{ref:v.ref,type:`button`,title:v.title??`Run the workout`,onClick:D,className:`inline-flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-[11px] font-medium text-primary-foreground transition-colors hover:bg-primary/90`,children:[(0,W.jsx)(pn,{size:11,fill:`currentColor`}),v.label??`Run`]})]});return(0,W.jsx)(PK,{title:e,subtitle:t,onReset:_,headerActions:O,className:S,children:(0,W.jsxs)(`div`,{className:`flex h-full flex-col min-h-0`,children:[b,(0,W.jsxs)(`div`,{ref:w,className:G(`relative flex-1 min-h-0`,C),children:[(0,W.jsx)(OX,{noteId:i,value:n,onChange:r,onBlocksChange:E,theme:o,readonly:s,showLineNumbers:c,enableOverlay:l,enableInlineRuntime:u,enablePreview:d,showFrontmatter:f,enableLinting:p,commands:m,hideDefaultCommands:h,onViewCreated:g,className:`h-full`}),x]})]})})}function PX({editorSource:e,editorOpacity:t,activeOriginalSource:n,handleEditorChange:r,onResetToSource:i,canvasNoteId:a,theme:o,commands:s,onBlocksChange:c,onViewCreated:l,panelTitle:u,panelSubtitle:d,panelThemeClass:f,headerActions:p,onRun:m,readonly:h=!1,showFrontmatter:g}){return(0,W.jsx)(`div`,{className:`h-full`,style:{opacity:t,transition:`opacity 180ms ease`},children:(0,W.jsx)(NX,{title:u,subtitle:d,doc:e,onDocChange:r,noteId:a,onBlocksChange:c,onViewCreated:l,theme:o,readonly:h,showLineNumbers:!1,showFrontmatter:g,enableOverlay:!1,enableInlineRuntime:!1,commands:s,hideDefaultCommands:!1,headerActions:p,className:f,subheader:(0,W.jsxs)(`div`,{style:{opacity:t,transition:`opacity 180ms ease`},className:`flex items-center justify-between gap-3 border-b border-border/40 bg-primary/5 px-4 py-2 text-[11px] font-bold uppercase tracking-[0.18em] text-muted-foreground`,children:[(0,W.jsx)(`span`,{children:`Try editing this example ↓`}),e===n?null:(0,W.jsx)(`button`,{type:`button`,onClick:()=>{i()},className:`rounded-full border border-primary/30 px-3 py-1 text-[10px] font-black text-primary transition-colors hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50`,children:`Reset to example`})]}),run:m?{onRun:m}:void 0})})}function FX(e,t){return e>=t?`split`:`stack`}function IX(e,t){let n=(0,U.useCallback)(()=>{if(typeof window>`u`)return{width:0,height:0,mode:`stack`};let t=window.innerWidth,n=Math.max(0,window.innerHeight-e);return{width:t,height:n,mode:FX(t,n)}},[e]),[r,i]=(0,U.useState)(n);return(0,U.useEffect)(()=>{if(t&&typeof ResizeObserver<`u`){let e=new ResizeObserver(([e])=>{let{width:t,height:n}=e.contentRect;i(e=>e.width===t&&e.height===n?e:{width:t,height:n,mode:FX(t,n)})});return e.observe(t),()=>e.disconnect()}let e=()=>i(e=>{let t=n();return e.width===t.width&&e.height===t.height?e:t});return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[t,n]),r}var LX=e=>Math.max(0,Math.min(1,e)),RX=(e,t,n)=>e+(t-e)*n,zX=e=>1-(1-e)**2;function BX(e,t){return e===``||t===e}var VX={id:``,range:[0,1]};function HX(e,t){if(!t||t.length===0)return{index:-1,stage:VX,t:0,ring:null};let n=LX(e),r=t.map(e=>({...e,start:LX(Math.min(e.range[0],e.range[1])),end:LX(Math.max(e.range[0],e.range[1]))})),i=r.findIndex(e=>n>=e.start&&n<e.end);i===-1&&(i=n>=1?r.length-1:0);let a=r[i]??VX,o=(a.end??1)-(a.start??0),s=o>0?LX((n-(a.start??0))/o):0,c=a.ring?{tag:a.ring===!0?void 0:a.ring.tag,key:a.ring===!0?void 0:a.ring.key,lines:a.ring===!0?void 0:a.ring.lines}:null;return{index:i,stage:a,t:s,ring:c}}function UX(e,t,n){let r=t-n;return{progress:r>0?LX(-e/r):0,reached:e<=0,inView:e<n&&e+t>0}}function WX(e,t){let n=t/2;for(let t of e)if(t.top<=n&&t.bottom>n)return t.id;return null}var GX=(0,U.createContext)(null);function KX(){return(0,U.useContext)(GX)}function qX({children:e}){let t=(0,U.useRef)(new Map),n=(0,U.useRef)(new Map),r=(0,U.useRef)(null),i=(0,U.useRef)(0),[a,o]=(0,U.useState)(null),s=(0,U.useRef)(null),c=(0,U.useCallback)(e=>{r.current?.gateId===e&&(r.current=null,o(null))},[]),l=(0,U.useCallback)((e,t)=>{r.current={gateId:e,segmentId:t},o(e)},[]),u=(0,U.useCallback)(()=>{i.current&&cancelAnimationFrame(i.current),i.current=0;let e=window.innerHeight,a=new Map,c=(e,t)=>{let n=t();n&&a.set(e,n.getBoundingClientRect())};t.current.forEach((e,t)=>c(t,e)),n.current.forEach((e,t)=>c(t,e.getEl));let l=[];a.forEach((e,t)=>l.push({id:t,top:e.top,bottom:e.top+e.height}));let u=WX(l,e);if(u!==s.current){s.current=u;let e=r.current;e&&e.segmentId!==u&&(r.current=null,o(null))}n.current.forEach((t,n)=>{let r=a.get(n);if(!r||r.height-e<=0)return;let i=UX(r.top,r.height,e);t.onMeasure({slice:HX(i.progress,t.getStages()),progress:i.progress,reached:i.reached})})},[]),d=(0,U.useCallback)(()=>{i.current||=requestAnimationFrame(u)},[u]);(0,U.useEffect)(()=>(window.addEventListener(`scroll`,d,{passive:!0,capture:!0}),window.addEventListener(`resize`,d),u(),()=>{window.removeEventListener(`scroll`,d,{capture:!0}),window.removeEventListener(`resize`,d),i.current&&cancelAnimationFrame(i.current)}),[d,u]);let f=(0,U.useCallback)((e,n)=>(t.current.set(e,n),d(),()=>{t.current.delete(e)}),[d]),p=(0,U.useCallback)((e,t)=>(n.current.set(e,t),d(),()=>{n.current.delete(e)}),[d]),m=(0,U.useCallback)(()=>u(),[u]),h=(0,U.useMemo)(()=>({registerAnchor:f,registerDriver:p,resync:m,capturedGateId:a,captureGate:l,releaseGate:c}),[f,p,m,a,l,c]);return(0,W.jsx)(GX.Provider,{value:h,children:e})}function JX(e,t){let n=KX()?.registerAnchor;(0,U.useEffect)(()=>{if(n)return n(e,()=>t.current)},[n,e,t])}function YX({gateId:e,segmentId:t,className:n,children:r}){let i=KX(),a=(0,U.useRef)(null),[o,s]=(0,U.useState)(!1);if((0,U.useEffect)(()=>{let e=a.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.querySelectorAll(`.cm-scroller, [data-scroll-pane], .overflow-auto, .overflow-y-auto`);s(e.scrollHeight>e.clientHeight+1||[...t].some(e=>e.scrollHeight>e.clientHeight+1))},n=new ResizeObserver(t);n.observe(e);let r=0,i=new MutationObserver(()=>{t(),window.clearTimeout(r),r=window.setTimeout(t,400)});i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`resize`,t);let o=window.setTimeout(t,1200);return t(),()=>{window.clearTimeout(r),window.clearTimeout(o),n.disconnect(),i.disconnect(),window.removeEventListener(`resize`,t)}},[]),!i)return(0,W.jsx)(`div`,{className:n,children:r});let c=i.capturedGateId===e?`captured`:`yield`;return(0,W.jsxs)(`div`,{"data-scroll-gate":c,"data-gate-id":e,className:`${n??``} flex flex-col`,onFocus:n=>{let r=n.target;r instanceof HTMLElement&&r.closest(`input:not([readonly]):not([disabled]), textarea:not([readonly]):not([disabled]), select:not([disabled]), [contenteditable="true"]`)&&i.captureGate(e,t??null)},onBlur:t=>{(!(t.relatedTarget instanceof Node)||!t.currentTarget.contains(t.relatedTarget))&&i.releaseGate(e)},children:[(0,W.jsx)(`div`,{ref:a,className:`relative min-h-0 flex-1`,children:r}),(o||c===`captured`)&&(0,W.jsx)(`button`,{type:`button`,className:`min-h-11 self-start rounded px-3 py-2 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-primary`,"aria-label":`Scroll ${e.replace(/-/g,` `)} content`,"aria-pressed":c===`captured`,onClick:()=>c===`captured`?i.releaseGate(e):i.captureGate(e,t??null),onKeyDown:t=>{t.key===`Escape`&&i.releaseGate(e)},children:c===`captured`?`Scroll page`:`Scroll panel`})]})}function XX({trackRef:e,height:t,stages:n,activeIndex:r,pane:i,captions:a,status:o,segmentId:s,testId:c,className:l}){let[u,d]=(0,U.useState)(null),f=IX(104,u).mode===`split`,p={status:o,pips:(0,W.jsx)(`div`,{className:`flex items-center gap-1.5`,"aria-hidden":`true`,children:n.map((e,t)=>{let n=r===t;return(0,W.jsx)(`span`,{className:`h-1 rounded-full transition-all duration-300`,style:{width:n?30:10,background:n?e.accent??`hsl(var(--primary))`:r>t?`hsl(var(--foreground))`:`hsl(var(--foreground) / 0.15)`}},e.id)})})};return(0,W.jsx)(`section`,{ref:e,"data-testid":c,className:l?`relative ${l}`:`relative`,style:{height:t},children:(0,W.jsx)(MK.Provider,{value:p,children:(0,W.jsx)(`div`,{className:`sticky top-[65px] flex h-[calc(100dvh-65px)] flex-col overflow-hidden lg:top-[104px] lg:h-[calc(100dvh-104px)]`,children:(0,W.jsxs)(`div`,{ref:d,className:`mx-auto flex min-h-0 w-full max-w-[1500px] 2xl:max-w-[1720px] flex-1 px-5 pt-2 pb-5 lg:px-10 lg:pt-3 xl:px-16 xl:pb-8 2xl:pb-10 ${f?`flex-row items-stretch gap-[clamp(20px,2.5vw,56px)] xl:gap-12 2xl:gap-16`:`flex-col gap-6 xl:gap-8`}`,children:[(0,W.jsx)(`div`,{className:`relative min-h-0 min-w-0 flex-[3_1_0%]`,children:i}),(0,W.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-[2_1_0%] flex-col`,children:s?(0,W.jsx)(YX,{gateId:`${s}-captions`,segmentId:s,className:`relative min-h-0 flex-1`,children:a}):(0,W.jsx)(`div`,{className:`relative min-h-0 flex-1`,children:a})})]})})})})}function ZX(e){let t=e.parentElement;for(;t;){let e=window.getComputedStyle(t).overflowY;if(e===`auto`||e===`scroll`)return t;t=t.parentElement}return window}function QX(e,t,n=`smooth`){let r=ZX(e),i=e.offsetHeight-window.innerHeight;if(i<=0)return;if(r instanceof HTMLElement){let a=e.offsetTop;r.scrollTo({top:a+t*i,behavior:n});return}let a=e.getBoundingClientRect().top+window.scrollY;window.scrollTo({top:a+t*i,behavior:n})}function $X(e,t,n,r){let[i,a]=(0,U.useState)(()=>HX(0,n)),[o,s]=(0,U.useState)(!1),c=(0,U.useRef)(0),l=(0,U.useRef)(i),u=(0,U.useRef)(new Set),d=(0,U.useRef)(0),f=(0,U.useRef)(t);f.current=t;let p=KX(),m=p?.registerDriver,h=(0,U.useRef)(p);h.current=p;let g=(0,U.useId)(),_=r??g,v=(0,U.useRef)(n);v.current=n;let y=(0,U.useCallback)((e,t)=>{let n=l.current;l.current=e,c.current=t,(n.index!==e.index||n.ring?.key!==e.ring?.key)&&a(e),u.current.forEach(n=>n(e,t))},[]),b=(0,U.useCallback)(()=>{if(d.current=0,f.current)return;let t=e.current;if(!t)return;let n=t.getBoundingClientRect(),r=n.height-window.innerHeight;if(r<=0)return;let i=Math.max(0,Math.min(1,-n.top/r));s(n.top<=0),y(HX(i,v.current),i)},[e,y]),x=(0,U.useCallback)(()=>{if(h.current){h.current.resync();return}b()},[b]),S=(0,U.useCallback)(()=>{d.current||=requestAnimationFrame(x)},[x]);(0,U.useEffect)(()=>{if(m)return m(_,{getEl:()=>e.current,getStages:()=>v.current,onMeasure:({slice:e,progress:t,reached:n})=>{f.current||(s(n),y(e,t))}})},[m,_,e,y]),(0,U.useEffect)(()=>{if(!m)return window.addEventListener(`scroll`,S,{passive:!0,capture:!0}),window.addEventListener(`resize`,S),b(),()=>{window.removeEventListener(`scroll`,S,{capture:!0}),window.removeEventListener(`resize`,S),d.current&&cancelAnimationFrame(d.current)}},[m,S,b]);let C=(0,U.useCallback)(e=>(u.current.add(e),e(l.current,c.current),()=>{u.current.delete(e)}),[]),w=(0,U.useCallback)(()=>{x()},[x]);return{slice:i,progress:c.current,runwayReached:o,subscribe:C,resync:w}}var eZ={reference:!0},tZ={start:[[`fences`,`first-workout`],[`measurements`,`actions-comments`],[`system`,`try-it`]],protocols:[[`countdown-countup`,`required-rest`],[`amrap`,`emom`],[`tabata-intervals`,`caps`,`distance-intervals`,`try-it`]],structure:[[`rounds`,`rep-schemes`,`sets`],[`nesting`,`rep-math`,`named-sections`,`try-it`]],metrics:[[`planned-vs-recorded`,`custom-metrics`],[`capture`,`session-rpe`],[`calculated`,`try-it`]],clock:[[`run-next`,`pause-skip`],[`capture-prompts`,`casting`,`provenance`,`try-it`]],wql:[[`planes`,`aggregate`,`filters`,`sources`],[`windows`,`grouping-rollup`,`joins`],[`content`,`pipes`,`try-it`]],dashboards:[[`note-frontmatter`,`avg-tis`,`weekly-tonnage`,`widgets`],[`composer`,`cookbook`,`seeded-boards`,`try-it`]],sessions:[[`intent`,`full-session`],[`nested`,`partner`,`swimming`],[`barbell-cycling`,`climbing`,`try-it`]]};function nZ(e,t){let n=e.filter(e=>!eZ[e.id]),r=e.filter(e=>eZ[e.id]);if(n.length===0)return{groups:[],tail:r};let i=t?tZ[t]:void 0;if(i){let e=new Map(n.map(e=>[e.id,e])),t=new Set,a=[];for(let n of i){let r=n.map(t=>e.get(t)).filter(e=>!!e&&!t.has(e.id));for(let e of r)t.add(e.id);r.length>0&&a.push(r)}let o=n.filter(e=>!t.has(e.id));if(o.length>0){let e=a[a.length-1];if(e&&e.length+o.length<=4)e.push(...o);else for(let e=0;e<o.length;e+=4)a.push(o.slice(e,e+4))}if(a.length>0)return{groups:a,tail:r}}let a=Math.max(1,Math.ceil(n.length/4)),o=Math.floor(n.length/a),s=n.length%a,c=[],l=0;for(let e=0;e<a;e++){let t=o+ +(e<s);c.push(n.slice(l,l+t)),l+=t}return{groups:c,tail:r}}function rZ(e){let t=Math.max(1,e.length);return e.map((e,n)=>({id:e.id,range:[n/t,(n+1)/t]}))}var iZ=[{src:`/images/hero/editing.png`,alt:`WhiteboardScript editor with live syntax highlighting and inline previews`,eyebrow:`Write`,title:`Type your workout in plain Markdown.`,caption:"Movements, reps, time caps, and rounds — fenced in a familiar ```time block. No drag-and-drop. No proprietary DSL."},{src:`/images/hero/timer.png`,alt:`Live runtime timer HUD counting down an interval with active round and rest indicators`,eyebrow:`Run`,title:`Press Run. The compiler takes over.`,caption:`Your Markdown becomes a live wallclock. The JIT engine dispatches rounds, counts reps, and tracks rest — all offline.`},{src:`/images/hero/journal.png`,alt:`Unified Library listing journal notes, Catalog sessions, and dated posts`,eyebrow:`Library`,title:`Browse Notes, Sessions, and Posts in one Library.`,caption:`Your dated journal entries and preloaded Catalog benchmarks live in one unified surface. Search, filter by source, or clone to today’s entry.`},{src:`/images/hero/results.png`,alt:`WQL Metric Explorer displaying volume trends and embedded dashboard blocks`,eyebrow:`Query`,title:`Ask questions with Wod Query Language (WQL).`,caption:`Aggregate volume, track TIS intensity trends, or embed live query and dashboard blocks directly in your Markdown notes.`}];function aZ({slides:e=iZ,className:t}){let n=(0,U.useRef)(null),[r,i]=(0,U.useState)(0);(0,U.useEffect)(()=>{let t=n.current;if(!t)return;let r=()=>{let n=t.clientWidth,r=Math.round(t.scrollLeft/n);i(Math.min(Math.max(r,0),e.length-1))};return t.addEventListener(`scroll`,r,{passive:!0}),()=>t.removeEventListener(`scroll`,r)},[e.length]);let a=e=>{let t=n.current;t&&t.scrollTo({left:e*t.clientWidth,behavior:`smooth`})};return(0,W.jsxs)(`div`,{className:G(`relative w-full`,t),children:[(0,W.jsx)(`div`,{ref:n,className:`flex w-full snap-x snap-mandatory overflow-x-auto scroll-smooth scrollbar-none`,style:{scrollbarWidth:`none`},children:e.map((t,n)=>(0,W.jsxs)(`article`,{className:`relative flex w-full shrink-0 snap-start flex-col gap-4 sm:flex-row sm:items-center sm:gap-8`,"aria-label":`Slide ${n+1} of ${e.length}: ${t.title}`,children:[(0,W.jsx)(`div`,{className:`relative aspect-[16/10] w-full overflow-hidden rounded-2xl border border-border/60 bg-muted shadow-sm sm:w-1/2`,children:(0,W.jsx)(`img`,{src:t.src,alt:t.alt,loading:n===0?`eager`:`lazy`,className:`h-full w-full object-cover`})}),(0,W.jsxs)(`div`,{className:`flex w-full flex-col gap-2 sm:w-1/2 sm:gap-3`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-[0.24em] text-primary/80`,children:t.eyebrow}),(0,W.jsx)(`h3`,{className:`text-2xl font-black tracking-[-0.04em] text-foreground sm:text-3xl`,children:t.title}),(0,W.jsx)(`p`,{className:`text-sm leading-7 text-muted-foreground sm:text-base`,children:t.caption}),(0,W.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`text-primary`,children:[`Step `,n+1]}),(0,W.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,W.jsx)(`span`,{children:e.length})]})]})]},t.src))}),(0,W.jsx)(`div`,{className:`mt-4 flex items-center justify-center gap-2`,children:e.map((e,t)=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Go to slide ${t+1}: ${e.title}`,"aria-current":t===r?`true`:`false`,className:G(`h-2 rounded-full transition-all`,t===r?`w-8 bg-primary`:`w-2 bg-border hover:bg-muted-foreground/40`)},e.src))})]})}var oZ=`wodwiki:text-filter-navigation`,sZ=({paramName:e=`q`,placeholder:t=`Search…`,autoFocus:n=!1,className:r,navigationScope:i,inputTestId:a})=>{let[o,s]=Gt(e,{defaultValue:``}),c=i??e,l=(0,U.useRef)(null);return(0,U.useEffect)(()=>{let e=e=>{e.key===`/`&&document.activeElement?.tagName!==`INPUT`&&document.activeElement?.tagName!==`TEXTAREA`&&(e.preventDefault(),l.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,W.jsxs)(`div`,{className:G(`flex items-center gap-3 px-6 lg:px-10 pb-3`,r),children:[(0,W.jsx)(en,{className:`size-5 text-muted-foreground shrink-0`}),(0,W.jsx)(`input`,{ref:l,type:`text`,"data-testid":a,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{if(e.altKey||e.ctrlKey||e.metaKey||![`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Enter`].includes(e.key))return;let t=new CustomEvent(oZ,{detail:{key:e.key,scopeId:c},cancelable:!0});window.dispatchEvent(t),t.defaultPrevented&&e.preventDefault()},placeholder:t,autoFocus:n,autoComplete:`off`,spellCheck:!1,className:`flex-1 bg-transparent border-none outline-none text-foreground placeholder:text-muted-foreground text-sm sm:text-base font-medium`}),o&&(0,W.jsx)(`button`,{onClick:()=>s(``),"aria-label":`Clear`,className:`text-muted-foreground hover:text-foreground transition-colors text-lg leading-none`,children:`×`})]})};function cZ(e){let t=[],n=!1;for(let r of e){if(r.trim()===`---`){n=!n;continue}n||t.push(r)}return t}function lZ(e){let t=e;return t=t.replace(/\*\*([^*]+)\*\*/g,`$1`),t=t.replace(/__([^_]+)__/g,`$1`),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`),t=t.replace(/\*\*/g,``),t=t.replace(/__/g,``),t=t.replace(/`/g,``),t.trim()}function uZ(e){return new Date(e).toISOString().slice(0,10)}function dZ(e,t){let n=t.trim().toLowerCase();return!n||e.name.toLowerCase().includes(n)||e.content.toLowerCase().includes(n)||e.date!==void 0&&uZ(e.date).includes(n)}function fZ(e){if(!e)return null;let t=cZ(ox(e).split(`
161
+ `)).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```"))[0];return t?lZ(t):null}var pZ=({category:e,workoutItems:t,onSelect:n,showSearch:r=!0,variant:i=`card`,className:a,navigationScope:o=`q`,getItemActions:s})=>{let[c]=Gt(`q`,{defaultValue:``}),[l,u]=(0,U.useState)(0),[d,f]=(0,U.useState)(0),p=(0,U.useRef)([]),m=(0,U.useMemo)(()=>t.filter(t=>t.category===e&&t.name.toLowerCase()!==`readme`).filter(e=>dZ(e,c)),[t,e,c]),h=(0,U.useMemo)(()=>m.map(e=>({item:e,preview:fZ(e.content),actions:s?.(e)??[{id:`open`,label:`Open`,onSelect:n}]})),[m,s,n]);return(0,U.useEffect)(()=>{if(h.length===0){u(0),f(0);return}let e=Math.min(l,h.length-1),t=h[e]?.actions.length??1;e!==l&&u(e),d>t-1&&f(t-1)},[h,d,l]),(0,U.useEffect)(()=>{p.current=[]},[h]),(0,U.useEffect)(()=>{u(0),f(0)},[c]),(0,U.useEffect)(()=>{(p.current[l]?.[d])?.scrollIntoView({block:`nearest`,inline:`nearest`})},[d,l]),(0,U.useEffect)(()=>{let e=e=>{let t=e;if(t.detail.scopeId===o&&h.length!==0)switch(t.detail.key){case`ArrowDown`:t.preventDefault(),u(e=>Math.min(e+1,h.length-1)),f(0);break;case`ArrowUp`:t.preventDefault(),u(e=>Math.max(e-1,0)),f(0);break;case`ArrowRight`:{let e=h[l]?.actions.length??1;if(e<=1)return;t.preventDefault(),f(t=>Math.min(t+1,e-1));break}case`ArrowLeft`:if((h[l]?.actions.length??1)<=1)return;t.preventDefault(),f(e=>Math.max(e-1,0));break;case`Enter`:{let e=h[l]?.actions[d],n=h[l]?.item;if(!e||!n)return;t.preventDefault(),e.onSelect(n);break}}};return window.addEventListener(oZ,e),()=>{window.removeEventListener(oZ,e)}},[h,o,d,l]),(0,W.jsxs)(`div`,{className:G(`flex flex-col`,i===`card`&&`rounded-3xl border border-border bg-card overflow-hidden shadow-2xl shadow-black/5`,a),children:[r?(0,W.jsx)(`div`,{className:`border-b border-border/60 bg-background/95 backdrop-blur-md`,children:(0,W.jsx)(sZ,{placeholder:`Filter collection workouts…`,className:`pt-3`,navigationScope:o})}):null,h.length===0?(0,W.jsx)(`div`,{className:`px-6 py-10 text-sm font-medium text-muted-foreground`,children:`No workouts found.`}):(0,W.jsx)(`div`,{className:`divide-y divide-border/60`,role:`listbox`,"aria-label":`Collection workouts`,children:h.map((e,t)=>{let n=t===l;return(0,W.jsx)(`div`,{role:`option`,"aria-selected":n,className:G(`flex items-stretch gap-2 px-3 py-2 transition-colors`,n?`bg-muted/50`:`hover:bg-muted/40`),children:e.actions.map((r,i)=>{let a=i===0;return(0,W.jsx)(`button`,{ref:e=>{p.current[t]||(p.current[t]=[]),p.current[t][i]=e},onClick:()=>r.onSelect(e.item),onMouseEnter:()=>{u(t),f(i)},className:G(`transition-colors text-left`,a?`flex-1 flex items-center gap-4 rounded-2xl px-3 py-2 hover:bg-background/80`:`shrink-0 self-center rounded-full border border-border px-3 py-2 text-[11px] font-black uppercase tracking-[0.18em] text-muted-foreground hover:bg-background/80 hover:text-foreground`,n&&i===d&&`bg-background text-foreground ring-2 ring-primary/40`),children:a?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`flex-shrink-0 size-10 rounded-xl bg-muted flex items-center justify-center transition-colors`,children:(0,W.jsx)(Ye,{className:`size-4 text-primary`})}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate uppercase tracking-tight`,children:e.item.displayName??e.item.name}),e.preview?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground font-medium truncate mt-1`,children:e.preview}):null]}),e.item.date===void 0?null:(0,W.jsx)(`span`,{className:`shrink-0 self-center text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:BO(new Date(e.item.date))}),(0,W.jsx)(Qt,{className:`size-4 text-muted-foreground shrink-0 transition-opacity`})]}):r.label},r.id)})},e.item.id)})})]})};function mZ(){return(0,U.useEffect)(()=>{qL().catch(e=>console.warn(`[queryService] page source population failed`,e))},[]),(0,U.useSyncExternalStore)(XL,YL)}function hZ(e,t){let n=e.find(e=>e.key===t&&!e.negate);return n&&n.values.length===1?n.values[0].value:null}function gZ(e){let t=e.trim();if(!t.startsWith(`:`))return null;let n=X(t);if(n.error||!bm(n))return null;let r=`?q=${encodeURIComponent(t)}`;switch(n.target){case`effort`:return`/efforts${r}`;case`session`:case`segment`:case`event`:return`/sessions${r}`;case`note`:case`block`:{let e=hZ(n.filters,`notebook`)??hZ(n.filters,`catalog`);if(e){let t=wa(e);return t===`journal`?`/journal${r}`:t===`playground`?`/playgrounds${r}`:`/c/${encodeURIComponent(t)}${r}`}let t=hZ(n.filters,`source`);return t===`journal`?`/journal${r}`:t===`playground`?`/playgrounds${r}`:t===`feeds`||t===`notebooks`||t===`notebook`||t===`guides`?`/feeds${r}`:hZ(n.filters,`type`)===`dashboard`?`/dashboards${r}`:`/journal${r}`}default:return null}}var _Z=new Set([`pdf`,`doc`,`docx`,`xls`,`xlsx`,`ppt`,`pptx`,`zip`,`tar`,`gz`,`rar`,`mp4`,`mov`,`avi`,`mkv`,`webm`,`mp3`,`wav`,`flac`,`png`,`jpg`,`jpeg`,`gif`,`svg`,`webp`]);function vZ(e){let t=e.split(`.`).pop()?.split(`?`)[0]?.toLowerCase()??``;return _Z.has(t)}function yZ(e){return/^https?:\/\//.test(e)||e.startsWith(`//`)}function bZ({queryText:e,widgetType:t,widgetError:n}){return mZ()?(0,W.jsx)(`div`,{className:`my-5 not-prose`,children:(0,W.jsx)(sw,{query:e,widgetType:t,widgetError:n,executor:$L,readOnly:!0,noteHref:e=>XV(`blockContentId`in e||`dataType`in e?vR(e):fR(e))})}):(0,W.jsx)(`div`,{className:`my-5 not-prose text-xs text-muted-foreground py-2`,children:`Loading…`})}function xZ(e){let{meta:t,body:n}=tx(e);return Object.keys(t).length===0&&n===e?{fields:null,body:e}:{fields:t,body:n.trim()}}var SZ={table({children:e}){return(0,W.jsx)(`div`,{className:`my-6 overflow-x-auto rounded-xl border border-border`,children:(0,W.jsx)(`table`,{className:`w-full text-sm border-collapse`,children:e})})},thead({children:e}){return(0,W.jsx)(`thead`,{className:`bg-muted/50 text-left`,children:e})},tbody({children:e}){return(0,W.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e})},tr({children:e}){return(0,W.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e})},th({children:e}){return(0,W.jsx)(`th`,{className:`px-4 py-2.5 text-[11px] font-black tracking-widest uppercase text-muted-foreground border-b border-border`,children:e})},td({children:e}){return(0,W.jsx)(`td`,{className:`px-4 py-2.5 text-sm text-foreground`,children:e})},img({src:e,alt:t,node:n}){let r=n?.properties??{},i=r.width,a=r.height;return(0,W.jsxs)(`figure`,{className:`my-6`,children:[(0,W.jsx)(`img`,{src:e??``,alt:t??``,loading:`lazy`,width:i,height:a,className:`rounded-xl border border-border max-w-full h-auto`}),t&&(0,W.jsx)(`figcaption`,{className:`mt-2 text-center text-xs text-muted-foreground italic`,children:t})]})},a({href:e,children:t}){let n=e??``;if(n.startsWith(`:`)){let e=n;try{e=decodeURIComponent(n)}catch{}let r=gZ(e);if(r)return(0,W.jsx)(Nt,{to:r,className:`underline underline-offset-2 transition-colors text-primary hover:text-primary/70`,children:t})}let r=yZ(n),i=vZ(n);return(0,W.jsxs)(`a`,{href:n,rel:r?`noopener noreferrer`:void 0,target:r||i?`_blank`:void 0,className:G(`underline underline-offset-2 transition-colors`,i?`text-primary font-medium`:`text-primary hover:text-primary/70`),children:[t,r&&(0,W.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`↗`}),i&&!r&&(0,W.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`⬇`})]})},code({children:e,className:t}){let n=t?.replace(`language-`,``)??``,r=typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``);if(!t&&!r.includes(`
162
+ `))return(0,W.jsx)(`code`,{className:`px-1.5 py-0.5 rounded-md bg-muted font-mono text-[0.85em] text-foreground`,children:e});if(n===`query`||n.startsWith(`query:`)||n.startsWith(`query `)){let t=(typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``)).trim(),r=n.replace(/^query[:\s]?/,``).trim(),i=r?p_(r):void 0;return(0,W.jsx)(bZ,{queryText:t,widgetType:i?.type,widgetError:i?.error})}return(0,W.jsxs)(`div`,{className:`my-5 rounded-xl overflow-hidden border border-border`,children:[n&&(0,W.jsx)(`div`,{className:`flex items-center gap-2 px-4 py-2 bg-muted border-b border-border`,children:(0,W.jsx)(`span`,{className:`text-[10px] font-black tracking-widest uppercase text-muted-foreground`,children:n})}),(0,W.jsx)(`pre`,{className:`overflow-x-auto p-4 bg-muted/30`,children:(0,W.jsx)(`code`,{className:`font-mono text-sm text-foreground`,children:e})})]})},h1({children:e,id:t}){return(0,W.jsx)(`h1`,{id:t,className:`text-2xl lg:text-3xl font-black tracking-tight text-foreground uppercase leading-tight mt-10 mb-4 first:mt-0`,children:e})},h2({children:e,id:t}){return(0,W.jsx)(`h2`,{id:t,className:`text-xl lg:text-2xl font-black tracking-tight text-foreground uppercase leading-tight mt-8 mb-3 first:mt-0`,children:e})},h3({children:e,id:t}){return(0,W.jsx)(`h3`,{id:t,className:`text-base lg:text-lg font-black tracking-wide text-foreground uppercase mt-6 mb-2 first:mt-0`,children:e})},h4({children:e,id:t}){return(0,W.jsx)(`h4`,{id:t,className:`text-sm font-black tracking-widest text-primary uppercase mt-5 mb-2 first:mt-0`,children:e})},p({children:e}){return(0,W.jsx)(`p`,{className:`text-sm lg:text-[15px] font-medium text-muted-foreground leading-relaxed my-4 first:mt-0`,children:e})},ul({children:e}){return(0,W.jsx)(`ul`,{className:`my-4 pl-5 space-y-1.5 list-disc list-outside text-left text-sm text-muted-foreground font-medium leading-relaxed`,children:e})},ol({children:e}){return(0,W.jsx)(`ol`,{className:`my-4 pl-5 space-y-1.5 list-decimal list-outside text-left text-sm text-muted-foreground font-medium leading-relaxed`,children:e})},li({children:e}){return(0,W.jsx)(`li`,{className:`leading-relaxed`,children:e})},blockquote({children:e}){return(0,W.jsx)(`blockquote`,{className:`my-5 pl-4 border-l-2 border-primary/40 text-muted-foreground italic text-sm`,children:e})},hr(){return(0,W.jsx)(`hr`,{className:`my-8 border-border/50`})},strong({children:e}){return(0,W.jsx)(`strong`,{className:`font-black text-foreground`,children:e})},em({children:e}){return(0,W.jsx)(`em`,{className:`italic text-foreground/80`,children:e})}},CZ={...SZ,p({children:e}){return(0,W.jsx)(`p`,{className:`text-3xl sm:text-4xl lg:text-5xl font-black tracking-tight text-foreground leading-[1.08] my-0`,children:e})},strong({children:e}){let t=U.Children.toArray(e).map(e=>typeof e==`string`||typeof e==`number`?String(e):``).join(``).trim();return t.includes(`Write it in Markdown`)&&t.includes(`Run it as a Timer`)&&t.includes(`Own the Analytics`)?(0,W.jsxs)(`span`,{className:`flex flex-col select-none mt-4 w-full gap-5 sm:gap-7`,children:[(0,W.jsxs)(`span`,{className:`block text-3xl sm:text-4xl lg:text-5xl text-primary font-black text-left pl-[5%] sm:pl-[10%] transform hover:translate-x-1 transition-transform duration-200`,children:[`Write it in `,(0,W.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Markdown`}),`.`]}),(0,W.jsxs)(`span`,{className:`block text-3xl sm:text-4xl lg:text-5xl text-primary font-black text-center transform hover:scale-[1.02] transition-transform duration-200`,children:[(0,W.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Run`}),` it as a Timer.`]}),(0,W.jsxs)(`span`,{className:`block text-3xl sm:text-4xl lg:text-5xl text-primary font-black text-right pr-[5%] sm:pr-[10%] transform hover:-translate-x-1 transition-transform duration-200`,children:[`Own the `,(0,W.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Analytics`}),`.`]})]}):(0,W.jsx)(`strong`,{className:`font-black text-foreground`,children:e})}},wZ={...SZ,p({children:e}){return(0,W.jsx)(`p`,{className:`text-base lg:text-lg font-medium text-foreground/75 leading-relaxed my-4 first:mt-0`,children:e})}},TZ=[Un];function EZ(e){return e.startsWith(`:`)?e:Nn(e)}function DZ(e){return e.type===`text`&&typeof e.value==`string`?e.value:(e.children??[]).map(DZ).join(``)}function OZ(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N} _-]/gu,``).replace(/ /g,`-`).replace(/-+/g,`-`)||`heading`}var kZ=()=>e=>{let t=new Map,n=e=>{if(e.tagName&&/^h[1-6]$/.test(e.tagName)){let n=OZ(DZ(e)),r=t.get(n)??0;t.set(n,r+1),(e.properties??={}).id=r===0?n:`${n}-${r}`}for(let t of e.children??[])n(t)};n(e)};function AZ({fields:e}){let t=Object.entries(e);return t.length===0?null:(0,W.jsxs)(`div`,{className:`my-6 rounded-xl border border-border bg-muted/30 overflow-hidden`,children:[(0,W.jsx)(`div`,{className:`px-4 py-2 border-b border-border bg-muted/50`,children:(0,W.jsx)(`span`,{className:`text-[10px] font-black tracking-[0.2em] uppercase text-muted-foreground`,children:`Metadata`})}),(0,W.jsx)(`dl`,{className:`divide-y divide-border/50`,children:t.map(([e,t])=>(0,W.jsxs)(`div`,{className:`flex items-baseline gap-4 px-4 py-2`,children:[(0,W.jsx)(`dt`,{className:`text-[11px] font-semibold text-muted-foreground uppercase tracking-wide min-w-[100px] shrink-0`,children:e}),(0,W.jsx)(`dd`,{className:`text-sm text-foreground break-words`,children:Array.isArray(t)?t.join(`, `):String(t)})]},e))})]})}var jZ={default:SZ,heroLead:CZ,heroBody:wZ};function MZ({prose:e,className:t,variant:n=`default`}){if(!e)return null;let{fields:r,body:i}=xZ(e);return(0,W.jsxs)(`div`,{className:G(`prose-canvas`,t),children:[r&&(0,W.jsx)(AZ,{fields:r}),i&&(0,W.jsx)(gn,{remarkPlugins:TZ,rehypePlugins:[kZ],urlTransform:EZ,components:jZ[n],children:i})]})}var NZ=({activations:e,fullBleed:t,runState:n,deps:r})=>{if(e.length===0)return null;let i=e[0];if(rF(i)&&n){let a=e.slice(1),o=n.isReconnect?(0,W.jsxs)(`button`,{onClick:n.onReconnect,className:G(`flex items-center gap-2 px-5 py-2 text-[11px] font-black uppercase tracking-widest`,`rounded-full border transition-all active:scale-95`,`border-amber-500/40 bg-amber-500/15 text-amber-600 hover:bg-amber-500/20`,`dark:text-amber-400`,t&&`mx-auto`),children:[(0,W.jsx)(P,{className:`size-3.5`}),`View`]}):(0,W.jsxs)(`button`,{type:`button`,onClick:n.onRun,className:G(`flex items-center gap-2 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest rounded-full shadow-lg shadow-primary/25 min-h-[44px] px-6 py-2 text-xs`,t&&`mx-auto`),children:[(()=>{let e=i.icon||pn;return(0,W.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,W.jsx)(`span`,{children:i.label})]});return(0,W.jsxs)(`div`,{className:G(`flex flex-wrap items-center gap-4 mt-8`,t&&`justify-center`),children:[o,a.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>eF(e.action,r),className:`flex items-center gap-2 px-6 py-2 text-xs font-black uppercase tracking-widest rounded-full bg-background border border-border text-foreground hover:bg-muted transition-all active:scale-95`,children:e.label},e.id||t))]})}return(0,W.jsx)(`div`,{className:G(`flex flex-wrap gap-4 mt-8`,t&&`justify-center`),children:e.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>eF(e.action,r),className:G(`flex items-center gap-2 px-8 py-4 text-xs font-black uppercase tracking-widest rounded-full transition-all active:scale-95`,t===0?`bg-primary text-primary-foreground shadow-xl shadow-primary/25 hover:scale-[1.04]`:`bg-background border border-border text-foreground hover:bg-muted`),children:e.label},e.id||t))})},PZ=({examples:e,activeIndex:t,onSelect:n})=>e.length===0?null:(0,W.jsx)(`div`,{className:`mt-6 rounded-2xl border border-border/70 bg-card/80 backdrop-blur-sm`,children:(0,W.jsx)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-3`,children:e.map((e,r)=>{let i=r===t,a=e.anchor===!0&&!i,o=!!e.badge&&a;return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(r),"aria-current":i?`true`:void 0,className:G(`relative rounded-full px-4 py-2 text-[11px] font-black uppercase tracking-[0.18em] transition-all active:scale-95`,i?`bg-primary text-primary-foreground shadow-lg shadow-primary/25`:a?`border border-brand bg-brand/5 text-brand-deep hover:bg-brand/10 dark:text-brand-light`:`border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground`),children:[e.label,o?(0,W.jsx)(`span`,{className:`ml-2 inline-block rounded-pill bg-brand px-1.5 py-0.5 align-middle text-[8px] font-black leading-none tracking-[0.12em] text-background`,children:e.badge}):null]},`${e.label}-${r}`)})})}),FZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M35 35 L65 35 L65 45 L45 45 L45 65 L35 65 Z`,fill:`url(#struct-grad)`}),(0,W.jsx)(`path`,{d:`M55 45 L65 45 L65 65 L45 65 L45 55 L55 55 Z`,fill:`url(#struct-grad)`,opacity:`0.7`})]}),IZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`4`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:`5`,fill:`url(#proto-grad)`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:`15`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`2`,strokeDasharray:`4 2`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:`25`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`1`,opacity:`0.5`}),(0,W.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:`25`,stroke:`url(#proto-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),LZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`complex-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#F50057`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#D500F9`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#complex-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M40 35 H60 V45 A5 5 0 0 1 60 55 V65 H40 V55 A5 5 0 0 0 40 45 Z`,fill:`url(#complex-grad)`})]}),RZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsxs)(`defs`,{children:[(0,W.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]}),(0,W.jsxs)(`filter`,{id:`glow`,x:`-20%`,y:`-20%`,width:`140%`,height:`140%`,children:[(0,W.jsx)(`feGaussianBlur`,{stdDeviation:`3`,result:`blur`}),(0,W.jsx)(`feComposite`,{in:`SourceGraphic`,in2:`blur`,operator:`over`})]})]}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#basics-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M55 20 L30 55 L45 55 L40 85 L70 45 L55 45 Z`,fill:`url(#basics-grad)`,filter:`url(#glow)`})]}),zZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#basics-grad)`,strokeWidth:`4`}),(0,W.jsx)(`text`,{x:`50`,y:`65`,fontFamily:`monospace`,fontSize:`40`,fontWeight:`bold`,fill:`url(#basics-grad)`,textAnchor:`middle`,children:`10`})]}),BZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#basics-grad)`,strokeWidth:`4`}),(0,W.jsx)(`rect`,{x:`30`,y:`30`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,W.jsx)(`rect`,{x:`30`,y:`45`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,W.jsx)(`rect`,{x:`30`,y:`60`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`})]}),VZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M50 30 A20 20 0 1 1 35.8 35.8 L30 30 M35.8 35.8 L42 38`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`6`,strokeLinecap:`round`})]}),HZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M30 40 L45 40 M30 50 L55 50 M30 60 L70 60`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`6`,strokeLinecap:`round`}),(0,W.jsx)(`text`,{x:`50`,y:`30`,fontFamily:`monospace`,fontSize:`12`,fill:`url(#struct-grad)`,textAnchor:`middle`,children:`21-15-9`})]}),UZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M35 35 H65 V55 L50 70 L35 55 Z`,fill:`url(#proto-grad)`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`45`,r:`4`,fill:`#0b1326`})]}),WZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#metric-grad)`,strokeWidth:`4`}),(0,W.jsx)(`rect`,{x:`30`,y:`60`,width:`10`,height:`15`,fill:`url(#metric-grad)`}),(0,W.jsx)(`rect`,{x:`45`,y:`40`,width:`10`,height:`35`,fill:`url(#metric-grad)`}),(0,W.jsx)(`rect`,{x:`60`,y:`25`,width:`10`,height:`50`,fill:`url(#metric-grad)`})]}),GZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#metric-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M35 40 L65 60 M65 40 L35 60 M35 30 H65 M35 70 H65`,fill:`none`,stroke:`url(#metric-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),KZ=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`dialect-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#76FF03`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00E676`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#dialect-grad)`,strokeWidth:`4`,strokeLinecap:`round`}),(0,W.jsx)(`path`,{d:`M35 30 H65 M35 45 H65 M35 60 H55 M35 75 H65`,fill:`none`,stroke:`url(#dialect-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]});function qZ(e){switch(e){case`trophy`:return RZ;case`dumbbell`:return Ye;case`timer`:return IZ;case`play`:return pn;case`blocks`:return FZ;case`puzzle`:return LZ;case`activity`:return WZ;case`file-text`:return KZ;default:return qe}}function JZ(e){switch(e){case`basics-movement`:return RZ;case`basics-reps`:return zZ;case`basics-load`:return BZ;case`structure-rounds`:case`complex-rounds`:case`protocols-rounds`:return VZ;case`structure-repscheme`:return HZ;case`protocols-timer`:case`complex-time`:return IZ;case`protocols-tag`:return UZ;case`metrics-custom`:return WZ;case`metrics-calc`:return GZ;case`dialects-log`:case`dialects-climb`:return KZ;default:return null}}function YZ({quest:e,onClick:t,className:n,compact:i=!1,disabled:a=!1}){let o=JZ(e.id),s=t?`Select to jump to its section.`:`Open the editor to begin.`,c=e.isCompleted?`Challenge complete.`:e.result?e.result.pass?`Ready — ${e.result.detail??`looks good`}`:e.result.reason??s:s,l={"data-testid":`challenge-row-${e.id}`,"data-completed":e.isCompleted?`true`:`false`,className:G(`w-full text-left flex items-start gap-3 rounded-xl border px-3 py-2 text-sm transition-colors`,e.isCompleted?`border-primary/40 bg-primary/5`:`border-border/50 bg-background/60`,t&&!a&&`cursor-pointer hover:bg-background/80`,a&&`opacity-60 cursor-default`,i&&`px-2.5 py-1.5`,n)},u=(0,W.jsxs)(W.Fragment,{children:[o?(0,W.jsxs)(`span`,{className:G(`relative shrink-0 mt-0.5`,i?`size-5`:`size-6`),children:[(0,W.jsx)(o,{className:`w-full h-full`}),e.isCompleted&&(0,W.jsx)(`span`,{className:`absolute -bottom-1 -right-1 flex size-3.5 items-center justify-center rounded-full bg-emerald-500 text-white border border-background shadow`,children:(0,W.jsx)(Vn,{className:`size-2`,strokeWidth:3})})]}):(0,W.jsx)(`span`,{className:G(`mt-0.5 shrink-0`,e.isCompleted?`text-primary`:`text-muted-foreground/50`),"aria-hidden":`true`,children:e.isCompleted?(0,W.jsx)(Ft,{className:i?`size-3.5`:`size-4`}):(0,W.jsx)(r,{className:i?`size-3.5`:`size-4`})}),(0,W.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,W.jsx)(`p`,{className:G(`font-semibold`,e.isCompleted?`text-foreground line-through decoration-primary/40`:`text-foreground`,i&&`text-xs`),children:e.label}),e.desc&&!i&&(0,W.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:e.desc}),(0,W.jsx)(`p`,{"data-testid":`challenge-hint-${e.id}`,className:G(`mt-1 text-xs`,e.isCompleted||e.result?.pass?`text-primary/80`:`text-muted-foreground`),children:c})]})]});return t?(0,W.jsx)(`button`,{type:`button`,onClick:t,disabled:a,...l,children:u}):(0,W.jsx)(`div`,{...l,children:u})}function XZ(e){let t=e.replace(/^\s+/,``),n=t.match(/\n\s*\n/);return!n||n.index===void 0?{lead:t,rest:``}:{lead:t.slice(0,n.index),rest:t.slice(n.index).trimStart()}}var ZZ=({section:e,idx:t,prose:n,blockId:r,keySuffix:i,showHeading:a=!0,showEyebrow:o=!0,renderButtons:s=!0,isActive:c=!1,hasViewDef:l=!1,runState:u,deps:d,onExampleSelect:f,selectedExampleIndex:p,chapters:m=[],challengeQuests:h=[],isCollection:g=!1,collectionSlug:_=null,workoutItems:v=[],handleSelectWorkout:y,onScrollToSection:b,variant:x=`default`})=>{let S=!!e.isFullBleed,C=!!e.isDark&&x!==`caption`,w=e.density,T=lI[e.theme||`slate`]??lI.slate,E=e.examples??[],D=t===-1,O=U.useMemo(()=>{if(!m||!h)return null;for(let t of m){let n=t.sectionIds.indexOf(e.id);if(n>=0&&t.questIds[n]){let e=t.questIds[n],r=h.find(t=>t.id===e);if(r)return{quest:r,chapterTitle:t.title}}}return null},[m,h,e.id]);if(D){let t=e.proseChunks.filter(e=>e.kind===`button`).map(e=>e.button),n=e.proseChunks.findIndex(e=>e.kind===`prose`&&e.text.trim()!==``),a=n>=0?e.proseChunks[n]:null,{lead:o,rest:s}=a&&a.kind===`prose`?XZ(a.text.trim()):{lead:``,rest:``},c=e.proseChunks.slice(n+1);return(0,W.jsxs)(`div`,{id:r,"data-section-id":i==="default"?e.id:void 0,className:`group relative flex min-h-[70vh] lg:min-h-[80vh] items-center justify-center overflow-hidden border-b-2 border-primary/10 bg-gradient-to-b from-primary/[0.08] via-muted/30 to-background px-6 py-16 lg:px-10 lg:py-24`,children:[(0,W.jsx)(`div`,{className:`pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_75%_60%_at_50%_0%,_var(--tw-gradient-stops))] from-primary/30 via-primary/5 to-transparent`}),(0,W.jsx)(`div`,{className:`pointer-events-none absolute inset-0 text-primary opacity-[0.15]`,style:{backgroundImage:`radial-gradient(circle, currentColor 1.5px, transparent 1.5px)`,backgroundSize:`24px 24px`,maskImage:`radial-gradient(ellipse 70% 60% at 50% 40%, black 40%, transparent 90%)`,WebkitMaskImage:`radial-gradient(ellipse 70% 60% at 50% 40%, black 40%, transparent 90%)`}}),(0,W.jsxs)(`div`,{className:`relative max-w-2xl w-full text-center`,children:[o&&(0,W.jsx)(MZ,{prose:o,variant:`heroLead`,className:`mb-5`}),s&&(0,W.jsx)(MZ,{prose:s,variant:`heroBody`,className:`mb-2`}),c.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,W.jsx)(MZ,{prose:n,className:`mt-6 mb-2`},`hero-prose-${t}`):null}if(e.kind===`challenge`){let n=h.find(t=>t.id===e.id);return n?(0,W.jsx)(`div`,{className:`my-4 flex justify-center`,children:(0,W.jsx)(YZ,{quest:n,onClick:()=>b?.(r),compact:!0})},`hero-challenge-${t}`):null}return null}),t.length>0&&(0,W.jsx)(NZ,{activations:t.map((e,t)=>nF(e,t)),fullBleed:!0,runState:l?u:void 0,deps:d})]})]})}let k=n===void 0?e.proseChunks??[]:[{kind:`prose`,text:n}],A=!k.some(e=>e.kind===`button`)&&(e.buttons??[]).length>0;return(0,W.jsxs)(`div`,{id:r,"data-section-id":i==="default"||i===`before-workouts`?e.id:void 0,className:G(`group relative border-b border-border/50 transition-colors duration-300`,x===`caption`?`py-6 pb-10`:l?S?`flex items-center justify-center min-h-[35vh] py-12 lg:py-16 px-6 lg:px-10`:w===`compact`?`py-10 lg:py-12 px-6 lg:px-10`:`py-14 lg:py-20 px-6 lg:px-10`:w===`compact`?`py-10 lg:py-12 px-6 lg:px-12`:`py-16 lg:py-20 px-6 lg:px-12`,!x||x==="default"?C&&`bg-muted/20 overflow-hidden`:void 0,x!==`caption`&&!C&&!S&&(t%2==0?`bg-background`:`bg-muted/[0.18]`)),children:[x!==`caption`&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:G(`pointer-events-none absolute inset-y-0 left-0 w-px bg-gradient-to-b opacity-0 transition-opacity duration-300`,T.accent,c&&`opacity-100`)}),(0,W.jsx)(`div`,{className:G(`pointer-events-none absolute left-0 top-0 h-full w-1 origin-top rounded-r-full bg-gradient-to-b transition-all duration-300`,T.progress,c?`scale-y-100 opacity-100`:`scale-y-[0.18] opacity-25`)})]}),C&&(0,W.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-40 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-primary/20 via-transparent to-transparent`}),(0,W.jsxs)(`div`,{className:G(`relative`,x===`caption`?`max-w-none`:l?S?`max-w-md w-full text-center`:`max-w-sm`:`max-w-4xl w-full mx-auto`),children:[o&&(!S||!l)&&O&&(0,W.jsx)(`div`,{className:`mb-4 flex items-center gap-2 select-none min-h-[14px]`,children:O.quest.isCompleted?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20`,children:[(0,W.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse`}),`Challenge Complete`]}):(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-muted-foreground/80 bg-muted/60 px-2 py-0.5 rounded-full border border-border/50`,children:[(0,W.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-zinc-400 dark:bg-zinc-500`}),O.chapterTitle,`: Challenge Pending`]})}),a?(0,W.jsx)(`h2`,{className:G(`font-bold tracking-tight text-foreground leading-tight`,x===`caption`?`text-xl lg:text-2xl mb-4`:`text-2xl lg:text-3xl font-black uppercase mb-5`),children:e.heading}):null,k.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,W.jsx)(MZ,{prose:n,className:t===0?`mb-6`:`mt-4 mb-6`},`prose-${t}`):null}if(e.kind===`button`)return(0,W.jsx)(NZ,{activations:[nF(e.button,t)],fullBleed:S,runState:l?u:void 0,deps:d},`button-${t}`);if(e.kind===`widget`){if(e.widget===`hero-carousel`)return(0,W.jsx)(`div`,{className:`my-6`,children:(0,W.jsx)(aZ,{})},`hero-carousel-${t}`);if(e.widget===`workouts-list`&&g&&_&&y)return(0,W.jsx)(`div`,{id:`collection-workouts`,className:`border-b border-border/50 bg-card my-6`,children:(0,W.jsx)(`div`,{className:`w-full mx-auto`,children:(0,W.jsx)(pZ,{category:_,workoutItems:v,onSelect:y,showSearch:!1,variant:`flat`})})},`workouts-${t}`)}if(e.kind===`challenge`){let n=h.find(t=>t.id===e.id);return n?(0,W.jsx)(`div`,{className:`my-4`,children:(0,W.jsx)(YZ,{quest:n,onClick:()=>b?.(r),compact:!0})},`challenge-${t}`):null}return null}),E.length>0?(0,W.jsx)(PZ,{examples:E,activeIndex:Math.min(p,E.length-1),onSelect:t=>f(e,t)}):null,s&&A?(0,W.jsx)(NZ,{activations:e.buttons.map((e,t)=>nF(e,t)),fullBleed:S,runState:l?u:void 0,deps:d}):null]})]},`${e.id}-${i}`)};function QZ({sections:e,activeIndex:t,part:n,args:r}){return(0,W.jsx)(`div`,{className:`h-full min-h-0 pr-1`,"data-testid":`guide-captions-${n}`,children:e.map((e,n)=>{let i=n===t;return(0,W.jsx)(`div`,{className:`absolute inset-0 min-h-0 overflow-y-auto transition-opacity duration-300 ${i?`opacity-100`:`pointer-events-none invisible opacity-0`}`,"aria-hidden":!i,children:(0,W.jsx)(ZZ,{section:e,idx:n,blockId:`guide-caption-${e.id}`,keySuffix:`caption`,variant:`caption`,isActive:i,hasViewDef:r.hasViewDef??!0,runState:r.runState,deps:r.deps,onExampleSelect:r.onExampleSelect,selectedExampleIndex:r.selectedExamples[e.id]??0,chapters:r.chapters,challengeQuests:r.challengeQuests,onScrollToSection:r.onScrollToSection})},e.id)})})}function $Z({sections:e,part:t,partCount:n,title:r,pane:i,cardArgs:a,onActivateSection:o}){let s=(0,U.useRef)(null),c=(0,U.useMemo)(()=>rZ(e),[e]),{slice:l,subscribe:u}=$X(s,!1,c),d=(0,U.useRef)(e);d.current=e;let[f,p]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=s.current;if(!e||typeof IntersectionObserver>`u`){p(!0);return}let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(p(!0),t.disconnect())},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let m=()=>{let e=s.current;if(!e)return!1;let{top:t,bottom:n}=e.getBoundingClientRect();return t<=0&&n>window.innerHeight},[h,g]=(0,U.useState)(!1);(0,U.useEffect)(()=>u(()=>{let e=m();g(t=>t===e?t:e)}),[u]);let _=(0,U.useRef)(!1),v=(0,U.useRef)(-1),y=(0,U.useRef)(o);y.current=o,(0,U.useEffect)(()=>{let e=_.current,t=v.current;if(_.current=h,v.current=l.index,!h||e&&t===l.index)return;let n=d.current[l.index];n&&y.current(n)},[h,l.index]);let b=e[l.index]??null;return(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`header`,{"data-testid":`guide-runway-header-${t}`,className:`mx-auto w-full max-w-[1500px] px-6 pt-12 pb-6 lg:px-12`,children:[(0,W.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[`Part `,t,` / `,n]}),(0,W.jsx)(`h2`,{className:`mt-1 text-xl font-black uppercase tracking-tight text-foreground`,children:r})]}),(0,W.jsxs)(`div`,{className:`relative`,children:[(0,W.jsx)(XX,{trackRef:s,height:`${(e.length+1)*100}vh`,stages:c,activeIndex:l.index,pane:f?i:null,captions:(0,W.jsx)(QZ,{sections:e,activeIndex:l.index,part:t,args:a}),status:(0,W.jsxs)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[String(l.index+1).padStart(2,`0`),b?` — ${b.heading}`:``]}),testId:`guide-runway-${t}`}),e.map((t,n)=>(0,W.jsx)(`span`,{id:t.id,"data-section-id":t.id,"aria-hidden":`true`,className:`pointer-events-none absolute left-0 h-px w-px`,style:{top:`calc((100% - 100vh) * ${n/e.length} + 50vh + 120px)`}},t.id))]})]})}function eQ({sections:e,groupKey:t,title:n,pane:r,cardArgs:i,onActivateSection:a}){let{groups:o,tail:s}=nZ(e,t);return(0,W.jsxs)(W.Fragment,{children:[o.map((e,t)=>(0,W.jsx)($Z,{sections:e,part:t+1,partCount:o.length,title:n,pane:r,cardArgs:i,onActivateSection:a},e[0]?.id??t)),s.length>0&&(0,W.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] px-6 lg:px-12`,"data-testid":`guide-static-tail`,children:(0,W.jsx)(`div`,{className:`lg:max-w-[50%]`,children:s.map((e,t)=>(0,W.jsx)(ZZ,{section:e,idx:t,blockId:e.id,keySuffix:`default`,isActive:i.activeSectionId===e.id,hasViewDef:i.hasViewDef??!0,runState:i.runState,deps:i.deps,onExampleSelect:i.onExampleSelect,selectedExampleIndex:i.selectedExamples[e.id]??0,chapters:i.chapters,challengeQuests:i.challengeQuests,onScrollToSection:i.onScrollToSection},`tail-${e.id}`))})})]})}function tQ({videoId:e,title:t=`YouTube video`,onClose:n}){return(0,U.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,RS.createPortal)((0,W.jsxs)(`div`,{className:`fixed inset-0 z-[100] flex items-center justify-center bg-black/90 p-4 animate-in fade-in duration-200`,"data-testid":`youtube-lightbox`,onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,W.jsx)(`button`,{type:`button`,onClick:n,title:`Close video`,"data-testid":`youtube-lightbox-close`,className:`absolute right-4 top-4 z-[110] flex size-11 items-center justify-center rounded-full border border-border bg-background/80 text-foreground transition-colors hover:bg-accent`,children:(0,W.jsx)(we,{className:`size-5`})}),(0,W.jsx)(`div`,{className:`aspect-video w-full max-w-5xl overflow-hidden rounded-lg border border-border bg-black shadow-2xl`,children:(0,W.jsx)(`iframe`,{className:`h-full w-full border-0`,src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(e)}?autoplay=1&rel=0`,title:t,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})})]}),document.body)}function nQ({index:e,before:t,accentText:n,after:r,accent:i,blurb:a}){return(0,W.jsx)(`header`,{className:`flex items-center px-6 py-14 lg:px-12 xl:py-20 2xl:py-24 xl:px-16`,children:(0,W.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px]`,children:[(0,W.jsxs)(`h2`,{className:`flex items-baseline gap-4 xl:gap-6 text-[clamp(26px,3.6vw,52px)] font-extrabold leading-[1.1] tracking-[-0.03em]`,children:[(0,W.jsx)(`span`,{className:`font-mono text-xs font-normal tracking-normal text-muted-foreground`,children:e}),(0,W.jsxs)(`span`,{children:[t,n,r]})]}),(0,W.jsx)(`p`,{className:`mt-3 xl:mt-4 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[clamp(14px,1.2vw,18px)] leading-[1.65] text-muted-foreground`,children:a})]})})}var rQ=`hsl(var(--primary))`,iQ={ink:`hsl(var(--foreground))`,editor:rQ,timer:rQ,analytics:rQ,library:rQ,rounds:rQ},aQ={editor:`WOD Editor & Autocomplete`,timer:`Clock`,analytics:`WQL Analytics`,metrics:`Own the Metrics`,result:`Run Results`},oQ={start:`/guide/start`,protocols:`/guide/protocols`,structure:`/guide/structure`,metrics:`/guide/metrics`,clock:`/guide/clock`,wql:`/guide/wql`,dashboards:`/guide/dashboards`,sessions:`/guide/sessions`,basics:`/guide/start`,"custom-metrics":`/guide/metrics`,dialects:`/guide/sessions#intent`,complex:`/guide/sessions#full-session`},sQ=`dQw4w9WgXcQ`,cQ=`https://i.ytimg.com/vi/${sQ}/hqdefault.jpg`;function lQ({variant:e=`index`}){let t=zI(),{pathname:n}=Xt(),[r,i]=(0,U.useState)(null),a=(0,U.useMemo)(()=>tI(t).flatMap(e=>e.action?.type===`route`?[{id:e.id,label:e.label,to:e.action.to}]:[]),[t]),o=(0,U.useMemo)(()=>{let e=new Map;for(let n of t){if(n.route.startsWith(`/collections`)||n.page.frontmatter?.type!==`guide`)continue;let t=n.page.frontmatter?.description;t&&e.set(`guide-${n.route}`,String(t))}return e},[t]);if(a.length===0)return null;let s=a.findIndex(e=>e.to===n),c=s>=0,l=c&&a.length>1?(s+1)%a.length:-1,u=r&&(0,W.jsx)(tQ,{videoId:sQ,title:r.label,onClose:()=>i(null)});return e===`university`?(0,W.jsxs)(`section`,{id:`tour-section-university`,"data-testid":`tour-section-university`,"aria-label":`Wod Wiki University`,children:[(0,W.jsx)(nQ,{index:`05`,before:`Wod Wiki `,accentText:`University`,after:``,accent:iQ.library,blurb:`Eight short chapters take you from your first workout to querying your training history. Each guide pairs a video walkthrough with a runnable example.`}),(0,W.jsx)(`nav`,{"aria-label":`Wod Wiki University`,className:`px-6 pb-16 lg:px-12 xl:px-16`,children:(0,W.jsx)(`ul`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-5`,children:a.map((e,t)=>(0,W.jsxs)(`li`,{className:G(`flex flex-col gap-5 rounded-lg border border-border p-5 md:flex-row md:items-center md:gap-8 md:p-6`,t%2==1&&`md:flex-row-reverse`),children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>i({id:e.id,label:e.label}),title:`Watch: ${e.label}`,"aria-label":`Watch: ${e.label}`,"data-testid":`guide-watch`,className:`group relative block w-full flex-none overflow-hidden rounded-md border border-border md:w-56`,children:[(0,W.jsx)(`img`,{src:cQ,alt:``,loading:`lazy`,className:`aspect-video w-full object-cover transition-transform duration-300 group-hover:scale-105`}),(0,W.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/25 transition-colors group-hover:bg-black/40`,children:(0,W.jsx)(pn,{className:`size-9 fill-white text-white`})})]}),(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,W.jsx)(Nt,{to:e.to,className:`font-semibold hover:underline`,children:e.label}),(0,W.jsx)(`p`,{className:`text-sm leading-relaxed text-muted-foreground`,children:o.get(e.id)??e.to})]})]},e.id))})}),u]}):(0,W.jsxs)(`nav`,{"aria-label":c?`What’s Next`:`Syntax & Guides`,"data-testid":`guide-index-footer`,className:`border-t border-border px-6 py-12 xl:py-16`,children:[(0,W.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col rounded-lg border border-border overflow-hidden`,children:[(0,W.jsxs)(`h2`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[c?`What’s Next`:`Syntax & Guides`,` · `,a.length]}),(0,W.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:a.map((e,t)=>(0,W.jsxs)(`li`,{className:`flex items-stretch`,children:[(0,W.jsxs)(Nt,{to:e.to,"aria-current":t===s?`page`:void 0,className:G(`flex min-w-0 flex-1 flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,t===s&&`bg-muted/50`),children:[(0,W.jsxs)(`span`,{className:`flex w-full items-baseline justify-between gap-3`,children:[(0,W.jsx)(`span`,{className:`font-medium`,children:e.label}),t===l&&(0,W.jsx)(`span`,{className:`text-xs font-semibold text-primary`,"data-testid":`guide-next-marker`,children:`Next →`})]}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.to})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>i({id:e.id,label:e.label}),title:`Watch: ${e.label}`,"aria-label":`Watch: ${e.label}`,"data-testid":`guide-watch`,className:`flex flex-none items-center gap-1.5 border-l border-border px-4 text-xs font-semibold text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground`,children:[(0,W.jsx)(pn,{className:`size-3.5`}),`Watch`]})]},e.id))})]}),u]})}var uQ=`22rem`,dQ=`42rem`,fQ=`20rem`,pQ=`calc(100dvh - var(--canvas-sticky-top) - 2rem)`;function mQ(e){return{editorWidth:e||`50%`,editorMinWidth:uQ,editorMaxWidth:dQ,editorMinHeight:fQ,editorMaxHeight:pQ}}function hQ(e){let t=Math.max(1,e.split(`
163
+ `).length);return`calc(${Math.min(560,Math.max(180,t*22))}px + 3.5rem)`}function gQ(e,t){return{"--canvas-editor-width":e.editorWidth,"--canvas-editor-min-width":e.editorMinWidth,"--canvas-editor-max-width":e.editorMaxWidth,"--canvas-editor-min-height":e.editorMinHeight,"--canvas-editor-max-height":e.editorMaxHeight,"--canvas-editor-preferred-height":hQ(t)}}var _Q=(e,t,n)=>(0,W.jsx)(ZZ,{section:e,idx:t,blockId:e.id,keySuffix:`default`,isActive:n.activeSectionId===e.id,hasViewDef:n.hasViewDef,runState:n.runState,deps:n.deps,onExampleSelect:n.handleExampleSelect,selectedExampleIndex:n.selectedExamples[e.id]??0,chapters:n.chapters,challengeQuests:n.challengeQuests,isCollection:n.isCollection,collectionSlug:n.collectionSlug,workoutItems:n.workoutItems,handleSelectWorkout:n.handleSelectWorkout,onScrollToSection:n.onScrollToSection},`${e.id}-default`),vQ=({heroSlot:e,mobilePanel:t,desktopPanel:n,stickyAlign:r=`right`,editorWidth:i=`50%`,contentSections:a,isCollection:o,collectionSlug:s,workoutItems:c,handleSelectWorkout:l,activeSectionId:u,selectedExamples:d,runState:f,deps:p,handleExampleSelect:m,hasWorkoutsTag:h,hasViewDef:g,chapters:_=[],challengeQuests:v=[],onScrollToSection:y,editorAppearsAtSectionId:b})=>{let x=b?a.findIndex(e=>e.id===b):-1,S=x>0&&!!n,C={activeSectionId:u,selectedExamples:d,handleExampleSelect:m,hasViewDef:g,runState:f,deps:p,chapters:_,challengeQuests:v,isCollection:o,collectionSlug:s,workoutItems:c,handleSelectWorkout:l,onScrollToSection:y},w=S?{width:`calc(100% - ${i})`,flexBasis:`calc(100% - ${i})`,maxWidth:`calc(100% - ${i})`}:{},T=o&&s&&c?(0,W.jsx)(`div`,{id:`collection-workouts`,className:`border-b border-border/50 bg-card`,children:(0,W.jsx)(`div`,{className:`w-full mx-auto`,children:(0,W.jsx)(pZ,{category:s??``,workoutItems:c??[],onSelect:l,showSearch:!1,variant:`flat`})})}):null;if(S){let i=a.slice(0,x),o=a.slice(x);return(0,W.jsxs)(W.Fragment,{children:[e,i.map((e,t)=>_Q(e,t,C)),(0,W.jsxs)(`div`,{className:`lg:flex`,children:[r===`left`&&n,(0,W.jsxs)(`div`,{className:`w-full min-w-0`,style:w,children:[t,o.map((e,t)=>_Q(e,t,C)),T]}),r===`right`&&n]})]})}return(0,W.jsxs)(W.Fragment,{children:[t,(0,W.jsxs)(`div`,{className:`lg:flex`,children:[r===`left`&&n,(0,W.jsxs)(`div`,{className:`w-full min-w-0`,style:w,children:[e,a.map((e,t)=>_Q(e,t,C)),T]}),r===`right`&&n]})]})},yQ=({activations:e,runState:t,deps:n})=>{if(e.length===0)return null;let r=e[0];if(rF(r)&&t){let i=e.slice(1),a=t.isReconnect?(0,W.jsxs)(`button`,{onClick:t.onReconnect,className:`flex items-center gap-2 px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full border transition-all active:scale-95 border-amber-500/40 bg-amber-500/15 text-amber-600 hover:bg-amber-500/20 dark:text-amber-400`,children:[(0,W.jsx)(P,{className:`size-3.5`}),`View`]}):(0,W.jsxs)(`button`,{type:`button`,onClick:t.onRun,className:`flex items-center gap-2 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest rounded-full shadow-lg shadow-primary/25 min-h-[44px] px-6 py-2 text-xs`,children:[(()=>{let e=r.icon||pn;return(0,W.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,W.jsx)(`span`,{children:r.label})]});return(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 justify-end pt-3 px-1`,children:[a,i.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>eF(e.action,n),className:`px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full bg-muted border border-border text-foreground hover:bg-muted/80 transition-all active:scale-95`,children:e.label},e.id||t))]})}return(0,W.jsx)(`div`,{className:`flex flex-wrap gap-3 justify-end pt-3 px-1`,children:e.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>eF(e.action,n),className:`px-5 py-2 text-[11px] font-black uppercase tracking-widest rounded-full transition-all active:scale-95 bg-primary text-primary-foreground shadow-lg shadow-primary/25 hover:scale-[1.04]`,children:e.label},e.id||t))})},bQ=({variant:e,panelTitle:t,panelSubtitle:n,panelContent:r,panelThemeClass:i,headerActions:a,showPanelButtons:o=!1,viewDefButtons:s,runState:c,deps:l,width:u,source:d=``})=>{let f=r,p=o&&s&&s.length>0?(0,W.jsx)(yQ,{activations:s.map((e,t)=>nF(e,t)),runState:c,deps:l}):null;return e===`desktop`?(0,W.jsxs)(`div`,{className:`self-start sticky hidden lg:flex flex-col p-6 pt-8 pb-8 gap-3`,style:{top:`104px`,height:`calc(100vh - 104px)`,width:`clamp(var(--canvas-editor-min-width), var(--canvas-editor-width), var(--canvas-editor-max-width))`,...gQ(mQ(u),d)},children:[(0,W.jsx)(`div`,{className:`flex-1 min-h-0 flex flex-col justify-center py-4`,children:(0,W.jsx)(`div`,{className:`h-[min(var(--canvas-editor-preferred-height),var(--canvas-editor-max-height))] min-h-[var(--canvas-editor-min-height)] max-h-[var(--canvas-editor-max-height)] flex flex-col w-full`,children:f})}),p]}):(0,W.jsx)(`div`,{className:`lg:hidden sticky z-20 shrink-0 px-4 pt-2 pb-1`,"data-page-sticky-boundary":`true`,style:{top:`65px`,height:`min(var(--canvas-editor-preferred-height), calc(100dvh - 65px - 1rem))`,minHeight:`18rem`,"--canvas-editor-preferred-height":hQ(d)},children:(0,W.jsxs)(`div`,{className:`flex flex-col gap-2 h-full`,children:[(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:f}),p]})})},xQ=({heroSlot:e,children:t})=>(0,W.jsxs)(`section`,{className:`relative border-b border-border/50`,children:[e,t]}),SQ=new Set([q.Duration,q.Time]);function CQ(e){return e.metrics.some(e=>e.type===q.Hint&&e.value===`domain.wod`)}function wQ(e){return e?e.filter(e=>!CQ(e)&&e.metrics.some(e=>e.type===q.Effort)).length:0}function TQ(e){if(!e)return 0;let t=0;for(let n of e)if(!CQ(n))for(let e of n.metrics)e.type===q.Rounds&&typeof e.value==`number`&&(t+=e.value);return t}function EQ(e){return e?e.some(e=>!CQ(e)&&e.metrics.some(e=>SQ.has(e.type))):!1}function DQ(e){return e?e.some(e=>!CQ(e)&&e.metrics.some(e=>e.type===q.Rep)):!1}function OQ(e,t){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null}function kQ(e,t){return typeof e==`string`&&e.length>0?e:typeof e==`number`?String(e):null}var AQ={"has-movement":e=>{let t=wQ(e.statements);return t>0?{pass:!0,detail:`${t} movement${t===1?``:`s`}`}:{pass:!1,reason:"Add at least one movement line (e.g. `10 KB Swings`)."}},"exactly-movements":(e,t)=>{let n=OQ(t.count??t.value,`count`);if(n===null)return{pass:!1,reason:"exactly-movements: missing `count`."};let r=wQ(e.statements);return r===n?{pass:!0,detail:String(r)}:{pass:!1,reason:`Expected exactly ${n} movement${n===1?``:`s`}, found ${r}.`}},"has-reps":e=>DQ(e.statements)?{pass:!0}:{pass:!1,reason:"Add a rep count (e.g. `10` reps on a movement line)."},"has-timer":e=>EQ(e.statements)?{pass:!0}:{pass:!1,reason:"Add a timer (e.g. `*:30 Rest` or `5:00 cap`)."},"min-rounds":(e,t)=>{let n=OQ(t.count??t.min,`count`);if(n===null)return{pass:!1,reason:"min-rounds: missing `count`."};let r=TQ(e.statements);return r>=n?{pass:!0,detail:`${r} round${r===1?``:`s`}`}:{pass:!1,reason:`Need at least ${n} round${n===1?``:`s`} — found ${r}.`}},"contains-token":(e,t)=>{let n=kQ(t.value??t.token,`value`);return n===null?{pass:!1,reason:"contains-token: missing `value`."}:(e.content??``).includes(n)?{pass:!0,detail:`"${n}"`}:{pass:!1,reason:`Script must include the token "${n}".`}}};function jQ(e,t){if(!t||typeof t.type!=`string`||t.type.length===0)return{pass:!1,reason:`Quest has no validation schema.`};let n=AQ[t.type];return n?n(e,t):{pass:!1,reason:`Unknown validation type "${t.type}".`}}function MQ({pageRoute:e,quests:t,block:n,enabled:r=!0}){let{markComplete:i,quests:a,isComplete:o}=OK(e,t),[s,c]=(0,U.useState)(new Set),l=(0,U.useMemo)(()=>{let e={};if(!r||!n){for(let n of t)e[n.id]={pass:!1,reason:`No active block.`};return e}let i={content:n.content,statements:n.statements??[]};for(let n of t){if(!n.validation){e[n.id]={pass:!1};continue}if(n.validation?.type===`workout-complete`){e[n.id]={pass:!1,reason:`Finish the workout to check this off.`};continue}e[n.id]=jQ(i,n.validation)}return e},[n,t,r]);(0,U.useEffect)(()=>{if(r)for(let e of a)e.isCompleted||s.has(e.id)||l[e.id]?.pass&&(i(e.id),c(t=>{if(t.has(e.id))return t;let n=new Set(t);return n.add(e.id),n}))},[r,a,l,s,i]);let u=(0,U.useMemo)(()=>t.map(e=>e.id).join(`|`),[t]);return(0,U.useEffect)(()=>{c(new Set)},[e,u]),{quests:a.map(e=>{let t=l[e.id]??{pass:!1,reason:`No validator result.`},n=e.isCompleted?{...t,pass:!0,detail:`Completed`}:t;return{...e,result:n}}),isComplete:o,results:l}}function NQ({page:e,wodFiles:t,theme:n,workoutItems:r,onSelect:i,contentOverride:a,panelHeaderActions:o,onPanelActionsReady:s,heroSlot:c,onScrollToSection:l}){let u=ht(),d=Xt(),{sections:f,route:p,chapters:m}=e,h=d.pathname.startsWith(`/p/`)||p.startsWith(`/p/`),g=(0,U.useMemo)(()=>fB(p),[p]),_=e.type===`guide`||p.startsWith(`/guide`);uK(_?p:void 0);let v=p.startsWith(`/collections/`)||p.startsWith(`/c/`),y=jK(`(prefers-reduced-motion: reduce)`),b=_&&!v&&!y,x=v?p.split(`/`).pop()??null:null,S=(0,U.useCallback)(e=>{if(i){i(e);return}u(GM(e.category,e.name))},[u,i]),C=f.some(e=>e.proseChunks.some(e=>e.kind===`widget`&&e.widget===`workouts-list`)),w=f.slice(1),T=f[0]??null,E=!!T&&(T.proseChunks.some(e=>e.kind===`prose`&&e.text.trim()!==``)||T.buttons.length>0),D=f.find(e=>e.view)?.view??null,O=D?.align??`right`,k=D?.width??`50%`,A=w[0]??f[0]??null,j=p===`/`?`learn`:void 0,M=D?.source?pB(D.source,t):``,N=D?.source||`__initial__`,[P,F]=(0,U.useState)(A?.id??null),[I,L]=(0,U.useState)(A?.heading??`Whiteboard Script`),[R,ee]=(0,U.useState)(A?.heading??`Whiteboard Script`),te=(0,U.useMemo)(()=>hB(w),[w]),ne=b&&p.split(`/`).pop()||void 0,re=(0,U.useMemo)(()=>b?nZ(w,ne):null,[b,ne,w]),{guideOwnerBySection:ie,guideOwnerSource:ae}=(0,U.useMemo)(()=>{if(!b)return{guideOwnerBySection:null,guideOwnerSource:null};let e=new Map,t=new Map,n=null;for(let r of w){let i=r.proseChunks.find(e=>e.kind===`button`&&e.button.pipeline.some(e=>e.action===`set-source`))?.button.pipeline.find(e=>e.action===`set-source`)?.value??r.buttons.find(e=>e.pipeline.some(e=>e.action===`set-source`))?.pipeline.find(e=>e.action===`set-source`)?.value??null;i&&(n=r,t.set(r.id,i)),e.set(r.id,n)}return{guideOwnerBySection:e,guideOwnerSource:t}},[b,w]),[oe,se]=(0,U.useState)(()=>(A??f[0])?.theme??`slate`),[ce,le]=(0,U.useState)({}),{editorSource:z,editorOpacity:ue,isEditorLoading:de,activeOriginalSource:fe,swapSource:B,handleEditorChange:pe,resetActiveSource:me,setEditorView:he,getSource:ge}=bK({initialSource:M,initialSourceKey:N,contentOverride:a}),_e=(0,U.useRef)(t);_e.current=t;let ve=(0,U.useCallback)(()=>Me.current[0]??null,[]),{startRun:ye,closeRun:be,handleWorkoutComplete:xe,resetRun:Se,resetRequested:Ce,fullscreen:we,runState:Te,completedResults:Ee}=yK({getBlock:ve,getContent:ge,title:e.frontmatter.title}),De=(0,U.useCallback)(async()=>await Se(M)?(me(),!0):!1,[Se,M,me]),[Oe,ke]=(0,U.useState)(null),Ae=e.quests??[],je=MQ({pageRoute:e.route,quests:Ae,block:Oe});kK({pageRoute:e.route,quests:Ae,completedResults:Ee}),AK({pageRoute:e.route,quests:Ae,initialSource:M,currentSource:z});let Me=(0,U.useRef)([]),Ne=(0,U.useRef)(te.get(A?.id??``)?.id??null),Pe=(0,U.useCallback)(e=>{F(e.id),L(e.heading),se(e.theme??`slate`);let t=(ie??te).get(e.id)??null;ee(t?.heading??A?.heading??`Whiteboard Script`);let n=t?.id??null;if(n===Ne.current)return;if(Ne.current=n,!t){B(M,N);return}let r=t.examples??[];if(r.length>0){let e=r[ce[t.id]??0]??r[0];e?.source&&B(pB(e.source,_e.current),e.source)}for(let e of t.commands){let t=e.pipeline.filter(e=>!(r.length>0&&e.action===`set-source`)).map(t=>tF(t,e.open??`view`));t.length!==0&&eF(t.length===1?t[0]:{type:`pipeline`,steps:t},Be.current)}let i=ie?ae?.get(t.id):void 0;i&&B(pB(i,_e.current),i)},[ce,B,te,ie,ae,A,M,N]),Fe=(0,U.useCallback)((e,t)=>{le(n=>({...n,[e.id]:t})),F(e.id),L(e.heading),se(e.theme??`slate`),ee(e.heading),Ne.current=e.id;let n=e.examples?.[t];n?.source&&B(pB(n.source,_e.current),n.source)},[B]),[Ie,Le]=Gt(`h`,{history:`replace`,shallow:!0}),[Re]=Gt(`q`,{defaultValue:``,shallow:!0}),ze=(0,U.useMemo)(()=>({navigate:(e,t)=>u(e,{replace:t?.replace}),setQueryParam:(e,t)=>{let n=e.h;n!==void 0&&Le(n,{history:t?`replace`:`push`})},swapSource:e=>B(pB(e,_e.current),e),setPanelState:e=>{if(e===`track`){let e=ve();e&&ye(e)}}}),[u,B,Le,ve,ye]),Be=(0,U.useRef)(ze);Be.current=ze;let Ve=(0,U.useCallback)(e=>{Le(e.id,{history:`replace`}),Pe(e)},[Pe,Le]),He=Az(104),Ue=(0,U.useMemo)(()=>`-${He}px 0px -30% 0px`,[He]),We=re?re.tail.map(e=>e.id):w.map(e=>e.id),Ge=(0,U.useRef)(!1);Tz({ids:We,enabled:We.length>0,rootMargin:Ue,threshold:[0,.1,.25,.5,.75],dataAttribute:`data-section-id`,scrollDirection:`topmost-when-up`,debounceMs:50,shouldAcceptChange:()=>Ge.current?!0:(Ge.current=window.scrollY>0,Ge.current),onChange:e=>{let t=w.find(t=>t.id===e);t&&(Le(e,{history:`replace`}),Pe(t))}});let Ke=(0,U.useRef)(!1);(0,U.useEffect)(()=>{Ke.current||!Ie||w.length===0||(Ke.current=!0,requestAnimationFrame(()=>{let e=document.querySelector(`[data-section-id="${Ie}"]`);if(!e)return;let t=He+8,n=e.getBoundingClientRect().top+window.scrollY-t;window.scrollTo({top:Math.max(0,n),behavior:`smooth`})}))},[w,Ie,He]);let qe=(0,U.useRef)(Re);(0,U.useEffect)(()=>{if(!v){qe.current=Re;return}let e=Re.trim(),t=qe.current.trim();if(e&&e!==t){let e=document.getElementById(`collection-workouts`);if(e){let t=e.getBoundingClientRect().top+window.scrollY-He-8;window.scrollTo({top:Math.max(0,t),behavior:`smooth`})}}qe.current=Re},[Re,v,He]);let Je=(0,U.useRef)(s);Je.current=s,(0,U.useEffect)(()=>{Je.current?.({run:()=>{let e=Me.current[0]??null;e&&ye(e)},reset:()=>{Se()},results:()=>{},fullscreen:()=>{let e=Me.current[0]??null;e&&ye(e)},getSource:ge})},[ye,Se,ge]);let Ye=(0,U.useMemo)(()=>[{id:`run`,label:`Run`,icon:(0,W.jsx)(pn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:e=>{ye(e)}}],[ye]),Xe=lI[oe]??lI.slate,Ze=de?`${I} · loading`:I,Qe=!de&&I!==R?R:void 0,$e=(0,U.useCallback)(e=>{let t=e[0]??null;Me.current=e,ke(e=>e?.content===t?.content&&e?.id===t?.id?e:t)},[]),et=c??(E&&T?(0,W.jsx)(ZZ,{section:T,idx:-1,prose:void 0,blockId:T.id,keySuffix:`hero`,showEyebrow:!1,isActive:!1,hasViewDef:!!D,deps:ze,onExampleSelect:Fe,selectedExampleIndex:0,onScrollToSection:l,challengeQuests:je.quests}):null),tt=o,nt=(0,W.jsx)(PX,{editorSource:z,editorOpacity:ue,activeOriginalSource:fe,handleEditorChange:pe,onResetToSource:De,canvasNoteId:g,readonly:h,showFrontmatter:typeof e.frontmatter.showFrontmatter==`boolean`?e.frontmatter.showFrontmatter:!_&&p!==`/`&&!p.startsWith(`/syntax`),theme:n,commands:Ye,onBlocksChange:$e,onViewCreated:he,panelTitle:Ze,panelSubtitle:Qe,panelThemeClass:Xe.panel,headerActions:tt,onRun:(e,t)=>{t&&ye(t,e)}}),rt=D&&(0,W.jsx)(bQ,{variant:`desktop`,panelContent:nt,panelTitle:Ze,panelSubtitle:Qe,viewDefButtons:D.buttons,runState:Te,deps:ze,width:k,source:z}),it=D&&(0,W.jsx)(bQ,{variant:`mobile`,panelContent:nt,panelTitle:Ze,panelSubtitle:Qe,viewDefButtons:D.buttons,runState:Te,deps:ze,width:k,source:z});return(0,W.jsxs)(`div`,{className:`flex flex-col min-h-screen bg-background`,children:[we?.kind===`timer`&&(0,W.jsx)(`div`,{className:`sticky z-30 border-b border-border bg-background`,style:{top:He},children:(0,W.jsx)(`div`,{className:`mx-auto h-[max(320px,min(75vh,640px))] max-w-5xl px-4 py-2`,children:(0,W.jsx)(QG,{block:we.block,onClose:be,autoStart:!0,externalStop:Ce,onComplete:(e,t)=>{xe(t)}})})}),(0,W.jsx)(xQ,{heroSlot:et,children:b?(0,W.jsx)(eQ,{sections:w,groupKey:ne,title:String(e.frontmatter.title??``),pane:(0,W.jsx)(`div`,{className:`absolute inset-0`,style:{"--canvas-editor-preferred-height":hQ(z)},children:nt}),cardArgs:{activeSectionId:P,selectedExamples:ce,onExampleSelect:Fe,runState:Te,deps:ze,hasViewDef:!!D,chapters:m,challengeQuests:je.quests,onScrollToSection:l},onActivateSection:Ve}):(0,W.jsx)(vQ,{contentSections:w,isCollection:v,collectionSlug:x,workoutItems:r,handleSelectWorkout:S,activeSectionId:P,selectedExamples:ce,runState:Te,deps:ze,handleExampleSelect:Fe,hasWorkoutsTag:C,hasViewDef:!!D,chapters:m,challengeQuests:je.quests,onScrollToSection:l,mobilePanel:it,desktopPanel:rt,stickyAlign:O,editorWidth:k,editorAppearsAtSectionId:j})}),_&&(0,W.jsx)(lQ,{})]})}var PQ={"workout-complete":!0,"run-started":!0};function FQ(e,t,n){let{markComplete:r}=OK(e,t),i=(0,U.useRef)(new Set);i.current=new Set(t.filter(e=>!e.validation||!PQ[e.validation.type]).map(e=>e.id));let a=(0,U.useRef)({}),o={};for(let e of n)e.quest&&(o[e.id]=e.quest);return a.current=o,(0,U.useCallback)(e=>{let t=a.current[e];t&&i.current.has(t)&&r(t)},[r])}function IQ(){let e=jK(`(prefers-reduced-motion: reduce)`),t=jK(`(max-width: ${dB}px)`);return e?`reduced`:t?`mobile`:`desktop`}var LQ=.25;function RQ({sourcesByStageId:e,doc:t,setDoc:n,subscribe:r,enabled:i}){let[a,o]=(0,U.useState)(!1),s=(0,U.useRef)(t),c=(0,U.useRef)(null),l=(0,U.useRef)(t),u=(0,U.useRef)(a),d=(0,U.useRef)(``),f=(0,U.useRef)(null),p=(0,U.useRef)(!1);return l.current=t,u.current=a,(0,U.useEffect)(()=>{let e=d.current;if(c.current!==null){if(t===c.current){s.current=t,c.current=null;return}if(t!==s.current){o(!0);return}}t!==s.current&&t!==e&&o(!0)},[t]),(0,U.useEffect)(()=>{if(!i){c.current=null;return}let t=r(t=>{if(t.stage.id!==f.current&&(f.current=t.stage.id,d.current=e[t.stage.id]??``,s.current=``,c.current=null,o(!1),p.current=!0),u.current||c.current!==null)return;let r=d.current;if(!r)return;let i=t.index===0?r.length:Math.floor(zX(LX(t.t/LQ))*r.length),a=r.slice(0,i),m=l.current;p.current=!1,a!==m&&(c.current=a,n(a))});return()=>{t()}},[i,e,n,r]),{userDiverged:a,complete:(0,U.useCallback)(()=>{if(u.current)return;let e=d.current;e&&(c.current=e,n(e))},[n])}}function zQ({stages:e,activeIndex:t}){return(0,W.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`scroll-captions`,children:e.map((n,r)=>(0,W.jsxs)(`div`,{className:`absolute inset-0 overflow-y-auto transition-opacity duration-300`,style:{opacity:+(r===t)},"aria-hidden":r!==t,inert:r!==t,children:[(0,W.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em]`,style:{color:n.accent??`hsl(var(--muted-foreground))`},children:[String(r+1).padStart(2,`0`),` / `,String(e.length).padStart(2,`0`)]}),(0,W.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground`,children:n.id.replace(/-/g,` `)}),n.caption&&(0,W.jsx)(MZ,{prose:n.caption,className:`mt-3 text-sm text-muted-foreground`})]},n.id))})}var BQ=(0,U.forwardRef)(function({text:e,accent:t},n){let r=t??`hsl(var(--metric-rounds))`;return(0,W.jsxs)(`div`,{ref:n,className:`pointer-events-none absolute top-4 left-1/2 z-40 flex -translate-x-1/2 items-center gap-2.5 whitespace-nowrap rounded-full border bg-card px-5 py-2.5 font-mono text-[10.5px] tracking-[0.04em] opacity-0 shadow-xl`,style:{borderColor:`color-mix(in srgb, ${r} 55%, transparent)`},children:[(0,W.jsx)(`span`,{className:`size-[9px] rounded-sm`,style:{background:r}}),e]})}),VQ=8,HQ=3,UQ=2;function WQ(e,t,n){let r=e.querySelectorAll(`.cm-content .cm-line`),i=Math.max(1,Math.min(n[0],n[1]))-1,a=Math.max(1,Math.max(n[0],n[1])),o=Array.from(r).slice(i,a);if(o.length===0)return null;let s=e.getBoundingClientRect(),c=1/0,l=1/0,u=-1/0,d=-1/0;for(let e of o){let t=e.getBoundingClientRect();c=Math.min(c,t.top),l=Math.min(l,t.left),u=Math.max(u,t.bottom),d=Math.max(d,t.right)}return c-=HQ,l-=VQ,u+=HQ,d+=VQ,t&&(l=Math.max(l,t.left-UQ),d=Math.min(d,t.right+UQ),c=Math.max(c,t.top-UQ),u=Math.min(u,t.bottom+UQ)),{top:c-s.top,left:l-s.left,width:d-l,height:u-c}}function GQ(e,t){if(!t)return null;let n=t.getBoundingClientRect();if(n.width===0||n.height===0)return null;let r=e.getBoundingClientRect();return{top:n.top-r.top-UQ,left:n.left-r.left-UQ,width:n.width+4,height:n.height+4}}function KQ({accent:e,lines:t}){let n=e??`hsl(var(--foreground))`,r=(0,U.useRef)(null),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(!1);return(0,U.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let n=requestAnimationFrame(()=>s(!0)),i=e.parentElement;if(!i)return()=>cancelAnimationFrame(n);let o=()=>{let e=i.firstElementChild,n=e?.getBoundingClientRect()??null;a((t?WQ(i,n,t):null)??GQ(i,e))};o();let c=new ResizeObserver(o);return c.observe(i),()=>{cancelAnimationFrame(n),c.disconnect()}},[t]),(0,W.jsx)(`div`,{ref:r,className:`pointer-events-none absolute z-30 transition-all duration-300 ${i?t?`rounded-lg`:`rounded-2xl`:`-inset-1.5 rounded-2xl`}`,style:{boxShadow:`0 0 0 2px ${n}`,opacity:+!!o,...i??{}},"data-testid":`scroll-ring`,"data-ring-lines":t?`${t[0]}-${t[1]}`:void 0})}function qQ({scroll:e,wodFiles:t,theme:n,noteTitle:r=`note.md`,showFrontmatter:i,doc:a,onDocChange:o,onBlocksChange:s,onStageEnter:c,onRun:l,className:u}){let d=e.stages,f=(0,U.useRef)(null),p=(0,U.useRef)(null),m=(0,U.useRef)(null),h=(0,U.useRef)(new Set),g=(0,U.useMemo)(()=>Object.fromEntries(d.map(e=>[e.id,e.source?pB(e.source,t):``])),[d,t]),[_,v]=(0,U.useState)(()=>g[d[0]?.id]??``),y=a??_,b=o??v,[x,S]=(0,U.useState)(!1),{slice:C,subscribe:w,resync:T}=$X(f,x,d),[E,D]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=f.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&D(!0)},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let{userDiverged:O}=RQ({sourcesByStageId:g,doc:y,setDoc:b,subscribe:w,enabled:!x&&e.typewriter}),k=C.stage.id,A=BX(g[k]??``,y);(0,U.useEffect)(()=>{!x&&E&&c?.(k)},[x,k,E,c]),(0,U.useEffect)(()=>{if(!x){let e=requestAnimationFrame(T);return()=>cancelAnimationFrame(e)}},[x,T]),(0,U.useEffect)(()=>{let e=requestAnimationFrame(T);return()=>cancelAnimationFrame(e)},[k,T]),(0,U.useEffect)(()=>{O&&S(!0)},[O]),(0,U.useEffect)(()=>{let e=d.flatMap(e=>e.effects??[]);return w(t=>{let n=m.current;if(n){let e=LX((t.t-.04)/.12),r=LX((t.t-.5)/.2);n.style.opacity=String(Math.max(0,e-r)),n.style.transform=`translateX(-50%) translateY(${RX(-14,0,e)}px)`}let r=p.current;if(!r)return;let i=new Set;for(let n of e){if(!n.stages.includes(t.stage.id))continue;i.add(n.target);let[e,a]=n.in??[0,1],o=a>e?LX((t.t-e)/(a-e)):1,s=n.ease===`linear`?o:zX(o);r.querySelectorAll(`[data-effect-target="${n.target}"]`).forEach(e=>{n.opacity&&(e.style.opacity=String(RX(n.opacity[0],n.opacity[1],s))),n.translateY&&(e.style.transform=`translateY(${RX(n.translateY[0],n.translateY[1],s)}px)`)})}for(let e of h.current)i.has(e)||r.querySelectorAll(`[data-effect-target="${e}"]`).forEach(e=>{e.style.opacity=``,e.style.transform=``});h.current=i})},[w,d]);let j=C.stage.accent??`hsl(var(--foreground))`;return(0,W.jsxs)(`div`,{ref:p,className:u,"data-testid":`scroll-runway-section`,children:[(0,W.jsx)(XX,{trackRef:f,height:e.runway,stages:d,activeIndex:C.index,status:(0,W.jsx)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:x?`Playground mode`:C.stage.id.replace(/-/g,` `)}),pane:(0,W.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,W.jsx)(NX,{title:r??``,noteId:`canvas:scroll-runway`,doc:y,onDocChange:b,onBlocksChange:s,theme:n,showFrontmatter:i,run:l?{onRun:l}:void 0,className:`absolute inset-x-2 top-2 bottom-2`,children:C.stage.toast&&(0,W.jsx)(BQ,{ref:m,text:C.stage.toast,accent:j})}),C.ring&&!x&&A&&(0,W.jsx)(KQ,{accent:j,lines:C.ring.lines})]}),captions:(0,W.jsx)(zQ,{stages:d,activeIndex:C.index})}),x&&(0,W.jsxs)(`button`,{type:`button`,onClick:()=>S(!1),className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-full bg-foreground px-5 py-2.5 font-mono text-[10px] tracking-[0.06em] text-background opacity-95 transition-opacity hover:opacity-100`,children:[`▶ Playground mode — `,O?`your edits are kept`:`editing`,` · tap here to return to the tour`]})]})}function JQ({spec:e,wodFiles:t,onStageEnter:n,className:r}){let i=e.stages,a=(0,U.useMemo)(()=>Object.fromEntries(i.map(e=>[e.id,e.source?pB(e.source,t):``])),[i,t]),o=(0,U.useRef)(null);return(0,U.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=o.current;if(!e)return;let t=new IntersectionObserver(e=>{for(let r of e){if(!r.isIntersecting)continue;let e=r.target.dataset.cardId;e&&(n?.(e),t.unobserve(r.target))}},{threshold:.4});return e.querySelectorAll(`[data-card-id]`).forEach(e=>t.observe(e)),()=>t.disconnect()},[n]),(0,W.jsx)(`section`,{className:r,"data-testid":`runway-reduced`,children:(0,W.jsx)(`div`,{className:`px-6 pt-4 pb-24`,children:(0,W.jsx)(`div`,{ref:o,className:`mx-auto max-w-2xl`,children:i.map((e,t)=>(0,W.jsxs)(`article`,{"data-card-id":e.id,className:`mb-6 rounded-2xl border border-border bg-card p-7`,children:[(0,W.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em]`,style:{color:e.accent??`hsl(var(--muted-foreground))`},children:[String(t+1).padStart(2,`0`),` / `,String(i.length).padStart(2,`0`)]}),(0,W.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground`,children:e.id.replace(/-/g,` `)}),e.caption&&(0,W.jsx)(MZ,{prose:e.caption,className:`mt-3 text-sm text-muted-foreground`}),a[e.id]&&(0,W.jsx)(`pre`,{className:`mt-5 overflow-x-auto rounded-lg bg-background px-4 py-4 font-mono text-[12px] tracking-[0.04em] text-muted-foreground`,children:a[e.id]})]},e.id))})})})}function YQ(){return IQ()}function XQ({spec:e,formFactor:t,wodFiles:n,theme:r,noteTitle:i,showFrontmatter:a,doc:o,onDocChange:s,onBlocksChange:c,onStageEnter:l,onRun:u,className:d}){let f=YQ();return(t??f)===`reduced`?(0,W.jsx)(JQ,{spec:e,wodFiles:n,onStageEnter:l,className:d}):(0,W.jsx)(qQ,{scroll:e,wodFiles:n,theme:r,noteTitle:i,showFrontmatter:a,doc:o,onDocChange:s,onBlocksChange:c,onStageEnter:l,onRun:u,className:d})}function ZQ({page:e,wodFiles:t,theme:n,onScrollToSection:r}){let i=e.scroll,a=i.stages,o=ht();uK(e.type===`guide`||e.route.startsWith(`/guide`)?e.route:void 0);let s=(0,U.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,e.source?pB(e.source,t):``])),[a,t]),[c,l]=(0,U.useState)(()=>s[a[0]?.id]??``),u=(0,U.useRef)([]),[d,f]=(0,U.useState)(null),p=FQ(e.route,e.quests,a),m=(0,U.useCallback)(()=>u.current[0]??null,[]),h=yK({getBlock:m,getContent:(0,U.useCallback)(()=>c,[c]),title:e.frontmatter.title}),{startRun:g}=h,_=Az(104),v=MQ({pageRoute:e.route,quests:e.quests,block:d});kK({pageRoute:e.route,quests:e.quests,completedResults:h.completedResults});let[,y]=Gt(`h`,{history:`replace`,shallow:!0}),b=(0,U.useMemo)(()=>({navigate:(e,t)=>o(e,{replace:t?.replace}),setQueryParam:(e,t)=>{let n=e.h;n!==void 0&&y(n,{history:t?`replace`:`push`})},swapSource:e=>l(pB(e,t)),setPanelState:e=>{if(e===`track`){let e=m();e&&g(e)}}}),[o,y,t,m,g]),x=(0,U.useCallback)((e,n)=>{let r=e.examples?.[n];r?.source&&l(pB(r.source,t))},[t]),S=(0,U.useCallback)(e=>{let t=e[0]??null;u.current=e,f(e=>e?.content===t?.content&&e?.id===t?.id?e:t)},[]),C=(0,U.useCallback)((e,t)=>{t&&g(t,e)},[g]),w=`${e.route.split(`/`).pop()??`note`}.md`,T=e.sections.slice(1).map((e,t)=>(0,W.jsx)(ZZ,{section:e,idx:t,blockId:e.id,keySuffix:`scroll`,isActive:!1,hasViewDef:!1,deps:b,onExampleSelect:x,selectedExampleIndex:0,challengeQuests:v.quests,onScrollToSection:r},e.id));return(0,W.jsxs)(`div`,{className:`flex flex-col min-h-screen bg-background`,"data-testid":`scroll-canvas-page`,children:[h.fullscreen?.kind===`timer`&&(0,W.jsx)(`div`,{className:`sticky z-30 border-b border-border bg-background`,style:{top:_},children:(0,W.jsx)(`div`,{className:`mx-auto h-[max(320px,min(75vh,640px))] max-w-5xl px-4 py-2`,children:(0,W.jsx)(QG,{block:h.fullscreen.block,onClose:h.closeRun,autoStart:!0,externalStop:h.resetRequested,onComplete:(e,t)=>{h.handleWorkoutComplete(t)}})})}),(0,W.jsx)(XQ,{spec:i,wodFiles:t,theme:n,noteTitle:w,showFrontmatter:e.frontmatter.showFrontmatter===!0,doc:c,onDocChange:l,onBlocksChange:S,onStageEnter:p,onRun:C}),T]})}async function QQ({workoutName:e,category:t,sourceNoteLabel:n,sourceNotePath:r,wodContent:i,date:a,wrapInWod:o=!0}){let s=PN(a??new Date),c=r?.trim()||`/collections/${encodeURIComponent(t)}`,l=[`# ${e}`,``];return o?l.push("```time",i.trimEnd(),"```"):l.push(i.trimEnd()),l.push(``),BN.create({journalDate:s,title:NN(e),rawContent:l.join(`
164
+ `),sourceId:c})}function $Q(){let[e,t]=Gt(`s`,{defaultValue:``,shallow:!0,history:`replace`}),n=(0,U.useMemo)(()=>{if(e){let t=new Date(e+`T00:00:00`);if(!isNaN(t.getTime()))return t}return null},[e]),r=(0,U.useCallback)(e=>{if(!e)t(``);else{let n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,`0`),i=String(e.getDate()).padStart(2,`0`);t(`${n}-${r}-${i}`)}},[t]),[i,a]=Gt(`feed`,{defaultValue:``,shallow:!0,history:`replace`}),o=(0,U.useCallback)(e=>{a(t=>t===e?``:e)},[a]),s=(0,U.useCallback)(()=>a(``),[a]);return{dateParam:e,selectedDate:n,setSelectedDate:r,setDateParam:t,selectedFeed:i||null,selectFeed:o,clearFeed:s}}function e$({dateKeys:e,items:t,journalEntries:n,onSelectItem:r,onOpenEntry:i,onAddToToday:a,className:o}){let s=(0,U.useMemo)(()=>{let e=new Map;for(let n of t){let t=e.get(n.feedDate)??[];t.push(n),e.set(n.feedDate,t)}return e},[t]);return e.length===0?(0,W.jsxs)(`div`,{className:G(`flex flex-col items-center justify-center py-20 text-muted-foreground/50`,o),children:[(0,W.jsx)(`p`,{className:`text-sm font-medium`,children:`No feed content found.`}),(0,W.jsx)(`p`,{className:`text-xs mt-1`,children:`Feed workouts will appear here once content is available.`})]}):(0,W.jsx)(`div`,{className:G(`bg-card flex flex-col`,o),"data-testid":`feed-feed`,children:e.map(e=>{let t=new Date(e+`T00:00:00`),o=s.get(e)??[],c=n.get(e);return(0,W.jsxs)(`div`,{id:e,className:`flex flex-col`,children:[(0,W.jsxs)(`div`,{className:`sticky z-[5] px-6 py-2 bg-muted/80 backdrop-blur-sm border-y border-border flex items-center gap-2 top-0`,children:[(0,W.jsx)(zt,{className:`size-3 text-muted-foreground flex-shrink-0`}),(0,W.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,children:zO(t)})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-0 pb-1`,children:[c&&(0,W.jsxs)(`button`,{onClick:()=>i?.(e),className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group`,children:[(0,W.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors`,children:(0,W.jsx)(u,{className:`size-4 text-primary`})}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate`,children:c.title}),(0,W.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium`,children:`Journal note`})]}),(0,W.jsx)(Qt,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]}),o.map(e=>(0,W.jsxs)(`div`,{className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/30 transition-colors cursor-pointer group`,onClick:()=>r(e),children:[(0,W.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors`,children:(0,W.jsx)(`span`,{className:`text-[10px] font-black text-primary`,children:`WOD`})}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-semibold text-foreground truncate`,children:e.name}),(0,W.jsx)(`p`,{className:`text-[11px] text-muted-foreground font-medium mt-0.5`,children:e.feedName})]}),a&&(0,W.jsxs)(`button`,{onClick:t=>{t.stopPropagation(),a(e)},title:`Add to today's journal`,className:G(`flex items-center gap-1 rounded-full border border-border px-2.5 py-1`,`text-[10px] font-black uppercase tracking-widest text-muted-foreground`,`hover:text-primary hover:border-primary/50 transition-colors shrink-0`,`opacity-0 group-hover:opacity-100`),children:[(0,W.jsx)(En,{className:`size-3`}),`Today`]}),(0,W.jsx)(Qt,{className:`size-4 text-muted-foreground/40 group-hover:text-primary transition-colors flex-shrink-0`})]},e.id))]})]},e)})})}function t$({feedSlug:e}){let t=ht(),{dateParam:n}=$Q(),r=n&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:null,i=GD(),a=(0,U.useMemo)(()=>i?BV(i).find(t=>t.id===e):void 0,[i,e]),[o,s]=(0,U.useState)(new Map),[c,l]=(0,U.useState)(!0);(0,U.useEffect)(()=>{let e=!1;async function t(){l(!0);try{if(!a)return;let t=Array.from(new Set(a.items.map(e=>e.feedDate))),n=await Promise.all(t.map(async e=>{let t=await LV.getPage(`journal/${e}`).catch(()=>void 0);return t?[e,{title:t.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??e,updatedAt:t.updatedAt}]:null}));if(e)return;let r=new Map;n.forEach(e=>e&&r.set(e[0],e[1])),s(r)}catch{}finally{e||l(!1)}}return t(),()=>{e=!0}},[a]);let u=(0,U.useMemo)(()=>a?a.items.map(e=>({id:e.id,feedId:a.id,feedName:a.name,feedDate:e.feedDate,name:e.name,content:e.content,path:e.path})):[],[a]),d=(0,U.useMemo)(()=>{if(r)return[r];let e=new Set(u.map(e=>e.feedDate));return Array.from(e).sort().reverse()},[r,u]),f=(0,U.useCallback)(async e=>{try{let n=await QQ({workoutName:e.name,category:e.feedId,sourceNoteLabel:e.feedName,sourceNotePath:`/feeds/${encodeURIComponent(e.feedId)}/${e.feedDate}/${encodeURIComponent(e.id)}`,wodContent:e.content,wrapInWod:!1}),r=WO(new Date);Q({title:`Added to journal`,description:n.journalDate===r?`Added to today's journal`:`Added to ${n.journalDate}`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>t(BM(n.journalDate??r)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[t]),p=(0,U.useCallback)(e=>{t(`/feeds/${encodeURIComponent(e.feedId)}/${e.feedDate}/${encodeURIComponent(e.id)}`)},[t]),m=(0,U.useCallback)(e=>{t(`/journal/${e}`)},[t]);return a?c?(0,W.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-20 text-sm font-medium text-muted-foreground`,children:`Loading…`}):(0,W.jsx)(e$,{dateKeys:d,items:u,journalEntries:o,onSelectItem:p,onOpenEntry:m,onAddToToday:f}):(0,W.jsxs)(`div`,{className:`flex flex-1 items-center justify-center p-20 text-sm text-muted-foreground`,children:[`Feed not found: `,e]})}var n$=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function r$(e,t){return new Date(e,t+1,0).getDate()}function i$(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function a$(e,t,n){return`${e}-${String(t+1).padStart(2,`0`)}-${String(n).padStart(2,`0`)}`}function o$(e){return a$(e.getFullYear(),e.getMonth(),e.getDate())}var s$=({selectedDate:e,onDateSelect:t,entryDates:n=new Set,disabled:r=!1,className:i})=>{let[a,o]=(0,U.useState)(()=>e||new Date),s=a.getFullYear(),c=a.getMonth();(0,U.useEffect)(()=>{e&&o(t=>t.getFullYear()!==e.getFullYear()||t.getMonth()!==e.getMonth()?new Date(e.getFullYear(),e.getMonth(),1):t)},[e]);let l=e?o$(e):null,u=(0,U.useMemo)(()=>{let e=r$(s,c),t=i$(s,c),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[s,c]),d=e=>{e.stopPropagation(),e.preventDefault(),o(new Date(s,c-1,1))},f=e=>{e.stopPropagation(),e.preventDefault(),o(new Date(s,c+1,1))},p=a.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),m=o$(new Date);return(0,W.jsxs)(`div`,{className:G(`select-none px-2 py-2`,r&&`opacity-60 cursor-not-allowed`,i),onClick:e=>e.stopPropagation(),"aria-disabled":r||void 0,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,W.jsx)(`button`,{onClick:d,disabled:r,className:`p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none`,"aria-label":`Previous month`,children:(0,W.jsx)(_t,{className:`h-4 w-4`})}),(0,W.jsx)(`span`,{className:`text-sm font-medium text-foreground`,children:p}),(0,W.jsx)(`button`,{onClick:f,disabled:r,className:`p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none`,"aria-label":`Next month`,children:(0,W.jsx)(Qt,{className:`h-4 w-4`})})]}),(0,W.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 mb-1`,children:n$.map(e=>(0,W.jsx)(`div`,{className:`text-center text-[10px] text-muted-foreground font-medium py-0.5 w-8`,children:e},e))}),(0,W.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:u.map((e,i)=>{if(e===null)return(0,W.jsx)(`div`,{className:`w-8 h-8`},`empty-${i}`);let a=a$(s,c,e),o=n.has(a),u=a===l;return(0,W.jsxs)(`button`,{disabled:r,onClick:n=>{n.stopPropagation(),n.preventDefault(),t(new Date(s,c,e),n.ctrlKey||n.metaKey)},className:G(`w-8 h-8 flex items-center justify-center rounded text-xs transition-colors relative`,`disabled:pointer-events-none`,u?`bg-primary text-primary-foreground font-bold`:a===m?`font-bold text-primary ring-1 ring-primary/40`:o?`font-semibold text-foreground hover:bg-muted`:`text-muted-foreground hover:bg-muted/50`),"aria-label":`${e} ${p}${o?` (has entries)`:``}`,children:[e,o&&!u&&(0,W.jsx)(`span`,{className:`absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary/60`})]},a)})})]})};function c$({onSave:e,getSnapshotKey:t,onError:n}){let r=(0,U.useRef)(null),i=(0,U.useRef)(null),a=(0,U.useRef)(null),o=(0,U.useRef)(Promise.resolve()),s=(0,U.useRef)({onSave:e,getSnapshotKey:t,onError:n});s.current={onSave:e,getSnapshotKey:t,onError:n};let[c,l]=(0,U.useState)(null),u=(0,U.useCallback)(e=>{let t=o.current.then(async()=>{e.key!==i.current&&(await s.current.onSave(e.value),i.current=e.key,l(null))});return o.current=t.catch(e=>{l(e),s.current.onError?.(e)}),t},[]),d=(0,U.useCallback)(()=>r.current?u(r.current):o.current,[u]),f=(0,U.useCallback)(e=>{let t=s.current.getSnapshotKey?.(e)??(typeof e==`string`?e:JSON.stringify(e));r.current={value:e,key:t}},[]),p=(0,U.useCallback)((e,t)=>{a.current!==null&&a.current!==e&&d().catch(()=>{}),a.current=e},[d]),m=(0,U.useCallback)(()=>{d().catch(()=>{})},[d]);return(0,U.useEffect)(()=>{let e=()=>{d().catch(()=>{})},t=()=>{document.visibilityState===`hidden`&&e()};return window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`pagehide`,e),document.removeEventListener(`visibilitychange`,t),d().catch(()=>{})}},[d]),{onChange:f,onLineChange:p,onBlur:m,flush:d,error:c}}var l$=8e3;function u$({category:e,name:t,mdContent:n,seedOnMount:r=!0}){let i=MV(e,t),[a,o]=(0,U.useState)(n),[s,c]=(0,U.useState)(!0),[l,u]=(0,U.useState)(),[d,f]=(0,U.useState)({}),[p,m]=(0,U.useState)(0),[h,g]=(0,U.useState)(null),_=(0,U.useRef)({id:i,revision:0}),v=(0,U.useRef)(i);v.current=i;let y=(0,U.useRef)({rawContent:n,noteBlocks:{},sourceRevision:0}),b=(0,U.useCallback)(e=>{_.current.revision=e.sourceRevision,m(e.sourceRevision),y.current.rawContent===e.rawContent&&Object.keys(y.current.noteBlocks).length===Object.keys(e.blocks).length&&Object.values(y.current.noteBlocks).every(t=>{let n=e.blocks[t.id];return n&&n.from===t.from&&n.to===t.to&&n.kind===t.kind})&&(y.current={rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision},f(e.blocks))},[]),x=c$({onSave:(0,U.useCallback)(async e=>{if(e.routeId===v.current&&h)throw h;let t=await DN.saveNote({noteId:e.noteId,rawContent:e.rawContent,blocks:e.noteBlocks,expectedSourceRevision:_.current.id===e.noteId?_.current.revision:e.sourceRevision,metadata:{title:e.title},noteType:`playground`});v.current===e.routeId&&(_.current.id=t.id,u(t.id),b({rawContent:t.rawContent,blocks:t.blocks??{},sourceRevision:t.sourceRevision??1}))},[b,h]),getSnapshotKey:e=>JSON.stringify([e.noteId,e.rawContent,Object.values(e.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])])});(0,U.useEffect)(()=>{let e=!1;_.current={id:i,revision:0},c(!0),g(null);let a=Na(n,{sourceRevision:1,registeredWidgets:Da}),s=(e,t,n,r)=>{o(e),f(t),m(n),u(r),_.current={id:r??i,revision:n},y.current={rawContent:e,noteBlocks:t,sourceRevision:n}},l=setTimeout(()=>{e||(e=!0,s(n,a,0),g(Error(`Note load timed out. Reload before saving to avoid overwriting stored content.`)),c(!1))},l$);return(async()=>{try{let o=await LV.getPage(i);if(e)return;if(o)s(o.content,o.noteBlocks??{},o.sourceRevision??1,o.id);else if(r){let r=await DN.saveNote({noteId:i,rawContent:n,blocks:a,expectedSourceRevision:0,metadata:{title:t},noteType:`playground`});e||s(r.rawContent,r.blocks??{},r.sourceRevision??1,r.id)}else s(n,a,0)}catch(t){e||(s(n,a,0),g(t))}finally{clearTimeout(l),e||c(!1)}})(),()=>{e=!0,clearTimeout(l)}},[i,n,t,r]);let S=(0,U.useCallback)(e=>{(y.current.rawContent!==e.rawContent||JSON.stringify(Object.values(y.current.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])))&&(y.current=e,o(e.rawContent),f(e.noteBlocks),x.onChange({...e,routeId:i,noteId:_.current.id,title:t}))},[x.onChange,i,t]),C=(0,U.useCallback)(e=>{if(o(e),y.current.rawContent===e)return;let t=Na(e,{sourceRevision:_.current.revision||1,registeredWidgets:Da});S({rawContent:e,noteBlocks:t,sourceRevision:_.current.revision})},[S]),w=(0,U.useCallback)(async()=>{S({rawContent:n,sourceRevision:_.current.revision,noteBlocks:Na(n,{sourceRevision:_.current.revision||1,registeredWidgets:Da})}),await x.flush()},[n,S,x.flush]),T=(0,U.useCallback)(()=>_.current.revision,[]);return{content:a,loading:s,entryId:l,noteBlocks:d,sourceRevision:p,onIdentityChange:S,onSaved:b,onChange:C,onLineChange:x.onLineChange,onBlur:x.onBlur,flush:x.flush,committedSourceRevision:T,resetToOriginal:w,isModified:a!==n,error:x.error??h}}var d$=new Map,f$=new Map;function p$(e){f$.set(e.runtimeId,e)}function m$(e){let t=f$.get(e);return t&&f$.delete(e),t}function h$(e){for(let t of f$.values())if(t.journalDate===e)return t}function g$(e){f$.delete(e)}function _$(e,t,n){let r=t?e.filter(e=>e.blockId===t):e;if(r.length===0)return{current:[],currentVersion:0,history:new Map};let i=new Map;for(let e of r){let t=e.blockVersion;i.has(t)||i.set(t,[]),i.get(t).push(e)}let a=[],o=0;for(let[e,t]of i)t.some(e=>e.blockContentId===n)&&(e>o?(o=e,a.length=0,a.push(...t)):e===o&&a.push(...t));let s=new Map;for(let[e,t]of i)e!==o&&s.set(e,{version:e,contentId:t[0]?.blockContentId,results:t});return{current:a,currentVersion:o,history:s}}function v$(e,t,n,r,i){let a=e.map(e=>{if(e.type!==`time`&&e.type!==`log`)return e;let i=parseInt(e.id.replace(`${e.type}-line-`,``),10),a=t.find(e=>e.startLine+1===i),o={};if(r&&a){let{current:e}=_$(r,a.id,a.contentId);o={hasResult:e.length>0,resultCount:e.length}}return e.type===`log`||!n?{...e,...o}:{...e,...o,onRun:()=>{let e=a||t.find(e=>e.startLine+1===i)||t[0];e&&n(e)}}});if(i){let e=a.findIndex(e=>e.type===`heading`),t=e===-1?0:e;if(a[t])return a.map((e,n)=>n===t?{...e,onRun:i,runIcon:`edit`}:e)}return a}function y$({content:e,scriptBlocks:t,onStartWorkout:n,results:r,onEditNote:i}){let a=(0,U.useMemo)(()=>v$(vH(e),t,n,r,i),[e,t,n,r,i]),{setL3Items:o}=lM();return(0,U.useEffect)(()=>(o(yH(a)),()=>o([])),[a,o]),a}function b$(e){switch(e.kind){case`journal`:return BM(e.id);case`playground`:return RM(e.id);case`workout`:return e.category===`effort`?nN(e.id):e.category===`equipment`?QM(e.id):e.category?GM(e.category,e.id):VM(e.raw)}}function x$(e){let t=eR(e);return t.kind===`workout`&&!t.category?VM(e):b$(t)}var S$={efforts:[],related:[],backlinks:[]},C$=8;function w$(e){let t=e.id,n=e.type===`playground`||e.sourceId===`playground`||t.startsWith(`playground/`),r=eR(t);if(e.type===`journal`||e.journalDate||!n&&r.kind===`journal`){let n=e.journalDate??(r.kind===`journal`?r.id:void 0);return{zone:`journal`,up:n?{id:n,title:`Journal`,to:zM(n)}:null,stamps:[t]}}if(n||r.kind===`playground`){let e=dR({id:t});return{zone:`playgrounds`,up:{id:`playgrounds`,title:`Playgrounds`,to:XM()},stamps:[`/playground/${e}`]}}if(r.kind===`workout`){if(r.category===`effort`)return{zone:`efforts`,up:{id:`efforts`,title:`Efforts`,to:ZM()},stamps:[nN(r.id)]};if(r.category===`equipment`)return{zone:`equipment`,up:{id:`equipment`,title:`Equipment`,to:$.equipment},stamps:[QM(r.id)]};if(r.category===`feeds`){let[,e,n,r]=t.split(`/`);return{zone:`feeds`,up:e?{id:e,title:e,to:UM(e)}:null,stamps:e&&n&&r?[`/feeds/${e}/${n}/${r}`]:[]}}if(r.category)return{zone:`feeds`,up:{id:r.category,title:r.category,to:WM(r.category)},stamps:[GM(r.category,r.id)]}}if(e.type===`page`&&(e.pageId??e.slug)){let t=e.pageId??e.slug;return{zone:null,up:{id:t,title:`/p/${t}`,to:YM(t)},stamps:[]}}return{zone:null,up:null,stamps:[]}}function T$(e){if(!e.startsWith(`/`))return null;let t=e.split(`#`)[0],n=t.replace(/\/+$/,``).split(`/`).filter(Boolean),r=n[n.length-1];if(r)try{r=decodeURIComponent(r)}catch{}return{id:t,title:r||t,to:t}}function E$(e,t){let n=new Set,r=[];for(let i of e){if(!i.effortSlug||n.has(i.effortSlug))continue;n.add(i.effortSlug);let e=!t||t.has(i.effortSlug);r.push({id:i.effortSlug,title:i.effortSlug,to:e?nN(i.effortSlug):`${ZM()}?q=${encodeURIComponent(i.effortSlug)}`})}return r}function D$(e,t,n=C$){let r=new Set(e.filter(e=>e.noteId===t&&e.dataType===`wod`&&e.blockContentId).map(e=>e.blockContentId));if(r.size===0)return[];let i=new Map;for(let a of e)if(a.dataType===`wod`&&!(!a.blockContentId||!r.has(a.blockContentId)||a.noteId===t)&&!i.has(a.noteId)&&(i.set(a.noteId,{id:a.noteId,title:a.noteTitle||a.noteId,to:x$(a.noteId)}),i.size>=n))break;return[...i.values()]}function O$(e,t,n){if(t.length===0)return[];let r=e.filter(e=>e.id!==n&&!!e.sourceId&&t.some(t=>e.sourceId===t||e.sourceId.startsWith(`${t}#`)));return r.sort((e,t)=>t.createdAt-e.createdAt),r.map(e=>({id:e.id,title:e.title||e.id,to:x$(e.id)}))}function k$(e,t){let n=new Map;for(let r of e)r.noteId===t||n.has(r.noteId)||n.set(r.noteId,{id:r.noteId,title:r.noteId,to:x$(r.noteId)});return[...n.values()]}function A$({noteId:e,stamps:t,effortSlug:n}){let r=t.join(`
165
+ `),[i,a]=(0,U.useState)({key:``,data:S$}),o=`${e}\u0000${r}\u0000${n??``}`,s=i.key===o?i.data:S$;return(0,U.useEffect)(()=>{let t=!1,i=r?r.split(`
166
+ `):[];return Promise.all([Z.getAllFromIndex(`block_efforts`,`by-note`,e),Z.getAllFromIndex(`block_index`,`by-note`,e),Z.getAllNotes(),Z.getAllEfforts(),n?Z.getAllFromIndex(`block_efforts`,`by-effort`,n):Promise.resolve([])]).then(async([r,a,o,s,c])=>{if(t)return S$;let l=new Set(s.map(e=>e.slug)),u=[...new Set(a.filter(e=>e.dataType===`wod`&&e.blockContentId).map(e=>e.blockContentId))],d=await Promise.all(u.map(e=>Z.getAllFromIndex(`block_index`,`by-content`,e)));if(t)return S$;let f=D$([...a,...d.flat()],e);if(n){let t=new Set(f.map(e=>e.id));for(let n of k$(c,e))t.has(n.id)||(t.add(n.id),f.push(n))}return{efforts:E$(r,l),related:f,backlinks:O$(o,i,e)}}).then(e=>{!t&&e&&a({key:o,data:e})}).catch(()=>{}),()=>{t=!0}},[e,r,n,o]),s}function j$({data:e,up:t,source:n,relatedLabel:r=`Related workouts`}){let{setContextNav:i}=lM(),a=Xt();return(0,U.useEffect)(()=>{let o=[],s=(e,t,n)=>{n.length!==0&&o.push({kind:`section`,id:e,label:t,entries:n.map(t=>({kind:`link`,id:`${e}:${t.id}`,label:t.title,to:t.to}))})};return s(`note-context-up`,`Up`,t?[t]:[]),s(`note-context-source`,`Source`,n?[n]:[]),s(`note-context-efforts`,`Efforts`,e.efforts),s(`note-context-backlinks`,`Journal copies`,e.backlinks),s(`note-context-related`,r,e.related),i({pathname:a.pathname,spec:o}),()=>i(void 0)},[e,t,n,r,a.pathname,i]),null}function M$(e,t){return(0,U.useMemo)(()=>{let n=[];return t.onPlay&&(e===`playground`||e===`journal-active`||e===`collection-readonly`)&&n.push({id:`play`,label:`Play`,icon:(0,W.jsx)(rn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:t.onPlay}),t.onLog&&(e===`playground`||e===`journal-active`||e===`collection-readonly`)&&n.push({id:`log`,label:`Log`,icon:(0,W.jsx)(Be,{className:`h-3 w-3`}),primary:!0,onClick:t.onLog}),t.onOpenInPlayground&&(e===`journal-plan`||e===`collection-readonly`)&&n.push({id:`open-in-playground`,label:`Playground`,icon:(0,W.jsx)(o,{className:`h-3 w-3`}),onClick:t.onOpenInPlayground}),t.onShare&&n.push({id:`share`,label:`Share`,icon:(0,W.jsx)(_,{className:`h-3 w-3`}),onClick:t.onShare}),t.onAddToToday&&e===`playground`&&n.push({id:`add-to-today`,label:`Today`,icon:(0,W.jsx)(ve,{className:`h-3 w-3`}),onClick:t.onAddToToday}),t.onSchedule&&n.push({id:`schedule`,label:`Schedule`,icon:(0,W.jsx)(ke,{className:`h-3 w-3`}),onClick:t.onSchedule}),n},[e,t.onPlay,t.onLog,t.onShare,t.onAddToToday,t.onSchedule,t.onOpenInPlayground])}async function N$(e){let t=new TextEncoder().encode(e),n=new CompressionStream(`gzip`),r=n.writable.getWriter(),i=n.readable.getReader();r.write(t),r.close();let a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;let l=``;for(let e=0;e<s.length;e++)l+=String.fromCharCode(s[e]);return btoa(l).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}async function P$(e,t){let n=e.dialect||`time`,r=await N$(`\`\`\`${e.sport?`${n}:${e.sport}`:n}\n${e.content.trimEnd()}\n\`\`\`\n`),i=`${window.location.origin}${qM({zip:r})}`;return t?`${i}&src=${encodeURIComponent(t)}`:i}async function F$(e,t){let n=await P$(e,window.location.pathname),{pathname:r,search:i}=new URL(n);t(`${r}${i}`)}async function I$(e){let t=await P$(e,window.location.pathname);window.open(t,`_blank`)}async function L$(e){let t=e.dialect||`time`,n=await N$(`\`\`\`${e.sport?`${t}:${e.sport}`:t}\n${e.content.trimEnd()}\n\`\`\`\n`),r=`shared by ${yb()}`;return`${window.location.origin}/?z=${n}&by=${encodeURIComponent(r)}`}function R$(e){L$(e).then(e=>{navigator.clipboard.writeText(e).then(()=>{Q({title:`Link copied`,description:`Share link copied to clipboard.`})}).catch(()=>{Q({title:`Could not copy`,description:e,variant:`destructive`})})})}function z$(e=`end`){let t=(0,U.useRef)(null),[n,r]=(0,U.useState)(e);return{triggerRef:t,align:n,recompute:(0,U.useCallback)(()=>{let e=t.current;if(!e)return;let{left:n,right:i}=e.getBoundingClientRect(),a=(n+i)/2;r(a>window.innerWidth/2?`end`:`start`)},[])}}function B$(e,t){if(t){t();return}let n=new Blob([e.content],{type:`text/markdown`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e.name.replace(/[/\\:*?"<>|]/g,`-`)}.md`,i.click(),URL.revokeObjectURL(r)}function V$({currentWorkout:e,onDownload:t}){return e.content===``?null:(0,W.jsxs)(`button`,{type:`button`,onClick:()=>B$(e,t),className:`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,W.jsx)(Be,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:`Download Markdown`})]})}function H$(e,t,n){let r=ht(),{l3Items:i,scrollToSection:a,secondarySpec:o,streamControls:s}=lM(),c=t&&t.length>0?t:i,l=FR(o),u=[];s&&u.push({kind:`custom`,id:`l3-stream-controls`,nav:!0,render:()=>(0,W.jsx)(lB,{streamControls:s})});for(let e of l)if(e.kind===`section`){if(e.entries.length===0)continue;u.push({kind:`heading`,id:e.id,label:e.label,nav:!0});for(let t of e.entries)u.push({kind:`row`,id:t.id,label:t.label,nav:!0,onSelect:()=>{t.onRun?t.onRun():t.to?r(t.to):t.sectionId&&a(t.sectionId)}})}else u.push({kind:`row`,id:e.id,label:e.label,nav:!0,onSelect:()=>{e.onRun?e.onRun():e.to?r(e.to):e.sectionId&&a(e.sectionId)}});if(c.length>0){u.push({kind:`heading`,id:`on-this-page`,label:`On this page`,nav:!0});for(let e of c)u.push({kind:`row`,id:e.id,label:e.label,nav:!0,secondary:e.secondaryAction?{label:e.secondaryAction.label,icon:e.secondaryAction.icon&&(0,W.jsx)(e.secondaryAction.icon,{className:`size-3.5`}),onSelect:()=>{e.secondaryAction?.action.type===`call`&&e.secondaryAction.action.handler()}}:void 0,onSelect:()=>{e.action.type===`call`?e.action.handler():a(e.id)}})}return e.content!==``&&u.push({kind:`row`,id:`download-markdown`,label:`Download Markdown`,icon:(0,W.jsx)(Be,{className:`size-4`}),nav:!1,onSelect:()=>B$(e,n)}),u}function U$({currentWorkout:e,onDownload:t,items:n}){let r=H$(e,n,t),i=e=>e.kind===`heading`?(0,W.jsx)(Jz,{children:e.label},e.id):e.kind===`custom`?(0,W.jsx)(`div`,{className:`px-1 py-1`,children:e.render()},e.id):(0,W.jsxs)(Gz,{onClick:e.onSelect,className:`gap-2`,children:[e.icon,(0,W.jsx)(`span`,{className:G(`flex-1 truncate`,e.secondary&&`pr-8`),children:e.label}),e.secondary&&(0,W.jsx)(`button`,{className:`ml-auto flex items-center justify-center size-5 rounded text-primary hover:bg-primary/10 transition-colors`,title:e.secondary.label,onClick:t=>{t.stopPropagation(),e.secondary?.onSelect()},children:e.secondary.icon})]},e.id),a=r.filter(e=>e.nav),o=r.filter(e=>!e.nav);return r.length===0?null:(0,W.jsxs)(Hz,{children:[(0,W.jsx)(Uz,{asChild:!0,children:(0,W.jsxs)(K,{variant:`ghost`,size:`icon`,"aria-label":`Page options`,className:G(`text-muted-foreground`,`2xl:hidden`),children:[(0,W.jsx)(he,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Page options`})]})}),(0,W.jsxs)(Wz,{align:`end`,className:`min-w-56 max-h-[calc(100dvh-6rem)] overflow-y-auto`,children:[a.length>0&&(0,W.jsxs)(`div`,{className:`2xl:hidden`,children:[a.map(i),(0,W.jsx)(qz,{})]}),o.map(i)]})]})}var W$=gH("# My Workout\n\n```time\n$CURSOR\n```\n"),G$={content:W$.content,cursorOffset:W$.cursorOffset};function K$({mode:e,currentWorkout:t,index:n,onReset:r}){let i=ht(),[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(!1),l=OB(),u=gB(),d=l&&u;return d&&e!==`playground`?null:(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[e===`playground`&&(0,W.jsx)(kq,{primary:{id:`new-playground`,label:a?`Creating…`:`New`,icon:ve,action:{type:`call`,handler:async()=>{if(!a){o(!0);try{let e=await hK(G$.content);i(`/playground/${encodeURIComponent(e)}`)}finally{o(!1)}}}}},secondary:{id:`reset-playground`,label:s?`Resetting…`:`Reset to default`,icon:We,action:{type:`call`,handler:async()=>{if(!(!r||s)){c(!0);try{await r()}finally{c(!1)}}}}},size:`sm`}),!d&&(0,W.jsx)(lV,{}),!d&&(0,W.jsx)(rX,{}),!d&&(0,W.jsx)(U$,{currentWorkout:t,items:n&&n.length>0?yH(n):void 0})]})}function q$({feedSlug:e,feedDate:t,feedItem:n,theme:r,onViewCreated:i}){let a=ht(),o=GD(),{item:s,feed:c}=(0,U.useMemo)(()=>{if(!o)return{item:void 0,feed:void 0};let r=BV(o).find(t=>t.id===e);return{item:r?.items.find(e=>e.feedDate===t&&e.id===n),feed:r}},[o,e,t,n]),{content:l,noteBlocks:u,sourceRevision:d,onIdentityChange:f,onSaved:p,onChange:m,onLineChange:h,onBlur:g,flush:_}=u$({category:`feed/${e}/${t}`,name:n,mdContent:s?.content??`# ${n}\n\n*Feed item not found.*\n`,seedOnMount:!1}),[v,y]=(0,U.useState)([]),b=`feed/${e}/${t}/${n}`,x=(0,U.useCallback)(async r=>{try{let i=w(),o=await QQ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content}),l=Object.values(o.blocks??{}).find(e=>e.kind===`wod`);if(!l)throw Error(`The saved journal workout is unavailable.`);d$.set(i,{block:{...r,id:l.id},noteId:o.id}),a(HM(o.journalDate??``,i))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[c,t,n,e,s,a,b]),S=(0,U.useCallback)(async r=>{try{let i=await QQ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content}),o=WO(new Date);Q({title:`Added to journal`,description:i.journalDate===o?`Added to today's journal`:`Added to ${i.journalDate}`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>a(BM(i.journalDate??o)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[c,t,n,e,s,a]),[C,T]=(0,U.useState)(null),E=(0,U.useCallback)(async(r,i)=>{let o=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,`0`)}-${String(i.getDate()).padStart(2,`0`)}`;try{await QQ({workoutName:s?.name??n,category:e,sourceNoteLabel:c?.name,sourceNotePath:`/feeds/${encodeURIComponent(e)}/${t}/${encodeURIComponent(n)}`,wodContent:r.content,date:i}),a(BM(o)),Q({title:`Scheduled`,description:`Added to journal for ${o}`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>a(BM(o)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[c,t,n,e,s,a]),D=y$({content:l,scriptBlocks:v,onStartWorkout:x}),O=`feeds/${e}/${t}/${n}`,k=(0,U.useMemo)(()=>w$({id:O,type:`collection`}),[O]),A=A$({noteId:O,stamps:k.stamps}),j=M$(`collection-readonly`,{onPlay:x,onShare:R$,onAddToToday:S,onSchedule:T,onOpenInPlayground:e=>F$(e,a)});return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(Lz,{title:s?.name??n,actions:(0,W.jsx)(kB,{label:`Workout actions`,children:(0,W.jsx)(K$,{mode:`collection-readonly`,currentWorkout:{name:s?.name??n,content:l},index:D})}),editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,W.jsx)(j$,{data:A,up:k.up}),(0,W.jsx)(OX,{value:l,onChange:m,onCursorPositionChange:h,onBlur:g,noteId:b,noteBlocks:u,sourceRevision:d,onIdentityChange:e=>f({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:p,onSaveRequest:_,onCommitChange:_,commands:j,enableInlineRuntime:!1,onViewCreated:i,theme:r,showLineNumbers:!1,onBlocksChange:y})]})}),C&&(0,W.jsx)(HS,{open:!0,onClose:()=>T(null),title:`Schedule workout`,children:(0,W.jsx)(s$,{selectedDate:null,onDateSelect:e=>{E(C,e),T(null)}})})]})}function J$(e,t){if(e.startsWith(`# 👋`))return e;let n=t?.replace(/^shared by:?\s*/i,``).trim();return`${n?`# 👋 ${n} sent you this workout`:`# 👋 Edit Me`}\n\nChange the reps, distance, or load below — this is live.\n\n${e}\n\n> Press **Run** ↑ to start the Clock.\n`}var Y$=`wodwiki.homeShared.v1`;function X$(){return typeof window<`u`&&window.localStorage?window.localStorage:null}function Z$(e){try{X$()?.setItem(Y$,JSON.stringify(e)),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`wodwiki:home-shared`,{detail:e}))}catch{}}function Q$(){try{let e=X$()?.getItem(Y$);if(!e)return null;let t=JSON.parse(e);return typeof t?.content==`string`?{content:t.content,by:typeof t.by==`string`?t.by:void 0}:null}catch{return null}}function $$(){try{X$()?.removeItem(Y$)}catch{}}function e1({pageRoute:e,quests:t,running:n}){let{markComplete:r}=OK(e,t),i=(0,U.useMemo)(()=>t.filter(e=>e.validation?.type===`run-started`),[t]);(0,U.useEffect)(()=>{if(n)for(let e of i)r(e.id)},[n,i,r])}var t1={"session-insights":`qs-tour-analytics`},n1={"workout-complete":!0,"run-started":!0};function r1(e,t){let{markComplete:n}=OK(e,t),r=(0,U.useRef)(new Set);return r.current=new Set(t.filter(e=>!e.validation||!n1[e.validation.type]).map(e=>e.id)),(0,U.useCallback)(e=>{let t=t1[e];t&&r.current.has(t)&&n(t)},[n])}var i1=.4;function a1(e){let{dispatch:t}=lM();(0,U.useEffect)(()=>{let n=e.map(e=>document.getElementById(e)).filter(e=>e!==null);if(n.length===0||typeof IntersectionObserver>`u`)return;let r=()=>{let e=window.innerHeight*i1,t=null;for(let r of n){let n=r.getBoundingClientRect();if(n.width!==0||n.height!==0){if(n.top>e)break;t=r.id}}return t},i=new IntersectionObserver(()=>{let e=r();e&&t({type:`SET_ACTIVE_L3`,id:e})},{threshold:Array.from({length:21},(e,t)=>t/20)});return n.forEach(e=>i.observe(e)),()=>i.disconnect()},[e.join(`
167
+ `),t])}var o1=(0,U.createContext)(null);function s1({children:e}){let t=(0,U.useRef)({"editor.window":null,"editor.wodBlock":null,"editor.runButton":null,"editor.typeahead":null,"timer.floor":null,"timer.nextButton":null,"timer.castButton":null,"metrics.efforts":null,"metrics.data":null,"metrics.compound":null,"analytics.vocab":null,"analytics.table":null,"analytics.graphs":null,"analytics.dashboard":null}),[n,r]=(0,U.useState)(0),i=(0,U.useCallback)((e,n)=>{t.current[e]!==n&&(t.current[e]=n,r(e=>e+1))},[]);return(0,W.jsx)(o1.Provider,{value:{register:i,registry:t,version:n},children:e})}function c1(){return(0,U.useContext)(o1)||{registry:{current:{}},register:()=>()=>{},version:0}}function l1(e){let t=(0,U.useContext)(o1)?.register;return(0,U.useCallback)(n=>t?.(e,n),[e,t])}function u1({ringKey:e,el:t}){let{register:n}=c1();return(0,U.useLayoutEffect)(()=>{n(e,t)},[e,t,n]),null}function d1({target:e,accent:t,canvasRef:n}){let{registry:r,version:i}=c1(),[a,o]=(0,U.useState)(null),s=e?.key??null;return(0,U.useLayoutEffect)(()=>{if(!s){o(null);return}let e=()=>{let e=r.current[s],t=n.current;if(!e||!t){o(null);return}let i=e.getBoundingClientRect(),a=t.getBoundingClientRect(),c=Math.round(i.left-a.left),l=Math.round(i.top-a.top),u=Math.round(i.width),d=Math.round(i.height);if(u<=0||d<=0||c+u<0||l+d<0||c>a.width||l>a.height){o(null);return}o({x:c,y:l,w:u,h:d})};e();let t=window.setTimeout(e,120),i=window.setTimeout(e,480),a=null,c=r.current[s];c&&typeof ResizeObserver<`u`&&(a=new ResizeObserver(e),a.observe(c));let l=new MutationObserver(e);return c&&l.observe(c,{attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`resize`,e),()=>{window.clearTimeout(t),window.clearTimeout(i),a?.disconnect(),l.disconnect(),window.removeEventListener(`resize`,e)}},[s,i,r,n]),!e||!a?null:(0,W.jsx)(`div`,{"data-testid":`tour-ring`,className:`pointer-events-none absolute z-30 rounded-2xl transition-all duration-500 ease-out`,style:{left:a.x-6,top:a.y-6,width:a.w+12,height:a.h+12,boxShadow:`0 0 0 2px ${t}`}})}function f1(){return(0,W.jsxs)(`div`,{className:`@container flex w-full flex-col items-center text-center`,children:[(0,W.jsxs)(`h1`,{className:`text-[clamp(32px,6.5cqi,64px)] font-extrabold leading-[1.02] tracking-[-0.04em]`,children:[(0,W.jsxs)(`span`,{className:`block`,children:[(0,W.jsx)(`span`,{className:`mr-[0.35em]`,children:`Write it.`}),(0,W.jsx)(`span`,{children:`Time it.`})]}),(0,W.jsxs)(`span`,{className:`block`,children:[(0,W.jsx)(`span`,{className:`mr-[0.35em]`,children:`Track it.`}),(0,W.jsx)(`span`,{children:`Own it.`})]})]}),(0,W.jsxs)(`p`,{className:`mt-4 xl:mt-6 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[15px] sm:text-base xl:text-lg leading-relaxed text-muted-foreground`,children:[`Plain-text Markdown becomes a step-through workout clock, `,(0,W.jsx)(`br`,{}),`line and splits become queryable training data points.`]})]})}var p1=`dQw4w9WgXcQ`;function m1({onWatched:e}){let[t,n]=(0,U.useState)(!1);return(0,W.jsxs)(`div`,{className:`flex w-full flex-col items-center gap-4 xl:gap-5`,children:[(0,W.jsxs)(`div`,{className:`group relative aspect-video w-full max-w-2xl rounded-xl border border-border bg-black text-left shadow-xl transition-shadow hover:shadow-2xl 2xl:max-w-3xl`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(!0),"data-testid":`tour-why-video`,"aria-label":`Play the Why Wod Wiki? video`,className:`block h-full w-full overflow-hidden rounded-xl`,children:[(0,W.jsx)(`img`,{src:`https://i.ytimg.com/vi/${p1}/hqdefault.jpg`,alt:`Why Wod Wiki? video thumbnail`,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.02]`}),(0,W.jsx)(`span`,{className:`absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-transparent`}),(0,W.jsx)(`span`,{className:`absolute left-1/2 top-1/2 flex size-14 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full bg-background/90 text-foreground shadow-lg transition-transform duration-300 group-hover:scale-110 xl:size-16`,children:(0,W.jsx)(pn,{className:`ml-1 size-6 fill-current xl:size-7`})}),(0,W.jsx)(`span`,{className:`absolute bottom-3 left-4 font-mono text-[11px] uppercase tracking-[0.2em] text-white/90`,children:`Why Wod Wiki? · YouTube`})]}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>{n(!1),e?.()},"data-testid":`tour-why-video-skip`,title:`Skip the video`,"aria-label":`Skip the Why Wod Wiki? video`,className:`absolute right-0 top-0 z-10 flex size-8 items-center justify-center rounded-full border border-border bg-background/90 text-foreground shadow-lg backdrop-blur-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary after:absolute after:-inset-3 after:content-[''] md:-right-2 md:-top-2`,children:(0,W.jsx)(we,{className:`size-4`})})]}),(0,W.jsxs)(`p`,{"data-testid":`tour-scroll-hint`,className:`flex items-center gap-2 font-mono text-[11px] uppercase tracking-[0.3em] text-muted-foreground`,children:[(0,W.jsx)(Cn,{className:`size-4 animate-bounce`}),`Keep scrolling for the demo`]}),t&&(0,W.jsx)(tQ,{videoId:p1,title:`Why Wod Wiki?`,onClose:()=>{n(!1),e?.()}})]})}var h1=`https://github.com/bitcobblers/wod-wiki`;function g1(){return(0,W.jsx)(`footer`,{"data-testid":`tour-footer`,className:`border-t border-border px-6 py-8`,children:(0,W.jsxs)(`p`,{className:`mx-auto flex max-w-3xl flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground`,children:[(0,W.jsxs)(`span`,{children:[`© `,new Date().getFullYear(),` WOD Wiki`]}),(0,W.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,W.jsx)(`a`,{href:h1,target:`_blank`,rel:`noopener noreferrer`,className:`underline-offset-4 transition-colors hover:text-foreground hover:underline`,children:`GitHub repository`})]})})}async function _1(){try{await Z.wipe()}catch{}try{for(let e=localStorage.length-1;e>=0;e--){let t=localStorage.key(e);t&&localStorage.removeItem(t)}}catch{}try{sessionStorage.clear()}catch{}}var v1=`https://github.com/bitcobblers/wod-wiki`,y1=`https://forms.gle/6YHpxwAJh6PAsyAQ6`,b1=`https://app.turso.tech/signup`,x1=`m23.31.803-.563-.42-1.11 1.189-.891-1.286-.512.235.704 1.798-.326.35L18.082 0l-.574.284 2.25 4.836-2.108.741h-.05l-1.143-1.359-1.144 1.36H8.687l-1.144-1.36-1.146 1.363H6.36l-2.12-.745L6.491.284 5.919 0l-2.53 2.668-.327-.349.705-1.798-.512-.236-.89 1.287L1.253.382.69.804 2.42 3.69l-.89.939.311 2.375 2.061.787L3.9 8.817H1.947v.444l.755 1.078 1.197.433v6.971l3.057 4.55L7.657 24l1.101-1.606L9.9 24l.999-1.606L12 24l1.102-1.606L14.1 24l1.141-1.606L16.343 24l.701-1.706 3.058-4.55v-6.972l1.196-.433.756-1.078v-.444h-1.952l.003-1.03 2.054-.784.311-2.375-.89-.939zm-8.93 18.718H8.033l.793-1.615.794 1.615.793-1.083.793 1.083.794-1.083.793 1.083.794-1.083.793 1.083.793-1.615.794 1.615zm3.886-7.39-3.3 1.084-.143 3.061-2.827.627-2.826-.627-.142-3.06-3.3-1.085v-1.635l4.266 1.21-.052 4.126h4.109l-.052-4.127 4.266-1.209z`,S1=[{id:`managed-hosting`,label:`Managed hosting — we run the database.`},{id:`public-profile`,label:`Profile page with a public feed.`},{id:`device-sync`,label:`Sync across your apps and devices.`}],C1=[{id:`coach-views`,label:`Member accounts with coach views.`},{id:`coaches-portal`,label:`Programming dashboards and leaderboards.`},{id:`athlete-portal`,label:`Private journals that roll up to their coach.`},{id:`gym-hosting`,label:`Gym website, competition timers, whiteboard displays.`},{id:`branding`,label:`Your gym's brand on pages and feeds.`}],w1=`underline-offset-4 transition-colors hover:text-foreground hover:underline`;function T1(e){let t=`inline-flex w-fit items-center gap-1.5 font-medium text-foreground underline-offset-4 transition-colors hover:underline`,n=(0,W.jsxs)(W.Fragment,{children:[e.children,(0,W.jsx)(lr,{className:`size-3.5 text-muted-foreground/50`,"aria-hidden":!0})]});return e.href===void 0?e.onClick===void 0?(0,W.jsx)(Nt,{to:e.to,className:t,children:n}):(0,W.jsx)(`button`,{type:`button`,onClick:e.onClick,className:`text-left ${t}`,children:n}):(0,W.jsx)(`a`,{href:e.href,target:`_blank`,rel:`noopener noreferrer`,className:t,children:n})}function E1({children:e}){return(0,W.jsxs)(`li`,{className:`flex gap-2.5 text-sm leading-6 text-muted-foreground`,children:[(0,W.jsx)(`span`,{"aria-hidden":!0,className:`mt-[11px] size-1 shrink-0 rounded-full bg-muted-foreground/50`}),(0,W.jsx)(`span`,{children:e})]})}function D1(){return(0,W.jsx)(`span`,{className:`rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 font-mono text-[11px] font-medium text-emerald-600`,children:`Active`})}function O1(e){return(0,W.jsxs)(`li`,{className:`flex flex-col gap-0.5`,children:[(0,W.jsxs)(`span`,{className:`flex gap-2.5 text-[13px] leading-5 text-muted-foreground`,children:[(0,W.jsx)(`span`,{"aria-hidden":!0,className:`mt-[9px] size-1 shrink-0 rounded-full bg-muted-foreground/50`}),(0,W.jsx)(`span`,{children:e.feature.label})]}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`hosted-interest-${e.feature.id}`,onClick:()=>e.onInterested(e.feature.id),disabled:e.interested,"aria-pressed":e.interested,className:`ml-[13px] w-fit shrink-0 rounded-full border px-2 py-px text-[11px] font-medium transition-colors ${e.interested?`border-emerald-500/30 bg-emerald-500/10 text-emerald-600`:`border-border text-muted-foreground hover:border-primary/50 hover:text-primary`}`,children:e.interested?`✓ Interested`:`Interested`})]})}function k1(){return(0,W.jsx)(`div`,{role:`status`,"data-testid":`hosted-survey-footer`,className:`mx-auto mt-5 max-w-5xl animate-in fade-in slide-in-from-bottom-4 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-4 duration-500`,children:(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,W.jsx)(Ft,{className:`size-5 shrink-0 text-emerald-600`,"aria-hidden":!0}),(0,W.jsxs)(`div`,{className:`text-sm`,children:[(0,W.jsx)(`p`,{className:`font-medium text-foreground`,children:`Thanks for showing interest — please fill out the survey and give us feedback.`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Opens the interest survey in a new tab.`})]})]}),(0,W.jsxs)(K,{type:`button`,"data-testid":`hosted-survey-button`,onClick:()=>{oK.record(sK.hostedSurveyOpened),window.open(y1,`_blank`,`noopener,noreferrer`)},children:[`Fill out interest survey`,(0,W.jsx)(lr,{className:`size-4`,"aria-hidden":!0})]})]})})}function A1(e){let t=e.icon;return(0,W.jsxs)(`article`,{className:`flex flex-col rounded-xl border border-border p-5 ${e.us?`bg-muted/40`:`bg-background`} ${e.className??``}`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-foreground text-background`,children:(0,W.jsx)(t,{className:`size-5`,"aria-hidden":!0})}),e.badge]}),e.eyebrow&&(0,W.jsx)(`p`,{className:`mt-3.5 font-mono text-[10px] font-semibold uppercase tracking-[0.18em] ${e.us?`text-emerald-600`:`text-muted-foreground`}`,children:e.eyebrow}),(0,W.jsx)(`h3`,{className:`${e.eyebrow?`mt-1`:`mt-4`} text-base font-semibold text-foreground`,children:e.title}),(0,W.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground`,children:e.text}),(0,W.jsx)(`div`,{className:`mt-4 flex flex-1 flex-col gap-2 text-sm`,children:e.children})]})}function j1({label:e,features:t,interested:n,onInterested:r}){return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`p`,{className:`mt-2.5 font-mono text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground first:mt-0`,children:e}),(0,W.jsx)(`ul`,{className:`space-y-2`,children:t.map(e=>(0,W.jsx)(O1,{feature:e,interested:n.has(e.id),onInterested:r},e.id))})]})}function M1(){let[e,t]=(0,U.useState)(!1),n=ht(),[r,i]=(0,U.useState)(new Set),a=e=>{i(t=>t.has(e)?t:new Set(t).add(e)),oK.record(sK.hostedInterestClicked,{feature:e})},[o]=(0,U.useState)(mO),s=o.state===`turso`?`turso`:o.state===`invalid`?`turso-invalid`:`browser`,c=async()=>{window.confirm(`Wipe every note, result, and setting stored in this browser? This cannot be undone.`)&&(t(!0),await _1(),window.location.reload())},l=async()=>{let e=FN(),t=await BN.create({journalDate:e,title:e,rawContent:``});oK.record(sK.noteCreated),n(VM(t.id))},u=s===`turso-invalid`?(0,W.jsx)(`span`,{className:`rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 font-mono text-[11px] font-medium text-amber-600`,children:`Invalid config`}):s===`api`?void 0:(0,W.jsx)(D1,{});return(0,W.jsxs)(`section`,{id:`tour-section-offerings`,"data-testid":`tour-section-offerings`,"aria-label":`You own your data`,children:[(0,W.jsx)(nQ,{index:`04`,before:`Who owns the data? `,accentText:`You!!!`,after:``,accent:iQ.library,blurb:`Run it in your browser, back it up to your own database, or host it on your own server — and if you'd rather hand the caretaking to us, mark the hosted features you want below and the interest survey unlocks.`}),(0,W.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px] px-6 pb-16 pt-10 lg:px-12 xl:px-16`,children:[(0,W.jsxs)(`p`,{className:`mx-auto mb-5 flex max-w-5xl flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground`,role:`status`,children:[(0,W.jsx)(`span`,{children:s===`api`?`Current mode: API server`:s===`turso`?`Current mode: local browser with Turso backup and sync`:s===`turso-invalid`?`Current mode: local browser. Repair the Turso connection to resume sync.`:`Current mode: local browser only`}),(0,W.jsx)(Nt,{to:$.settingsStorage,className:w1,children:`Configure data storage`})]}),(0,W.jsxs)(`div`,{className:`mx-auto grid max-w-5xl grid-cols-1 gap-5 md:grid-cols-3`,children:[(0,W.jsxs)(A1,{icon:R,eyebrow:`You own it`,title:`Playground in your browser`,badge:u,text:`Everything runs locally in this browser's IndexedDB — offline, no account, no server copy.`,children:[(0,W.jsx)(T1,{onClick:()=>void l(),children:`Create your journal`}),(0,W.jsx)(T1,{to:$.playgroundRoot,children:`Start Writing in a Playground`}),(0,W.jsx)(T1,{to:`/feeds`,children:`Explore the notebooks`}),(0,W.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,W.jsx)(E1,{children:`Offline and fast — notes and results never leave this browser by default.`}),(0,W.jsx)(E1,{children:`Tied to this browser — export or back it up before switching browsers or clearing site data.`})]}),(0,W.jsx)(`button`,{type:`button`,onClick:c,disabled:e,className:`mt-1 text-left text-xs text-muted-foreground disabled:opacity-50 ${w1}`,children:e?`Clearing…`:`Clear my data`}),(0,W.jsxs)(`div`,{className:`mt-auto border-t border-border pt-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,W.jsx)(`span`,{className:`mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg border border-border bg-background`,children:(0,W.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,className:`size-4`,"aria-hidden":!0,children:(0,W.jsx)(`path`,{d:x1})})}),(0,W.jsxs)(`div`,{className:`text-sm`,children:[(0,W.jsx)(`p`,{className:`font-medium text-foreground`,children:`Backup & sync, optional`}),(0,W.jsx)(`p`,{className:`text-xs leading-5 text-muted-foreground`,children:`Add a free Turso database you own — committed changes back up in the background; without network you keep working and upload later.`})]})]}),(0,W.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2`,children:[(0,W.jsx)(T1,{href:b1,children:`Create a free Turso account`}),(0,W.jsx)(T1,{to:$.settingsStorage,children:`Configure backup & sync`})]})]})]}),(0,W.jsxs)(A1,{icon:Bn,eyebrow:`You own it`,title:`Self-hosted`,badge:s===`api`?(0,W.jsx)(D1,{}):void 0,text:`Build the app for API storage and run the Wod Wiki server yourself — local or cloud data access through a server you administer.`,children:[(0,W.jsxs)(`ul`,{className:`mt-1 space-y-1.5`,children:[(0,W.jsx)(E1,{children:`Centralized data for a team or gym — one SQLite, Turso, or Postgres backend.`}),(0,W.jsxs)(E1,{children:[`Publish your notebooks as a seed with `,(0,W.jsx)(`code`,{className:`font-mono text-xs`,children:`wod build`}),` — every browser subscribes and syncs.`]}),(0,W.jsx)(E1,{children:`You run the server — network required, and server admin is on you.`})]}),(0,W.jsx)(`div`,{className:`mt-auto border-t border-border pt-4`,children:(0,W.jsx)(T1,{href:v1,children:`View source`})})]}),(0,W.jsxs)(A1,{icon:re,us:!0,eyebrow:`Us — we'd host it`,title:`Wod-Wiki hosted`,text:`Mark the features you want — the survey unlocks below.`,children:[(0,W.jsx)(j1,{label:`Individuals`,features:S1,interested:r,onInterested:a}),(0,W.jsx)(j1,{label:`Coaching & gyms`,features:C1,interested:r,onInterested:a})]})]}),r.size>0&&(0,W.jsx)(k1,{})]})]})}var N1=({doc:e,onDocChange:t,onBlocksChange:n,onRun:r,theme:i,withRingTargets:a=!1})=>{let o=l1(`editor.wodBlock`),s=l1(`editor.runButton`),c=(0,U.useRef)(null),l=(0,U.useRef)(null),[u,d]=(0,U.useState)(null),[f,p]=(0,U.useState)(null),m=(0,U.useCallback)(()=>{if(!a)return null;let e=c.current;if(!e)return null;let t=null,n=e.querySelector(`.cm-wod-fence-open`),r=e.querySelector(`.cm-wod-fence-close`);if(n&&r){let i=e.getBoundingClientRect(),a=n.getBoundingClientRect(),o=r.getBoundingClientRect();if(a.top>=i.top-2&&o.bottom<=i.bottom+2){let n=e.offsetWidth?i.width/e.offsetWidth:1;t={top:(a.top-i.top)/n,left:(Math.min(a.left,o.left)-i.left)/n,width:(Math.max(a.right,o.right)-Math.min(a.left,o.left))/n,height:(o.bottom-a.top)/n}}}d(t);let i=null,o=e.querySelector(`[data-testid="${FH.EDITOR_START_WORKOUT}"]`);if(o){let t=e.getBoundingClientRect(),n=o.getBoundingClientRect();if(n.width>0&&n.height>0&&n.top>=t.top-2&&n.bottom<=t.bottom+2&&n.left>=t.left-2&&n.right<=t.right+2){let r=e.offsetWidth?t.width/e.offsetWidth:1;i={top:(n.top-t.top)/r,left:(n.left-t.left)/r,width:n.width/r,height:n.height/r}}}return p(i),{block:t,run:i}},[a]);(0,U.useLayoutEffect)(()=>{if(!a)return;let e=c.current;if(!e)return;m();let t=window.setTimeout(m,120),n=window.setTimeout(m,480),r=null;if(typeof ResizeObserver<`u`){r=new ResizeObserver(m),r.observe(e);let t=l.current?.contentDOM;t&&r.observe(t)}let i=new MutationObserver(e=>{e.some(e=>e.target instanceof Element&&e.target.closest(`.cm-note-editor`))&&m()});i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`]});let o=0,s=0,u=()=>{m(),performance.now()-s<3e3&&(o=requestAnimationFrame(u))},d=()=>{s=performance.now(),cancelAnimationFrame(o),o=requestAnimationFrame(u)};d(),document.fonts?.ready?.then(d).catch(()=>{});let f=l.current?.scrollDOM;return f?.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m),()=>{window.clearTimeout(t),window.clearTimeout(n),r?.disconnect(),i.disconnect(),f?.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),cancelAnimationFrame(o)}},[e,a,m]);let h=(0,U.useCallback)(()=>{r()},[r]),g=(0,U.useMemo)(()=>[{id:`run`,label:`Run`,icon:(0,W.jsx)(pn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:h},{id:`playground`,label:`Playground`,icon:(0,W.jsx)(Ve,{className:`h-3 w-3`}),onClick:e=>{I$(e)},splitIcon:(0,W.jsx)(An,{className:`h-3 w-3`}),splitSuccessIcon:(0,W.jsx)(Vn,{className:`h-3 w-3 text-emerald-500`}),onSplitClick:e=>{R$(e)}}],[h]);return(0,W.jsx)(`div`,{className:`relative flex h-full flex-col bg-background text-left`,children:(0,W.jsxs)(`div`,{ref:c,className:`relative flex-1 min-h-0`,children:[(0,W.jsx)(OX,{noteId:`canvas:home`,value:e,onChange:t,onBlocksChange:n,onStartWorkout:h,commands:g,onViewCreated:e=>{l.current=e,a&&m()},theme:i,readonly:!1,showLineNumbers:!1,showFrontmatter:!1,enableOverlay:!1,enableInlineRuntime:!1,className:`h-full`}),a&&u&&(0,W.jsx)(`div`,{ref:o,"data-testid":`tour-wod-block-region`,"aria-hidden":!0,className:`pointer-events-none absolute`,style:{top:u.top,left:u.left,width:u.width,height:u.height}}),a&&f&&(0,W.jsx)(`div`,{ref:s,"data-testid":`tour-run-button-region`,"aria-hidden":!0,className:`pointer-events-none absolute`,style:{top:f.top,left:f.left,width:f.width,height:f.height}})]})})};function P1(e){let t=Number.isFinite(e.startTime)?e.startTime:0,n=[],r=[];for(let i of e.logs??[]){if(i.outputType!==`segment`||i.stackLevel!==1||i.line==null)continue;let e=i.timeSpan;if(!e||typeof e.started!=`number`||typeof e.ended!=`number`||e.ended<=e.started)continue;let a=i.metrics??[],o=e=>a.some(t=>t.type===e),s=a.find(e=>e.type===`effort`&&typeof e.value==`string`),c=o(`duration`)&&!o(`rep`)?`clock`:i.completionReason===`user-advance`?`next`:null;if(c){if(c===`clock`&&i.completionReason===`user-advance`){let t=(a.find(e=>e.type===`duration`&&typeof e.value==`number`)?.value??0)-(e.ended-e.started);t>0&&r.push(t)}n.push({start:e.started-t,end:e.ended-t,kind:c,label:s?.value??`Line ${i.line+1}`})}}if(n.length===0)return null;let i=r.reduce((e,t)=>e+t,0);return{segments:n,totalMs:Number.isFinite(e.duration)&&e.duration>0?e.duration:Math.max(...n.map(e=>e.end)),impatienceMs:i,impatiences:r,reactions:n.filter(e=>e.kind===`next`).map(e=>e.end-e.start)}}var F1=e=>{let t=Math.max(0,Math.round(e/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},I1=e=>`${(Math.round(e/100)/10).toFixed(1)}s`;function L1({onRun:e}){return(0,W.jsxs)(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-4 p-8 text-center`,"data-testid":`tour-insights-empty`,children:[(0,W.jsx)(`p`,{className:`max-w-sm text-sm leading-relaxed text-muted-foreground`,children:`Run the workout and this window turns your run into data — rest vs. work, how fast you answered the clock, round by round.`}),(0,W.jsxs)(`button`,{type:`button`,onClick:e,"data-testid":`tour-insights-run`,className:`inline-flex min-h-11 items-center gap-2 rounded-full bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow transition-colors hover:bg-primary/90`,children:[(0,W.jsx)(pn,{className:`size-4`}),`Run to view the results`]})]})}function R1({result:e,onRun:t}){let n=(0,U.useMemo)(()=>e?P1(e):null,[e]);if(!e||!n)return(0,W.jsx)(L1,{onRun:t});let{segments:r,totalMs:i,impatienceMs:a,impatiences:o,reactions:s}=n,c=s.length>0?s.reduce((e,t)=>e+t,0)/s.length:0,l=s.length>0?Math.max(...s):0,u=o.length>0?Math.max(...o):0;return(0,W.jsxs)(`div`,{className:`flex h-full w-full flex-col gap-4 overflow-y-auto p-4`,"data-testid":`tour-insights`,children:[(0,W.jsxs)(`div`,{"data-testid":`tour-insights-timeline`,children:[(0,W.jsx)(`div`,{className:`flex h-3 w-full overflow-hidden rounded-full border border-border/60 bg-muted/40`,children:r.map((e,t)=>(0,W.jsx)(`div`,{title:`${e.label} — ${e.kind===`clock`?`countdown`:`to Next`} ${F1(e.end-e.start)}`,className:`h-full`,style:{flexGrow:e.end-e.start,flexBasis:0,backgroundColor:e.kind===`clock`?`hsl(var(--metric-rest))`:`hsl(var(--metric-time))`,marginLeft:+(t>0)}},t))}),(0,W.jsxs)(`div`,{className:`mt-1.5 flex items-center gap-4 font-mono text-[10px] uppercase tracking-wider text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,W.jsx)(`span`,{className:`size-2 rounded-sm`,style:{backgroundColor:`hsl(var(--metric-rest))`}}),`Countdown`]}),(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,W.jsx)(`span`,{className:`size-2 rounded-sm`,style:{backgroundColor:`hsl(var(--metric-time))`}}),`To Next click`]}),(0,W.jsxs)(`span`,{className:`ml-auto`,children:[F1(i),` total`]})]})]}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsxs)(`div`,{"data-testid":`tour-insights-impatience`,className:`rounded-xl border border-border bg-card p-4`,children:[(0,W.jsx)(`p`,{className:`font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground`,children:`Impatience Score`}),(0,W.jsx)(`p`,{className:`mt-2 text-2xl font-black tracking-tight text-foreground`,children:I1(a)}),(0,W.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:o.length===0?`every countdown ran to zero`:`${o.length} early click${o.length===1?``:`s`}${o.length>1?` · worst ${I1(u)}`:``}`})]}),(0,W.jsxs)(`div`,{"data-testid":`tour-insights-reaction`,className:`rounded-xl border border-border bg-card p-4`,children:[(0,W.jsx)(`p`,{className:`font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground`,children:`Reaction Time`}),(0,W.jsx)(`p`,{className:`mt-2 text-2xl font-black tracking-tight text-foreground`,children:s.length>0?I1(c):`—`}),(0,W.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[s.length,` click`,s.length===1?``:`s`,s.length>1?` · slowest ${I1(l)}`:``]})]})]})]})}var z1=864e5;function B1(e){let t=new Date(e);return Math.round(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())/z1)}function V1(e,t){let n=[...e.keys()].filter(e=>e<=t);if(n.length===0)return[];let r=Math.min(...n),i=t=>e.get(t)??0,a=[];for(let e=r;e<=t;e++){let t=0,n=0;for(let r=0;r<28;r++){let a=i(e-r);n+=a,r<7&&(t+=a)}let r=t/7,o=n/28,s=0;for(let t=0;t<7;t++){let n=i(e-t)-r;s+=n*n}let c=Math.sqrt(s/7),l={day:e};o>0&&(l.acwr=r/o),c>0&&(l.monotony=r/c,l.strain=l.monotony*t),(l.acwr!==void 0||l.monotony!==void 0)&&a.push(l)}return a}var H1=864e5;function U1(e){return Math.round(e*10)/10}function W1(e,t,n=9){let r=new Date(e-t*H1);return r.setHours(n,0,0,0),r.getTime()}function G1(e,t,n,r,i,a={}){let o={canonicalKey:i};a.effortSlug&&(o.effortSlug=a.effortSlug),a.discipline&&(o.effortDiscipline=a.discipline),a.intensityTier&&(o.effortIntensityTier=a.intensityTier),e.push({id:e.length,outputType:`analytics`,timeSpan:{started:0},metrics:[{type:q.Label,value:t,origin:`analyzed`},{type:q.Metric,value:n,unit:r,origin:`analyzed`,metadata:o}],sourceBlockKey:``,stackLevel:0})}var K1=new Set([`tis`,`calc.acwr`,`calc.adherence`,`calc.ef`,`calc.pct1rm`]);function q1(e,t){return Dg(e,{noteId:t.noteId,resultId:t.resultId,blockId:`example-block`,blockVersion:1,blockContentId:t.blockContentId,origin:`journal`,workoutTimestamp:t.timestamp}).map(e=>{let t=e.metrics[0];if(!t||!(`metadata`in t))return e;let n=t.metadata?.canonicalKey;return typeof n!=`string`||!K1.has(n)||typeof t.value!=`number`?e:{...e,reducerStats:{observedCount:1,sum:t.value,min:t.value,max:t.value}}})}function J1(e=Date.now()){let t=[],n=new Map,r=[],i=[],a=(e,t)=>{let r=B1(e);n.set(r,(n.get(r)??0)+t)};for(let n=0;n<16;n++){let o=(15-n)*7+1,s=W1(e,o);{let e=[{slug:`back-squat`,top:100+4*n,reps:5,tis:12.5},{slug:`bench-press`,top:80+2.5*n,reps:5,tis:10},{slug:`deadlift`,top:140+4*n,reps:3,tis:8.4}],r=[],i=0,o=0;for(let t of e){let e=t.reps*t.top;i+=e,o+=t.tis;let n={effortSlug:t.slug,discipline:`strength`,intensityTier:`high`};G1(r,`Total reps`,t.reps,`reps`,`totalReps`,n),G1(r,`Training intensity score`,t.tis,`pts`,`tis`,n),G1(r,`Total volume`,e,`kg`,`totalVolume`,n),G1(r,`Estimated 1RM`,U1(t.top*(1+t.reps/30)),`kg`,`calc.e1rm`,n),G1(r,`%1RM intensity`,U1(100/(1+t.reps/30)),`%`,`calc.pct1rm`,n)}let c=U1(i/100+13+o/10);G1(r,`Session load`,c,`AU`,`sessionLoad`,{discipline:`strength`,intensityTier:`high`}),t.push(...q1(r,{noteId:`example-strength-w${n}`,resultId:`example-strength-w${n}-r`,blockContentId:`example-content-strength`,timestamp:s})),a(s,c)}let c=W1(e,o+2);{let e=[],r;if(n%3==0){r=`high`;for(let[t,n,i,a]of[[`thruster`,45,2.2,42.5],[`pull-up`,45,1.6,0]]){let o={effortSlug:t,discipline:a?`strength`:`gymnastics`,intensityTier:r};G1(e,`Total reps`,n,`reps`,`totalReps`,o),G1(e,`Training intensity score`,U1(n*i),`pts`,`tis`,o),a&&G1(e,`Total volume`,n*a,`kg`,`totalVolume`,o)}}else if(n%3==1){r=`moderate`;let t=16+n%5;for(let[n,i,a]of[[`pull-up`,5,1.5],[`push-up`,10,1.2],[`air-squat`,15,1.1]]){let o=t*i,s={effortSlug:n,discipline:`gymnastics`,intensityTier:r};G1(e,`Total reps`,o,`reps`,`totalReps`,s),G1(e,`Training intensity score`,U1(o*a),`pts`,`tis`,s)}}else{r=`moderate`;for(let[t,n,i]of[[`double-under`,150,.5],[`sit-up`,150,1.3]]){let a={effortSlug:t,discipline:`gymnastics`,intensityTier:r};G1(e,`Total reps`,n,`reps`,`totalReps`,a),G1(e,`Training intensity score`,U1(n*i),`pts`,`tis`,a)}}let i=U1(30.6);G1(e,`Session load`,i,`AU`,`sessionLoad`,{intensityTier:r}),t.push(...q1(e,{noteId:`example-conditioning-w${n}`,resultId:`example-conditioning-w${n}-r`,blockContentId:`example-content-conditioning`,timestamp:c})),a(c,i)}let l=W1(e,o+4,8);if(n%4==1)r.push(B1(l));else{let e=6e3+100*n,r=U1(e/2.8),o=[],s={effortSlug:`running`,discipline:`running`,intensityTier:`low`};G1(o,`Total distance`,e,`m`,`totalDistance`,s),G1(o,`Elapsed time`,r,`s`,`elapsed`,s),G1(o,`Training intensity score`,r,`pts`,`tis`,s);let c=U1(r/10);G1(o,`Session load`,c,`AU`,`sessionLoad`,{intensityTier:`low`}),t.push(...q1(o,{noteId:`example-run-w${n}`,resultId:`example-run-w${n}-r`,blockContentId:`example-content-run`,timestamp:l})),a(l,c),i.push({day:B1(l),pace:e/r})}let u=W1(e,o+6,10);{let e=4e3+50*n,r=U1(e/2),i=[],o={effortSlug:`rowing`,discipline:`rowing`,intensityTier:`moderate`};G1(i,`Total distance`,e,`m`,`totalDistance`,o),G1(i,`Elapsed time`,r,`s`,`elapsed`,o),G1(i,`Training intensity score`,r,`pts`,`tis`,o);let s=U1(r/10);G1(i,`Session load`,s,`AU`,`sessionLoad`,{intensityTier:`moderate`}),t.push(...q1(i,{noteId:`example-row-w${n}`,resultId:`example-row-w${n}-r`,blockContentId:`example-content-row`,timestamp:u})),a(u,s)}}let o=Math.max(...n.keys()),s=(e,t=10)=>{let n=new Date(e*H1);return n.setHours(t,0,0,0),n.getTime()},c=(e,n,r)=>{let i=[];for(let[e,t,n]of r)G1(i,e,t,n,e);t.push(...q1(i,{noteId:`example-calc`,resultId:e,blockContentId:`example-content-calc`,timestamp:n}))};for(let e of V1(n,o))e.acwr!==void 0&&c(`example-calc-d${e.day}`,s(e.day),[[`calc.acwr`,U1(e.acwr),`ratio`]]);let l=0,u=0,d=Math.min(...n.keys());for(let e=d;e<=o;e++){let t=n.get(e)??0;l+=(t-l)/42,u+=(t-u)/7,n.has(e)&&c(`example-calc-pmc-d${e}`,s(e),[[`calc.ctl`,U1(l),`AU`],[`calc.atl`,U1(u),`AU`],[`calc.tsb`,U1(l-u),`AU`]])}let f=new Set([...n.keys()]);for(let e of r)f.add(e);for(let e of f){let t=+!!n.has(e);c(`example-calc-adh-d${e}`,s(e,7),[[`calc.adherence`,t,`ratio`]])}for(let e of i)c(`example-calc-ef-d${e.day}`,s(e.day,8),[[`calc.ef`,U1(e.pace/141*1e5),`pts`]]);return t}function Y1(e=Date.now()){return new o_(q_(J1(e)))}var X1=null;function Z1(){return X1??=Y1()}var Q1=[4,8,16],$1={parse(e){let t=Number.parseInt(e,10);return Q1.includes(t)?t:null},serialize(e){return String(e)},withDefault(e){return{...this,defaultValue:e}}};function e0(){return Gt(`weeks`,$1.withDefault(16))}function t0(e){let t=e.trim().split(/\s+/).filter(e=>e!==``);if(t.length===0)return;let n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)continue;let r=e.slice(0,t),i=e.slice(t+1);i.startsWith(`"`)&&i.endsWith(`"`)&&i.length>=2&&(i=i.slice(1,-1)),n[r]=i}return Object.keys(n).length===0?void 0:n}var n0=[{label:`Auto`,spanCols:void 0,spanFull:!1},{label:`1 col`,spanCols:1,spanFull:!1},{label:`2 cols`,spanCols:2,spanFull:!1},{label:`4 cols`,spanCols:4,spanFull:!1},{label:`Full row`,spanCols:void 0,spanFull:!0}],r0=300;function i0({open:e,...t}){return e?(0,W.jsx)(a0,{...t}):null}function a0({onClose:e,mode:t,initialWql:n,initial:r,subsetQuery:i,destination:a,executor:o,rangeStart:s,rangeEnd:c,preferredUnit:l,tokenValues:u,onApply:d,footerExtra:f,applyLabel:p=t===`edit`?`Apply changes`:`Add widget`}){let m=t===`inspect`,[h,g]=(0,U.useState)(n),[_,v]=(0,U.useState)(r?.title??``),[y,b]=(0,U.useState)(r?.question??``),[x,S]=(0,U.useState)(r?.type||`table`),[C,w]=(0,U.useState)({spanCols:r?.spanCols,spanFull:r?.spanFull}),[T,E]=(0,U.useState)(Object.entries(r?.attributes??{}).map(([e,t])=>`${e}=${t}`).join(` `)),[D,O]=(0,U.useState)(!1),[k,A]=(0,U.useState)(()=>!X(n).error),[j,M]=(0,U.useState)(null),N=(0,U.useMemo)(()=>X(h.trim()),[h]),P=x===``?`table`:x,F=!N.error&&h.trim()!==``&&(bm(N)?P===`table`||P===`list`:P!==`list`),[I,L]=(0,U.useState)({status:`idle`}),R=(0,U.useRef)(0);(0,U.useEffect)(()=>{if(!F||!o){L(e=>e.status===`ok`?e:{status:`idle`});return}let e=b_(h.trim(),u??{});if(e.missing.length>0){L({status:`blocked`,message:d_(e.missing)});return}let t=++R.current;L({status:`loading`});let n=setTimeout(()=>{o.runQuery(e.query,{rangeStart:s,rangeEnd:c,preferredUnit:l}).then(e=>{R.current===t&&L({status:`ok`,result:e})}).catch(e=>{R.current===t&&L({status:`error`,message:e instanceof Error?e.message:String(e)})})},r0);return()=>clearTimeout(n)},[h,F,o,s,c,l,u]);let ee=!F&&I.status===`ok`,te=F&&k,ne=async()=>{if(!(!te||!d||D)&&!(X(h.trim()).error||h.trim()===``)){O(!0),M(null);try{await d({title:_.trim()||void 0,question:y.trim()||void 0,type:x===`table`?``:x,spanCols:C.spanFull?void 0:C.spanCols,spanFull:C.spanFull||void 0,wql:h.trim(),attributes:t0(T)}),e()}catch(e){M(e instanceof Error?e.message:String(e))}finally{O(!1)}}};return(0,W.jsx)(HS,{open:!0,onClose:e,presentation:`sheet`,title:t===`inspect`?`Inspect widget`:t===`edit`?`Edit widget`:`Add widget`,description:m?`Read-only — clone the dashboard to edit this widget.`:`Dataset, calculation, visualization, preview — then apply.`,footer:m&&!f?void 0:(0,W.jsxs)(W.Fragment,{children:[f,(0,W.jsx)(`div`,{className:`flex-1`}),!m&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`button`,{type:`button`,onClick:e,className:`min-h-12 px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground rounded-lg border border-border hover:bg-muted transition-colors`,children:`Cancel`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`widget-composer-apply`,disabled:!te||D,title:N.error?N.error:void 0,onClick:()=>void ne(),className:`min-h-12 px-3 py-1.5 text-xs font-medium text-primary-foreground bg-primary hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg shadow transition-colors`,children:D?`Applying…`:p})]})]}),children:(0,W.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[i!==void 0&&(0,W.jsxs)(`section`,{children:[(0,W.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Dataset — the subset`}),i?(0,W.jsx)(`code`,{className:`block rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-subset`,children:i}):(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`widget-composer-subset`,children:`No subset — the calculation runs over the whole store.`})]}),a,(0,W.jsxs)(`section`,{children:[(0,W.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Calculation`}),m?(0,W.jsx)(`code`,{className:`block rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-query`,children:h}):(0,W.jsx)(aw,{query:h,onQueryChange:g,onValidationChange:e=>A(e.valid),showDiagnostics:!0,...o?{execute:e=>o.runQuery(e.raw,{rangeStart:s,rangeEnd:c,preferredUnit:l})}:{}}),!m&&h.trim()!==``&&(0,W.jsx)(`code`,{className:`mt-1.5 block rounded-md border border-primary/30 bg-primary/[0.04] px-3 py-2 font-mono text-xs text-foreground break-all`,"data-testid":`widget-composer-wql`,children:h.trim()}),!m&&(0,W.jsxs)(`label`,{className:`mt-3 flex flex-col gap-1`,children:[(0,W.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Visualization`}),(0,W.jsx)(`select`,{value:x,onChange:e=>S(e.target.value),"data-testid":`widget-composer-type`,className:`min-h-12 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary sm:min-h-0`,children:s_.map(e=>(0,W.jsx)(`option`,{value:e,children:e},e))})]})]}),!m&&(0,W.jsxs)(`section`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[(0,W.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,W.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Title`}),(0,W.jsx)(`input`,{type:`text`,value:_,onChange:e=>v(e.target.value),placeholder:`Weekly volume`,"data-testid":`widget-composer-title`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),(0,W.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,W.jsxs)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:[`Coaching question `,(0,W.jsx)(`span`,{className:`normal-case font-normal`,children:`(optional)`})]}),(0,W.jsx)(`input`,{type:`text`,value:y,onChange:e=>b(e.target.value),placeholder:`How much work per week?`,"data-testid":`widget-composer-question`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,W.jsx)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:`Size`}),(0,W.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-border bg-card p-1 self-start`,children:n0.map(e=>{let t=e.spanFull?C.spanFull===!0:e.spanCols==null?!C.spanFull&&C.spanCols==null:!C.spanFull&&C.spanCols===e.spanCols;return(0,W.jsx)(`button`,{type:`button`,"aria-pressed":t,onClick:()=>w(e.spanFull?{spanFull:!0}:{spanCols:e.spanCols}),className:`text-xs px-2.5 py-1 rounded-md transition-colors ${t?`bg-primary text-primary-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:e.label},e.label)})})]}),(0,W.jsxs)(`label`,{className:`flex flex-col gap-1 sm:col-span-2`,children:[(0,W.jsxs)(`span`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground`,children:[`Parameters `,(0,W.jsx)(`span`,{className:`normal-case font-normal`,children:`(goal targets, space-separated)`})]}),(0,W.jsx)(`input`,{type:`text`,value:T,onChange:e=>E(e.target.value),placeholder:`300 200`,"data-testid":`widget-composer-params`,className:`rounded-lg border border-border bg-card px-3 py-1.5 text-sm font-mono text-foreground focus:outline-none focus:border-primary`})]})]}),m&&(0,W.jsxs)(`section`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs text-muted-foreground`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Title`}),(0,W.jsx)(`div`,{className:`text-foreground`,children:r?.title||`—`})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Question`}),(0,W.jsx)(`div`,{className:`text-foreground`,children:r?.question||`—`})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Type`}),(0,W.jsx)(`div`,{className:`font-mono text-foreground`,children:x||`table`})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`span`,{className:`font-bold uppercase tracking-wider text-[10px]`,children:`Size`}),(0,W.jsx)(`div`,{className:`font-mono text-foreground`,children:r?.spanFull?`full row`:r?.spanCols?`${r.spanCols} cols`:`default`})]})]}),(0,W.jsxs)(`section`,{children:[(0,W.jsxs)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5 flex items-center gap-2`,children:[`Preview`,ee&&(0,W.jsx)(`span`,{"data-testid":`widget-preview-stale`,className:`font-medium normal-case tracking-normal text-amber-600`,children:`stale — showing the last valid query`})]}),(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-background/50 p-3 h-56 overflow-hidden`,children:[I.status===`idle`&&(F?(0,W.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-muted-foreground`,children:`Preview runs as you compose…`}):(0,W.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:N.error?N.error:bm(N)?`find: queries return things — use a table or list widget instead`:`Compose a calculation to preview.`})),I.status===`loading`&&(0,W.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-muted-foreground`,children:`Running preview…`}),I.status===`blocked`&&(0,W.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:I.message}),I.status===`error`&&(0,W.jsx)(`div`,{className:`h-full flex items-center justify-center text-xs text-destructive font-mono px-4 text-center`,children:I.message}),I.status===`ok`&&(0,W.jsx)(zx,{type:x,result:I.result,label:_.trim()||void 0,unit:l,attributes:t0(T)})]})]}),j&&(0,W.jsx)(`p`,{role:`alert`,"data-testid":`widget-composer-error`,className:`rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive font-mono`,children:j})]})})}function o0({boardSlug:e}){let t=Z1(),n=GD(),r=(0,U.useMemo)(()=>n?ON(n):[],[n]),i=(0,U.useMemo)(()=>r.find(t=>t.slug===e)??r[0],[r,e]),a=(0,U.useMemo)(()=>{if(!i?.rawContent)return null;try{let{meta:e,sections:t}=k_(i.rawContent);return C_(t,e)}catch{return null}},[i]),[o,s]=e0(),[c,l]=(0,U.useMemo)(()=>{let e=Date.now();return[e-o*7*864e5,e]},[o]),[u,d]=(0,U.useState)(null);return(0,W.jsxs)(`div`,{className:`flex h-full w-full flex-col`,"data-testid":`tour-session-dashboard`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 px-5 pt-4`,children:[(0,W.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`truncate text-[11px] font-semibold uppercase tracking-wide text-primary`,children:i?.title??e}),(0,W.jsx)(`span`,{"data-testid":`tour-session-dashboard-source`,className:`flex-none rounded-full border border-border bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground`,children:`Example data`})]}),(0,W.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,W.jsx)(tS,{weeks:o,onWeeksChange:s})})]}),(0,W.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto px-5 pb-5 pt-3 [&_[data-testid=dashboard-view]>div.grid]:grid-cols-1 [&_[data-testid=dashboard-view]>div.grid]:sm:grid-cols-2 [&_[data-testid=dashboard-view]>div.grid]:lg:grid-cols-2 [&_[data-testid=dashboard-view]>div.grid>*]:col-span-1`,children:a?(0,W.jsx)(eS,{document:a,executor:t,onInspectWidget:d,rangeStart:c,rangeEnd:l}):(0,W.jsx)(`p`,{className:`pt-8 text-center text-sm text-muted-foreground`,children:`Loading board…`})}),(0,W.jsx)(i0,{open:u!==null,onClose:()=>d(null),mode:`inspect`,initialWql:u?.body??`sum:totalVolume{}`,initial:u?{title:u.title,question:u.question,type:u.type,spanCols:u.spanCols,spanFull:u.spanFull,attributes:u.attributes}:void 0,executor:t,rangeStart:c,rangeEnd:l,tokenValues:a?__(a.tokens):void 0,onApply:void 0})]})}var s0=[`analytics`,`boards`],c0={analytics:{index:`01`,heading:`h2`,title:`Session Insights`,blurb:`Run the workout and this window turns your run into data — rest vs. work, how fast you answered the clock, round by round.`},boards:{index:`02`,heading:`h2`,title:`One Run Becomes Many`,blurb:`Dashboards let you visualise your progress — every recorded run rolls up into analytics boards. Aggregate results across flexible search criteria, from note frontmatter to session metrics: one run becomes many insights.`}};function l0({scope:e}){let t=c0[e],n=t.heading;return(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(n,{className:`flex items-baseline gap-4 text-[clamp(26px,3.2vw,44px)] font-extrabold leading-[1.1] tracking-[-0.03em]`,children:[t.index&&(0,W.jsx)(`span`,{className:`font-mono text-xs font-normal tracking-normal text-muted-foreground`,children:t.index}),(0,W.jsx)(`span`,{children:t.title})]}),(0,W.jsx)(`p`,{className:`mt-3 max-w-xl text-[clamp(14px,1.2vw,18px)] leading-[1.65] text-muted-foreground`,children:t.blurb})]})}var u0=[{id:`road-to-560-total`,label:`Road to 560 Total`,title:`Road to 560 Total`},{id:`polarized-base-marathon`,label:`Polarized Base`,title:`Polarized Base Marathon`}];function d0({onClick:e}){return(0,W.jsxs)(`button`,{type:`button`,onClick:e,title:`Back to the editor`,"data-testid":`tour-pane-back-to-editor`,className:`flex shrink-0 items-center gap-1 rounded-md border border-border px-2 py-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:[(0,W.jsx)(xt,{className:`size-3`}),`Editor`]})}function f0({session:e,onRun:t,onBackToEditor:n}){let[r,i]=(0,U.useState)(`analytics`),[a,o]=(0,U.useState)(0),s=u0[a],c=(0,U.useRef)(new Map);(0,U.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target.getAttribute(`data-scope`);(e===`analytics`||e===`boards`)&&i(e)}},{rootMargin:`-45% 0px -45% 0px`});return c.current.forEach(t=>e.observe(t)),()=>e.disconnect()},[]);let l=e=>t=>{t?c.current.set(e,t):c.current.delete(e)},u=r=>r===`analytics`?(0,W.jsx)(PK,{title:`Session Insights`,className:`h-[460px]`,headerActions:(0,W.jsx)(d0,{onClick:n}),children:(0,W.jsx)(R1,{result:e,onRun:t})}):(0,W.jsxs)(`div`,{className:`flex h-full flex-col gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,W.jsx)(`div`,{role:`tablist`,"aria-label":`Dashboard slides`,className:`flex flex-wrap gap-1 rounded-lg border border-border bg-muted/30 p-1`,children:u0.map((e,t)=>(0,W.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":a===t,"aria-pressed":a===t,"data-testid":`dashboard-slide-tab-${e.id}`,onClick:()=>o(t),className:G(`min-h-11 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors`,a===t?`bg-background text-foreground shadow`:`text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:()=>o(e=>(e+u0.length-1)%u0.length),"aria-label":`Previous dashboard`,"data-testid":`dashboard-slide-prev`,className:`flex size-11 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,W.jsx)(_t,{className:`size-4`})}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>o(e=>(e+1)%u0.length),"aria-label":`Next dashboard`,"data-testid":`dashboard-slide-next`,className:`flex size-11 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,W.jsx)(Qt,{className:`size-4`})})]})]}),(0,W.jsx)(PK,{title:s.title,className:`min-h-0 flex-1`,headerActions:(0,W.jsx)(d0,{onClick:n}),children:(0,W.jsx)(`div`,{className:`flex h-full w-full flex-col`,role:`tabpanel`,children:(0,W.jsx)(o0,{boardSlug:s.id})},s.id)}),(0,W.jsxs)(`p`,{className:`text-center font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60`,children:[a+1,` / `,u0.length]})]}),d=(0,W.jsx)(`div`,{"data-testid":`tour-sticky-pane`,className:`sticky top-[72px] hidden h-[calc(100dvh-72px)] flex-col items-center justify-center self-start lg:top-[104px] lg:flex lg:h-[calc(100dvh-104px)]`,children:(0,W.jsx)(`div`,{className:`relative w-full max-w-[700px]`,children:(0,W.jsx)(`div`,{className:`relative h-[460px]`,children:s0.map(e=>(0,W.jsx)(`div`,{"aria-hidden":r!==e,"data-scope-active":r===e,className:G(`absolute inset-0 transition-opacity duration-500`,r===e?`opacity-100`:`invisible opacity-0`),children:u(e)},e))})})}),f=(e,t)=>(0,W.jsx)(`div`,{ref:l(e),"data-scope":e,className:`flex min-h-[85vh] flex-col justify-center scroll-mt-[104px]`,...t,children:(0,W.jsx)(l0,{scope:e})}),p=e=>(0,W.jsxs)(`div`,{"data-testid":`tour-step-mobile-${e}`,"data-scope":e,className:`flex flex-col gap-4 lg:hidden`,children:[(0,W.jsx)(l0,{scope:e}),(0,W.jsx)(`div`,{className:`h-[460px]`,children:u(e)})]});return(0,W.jsx)(`section`,{id:`tour-section-insights`,"data-testid":`tour-section-insights`,className:`border-b border-border/60`,children:(0,W.jsxs)(`div`,{className:`mx-auto grid max-w-[1500px] gap-10 px-5 py-14 lg:grid-cols-2 lg:gap-16 lg:px-12 lg:py-0 xl:px-16 2xl:max-w-[1720px]`,children:[(0,W.jsxs)(`div`,{className:`hidden flex-col lg:flex`,children:[(0,W.jsx)(`div`,{id:`tour-scroll-target-insights`,className:`scroll-mt-[72px] lg:scroll-mt-[104px]`,children:f(`analytics`)}),f(`boards`,{id:`tour-section-boards`,"data-testid":`tour-section-boards`})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-12 lg:hidden`,children:[p(`analytics`),p(`boards`)]}),d]})})}function p0(e){let t=e.match(/^feed\.(.+)$/);if(t)return{kind:`feed`,slug:t[1]};let n=e.match(/^collection\.(.+)$/);return n?{kind:`collection`,slug:n[1]}:null}function m0(e,t){let n=t.items.map(e=>e.date).filter(e=>!!e).sort();return{packageId:`local-${e}-${t.id}`,slug:t.id,kind:e,label:t.name,description:t.description,image:t.image,categories:t.categories,sourceLabel:`Local`,href:e===`feed`?`/feeds/${encodeURIComponent(t.id)}`:`/collections/${encodeURIComponent(t.id)}`,itemCount:t.items.length,...n.length>0?{latestDate:n[n.length-1],firstDate:n[0]}:{},...t.readme===void 0?{}:{readme:t.readme},installed:!0}}function h0(e,t,n){let r=[],i=new Map;if(t)for(let e of[`feed`,`collection`])for(let n of wD(e===`feed`?`feeds`:`collections`,t))i.set(`${e}:${n.id}`,n),r.push(m0(e,n));let a=e.map(e=>{let t=p0(e.chunkId);if(!t)return null;let r=i.get(`${t.kind}:${t.slug}`),a=Pk(e.seedId),o=(r?.items??[]).map(e=>e.date).filter(e=>!!e).sort();return{packageId:e.id,seedId:e.seedId,chunkId:e.chunkId,slug:t.slug,kind:t.kind,label:e.label,description:e.description||r?.description,image:r?.image,categories:r?.categories??[],sourceLabel:a?.label??e.seedId,...a?.repositoryUrl?{repositoryUrl:a.repositoryUrl}:{},href:t.kind===`feed`?`/feeds/${encodeURIComponent(t.slug)}`:`/collections/${encodeURIComponent(t.slug)}`,itemCount:r?.items.length??0,...o.length>0?{latestDate:o[o.length-1],firstDate:o[0]}:{},...r?.readme===void 0?{}:{readme:r.readme},installed:!!r,subscribed:!n||n(e.seedId,e.chunkId)}}).filter(e=>e!==null),o=new Set(a.map(e=>`${e.kind}:${e.slug}`));return[...a,...r.filter(e=>!o.has(`${e.kind}:${e.slug}`))]}function g0(e,t){let n={},r=[];for(let t of e)t.seedId?(n[t.seedId]??=[]).push(t):r.push(t);let i=[];for(let e of t){let t=n[e.id];t?.length&&i.push({seed:e,label:e.label,...e.description?{description:e.description}:{},url:e.url,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},notebooks:t})}return r.length>0&&i.push({label:`Local`,notebooks:r}),i}function _0(e,t,n,r){return g0(h0(e,t,r),n).map(e=>{let t=e.notebooks.map(e=>e.latestDate).filter(e=>!!e).sort();return{seedId:e.seed?.id,slug:e.seed?.id??`local`,label:e.label,...e.description?{description:e.description}:{},...e.url?{url:e.url}:{},...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},notebooks:e.notebooks,itemCount:e.notebooks.reduce((e,t)=>e+t.itemCount,0),installed:e.notebooks.every(e=>e.installed),subscribed:e.notebooks.some(e=>e.subscribed),...t.length>0?{latestDate:t[t.length-1]}:{},href:`/catalogs`}})}function v0(e,t){let n=t.text?.trim().toLowerCase();return e.filter(e=>t.seedId&&e.seedId!==t.seedId||t.kind&&!e.notebooks.some(e=>e.kind===t.kind)||t.subscribedOnly&&!e.notebooks.some(e=>e.subscribed)?!1:!n||e.label.toLowerCase().includes(n)||(e.description?.toLowerCase().includes(n)??!1)||e.notebooks.some(e=>e.label.toLowerCase().includes(n)||(e.description?.toLowerCase().includes(n)??!1)))}function y0(e,t){let n=[...e];switch(t){case`name`:return n.sort((e,t)=>e.label.localeCompare(t.label));case`size`:return n.sort((e,t)=>t.itemCount-e.itemCount||e.label.localeCompare(t.label));default:return n.sort((e,t)=>e.latestDate&&t.latestDate?t.latestDate.localeCompare(e.latestDate):e.latestDate?-1:t.latestDate?1:e.label.localeCompare(t.label))}}var b0=[`bg-rose-500/12 text-rose-600 dark:text-rose-400`,`bg-amber-500/12 text-amber-600 dark:text-amber-400`,`bg-emerald-500/12 text-emerald-600 dark:text-emerald-400`,`bg-sky-500/12 text-sky-600 dark:text-sky-400`,`bg-violet-500/12 text-violet-600 dark:text-violet-400`,`bg-cyan-500/12 text-cyan-600 dark:text-cyan-400`];function x0(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return b0[Math.abs(t)%b0.length]}function S0(e){return(e.match(/[a-z0-9]/i)?.[0]??`•`).toUpperCase()}function C0(e){if(!e)return null;let t=new Date(`${e}T00:00:00`);return isNaN(t.getTime())?null:t.toLocaleDateString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}var w0=4;function T0({seed:e,testId:t=`seed-card`,className:n,onImport:r,importing:i,busy:a,status:o,onToggleNotebookSubscription:c}){let[l,u]=x0(e.slug).split(` `),d=C0(e.latestDate),f=e.notebooks.slice(0,w0),p=e.notebooks.length-f.length,m=e.installed&&e.seedId?e.href:void 0,h=e.notebooks.find(e=>e.image)?.image,g=(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/70`,children:[(0,W.jsxs)(`span`,{className:`tabular-nums`,children:[e.notebooks.length,` `,e.notebooks.length===1?`notebook`:`notebooks`]}),e.installed&&e.itemCount>0&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{"aria-hidden":!0,children:`·`}),(0,W.jsxs)(`span`,{className:`tabular-nums`,children:[e.itemCount,` `,e.itemCount===1?`item`:`items`]})]}),e.installed&&d&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{"aria-hidden":!0,children:`·`}),(0,W.jsxs)(`span`,{className:`tabular-nums`,children:[`updated `,d]})]}),!e.installed&&(0,W.jsx)(`span`,{"aria-hidden":!0,children:`·`}),!e.installed&&(0,W.jsx)(`span`,{children:`not imported`})]}),_=(0,W.jsx)(`div`,{className:G(`relative overflow-hidden bg-muted/40 aspect-[16/10]`,l),children:h?(0,W.jsx)(`img`,{src:h,alt:``,loading:`lazy`,className:`absolute inset-0 size-full object-cover`}):(0,W.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,W.jsx)(`span`,{className:G(`text-7xl font-black tracking-tighter select-none`,u),"aria-hidden":!0,children:S0(e.label)}),(0,W.jsx)(s,{className:G(`absolute bottom-4 right-4 size-6 opacity-50`,u),"aria-hidden":!0})]})});return(0,W.jsxs)(`article`,{"data-testid":t,"data-installed":e.installed,className:G(`group relative flex flex-col overflow-hidden rounded-2xl border border-border bg-card`,`transition-colors hover:border-foreground/25 focus-within:border-foreground/25`,n),children:[m?(0,W.jsx)(Nt,{to:m,"data-testid":`${t}-open`,className:`block outline-none`,"aria-label":`Open the library for ${e.label}`,children:_}):_,(0,W.jsxs)(`div`,{className:`flex flex-1 flex-col gap-2 p-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,W.jsx)(`h3`,{className:`min-w-0 text-sm font-bold leading-snug text-foreground`,children:m?(0,W.jsx)(Nt,{to:m,className:`transition-colors hover:text-primary`,children:e.label}):e.label}),m?(0,W.jsx)(Nt,{to:m,"data-testid":`${t}-cta`,"aria-label":`Open the library for ${e.label}`,className:`flex size-8 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground transition-colors hover:border-primary/50 hover:text-primary`,children:(0,W.jsx)(lr,{className:`size-3.5`,"aria-hidden":!0})}):r&&e.seedId?(0,W.jsxs)(`button`,{type:`button`,"data-testid":`${t}-import`,disabled:i||a,onClick:()=>r(e.seedId),className:G(`flex h-8 shrink-0 items-center gap-1.5 rounded-full border px-3`,`text-[10px] font-black uppercase tracking-widest`,`border-primary/30 bg-primary/10 text-primary`,`transition-colors hover:bg-primary/20`,`disabled:cursor-wait disabled:opacity-60`),children:[i?(0,W.jsx)(ir,{className:`size-3 animate-spin`,"aria-hidden":!0}):(0,W.jsx)($e,{className:`size-3`,"aria-hidden":!0}),i?`Importing`:`Import seed`]}):null]}),e.description&&(0,W.jsx)(`p`,{className:`line-clamp-2 text-xs leading-relaxed text-muted-foreground`,children:e.description}),e.notebooks.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,"data-testid":`${t}-notebooks`,children:[f.map(n=>(0,W.jsxs)(`span`,{"data-testid":`${t}-notebook-${n.packageId}`,className:G(`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[9px] font-black uppercase tracking-widest transition-colors`,n.subscribed?`border-emerald-500/40 bg-emerald-500/10 text-emerald-600`:`border-border text-muted-foreground/70`),children:[n.installed?(0,W.jsx)(Nt,{to:n.href,className:`hover:text-primary`,children:n.label}):(0,W.jsx)(`span`,{children:n.label}),c&&e.seedId&&n.chunkId&&(0,W.jsx)(`button`,{type:`button`,onClick:t=>{t.preventDefault(),t.stopPropagation(),c(e.seedId,n.chunkId,!n.subscribed)},title:n.subscribed?`Unsubscribe ${n.label}`:`Subscribe ${n.label}`,"aria-label":n.subscribed?`Unsubscribe ${n.label}`:`Subscribe ${n.label}`,"data-testid":`${t}-notebook-toggle-${n.packageId}`,className:`ml-0.5 font-bold hover:text-foreground`,children:n.subscribed?`✓`:`+`})]},n.packageId)),p>0&&(0,W.jsxs)(`span`,{className:`rounded-full border border-dashed border-border px-2 py-0.5 text-[9px] font-black uppercase tracking-widest text-muted-foreground/60`,children:[`+`,p,` more`]})]}),(0,W.jsxs)(`div`,{className:`mt-auto pt-1`,children:[g,o&&(0,W.jsx)(`p`,{role:o.tone===`error`?`alert`:`status`,"data-testid":`${t}-status`,className:G(`mt-1.5 flex items-start gap-1.5 text-xs`,o.tone===`error`?`text-destructive`:`text-muted-foreground`),children:(0,W.jsx)(`span`,{children:o.text})})]})]})]})}function E0({direction:e,children:t,testId:n,className:r}){let i=(0,U.useRef)(null),a=(0,U.useRef)(null),[o,s]=(0,U.useState)(1),c=jK(`(prefers-reduced-motion: reduce)`);(0,U.useEffect)(()=>{let e=i.current,t=a.current;if(!e||!t)return;let n=()=>{let n=o*2,r=t.scrollWidth/n;if(r<=0)return;let i=Math.max(1,Math.ceil(e.clientWidth/r));i!==o&&s(i)};n();let r=new ResizeObserver(n);return r.observe(e),r.observe(t),()=>r.disconnect()},[o,t]);let l=c?1:o*2;return(0,W.jsx)(`div`,{ref:i,"data-testid":n,className:G(`wod-marquee overflow-hidden`,r),children:(0,W.jsx)(`div`,{ref:a,className:G(`flex w-max`,!c&&`wod-marquee-track`,!c&&e===`left`&&`wod-marquee-track--left`,!c&&e===`right`&&`wod-marquee-track--right`,!c&&e===`alternate`&&`wod-marquee-track--left wod-marquee-track--alternate`),children:Array.from({length:l},(e,n)=>(0,W.jsx)(`div`,{"data-marquee-copy":n,"aria-hidden":n>0,className:`flex shrink-0 items-stretch gap-4 pr-4`,children:t},n))})})}var D0=[{value:`feed`,label:`Feeds`},{value:`collection`,label:`Collections`}],O0=[{value:`updated`,label:`Updated`},{value:`name`,label:`Name`},{value:`size`,label:`Size`}],k0=`group flex flex-col justify-between rounded-2xl border border-border bg-card p-5 text-left transition-colors hover:border-primary/40 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`;function A0(e){let t=e.icon;return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-foreground text-background`,children:(0,W.jsx)(t,{className:`size-5`,"aria-hidden":!0})}),(0,W.jsx)(`h3`,{className:`mt-4 text-base font-semibold text-foreground`,children:e.title}),(0,W.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-muted-foreground`,children:e.description})]}),e.note?(0,W.jsx)(`span`,{className:`mt-4 text-xs font-medium text-muted-foreground`,children:e.note}):(0,W.jsxs)(`span`,{className:`mt-4 inline-flex items-center gap-1.5 text-sm font-medium text-foreground`,children:[(0,W.jsx)(`span`,{children:e.action}),(0,W.jsx)(lr,{className:`size-4 transition-transform group-hover:translate-x-0.5`,"aria-hidden":!0})]})]})}function j0(e){switch(e.phase){case`checking`:return`Checking the seed…`;case`fetching`:return`Downloading ${e.chunkId??`notebook`}…`;case`applying`:return`Importing ${e.chunkId??`notebook`}…`;case`committed`:return`Committed ${e.chunkId??`notebook`}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return`Done`;default:return`Working…`}}function M0(){let e=ht(),[t,n]=(0,U.useState)(``),[r,i]=(0,U.useState)(),[a,o]=(0,U.useState)(`updated`),[s,c]=(0,U.useState)(null),[l,u]=(0,U.useState)({}),[d,f]=(0,U.useState)(!1),[p,m]=(0,U.useState)(),[h,g]=(0,U.useState)(0);(0,U.useEffect)(()=>aA(()=>g(e=>e+1)),[]);let _=s!==null,y=GD(),b=jK(`(min-width: 1024px)`),x=(0,U.useMemo)(()=>_0(zk(),y,Rk(),(e,t)=>nA(e,t)),[y,h]),S=(0,U.useMemo)(()=>y0(v0(x,{text:t,kind:r,seedId:p,subscribedOnly:d}),a),[x,t,r,a,p,d]),C=Math.ceil(S.length/2),w=S.slice(0,C),T=S.slice(C),E=(0,U.useCallback)(()=>{oK.record(sK.libraryOpened)},[]),[D,O]=(0,U.useState)(!0);(0,U.useEffect)(()=>{let e=!1,t=()=>{kj().then(t=>{e||O(t.libraryImported)}).catch(()=>{})};t();let n=aA(t);return()=>{e=!0,n()}},[_]);let k=(0,U.useCallback)(async e=>{if(s)return;c(e);let t=t=>u(n=>({...n,[e]:t}));t({text:`Checking the seed…`,tone:`muted`});try{let n=await Ej(e,{onProgress:e=>t({text:j0(e),tone:`muted`})});t(n===`imported`||n===`current`?{text:tA(e,!0)?n===`imported`?`Imported — this seed is available offline.`:`Already up to date.`:`Subscribed for this session only — browser storage is unavailable.`,tone:`muted`}:{text:n===`server-stale`?`Published version is older than stored copy.`:n===`busy`?`Another tab is syncing. Try again shortly.`:`Sync failed. Check connection and try again.`,tone:`error`})}catch(e){t({text:e instanceof Error?e.message:String(e),tone:`error`})}finally{c(null)}},[s]),A=(0,U.useCallback)(async(e,t,n)=>{rA(e,t,n),n&&Ej(e,{force:!1})},[]),j=(0,U.useCallback)(async()=>{let t=FN(),n=await BN.create({journalDate:t,title:t,rawContent:``});oK.record(sK.noteCreated),e(VM(n.id))},[e]),M=!!t.trim()||r!==void 0;return(0,W.jsxs)(`section`,{id:`tour-section-community-feeds`,"data-testid":`tour-jump-section`,className:`flex flex-col border-b border-border bg-muted/20 pb-8 xl:pb-12`,"aria-label":`Library and community feeds`,children:[(0,W.jsx)(nQ,{index:`03`,before:`Library & `,accentText:`Community Feeds`,after:``,accent:``,blurb:`Subscribe to a seed — one Markdown repository compiled with npx wod build into a versioned manifest, served from its own GitHub Pages. One Subscribe imports every notebook the seed publishes; browse the seeds below, notebooks and all.`}),(0,W.jsxs)(`div`,{className:`mx-auto w-full max-w-6xl px-4 sm:px-6`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsxs)(`label`,{className:`relative w-full sm:w-64`,children:[(0,W.jsx)(Tt,{className:`pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground/60`,"aria-hidden":!0}),(0,W.jsx)(`input`,{type:`search`,value:t,onChange:e=>n(e.target.value),placeholder:`Search seeds…`,"aria-label":`Search seeds`,"data-testid":`package-search-input`,className:`h-9 w-full rounded-full border border-border bg-background pl-9 pr-8 text-sm text-foreground placeholder:text-muted-foreground/50 outline-none transition-colors focus:border-primary/50`}),t&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>n(``),"aria-label":`Clear search`,className:`absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,children:(0,W.jsx)(we,{className:`size-3.5`})})]}),(0,W.jsx)(`div`,{className:`flex items-center gap-1.5`,role:`group`,"aria-label":`Filter by kind`,children:D0.map(e=>{let t=r===e.value;return(0,W.jsx)(`button`,{type:`button`,"aria-pressed":t,"data-testid":`package-kind-${e.value}`,onClick:()=>i(t?void 0:e.value),className:G(`h-8 rounded-full border px-3 text-[10px] font-black uppercase tracking-widest transition-colors`,t?`border-primary/40 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:border-foreground/25 hover:text-foreground`),children:e.label},e.value)})}),(0,W.jsxs)(`label`,{className:`flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked),"data-testid":`filter-subscribed-only`,className:`size-3.5 accent-primary rounded`}),(0,W.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-widest`,children:`Subscribed only`})]}),(0,W.jsxs)(`select`,{value:p??``,onChange:e=>m(e.target.value?e.target.value:void 0),"aria-label":`Filter by seed source`,"data-testid":`filter-seed-source`,className:`h-8 rounded-full border border-border bg-background px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground outline-none transition-colors hover:border-foreground/25 focus:border-primary/50`,children:[(0,W.jsx)(`option`,{value:``,children:`All seeds`}),Rk().map(e=>(0,W.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),(0,W.jsx)(`div`,{className:`ml-auto flex items-center gap-0.5`,role:`group`,"aria-label":`Sort seeds`,children:O0.map(e=>{let t=a===e.value;return(0,W.jsx)(`button`,{type:`button`,"aria-pressed":t,"data-testid":`package-sort-${e.value}`,onClick:()=>o(e.value),className:G(`h-8 rounded-full px-3 text-[10px] font-black uppercase tracking-widest transition-colors`,t?`bg-foreground text-background`:`text-muted-foreground hover:text-foreground`),children:e.label},e.value)})})]}),(0,W.jsx)(`div`,{"data-testid":`jump-grid`,className:`mt-6`,children:(0,W.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 sm:grid-cols-2`,children:[D?(0,W.jsx)(Nt,{to:`/catalogs`,onClick:E,"data-testid":`jump-library`,className:k0,children:(0,W.jsx)(A0,{icon:v,title:`Library`,description:`Curated workouts and sessions, organized by tag.`,action:`Open the library`})}):(0,W.jsx)(`div`,{"data-testid":`jump-library`,"aria-disabled":`true`,className:`${k0} cursor-not-allowed opacity-60`,children:(0,W.jsx)(A0,{icon:v,title:`Library`,description:`Curated workouts and sessions, organized by tag.`,action:`Open the library`,note:`0 feeds synchronized`})}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>{j()},"data-testid":`jump-new-note`,className:k0,children:(0,W.jsx)(A0,{icon:Dn,title:`Start your own journal`,description:`Create today's note and log your first workout.`,action:`Create today's note`})})]})})]}),(0,W.jsx)(`div`,{"data-testid":`jump-rows`,className:`mt-6`,children:S.length>0?b?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(E0,{direction:`left`,testId:`jump-row-a`,children:w.map(e=>(0,W.jsx)(T0,{seed:e,testId:`seed-card-${e.seedId??e.slug}`,className:`w-[290px] sm:w-[320px] shrink-0`,onImport:k,importing:!!e.seedId&&s===e.seedId,busy:_,status:e.seedId?l[e.seedId]:void 0,onToggleNotebookSubscription:A},e.seedId??e.slug))}),T.length>0&&(0,W.jsx)(E0,{direction:`right`,testId:`jump-row-b`,className:`mt-4`,children:T.map(e=>(0,W.jsx)(T0,{seed:e,testId:`seed-card-${e.seedId??e.slug}`,className:`w-[290px] sm:w-[320px] shrink-0`,onImport:k,importing:!!e.seedId&&s===e.seedId,busy:_,status:e.seedId?l[e.seedId]:void 0,onToggleNotebookSubscription:A},e.seedId??e.slug))})]}):(0,W.jsx)(E0,{direction:`alternate`,testId:`jump-row-mobile`,children:S.map(e=>(0,W.jsx)(T0,{seed:e,testId:`seed-card-${e.seedId??e.slug}`,className:`w-[290px] shrink-0`,onImport:k,importing:!!e.seedId&&s===e.seedId,busy:_,status:e.seedId?l[e.seedId]:void 0,onToggleNotebookSubscription:A},e.seedId??e.slug))}):(0,W.jsx)(`div`,{className:`mx-auto w-full max-w-6xl px-4 sm:px-6`,children:(0,W.jsxs)(`div`,{"data-testid":`jump-empty`,className:`flex flex-col items-center justify-center rounded-2xl border border-dashed border-border p-10 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-bold text-muted-foreground`,children:`No seeds match your search.`}),(0,W.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground/70`,children:`Try a different term or clear the filters.`}),M&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`jump-clear-filters`,onClick:()=>{n(``),i(void 0),m(void 0),f(!1)},className:`mt-3 h-8 rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground transition-colors hover:border-primary/50 hover:text-primary`,children:`Clear filters`})]})})}),(0,W.jsx)(`div`,{className:`mx-auto w-full max-w-6xl px-4 sm:px-6`,children:(0,W.jsx)(`p`,{className:`mt-4 font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60 xl:text-[11px]`,children:`— or keep scrolling ↓`})})]})}var N0=`wods/examples/home/welcome-1.md`;function P0({wodFiles:e,theme:t,quests:n}){let r=jK(`(prefers-reduced-motion: reduce)`),i=cK()?.track;uK(`/`);let a=(0,U.useMemo)(()=>pB(N0,e),[e]),[o,s]=(0,U.useState)(()=>Q$()),c=o?.content??a,l=o?o.by?.trim()||`anonymous`:void 0;(0,U.useEffect)(()=>{let e=e=>{let t=e.detail;t?.content&&(s(t),d(t.content))};return window.addEventListener(`wodwiki:home-shared`,e),()=>window.removeEventListener(`wodwiki:home-shared`,e)},[]);let[u,d]=(0,U.useState)(c),f=(0,U.useRef)(u);f.current=u;let p=(0,U.useRef)([]),m=(0,U.useRef)(!1),{run:h,start:g,finalize:_,end:v}=vK(),y=(0,U.useRef)(h);y.current=h;let b=(0,U.useRef)(!1),x=(0,U.useRef)(!1),S=(0,U.useRef)(null),[C,w]=(0,U.useState)(!1),T=(0,U.useRef)(!1),E=(0,U.useRef)(null),[D,O]=(0,U.useState)(null),[k,A]=(0,U.useState)(!1),j=(0,U.useRef)(k);j.current=k;let M=(0,U.useRef)(!1),N=(0,U.useRef)(()=>{}),[P,F]=(0,U.useState)(0),[I,L]=(0,U.useState)(!1),[R,ee]=(0,U.useState)(!1),[te,ne]=(0,U.useState)(null),re=(0,U.useCallback)(async(e,t,n)=>{if(!t||M.current)return!1;M.current=!0,x.current=!1,b.current=!1,S.current=null,ne(t),F(e=>e+1),L(!0),O(null),A(!0);try{await g(e,t,{pageTitle:`Home`,sectionTitle:n})}catch(e){return console.error(`[HomeTour] failed to persist playground run note:`,e),A(!1),ne(null),Q({title:`Could not start workout`,description:`The playground entry could not be saved.`,variant:`destructive`}),!1}finally{M.current=!1}return!0},[g]),ie=(0,U.useCallback)(async()=>{if(T.current=!1,w(!1),S.current)try{await _(S.current,!1),S.current=null}catch(e){console.error(`[HomeTour] retry save failed:`,e),Q({title:`Session still not saved`,description:`The run is kept — try again.`,variant:`destructive`});return}let e=E.current;if(E.current=null,e)switch(e.kind){case`apply-doc`:m.current=!1,d(e.doc),A(!1),ne(null),F(e=>e+1),L(!1);break;case`restart`:await re(e.doc,e.block,e.sectionTitle)}},[re,_]),ae=(0,U.useCallback)(e=>{if(!E.current){if(!y.current||x.current||!b.current||S.current){E.current=e,ie();return}E.current=e,T.current=!0,w(!0)}},[ie]),oe=(0,U.useRef)(null),se=(0,U.useRef)(null),ce=(0,U.useRef)(null);JX(`hero`,ce);let[le,z]=(0,U.useState)(!1),ue=(0,U.useRef)(le);ue.current=le;let de=(0,U.useCallback)(()=>{let e=document.getElementById(`tour-section-editor`),t=oe.current;if(!e||!t||typeof window.scrollTo!=`function`)return;let n=t.getBoundingClientRect().top+window.scrollY;window.scrollTo({top:Math.max(0,e.getBoundingClientRect().top+window.scrollY-n),behavior:r?`auto`:`smooth`})},[r]),fe=(0,U.useCallback)(()=>{z(!0),window.setTimeout(de,350)},[de]),B=(0,U.useCallback)(()=>{z(!1),window.scrollTo({top:0,behavior:r?`auto`:`smooth`})},[r]),pe=(0,U.useRef)(!1),me=(0,U.useCallback)(()=>{ae({kind:`apply-doc`,doc:c})},[c,ae]);(0,U.useEffect)(()=>{let e=se.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting?pe.current&&!j.current&&(pe.current=!1,me()):pe.current=!0});return t.observe(e),()=>t.disconnect()},[me]);let he=(0,U.useCallback)(()=>{$$(),s(null),ae({kind:`apply-doc`,doc:a})},[a,ae]),ge=(0,U.useCallback)(()=>{me();let e=document.getElementById(`tour-section-editor`),t=oe.current;if(!e||!t||typeof window.scrollTo!=`function`)return;let n=t.getBoundingClientRect().top+window.scrollY;window.scrollTo({top:Math.max(0,e.getBoundingClientRect().top+window.scrollY-n),behavior:r?`auto`:`smooth`})},[r,me]);AK({pageRoute:`/`,quests:n,initialSource:c,currentSource:u}),kK({pageRoute:`/`,quests:n,completedResults:D}),N.current=r1(`/`,n),e1({pageRoute:`/`,quests:n,running:R}),(0,U.useEffect)(()=>{let e=document.getElementById(`tour-section-insights`);if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&N.current?.(`session-insights`)});return t.observe(e),()=>t.disconnect()},[]);let _e=(0,U.useCallback)(e=>{d(e),e!==c&&!m.current&&(m.current=!0,i?.(sK.demoEdited))},[c,i]),ve=(0,U.useCallback)(e=>{p.current=e},[]),ye=(0,U.useCallback)((e,t,n,r)=>{if(n){if(i?.(sK.demoRun),r&&ee(!0),ne(n),A(!0),L(!0),F(e=>e+1),O(null),M.current||E.current){E.current={kind:`restart`,doc:t,block:n,sectionTitle:e};return}if(y.current&&b.current&&!x.current){E.current={kind:`restart`,doc:t,block:n,sectionTitle:e},T.current=!0,w(!0);return}if(y.current&&!x.current){v().then(()=>re(t,n,e));return}re(t,n,e)}},[re,v,i]),be=(0,U.useCallback)(()=>{ye(`Run`,f.current,p.current[0],!0)},[ye]),xe=(0,U.useCallback)(()=>{let e=()=>{let e=document.getElementById(`tour-section-insights`),t=oe.current;if(!e||!t||typeof window.scrollTo!=`function`)return;let n=t.getBoundingClientRect().top+window.scrollY,i=Math.max(0,e.getBoundingClientRect().top+window.scrollY-n);window.scrollTo({top:i,behavior:r?`auto`:`smooth`})};if(ue.current){e();return}z(!0),window.setTimeout(e,350)},[r]),Se=(0,U.useCallback)((e,t)=>{if(!(x.current&&!S.current))return(t.logs??[]).length===0?(x.current=!0,O(t),A(!1),xe(),ie()):(x.current=!0,_(t,t.completed).then(()=>{if(S.current=null,O(t),T.current||E.current)return A(!1),ie()}).catch(e=>{throw x.current=!1,b.current=!1,S.current=t,T.current=!1,w(!1),E.current=null,Q({title:`Session not saved`,description:`The run could not be recorded. Nothing was lost — your next action retries the save.`,variant:`destructive`}),e}))},[_,ie,xe]),Ce=(0,U.useCallback)(()=>{A(!1),xe()},[xe]),we=(0,U.useRef)(null),Te=(0,U.useCallback)(e=>{we.current=e},[]),Ee=(0,U.useCallback)(()=>{b.current=!0;let e=we.current;I&&e&&e.handle(new tp(void 0,e.nowProvider)),L(!1)},[I]),{setL3Items:De}=lM(),Oe=(0,U.useMemo)(()=>[{id:`tour-hero`,label:`Welcome`,level:3,action:{type:`scroll`,sectionId:`tour-hero`}},{id:`editor`,label:`Live Preview`,level:3,action:{type:`scroll`,sectionId:`tour-section-editor`}},{id:`insights`,label:`Session Insights`,level:3,action:{type:`scroll`,sectionId:`tour-section-insights`},secondaryAction:{id:`run-start`,label:`Run the workout`,action:{type:`call`,handler:be}}},{id:`boards`,label:`One Run Becomes Many`,level:3,action:{type:`scroll`,sectionId:`tour-section-boards`}},{id:`community-feeds`,label:`Library & Community Feeds`,level:3,action:{type:`scroll`,sectionId:`tour-section-community-feeds`}},{id:`offerings`,label:`Who owns the Data?`,level:3,action:{type:`scroll`,sectionId:`tour-section-offerings`}},{id:`university`,label:`Wod Wiki University`,level:3,action:{type:`scroll`,sectionId:`tour-section-university`}}],[be]);(0,U.useEffect)(()=>(De(Oe),()=>De([])),[De,Oe]),a1((0,U.useMemo)(()=>Oe.map(e=>e.action.type===`scroll`?e.action.sectionId:e.id),[Oe]));let ke=h?.block??te,Ae=k&&ke&&(0,W.jsx)(sX,{block:ke,resultId:h?.resultId,autoStart:I,externalStop:C,onRunStarted:Ee,onRuntimeReady:Te,onClose:Ce,onCompleteWorkout:Se},P),je=(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(M1,{}),(0,W.jsxs)(`p`,{className:`-mt-8 text-center font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground/60 xl:text-[11px]`,children:[`— or learn the language with examples`,` `,(0,W.jsx)(Nt,{to:`/syntax`,className:`text-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:`on the syntax page →`})]})]}),Me=(0,W.jsx)(YX,{gateId:`editor-pane`,segmentId:`hero`,className:`w-full max-w-[720px] xl:max-w-[820px] 2xl:max-w-[920px]`,children:(0,W.jsx)(PK,{title:l?l.toLowerCase().startsWith(`shared by`)?l:`shared by: ${l}`:`welcome-1.md`,headerActions:l&&(0,W.jsx)(`button`,{type:`button`,onClick:he,title:`Reset`,className:`rounded-md border border-border px-2 py-1 text-[10px] transition-colors hover:bg-accent`,"data-testid":`tour-hero-reset-shared`,children:`Reset`}),className:`h-[540px] lg:h-[600px] 2xl:h-[640px]`,children:(0,W.jsx)(N1,{doc:u,theme:t,onDocChange:_e,onBlocksChange:ve,onRun:be})})}),Ne=(0,W.jsx)(`div`,{id:`tour-why-video-wrap`,"aria-hidden":le,className:G(`grid w-full transition-all duration-300 motion-reduce:transition-none`,le?`grid-rows-[0fr] opacity-0 invisible`:`grid-rows-[1fr] opacity-100`),children:(0,W.jsx)(`div`,{className:`min-h-0 overflow-hidden`,children:(0,W.jsx)(m1,{onWatched:fe})})}),Pe=(0,W.jsxs)(`div`,{ref:se,id:`tour-section-editor`,"data-testid":`tour-section-editor`,className:`flex w-full flex-col items-center px-5 py-8 text-center lg:px-10 xl:py-10 2xl:px-16`,children:[le&&(0,W.jsxs)(`button`,{type:`button`,onClick:B,"data-testid":`tour-why-watch-again`,className:`inline-flex items-center gap-1.5 rounded-t-lg border border-b-0 border-border bg-muted/40 px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground transition-colors hover:text-foreground`,children:[(0,W.jsx)(pn,{className:`size-3`}),`Watch again`]}),Me]});return r?(0,W.jsxs)(`div`,{"data-testid":`home-tour`,children:[(0,W.jsxs)(`section`,{id:`tour-hero`,"data-testid":`tour-hero`,className:`flex flex-col items-center gap-5 px-6 py-6 text-center`,children:[(0,W.jsx)(f1,{}),Ne,Pe]}),(0,W.jsx)(f0,{session:D,onRun:be,onBackToEditor:ge}),(0,W.jsx)(M0,{}),je,(0,W.jsx)(lQ,{variant:`university`}),(0,W.jsx)(g1,{}),Ae]}):(0,W.jsxs)(`div`,{"data-testid":`home-tour`,children:[(0,W.jsx)(`div`,{ref:oe,"aria-hidden":!0,className:`h-px`}),(0,W.jsxs)(`section`,{ref:ce,id:`tour-hero`,"data-testid":`tour-hero`,className:`relative flex min-h-[calc(100dvh-65px)] flex-col items-center justify-center gap-5 px-5 py-6 text-center lg:min-h-[calc(100dvh-104px)] lg:px-10 xl:gap-7 xl:py-8 2xl:px-16`,children:[(0,W.jsx)(f1,{}),Ne,Pe]}),(0,W.jsx)(f0,{session:D,onRun:be,onBackToEditor:ge}),(0,W.jsx)(M0,{}),je,(0,W.jsx)(lQ,{variant:`university`}),(0,W.jsx)(g1,{}),Ae]})}function F0(e){return(0,W.jsx)(s1,{children:(0,W.jsx)(qX,{children:(0,W.jsx)(P0,{...e})})})}function I0({wodFiles:e,theme:t}){let n=BI(`/`);return n?(0,W.jsx)(F0,{wodFiles:e,theme:t,quests:n.quests??[]}):(0,W.jsx)(`div`,{className:`flex items-center justify-center p-20 text-muted-foreground`,children:`Home canvas content not found (markdown/canvas/routes/home.md)`})}var L0=`idle`,R0=new Set,z0=null,B0=null;function V0(){for(let e of R0)e()}function H0(e){typeof document>`u`||(document.documentElement.dataset.seedState=e)}function U0(e){typeof document>`u`||(e===null?delete document.documentElement.dataset.seedOutcome:document.documentElement.dataset.seedOutcome=e)}H0(L0);function W0(e){L0!==e&&(L0=e,H0(e),V0())}function G0(){z0&&=(clearTimeout(z0),null),B0&&=(B0.close(),null)}function K0(){G0(),U0(null),W0(`preparing`)}function q0(e){switch(U0(e),e){case`busy`:if(L0!==`preparing`)return;typeof BroadcastChannel<`u`&&!B0&&(B0=new BroadcastChannel(av),B0.onmessage=e=>{e.data?.kind===`seed-imported`&&(G0(),W0(`ready`))}),z0=setTimeout(()=>{wj().then(q0)},ej);break;case`error`:G0(),W0(`error`);break;default:G0(),W0(`ready`)}}function J0(){return L0===`idle`?`ready`:L0}function Y0(e){return R0.add(e),()=>R0.delete(e)}function X0(){return(0,U.useSyncExternalStore)(Y0,J0)}var Z0=null;function Q0(e={}){return Z0??=$0(e),Z0}async function $0(e){let t=e.sources??aj();await Mj(e).catch(e=>console.error(`[seedSync] checkpoint adoption failed`,e)),await lA(t,e.storage).catch(e=>console.error(`[seedSync] subscription migration failed`,e));let n=e.storage??Wk(),r;try{r=await n.getSeedMeta(sv(`core`))}catch{r=void 0}if(!r||r.seedVersion<=0){K0(),q0(await wj({...e,sources:t,onFirstPaint:()=>q0(`imported`)})),t.some(e=>e.id!==`core`&&eA(e.id))&&await wj({...e,sources:t}).catch(e=>console.error(`[seedSync] background boot sync failed`,e));return}q0(`current`),await wj({...e,sources:t}).catch(e=>console.error(`[seedSync] background boot sync failed`,e))}function e2(){let[e,t]=(0,U.useState)(null);return(0,U.useEffect)(()=>{let e=!1,n=()=>{kj().then(n=>{e||t(!n.libraryImported)}).catch(()=>{e||t(!0)})};n();let r=Vb(()=>n()),i=gj(()=>n()),a=null;if(typeof BroadcastChannel<`u`)try{a=new BroadcastChannel(av),a.onmessage=()=>n()}catch{}return()=>{e=!0,r(),i(),a?.close()}},[]),e}var t2=mA.ICONS,n2=({open:e,onOpenChange:t,onCreate:n})=>{let[r,i]=(0,U.useState)(``),[a,o]=(0,U.useState)(``),[s,c]=(0,U.useState)(`📓`),[l,u]=(0,U.useState)(!1),d=async()=>{if(!(!r.trim()||l)){u(!0);try{if(!await n(r.trim(),a.trim(),s))return;i(``),o(``),c(`📓`),t(!1)}finally{u(!1)}}};return(0,W.jsx)(_U,{open:e,onOpenChange:t,children:(0,W.jsxs)(vU,{className:`bg-popover text-popover-foreground border border-border`,children:[(0,W.jsxs)(yU,{children:[(0,W.jsx)(bU,{className:`text-foreground`,children:`Create Notebook`}),(0,W.jsx)(xU,{children:`Organize your sessions into collections.`})]}),(0,W.jsxs)(`div`,{className:`space-y-4 mt-2`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`label`,{className:`text-sm font-medium text-foreground/80 mb-2 block`,children:`Icon`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:t2.map(e=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>c(e),className:G(`w-9 h-9 rounded-md flex items-center justify-center text-lg transition-all`,`hover:bg-accent hover:scale-110`,s===e?`bg-primary/20 ring-2 ring-primary scale-110`:`bg-muted/50`),children:e},e))})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`label`,{className:`text-sm font-medium text-foreground/80 mb-1 block`,children:[`Name `,(0,W.jsx)(`span`,{className:`text-destructive`,children:`*`})]}),(0,W.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&r.trim()&&(e.preventDefault(),d())},placeholder:`e.g., Morning Routines`,autoFocus:!0,className:G(`w-full px-3 py-2 rounded-md text-sm`,`bg-background border border-border`,`text-foreground placeholder:text-muted-foreground`,`focus:outline-none focus:ring-2 focus:ring-primary/50`,`transition-colors`)})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`label`,{className:`text-sm font-medium text-foreground/80 mb-1 block`,children:[`Description `,(0,W.jsx)(`span`,{className:`text-muted-foreground text-xs`,children:`(optional)`})]}),(0,W.jsx)(`textarea`,{value:a,onChange:e=>o(e.target.value),placeholder:`A brief description of this notebook...`,rows:2,className:G(`w-full px-3 py-2 rounded-md text-sm resize-none`,`bg-background border border-border`,`text-foreground placeholder:text-muted-foreground`,`focus:outline-none focus:ring-2 focus:ring-primary/50`,`transition-colors`)})]}),(0,W.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,W.jsx)(K,{variant:`ghost`,size:`sm`,onClick:()=>t(!1),children:`Cancel`}),(0,W.jsx)(K,{variant:`default`,size:`sm`,onClick:()=>void d(),disabled:!r.trim()||l,children:l?`Creating…`:`Create`})]})]})]})})};function r2({value:e,max:t,label:n,className:r}){let i=Math.max(1,t),a=Math.min(Math.max(e,0),i),o=Math.round(a/i*100),s=(0,U.useRef)(a),[c,l]=(0,U.useState)(!1);return(0,U.useEffect)(()=>{if(a>s.current){l(!0);let e=setTimeout(()=>l(!1),200);return s.current=a,()=>clearTimeout(e)}s.current=a},[a]),(0,W.jsxs)(`div`,{className:G(`w-full`,r),children:[n?(0,W.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between text-[11px] font-semibold uppercase tracking-[0.14em] text-brand-deep dark:text-brand-light`,children:[(0,W.jsx)(`span`,{children:n}),(0,W.jsxs)(`span`,{className:`tabular-nums text-muted-foreground`,children:[a,`/`,i]})]}):null,(0,W.jsx)(`div`,{role:`progressbar`,"aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":i,"aria-label":n??`Progress`,className:`h-2 w-full overflow-hidden rounded-pill bg-brand/10`,children:(0,W.jsx)(`div`,{className:G(`h-full rounded-pill transition-[width] duration-500 ease-out`,c?`bg-brand-deep`:`bg-brand`),style:{width:`${o}%`}})})]})}function i2(e,t,n){gV.getState().open({placeholder:`Craft the query…`,wql:{initialQuery:e,execute:t,onApply:n},sources:[oH()]})}function a2({query:e,onQueryChange:t,scopeOptions:n,execute:r,defaultQuery:i,compact:a=!1,className:o}){let s=(0,U.useCallback)(()=>i2(e,r,t),[e,r,t]);return a?(0,W.jsx)(`div`,{"data-testid":`stream-query-bar-dock`,className:G(`flex min-h-12 w-full items-stretch overflow-hidden rounded-xl border border-border bg-muted/40 shadow-xs`,o),children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`stream-query-bar`,onClick:s,className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 px-3 text-left transition-colors hover:bg-muted/70`,children:[(0,W.jsx)(Tt,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{"data-testid":`stream-query-summary`,className:`min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground`,children:e||i||`Filter or search…`}),(0,W.jsx)(In,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`})]})}):(0,W.jsx)(`div`,{"data-testid":`stream-query-bar`,className:G(`flex min-w-0 flex-1 items-center gap-1 text-xs`,o),children:(0,W.jsx)(aw,{query:e,onQueryChange:t,compact:!0,showDiagnostics:!1,preferredChoices:n,placeholder:`Filter or search…`,className:`min-w-0 flex-1`})})}function o2(e,t){let n=t??X(e);return n.error?null:n.groupBy?.length?n.groupBy.map(e=>String(e).toLowerCase()):null}function s2(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``)||`default`}function c2(e,t=`date`,n){let r=(Array.isArray(t)?t:[t]).map(e=>String(e).toLowerCase()).filter(Boolean);r.length===0&&r.push(`date`);let i=(e,t)=>{let r=l2(e,t[0],n);return t.length===1?r:r.flatMap(e=>e.key===`shelf`?[e]:i(e.entries,t.slice(1)).map(t=>({...t,key:`${e.key}/${t.key}`,id:`${e.id}--${t.id}`,label:`${e.label} / ${t.label}`,isToday:e.isToday||t.isToday})))};return i(e,r)}function l2(e,t,n){let r=t.toLowerCase(),i=WV();if(r===`date`||r===`day`){let t=new Map,r=[],a=[];for(let i of e){let e=i.date??(i.sourceCatalog===`playground`&&i.createdAt&&i.createdAt>9466848e5?new Date(i.createdAt).toISOString().slice(0,10):null);if(n?.shelfVisible&&(i.kind===`session`||e==null))r.push(i);else if(e){let n=t.get(e);n?n.push(i):t.set(e,[i])}else a.push(i)}let o=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)),s=[];n?.shelfVisible&&r.length>0&&s.push({id:`group-shelf`,key:`shelf`,label:`Catalog Sessions`,entries:r});for(let e of o)s.push({id:`date-group-${e}`,key:e,label:e===i?`Today`:GV(e),isToday:e===i,entries:t.get(e)??[]});return a.length>0&&s.push({id:`group-date-undated`,key:`undated`,label:`Undated`,entries:a}),s}if(r===`week`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let[e,i,a]=r.date.split(`-`).map(Number),o=new Date(Date.UTC(e,i-1,a)),s=o.getUTCDay(),c=o.getUTCDate()-s+(s===0?-6:1),l=new Date(Date.UTC(e,i-1,c)),u=l.toISOString().slice(0,10),d=`Week of ${l.toLocaleDateString(`en`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`})}`,f=t.get(u);f?f.entries.push(r):t.set(u,{label:d,entries:[r]})}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-week-${e}`,key:e,label:t.get(e).label,entries:t.get(e).entries}));return n.length>0&&r.push({id:`group-week-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`month`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let e=r.date.slice(0,7),[i,a]=e.split(`-`).map(Number),o=new Date(Date.UTC(i,a-1,1)).toLocaleDateString(`en`,{month:`long`,year:`numeric`,timeZone:`UTC`}),s=t.get(e);s?s.entries.push(r):t.set(e,{label:o,entries:[r]})}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-month-${e}`,key:e,label:t.get(e).label,entries:t.get(e).entries}));return n.length>0&&r.push({id:`group-month-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`year`){let t=new Map,n=[];for(let r of e){if(!r.date){n.push(r);continue}let e=r.date.slice(0,4),i=t.get(e);i?i.push(r):t.set(e,[r])}let r=Array.from(t.keys()).sort((e,t)=>t.localeCompare(e)).map(e=>({id:`group-year-${e}`,key:e,label:e,entries:t.get(e)??[]}));return n.length>0&&r.push({id:`group-year-undated`,key:`undated`,label:`Undated`,entries:n}),r}if(r===`discipline`){let t=new Map;for(let n of e){let e=n.effort?.discipline||n.tags?.find(e=>[`strength`,`gymnastics`,`cardio`,`running`,`rowing`,`weightlifting`,`olympic-weightlifting`].includes(e.toLowerCase()))||`General`,r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),i=t.get(r);i?i.push(n):t.set(r,[n])}return AP(Array.from(t.entries()),`priority-then-alpha`,{priority:[`Strength`,`Gymnastics`,`Cardio`,`Running`,`Rowing`,`Weightlifting`]}).map(([e])=>e).map(e=>({id:`group-discipline-${s2(e)}`,key:e,label:e,entries:t.get(e)??[]}))}if(r===`origin`){let t=new Map;for(let n of e){let e=n.effort?.registrySource===`bundled`?`Bundled Standards`:`Custom Movements`,r=t.get(e);r?r.push(n):t.set(e,[n])}return AP(Array.from(t.entries()),`alpha`).map(([e,t])=>({id:`group-origin-${s2(e)}`,key:e,label:e,entries:t}))}if(r===`source`||r===`notebook`){let t=new Map;for(let n of e){let e=n.sourceCatalog||`Other`,r=e.charAt(0).toUpperCase()+e.slice(1),i=t.get(r);i?i.push(n):t.set(r,[n])}return AP(Array.from(t.entries()),`alpha`).map(([e,t])=>({id:`group-source-${s2(e)}`,key:e,label:e,entries:t}))}if(r===`kind`||r===`type`){let t=new Map;for(let n of e){let e=n.kind.charAt(0).toUpperCase()+n.kind.slice(1)+`s`,r=t.get(e);r?r.push(n):t.set(e,[n])}return AP(Array.from(t.entries()),`alpha`).map(([e,t])=>({id:`group-kind-${s2(e)}`,key:e,label:e,entries:t}))}if(!Kp.includes(r)){let t=new Map;for(let n of e){let e=n.typedTags?.find(e=>e.type?.toLowerCase()===r)?.label??`Unassigned`,i=t.get(e);i?i.push(n):t.set(e,[n])}return AP(Array.from(t.entries()),`alpha-sink-last`,{sink:`Unassigned`}).map(([e,t])=>({id:`group-property-${s2(r)}-${s2(e)}`,key:e,label:e,entries:t}))}let a=new Map;for(let t of e){let e=t.tags?.[0]?`#${t.tags[0]}`:`Untagged`,n=a.get(e);n?n.push(t):a.set(e,[t])}return AP(Array.from(a.entries()),`alpha-sink-last`,{sink:`Untagged`}).map(([e,t])=>({id:`group-tag-${s2(e)}`,key:e,label:e,entries:t}))}var u2=[{id:CM.route,label:`Journal`,profile:CM,scopeChoices:qS,shortcuts:!0},{id:TM.route,label:`Notes`,profile:TM,scopeChoices:qS,shortcuts:!0},{id:wM.route,label:`Notebooks`,profile:wM,scopeChoices:qS,shortcuts:!0},{id:EM.route,label:`Efforts`,profile:EM,scopeChoices:qS,shortcuts:!0},{id:DM.route,label:`Equipment`,profile:DM,scopeChoices:qS,shortcuts:!0},{id:OM.route,label:`Sessions`,profile:OM,scopeChoices:qS,shortcuts:!0},{id:kM.route,label:`Playgrounds`,profile:kM,scopeChoices:qS,shortcuts:!0}],d2={id:`/dashboards`,label:`Dashboards`,systemDefaultWql:`:dashboard{}`},f2={id:PP,label:`Command palette`,systemDefaultWql:nH,scopeChoices:qS},p2=[...u2,d2,f2];function m2(e){return p2.find(t=>t.id===e)}function h2({className:e,...t}){return(0,W.jsx)(Ce,{"data-slot":`control`,...t,className:G(e,`group relative isolate inline-flex h-6 w-10 cursor-default rounded-full p-[3px] sm:h-5 sm:w-8`,`transition duration-0 ease-in-out data-changing:duration-200`,`forced-colors:outline forced-colors:bg-[Highlight] dark:forced-colors:bg-[Highlight]`,`bg-muted ring-1 ring-black/5 ring-inset dark:bg-white/5 dark:ring-white/15`,`data-checked:bg-primary data-checked:ring-primary/90`,`dark:data-checked:bg-primary dark:data-checked:ring-primary/90`,`focus:not-data-[focus]:outline-hidden data-[focus]:outline-2 data-[focus]:outline-offset-2 data-[focus]:outline-ring`,`data-[hover]:ring-black/15 dark:data-[hover]:ring-white/25 data-[hover]:data-checked:ring-primary/90 dark:data-[hover]:data-checked:ring-primary/90`,`data-[disabled]:bg-muted dark:data-[disabled]:bg-white/15 data-[disabled]:opacity-50 data-[disabled]:data-checked:bg-muted dark:data-[disabled]:data-checked:bg-white/15 data-[disabled]:data-checked:ring-black/5 dark:data-[disabled]:data-checked:ring-white/15`),children:(0,W.jsx)(`span`,{"aria-hidden":`true`,className:G(`pointer-events-none relative inline-block size-4.5 rounded-full sm:size-3.5`,`translate-x-0 transition duration-200 ease-in-out`,`border border-transparent`,`bg-background shadow-sm ring-1 ring-black/5 dark:ring-white/5`,`group-data-checked:bg-primary-foreground group-data-checked:shadow-sm group-data-checked:ring-primary/90`,`group-data-checked:translate-x-4 sm:group-data-checked:translate-x-3`,`group-data-checked:group-data-[disabled]:bg-background group-data-checked:group-data-[disabled]:shadow-sm group-data-checked:group-data-[disabled]:ring-black/5 dark:group-data-checked:group-data-[disabled]:ring-white/5`)})})}var g2=Object.fromEntries([...qS,...KS].map(e=>[e.value,e.label]));function _2({values:e,choices:t,labels:n,onChange:r,testPrefix:i,reorderable:a=!1}){let o=(t,n)=>{let i=[...e],a=t+n;if(a<0||a>=i.length)return;let o=i[t];i[t]=i[a],i[a]=o,r(i)};return(0,W.jsxs)(`div`,{className:`space-y-2`,children:[e.length>0&&(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map((t,s)=>(0,W.jsxs)(`span`,{"data-testid":`${i}-chip-${t}`,className:`inline-flex items-center gap-1 rounded-full border border-border/70 bg-muted/40 px-2.5 py-1 text-xs font-medium`,children:[n[t]??t,a&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`button`,{type:`button`,"aria-label":`Move ${t} up`,"data-testid":`${i}-up-${t}`,disabled:s===0,onClick:()=>o(s,-1),className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,children:(0,W.jsx)(xt,{className:`size-3`})}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Move ${t} down`,"data-testid":`${i}-down-${t}`,disabled:s===e.length-1,onClick:()=>o(s,1),className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,children:(0,W.jsx)(h,{className:`size-3`})})]}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Remove ${t}`,"data-testid":`${i}-remove-${t}`,onClick:()=>r(e.filter(e=>e!==t)),className:`text-muted-foreground hover:text-foreground`,children:(0,W.jsx)(we,{className:`size-3`})})]},t))}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.filter(t=>!e.includes(t.value)).map(t=>(0,W.jsxs)(`button`,{type:`button`,"aria-label":`Add ${t.value}`,"data-testid":`${i}-add-${t.value}`,onClick:()=>r([...e,t.value]),className:`rounded-full border border-dashed border-border/70 px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground hover:border-foreground/40`,children:[`+ `,t.label]},t.value))})]})}function v2({values:e,choices:t,onChange:n,testPrefix:r}){return(0,W.jsx)(_2,{values:e,choices:t,labels:g2,onChange:n,testPrefix:r,reorderable:!0})}function y2({values:e,onChange:t,testPrefix:n}){return(0,W.jsx)(_2,{values:e,choices:EP.map(e=>({value:e.id,label:e.label})),labels:Object.fromEntries(EP.map(e=>[e.id,e.label])),onChange:t,testPrefix:n,reorderable:!0})}function b2({label:e,enabled:t,onEnabledChange:n,testId:r,children:i}){return(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,W.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:e}),(0,W.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[`Custom`,(0,W.jsx)(h2,{checked:t,onChange:n,"data-testid":r})]})]}),i]})}function x2({shortcuts:e,icons:t,landingId:n,onEdit:r,onDelete:i,onCreate:a,error:o,testPrefix:s}){return(0,W.jsxs)(`div`,{className:`space-y-2`,"data-testid":`${s}-shortcuts`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Saved shortcuts`}),(0,W.jsx)(K,{variant:`ghost`,size:`sm`,onClick:a,"data-testid":`${s}-shortcut-new`,children:`New shortcut`})]}),e.map(e=>{let a=t[e.icon]??t.bookmark,o=e.to?`Opens ${e.to}`:e.wql||`Landing (no query)`;return(0,W.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border/50 px-2 py-1.5`,"data-testid":`${s}-shortcut-${e.id}`,children:[(0,W.jsx)(a,{className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`min-w-0 max-w-40 truncate text-xs font-medium`,children:e.label}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-[10px] text-muted-foreground`,children:o}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Edit ${e.label}`,"data-testid":`${s}-shortcut-edit-${e.id}`,onClick:()=>r(e),className:`shrink-0 rounded p-1 text-muted-foreground hover:text-foreground`,children:(0,W.jsx)(Kt,{className:`size-3`})}),!e.to&&e.id!==n&&(0,W.jsx)(`button`,{type:`button`,"aria-label":`Delete ${e.label}`,"data-testid":`${s}-shortcut-delete-${e.id}`,onClick:()=>i(e.id),className:`shrink-0 rounded p-1 text-muted-foreground hover:text-destructive`,children:(0,W.jsx)(Ue,{className:`size-3`})})]},e.id)}),o&&(0,W.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`${s}-shortcut-error`,children:o})]})}function S2(e){return{defaultWql:e.defaultWql??``,customScope:e.typeOptions!==void 0,scopeOptions:e.typeOptions??[],customGroupBy:e.groupByOptions!==void 0,groupByOptions:e.groupByOptions??[]}}function C2(e){return{defaultWql:e.defaultWql.trim()||void 0,typeOptions:e.customScope?e.scopeOptions:void 0,groupByOptions:e.customGroupBy?e.groupByOptions:void 0}}function w2({surface:e,onSaved:t}){let n=ZP(e.id),r=bP(e.id),[i,a]=(0,U.useState)(()=>S2(n)),[o,s]=(0,U.useState)(()=>n),[c,l]=(0,U.useState)(null),[u,d]=(0,U.useState)(null),[f,p]=(0,U.useState)(null);(0,U.useEffect)(()=>{a(S2(n)),s(n),l(null),d(null)},[n]);let m=e.profile?.defaultWql??e.systemDefaultWql??``,h=(()=>{let e=i.defaultWql.trim();return e?XC(e).error??null:null})(),g=C2(i),_=JSON.stringify(g)!==JSON.stringify(o),v=Object.values(o).some(e=>e!==void 0),y=[...o.invalidTypeOptions??[],...o.invalidGroupByOptions??[]],b=async()=>{if(!_)return;let n=i.defaultWql.trim();if(!(n&&XC(n).error)){if(!await WP(e.id,g)){l(`Save failed — storage is unavailable; the previous default still stands.`);return}l(null),s(UP(e.id)),t?.()}},x=async()=>{if(!await GP(e.id)){l(`Reset failed — storage is unavailable; the stored override still stands.`);return}l(null),s({}),a(S2({})),t?.()},S=async t=>{d(null),await mP(e.id,r.filter(e=>e.id!==t))||d(`Delete failed — storage is unavailable. Nothing was lost; the link remains.`)},C=e.scopeChoices??[],w=C.length>0;return(0,W.jsxs)(`div`,{className:`space-y-5`,"data-testid":`query-settings-panel`,children:[(0,W.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,W.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground`,children:`Landing default query`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`System default: `,(0,W.jsx)(`span`,{className:`font-mono`,children:m})]}),(0,W.jsx)(`textarea`,{rows:2,value:i.defaultWql,onChange:e=>a({...i,defaultWql:e.target.value}),placeholder:m,"data-testid":`query-settings-wql`,className:`w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs focus:outline-none focus:ring-1 focus:ring-primary/40`}),h?(0,W.jsxs)(`p`,{className:`text-xs text-destructive`,"data-testid":`query-settings-wql-error`,children:[`Couldn't parse — `,h]}):!i.defaultWql.trim()&&(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Empty — the system default is used.`})]}),y.length>0&&(0,W.jsxs)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-settings-invalid`,children:[`Stored options no longer recognized: `,y.join(`, `),` — remove them; they are never turned into query clauses.`]}),w&&(0,W.jsx)(b2,{label:`Where-stored options`,enabled:i.customScope,onEnabledChange:e=>a({...i,customScope:e}),testId:`query-settings-scope-custom`,children:i.customScope&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(v2,{values:i.scopeOptions,choices:C,onChange:e=>a({...i,scopeOptions:e}),testPrefix:`query-settings-scope`}),i.scopeOptions.length===0&&(0,W.jsx)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-settings-scope-empty`,children:`No predefined options — the page nudges for a pick instead.`})]})}),e.profile&&(0,W.jsxs)(b2,{label:`Group-by options`,enabled:i.customGroupBy,onEnabledChange:e=>a({...i,customGroupBy:e}),testId:`query-settings-group-custom`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The dimensions this page offers first, and the one a bare landing groups by. Order is the priority.`}),i.customGroupBy&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(y2,{values:i.groupByOptions,onChange:e=>a({...i,groupByOptions:e}),testPrefix:`query-settings-group`}),i.groupByOptions.length===0&&(0,W.jsx)(`p`,{className:`text-xs text-amber-600 dark:text-amber-400`,"data-testid":`query-settings-group-empty`,children:`No favorites — the page groups by its own default.`})]})]}),e.shortcuts&&(0,W.jsx)(x2,{shortcuts:r,icons:iP,landingId:`all`,onEdit:e=>p({editing:e}),onDelete:S,onCreate:()=>p({editing:null}),error:u,testPrefix:`query-settings`}),c&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,"data-testid":`query-settings-storage-error`,role:`alert`,children:c}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,W.jsxs)(K,{variant:`ghost`,size:`sm`,onClick:x,disabled:!v,"data-testid":`query-settings-reset`,children:[(0,W.jsx)(At,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Reset to system default`})]}),(0,W.jsx)(K,{size:`sm`,onClick:b,disabled:!_||!!h,"data-testid":`query-settings-save`,children:`Save`})]}),f&&(0,W.jsx)(TP,{open:!0,onOpenChange:e=>{e||p(null)},route:e.id,editing:f.editing})]})}function T2({surface:e,open:t,onOpenChange:n}){return(0,W.jsx)(HS,{open:t,onClose:()=>n(!1),title:`${e.label} query settings`,description:`Override the landing query and the Where-stored / Group-By options for this page. An empty query uses the system default; an emptied options list nudges you to pick instead of presetting one. Option lists are favorites — they reorder choices, they don't change what queries mean.`,presentation:`sheet`,children:(0,W.jsx)(w2,{surface:e})})}var E2=mt,D2=Jn,O2=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(sn,{ref:n,className:G(`fixed inset-0 z-50 bg-black/80 dark:bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0`,e),...t}));O2.displayName=sn.displayName;var k2=U.forwardRef(({className:e,children:t,...n},r)=>(0,W.jsxs)(D2,{children:[(0,W.jsx)(O2,{}),(0,W.jsxs)(Rn,{ref:r,className:G(`fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg`,e),...n,children:[t,(0,W.jsxs)(bn,{className:`absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground`,children:[(0,W.jsx)(we,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]}));k2.displayName=Rn.displayName;var A2=({className:e,...t})=>(0,W.jsx)(`div`,{className:G(`flex flex-col space-y-1.5 text-center sm:text-left`,e),...t});A2.displayName=`DialogHeader`;var j2=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Ot,{ref:n,className:G(`text-lg font-semibold leading-none tracking-tight`,e),...t}));j2.displayName=Ot.displayName;var M2=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Ct,{ref:n,className:G(`text-sm text-muted-foreground`,e),...t}));M2.displayName=Ct.displayName;var N2=[`date`,`datetime-local`,`month`,`time`,`week`],P2=(0,U.forwardRef)(function({className:e,...t},n){return(0,W.jsx)(`span`,{"data-slot":`control`,className:G(`relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`sm:focus-within:after:ring-2 sm:focus-within:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:(0,W.jsx)(ee,{ref:n,...t,className:G(t.type&&N2.includes(t.type)&&[`[&::-webkit-datetime-edit-fields-wrapper]:p-0`,`[&::-webkit-date-and-time-value]:min-h-[1.5em]`,`[&::-webkit-datetime-edit]:inline-flex`,`[&::-webkit-datetime-edit]:p-0`,`[&::-webkit-datetime-edit-year-field]:p-0`,`[&::-webkit-datetime-edit-month-field]:p-0`,`[&::-webkit-datetime-edit-day-field]:p-0`,`[&::-webkit-datetime-edit-hour-field]:p-0`,`[&::-webkit-datetime-edit-minute-field]:p-0`,`[&::-webkit-datetime-edit-second-field]:p-0`,`[&::-webkit-datetime-edit-millisecond-field]:p-0`,`[&::-webkit-datetime-edit-meridiem-field]:p-0`],`relative block w-full appearance-none rounded-lg px-[calc(theme(spacing.3.5)-1px)] py-[calc(theme(spacing.2.5)-1px)]`,`sm:px-[calc(theme(spacing.3)-1px)] sm:py-[calc(theme(spacing.1.5)-1px)]`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6`,`border border-border/60 hover:border-border data-[hover]:border-border`,`bg-transparent dark:bg-white/5`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 dark:data-[disabled]:border-border/30 dark:data-[disabled]:bg-white/2.5`,`dark:scheme-dark`,e)})})}),F2=e=>HO(new Date(e)),I2=e=>{if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`};function L2(e,t){Q(e===`imported`?{title:`${t} synced`,description:`Content was imported from the published seed. Your own edits were kept.`}:e===`error`?{title:`${t} sync failed`,description:`Check your connection and the browser console for details.`,variant:`destructive`}:e===`busy`?{title:`Another tab is already syncing`,description:`Wait for it to finish, then try again.`}:{title:`${t}: nothing to import (${e})`})}var R2={imported:`Synced`,current:`Up to date`,"server-stale":`Published version is older than the stored version`,"update-pending":`Update available`,busy:`Another tab is syncing`,disabled:`Seed import is disabled`,error:`Sync failed`};function z2(e){switch(e.phase){case`checking`:return`Checking source…`;case`fetching`:return`Downloading ${e.chunkId}…`;case`applying`:return`Importing ${e.chunkId}…`;case`committed`:return`Committed ${e.chunkId}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??R2[e.outcome]}}function B2({source:e,running:t,disabled:n,onSync:r,onSubscribe:i,onUnsubscribe:a,onDelete:o,onAutoSync:s,onToggleNotebook:c,subscribedOnly:l}){let u=(0,U.useSyncExternalStore)(aA,()=>sA(e.id)),d=e.notebooks.filter(t=>t.id!==e.id),f=l?d.filter(e=>e.subscribed):d,p=e.autoImport,m=e.subscribed&&!e.upToDate&&e.remote!==null;return(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-3`,"data-testid":`seed-source-${e.id}`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0 flex-wrap`,children:[(0,W.jsx)(`span`,{className:`text-sm font-medium text-foreground truncate`,children:e.label}),(0,W.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded shrink-0 ${e.subscribed?`bg-emerald-500/10 text-emerald-600`:`bg-muted text-muted-foreground`}`,children:e.subscribed?`Subscribed`:`Not subscribed`}),p&&(0,W.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0`,children:`Core`})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0 flex-wrap justify-end`,children:[e.subscribed?m?(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>r(e.id),disabled:n,"data-testid":`seed-sync-${e.id}`,className:`gap-2`,children:[(0,W.jsx)(Rt,{className:`size-3.5 ${t?`animate-spin`:``}`}),(0,W.jsx)(`span`,{children:t?`Syncing…`:`Sync`})]}):(0,W.jsxs)(`span`,{className:`text-xs text-muted-foreground flex items-center gap-1.5`,"data-testid":`seed-current-${e.id}`,children:[(0,W.jsx)(Ft,{className:`size-3.5 text-emerald-500`}),e.remote===null?`Remote unreachable`:`Up to date`]}):(0,W.jsxs)(K,{size:`sm`,onClick:()=>i(e.id),disabled:n,"data-testid":`seed-subscribe-${e.id}`,className:`gap-2`,children:[(0,W.jsx)($e,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Subscribe`})]}),(0,W.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:e.subscribed?`Apply new published versions automatically during the load-time check. Turning it off never removes content.`:`Unsubscribed sources never auto-import.`,children:[(0,W.jsx)(`input`,{type:`checkbox`,className:`size-3.5 accent-primary`,checked:u,disabled:n||!e.subscribed,onChange:t=>s(e.id,t.target.checked),"aria-label":`Auto-sync ${e.label}`,"data-testid":`seed-autosync-${e.id}`}),(0,W.jsx)(`span`,{children:`Auto-sync`})]}),(0,W.jsxs)(`details`,{className:`relative shrink-0`,"data-testid":`seed-more-${e.id}`,children:[(0,W.jsx)(`summary`,{"aria-label":`More actions for ${e.label}`,className:`flex cursor-pointer list-none items-center justify-center rounded-md border border-border px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden`,children:`…`}),(0,W.jsxs)(`div`,{className:`absolute right-0 z-20 mt-1 flex w-64 max-w-[80vw] flex-col items-stretch gap-1.5 rounded-lg border border-border bg-card p-2 text-xs shadow-lg`,children:[e.url?(0,W.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`break-all font-mono text-primary hover:underline`,children:[`Published HTML: `,e.url]}):(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Published HTML: bundled with this app (no standalone URL)`}),e.repositoryUrl?(0,W.jsx)(`a`,{href:e.repositoryUrl,target:`_blank`,rel:`noopener noreferrer`,className:`break-all text-primary hover:underline`,children:`Git source directory`}):(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Git repository: not published`}),!p&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>a(e.id),disabled:n||!e.subscribed,"data-testid":`seed-unsubscribe-${e.id}`,className:`min-h-8 rounded-md px-2 text-left text-destructive hover:bg-destructive/10 disabled:opacity-50`,children:`Unsubscribe`}),!p&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>o(e.id),disabled:n,"data-testid":`seed-delete-${e.id}`,className:`min-h-8 rounded-md px-2 text-left text-destructive hover:bg-destructive/10 disabled:opacity-50`,children:`Delete source`})]})]})]})]}),e.url&&(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground font-mono break-all`,"data-testid":`seed-origin-${e.id}`,children:e.url}),e.description&&(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`seed-description-${e.id}`,children:e.description}),f.length>0&&(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/20 px-3 py-2`,"data-testid":`seed-notebooks-${e.id}`,children:[(0,W.jsxs)(`p`,{className:`text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:[f.length===1?`1 notebook`:`${f.length} notebooks`,` · `,l?`subscribed`:`available in this seed`]}),(0,W.jsx)(`ul`,{className:`mt-1.5 flex flex-col gap-1`,children:f.map(t=>(0,W.jsxs)(`li`,{"data-testid":`seed-notebook-${e.id}-${t.chunkId}`,className:`flex items-center justify-between gap-4 text-xs`,children:[(0,W.jsxs)(`span`,{className:t.imported?`flex min-w-0 items-center gap-1.5 text-foreground`:`flex min-w-0 items-center gap-1.5 text-muted-foreground`,children:[t.imported?(0,W.jsx)(Ft,{className:`size-3 shrink-0 text-emerald-500`,"aria-hidden":!0}):(0,W.jsx)($e,{className:`size-3 shrink-0 opacity-60`,"aria-hidden":!0}),(0,W.jsx)(`span`,{className:`truncate`,children:t.label})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,W.jsxs)(`span`,{className:`tabular-nums text-muted-foreground`,children:[t.count.toLocaleString(),` `,t.count===1?`item`:`items`]}),!p&&c&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>c(e.id,t.chunkId,!t.subscribed),"data-testid":`seed-notebook-toggle-${e.id}-${t.chunkId}`,className:`text-[10px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded shrink-0 transition-colors ${t.subscribed?`bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/20`:`border border-border text-muted-foreground hover:bg-muted`}`,children:t.subscribed?`Subscribed`:`Subscribe`})]})]},t.chunkId))})]}),(0,W.jsxs)(`div`,{className:`grid gap-1 text-sm`,"data-testid":`seed-status-card`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Library`}),(0,W.jsxs)(`span`,{className:`font-medium text-foreground text-xs tabular-nums`,"data-testid":`seed-source-size`,children:[e.count.toLocaleString(),` catalog `,e.count===1?`item`:`items`,` · `,I2(e.bytes)]})]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Local database`}),(0,W.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-local-version`,children:e.stored?`v${e.stored.version} · schema ${e.stored.schema} · imported ${F2(e.stored.importedAt)}`:`Not imported yet`})]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Published version`}),(0,W.jsx)(`span`,{className:`font-medium text-foreground text-xs flex items-center gap-1.5`,"data-testid":`seed-remote-version`,children:e.remote?`v${e.remote.version} · schema ${e.remote.schema}`:e.remoteError?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(vn,{className:`size-3.5 text-muted-foreground`}),`Unavailable`]}):`Checking…`})]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Last check`}),(0,W.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-last-check`,children:e.checkedAt?F2(e.checkedAt):`—`})]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Last sync`}),(0,W.jsx)(`span`,{className:`font-medium text-foreground text-xs`,"data-testid":`seed-last-sync`,children:e.stored?F2(e.stored.importedAt):`Never`})]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Status`}),(0,W.jsx)(`span`,{className:`font-medium text-xs flex items-center gap-1.5`,"data-testid":`seed-sync-status`,children:e.subscribed?e.upToDate?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(Ft,{className:`size-3.5 text-emerald-500`}),`Up to date`]}):e.remote==null?`Unknown (remote unreachable)`:u?`Update available — applied automatically on next load`:`Update available — sync to apply`:`Not subscribed`})]})]})]})}function V2(){let[e,t]=(0,U.useState)(null),[n,r]=(0,U.useState)(!0),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(null),[c,l]=(0,U.useState)([]),[u,d]=(0,U.useState)(``),[f,p]=(0,U.useState)(``),[m,h]=(0,U.useState)(null),[g,_]=(0,U.useState)(!0),[v,y]=(0,U.useState)(),b=(0,U.useCallback)(async()=>{a(null);try{t(await Aj())}catch(e){a(e instanceof Error?e.message:String(e))}finally{r(!1)}},[]);(0,U.useEffect)(()=>{b()},[b]),(0,U.useEffect)(()=>aA(()=>{b()}),[b]),(0,U.useEffect)(()=>gj(()=>{b()}),[b]);let x=(0,U.useCallback)(async t=>{s(t??`all`),l([]);let n=e=>l(t=>{let n=t.find(t=>t.event.sourceId===e.sourceId),r={event:e,imported:e.phase===`checking`||e.phase===`finished`?n?.imported??null:e,chunks:e.phase===`committed`&&e.chunkId!==null?[...n?.chunks??[],e.chunkId]:n?.chunks??[]};return n?t.map(t=>t.event.sourceId===e.sourceId?r:t):[...t,r]});try{L2(t?await Ej(t,{force:!0,onProgress:n}):await Cj({force:!0,onProgress:n}),t?e?.sources.find(e=>e.id===t)?.label??t:`All sources`),await b()}finally{s(null)}},[b,e]),C=(0,U.useCallback)(async(e,t,n)=>{rA(e,t,n),n?await x(e):await b()},[x,b]),w=(0,U.useCallback)(async()=>{h(null);let e;try{e=wk(u,f)}catch(e){h(e instanceof Error?e.message:String(e));return}d(``),p(``),await x(e.id)},[u,f,x]),T=(0,U.useCallback)((e,t)=>{cA(e,t)||Q({title:`Couldn't save Auto-sync`,description:`Browser storage is unavailable — the choice lasts this session only.`,variant:`destructive`}),b()},[b]),E=(0,U.useCallback)(async t=>{let n=e?.sources.find(e=>e.id===t)?.label??t;if(window.confirm(`Unsubscribe from "${n}"? Imported content for this catalog is removed from your library; the source stays listed so you can subscribe again. Your own notes are never touched.`)){try{let{deleted:e}=await Dj(t);Q({title:`${n} unsubscribed`,description:`${e.toLocaleString()} imported ${e===1?`item`:`items`} removed. The source stays listed for a later Subscribe.`})}catch(e){Q({title:`${n} unsubscribe failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`});return}await b()}},[e,b]),D=(0,U.useCallback)(async t=>{let n=e?.sources.find(e=>e.id===t)?.label??t;if(window.confirm(`Delete "${n}"? Imported content is removed and the source is unregistered. Your own notes are never touched.`)){try{let{deleted:e}=await Oj(t);Q({title:`${n} deleted`,description:`${e.toLocaleString()} imported ${e===1?`item`:`items`} removed and the source unregistered.`})}catch(e){Q({title:`${n} delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`});return}await b()}},[e,b]),O=c.at(-1)?.event;return(0,W.jsxs)(`div`,{className:`space-y-8`,children:[(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)($e,{className:`size-4 text-primary`}),`Content Sources`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`A seed is one published Markdown repository — its notebooks, notes, guides, dashboards, and efforts import into your active data location together. Subscribed seeds are checked against their published manifest on every load: Auto-sync applies updates by itself, otherwise you press Sync when an update is pending. The core seed imports automatically at launch and is always subscribed.`})]}),i&&(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-destructive`,"data-testid":`seed-status-error`,children:[(0,W.jsx)(vn,{className:`size-3.5 shrink-0`}),`Couldn't read the seed status from the active storage: `,i]}),O&&(0,W.jsxs)(`div`,{className:`space-y-3 rounded-xl border border-border bg-card p-4`,"data-testid":`seed-sync-progress`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4 text-sm font-medium`,children:[(0,W.jsx)(`span`,{children:o===null?c.some(e=>e.event.phase===`finished`&&e.event.outcome===`error`)?`Sync finished with errors`:`Sync finished`:`Syncing…`}),(0,W.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[`Source `,O.sourceIndex,` of `,O.totalSources]})]}),(0,W.jsxs)(`p`,{role:`status`,"aria-live":`polite`,className:`sr-only`,"data-testid":`seed-sync-live-status`,children:[O.sourceLabel,`: `,z2(O)]}),c.map(({event:e,imported:t,chunks:n})=>(0,W.jsxs)(`div`,{className:`space-y-2 border-t border-border/50 pt-3`,children:[(0,W.jsxs)(`p`,{className:`text-xs ${e.phase===`finished`&&e.outcome===`error`?`text-destructive`:`text-muted-foreground`}`,children:[(0,W.jsx)(`span`,{className:`font-medium text-foreground`,children:e.sourceLabel}),` · `,z2(e)]}),t&&t.totalChunks>0?(0,W.jsx)(r2,{value:t.completedChunks,max:t.totalChunks,label:`Chunks committed · ${e.sourceLabel}`}):e.phase===`finished`?null:(0,W.jsx)(`progress`,{"aria-label":`Checking ${e.sourceLabel}`,className:`h-2 w-full`}),t&&(0,W.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-xs tabular-nums`,"data-testid":`seed-sync-totals`,children:[(0,W.jsxs)(`span`,{children:[t.totalNotes.toLocaleString(),` notes`]}),(0,W.jsxs)(`span`,{children:[t.totalEfforts.toLocaleString(),` efforts`]}),(0,W.jsxs)(`span`,{children:[t.totalBlocks.toLocaleString(),` blocks`]}),t.skippedUserOwned>0&&(0,W.jsxs)(`span`,{children:[t.skippedUserOwned.toLocaleString(),` user-owned rows preserved`]}),t.deleted>0&&(0,W.jsxs)(`span`,{children:[t.deleted.toLocaleString(),` seed rows removed`]})]}),n.length>0&&(0,W.jsxs)(`details`,{className:`text-xs`,"data-testid":`seed-sync-chunks`,children:[(0,W.jsxs)(`summary`,{className:`cursor-pointer text-muted-foreground`,children:[`Committed chunks (`,n.length,`)`]}),(0,W.jsx)(`ul`,{className:`mt-2 max-h-32 space-y-1 overflow-y-auto font-mono text-muted-foreground`,children:n.map(e=>(0,W.jsx)(`li`,{children:e},e))})]})]},e.sourceId))]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 p-2.5 rounded-xl border border-border bg-card text-xs`,children:[(0,W.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer select-none text-muted-foreground hover:text-foreground`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked),"data-testid":`sync-subscribed-only-toggle`,className:`size-3.5 accent-primary rounded`}),(0,W.jsx)(`span`,{className:`font-medium text-foreground`,children:`Subscribed only`})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Source:`}),(0,W.jsxs)(`select`,{value:v??``,onChange:e=>y(e.target.value?e.target.value:void 0),"data-testid":`sync-seed-source-filter`,"aria-label":`Filter notebooks by seed source`,className:`h-8 rounded-md border border-border bg-background px-2 text-xs text-foreground outline-none transition-colors hover:border-foreground/25 focus:border-primary/50`,children:[(0,W.jsx)(`option`,{value:``,children:`All sources`}),e?.sources.map(e=>(0,W.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]})]}),(0,W.jsxs)(`div`,{className:`grid gap-3`,"data-testid":`seed-source-list`,children:[e?.sources.filter(e=>{if(v&&e.id!==v)return!1;if(g){let t=e.notebooks.some(e=>e.subscribed);if(!e.subscribed&&!t)return!1}return!0}).map(e=>(0,W.jsx)(B2,{source:e,running:o===e.id||o===`all`,disabled:o!==null,onSync:e=>{x(e)},onSubscribe:e=>{x(e)},onUnsubscribe:e=>{E(e)},onDelete:e=>{D(e)},onAutoSync:T,onToggleNotebook:C,subscribedOnly:g},e.id)),n&&e===null&&(0,W.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,children:`Checking sources…`})]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-between pt-3 border-t border-border/50`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sync re-applies every published chunk. Your own notes, results, and edits are never overwritten.`}),(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>{x(null)},disabled:o!==null||n,"data-testid":`seed-resync-button`,className:`gap-2`,children:[(0,W.jsx)(Rt,{className:`size-3.5 ${o===`all`?`animate-spin`:``}`}),(0,W.jsx)(`span`,{children:o===`all`?`Syncing all…`:`Sync All Sources`})]})]})]}),(0,W.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)(S,{className:`size-4 text-primary`}),`Add a Source`]}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Register any URL serving a Wod Wiki seed (a directory with `,(0,W.jsx)(`code`,{children:`manifest.json`}),` and`,` `,(0,W.jsx)(`code`,{children:`chunks/`}),`) — a community library mirror or one you compiled yourself. The host must allow cross-origin reads (CORS). Added sources sync immediately and start subscribed; manage Auto-sync, Unsubscribe, and Delete on each source card above.`]})]}),(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-3`,"data-testid":`seed-add-source-form`,children:[(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`label`,{htmlFor:`seed-source-label`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Label`}),(0,W.jsx)(P2,{id:`seed-source-label`,value:u,onChange:e=>d(e.target.value),placeholder:`My library (optional — defaults to the host name)`,disabled:o!==null})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`label`,{htmlFor:`seed-source-url`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Seed directory URL`}),(0,W.jsx)(P2,{id:`seed-source-url`,type:`text`,autoComplete:`off`,spellCheck:!1,value:f,onChange:e=>p(e.target.value),placeholder:`https://example.com/seed/library/`,className:`font-mono`,disabled:o!==null})]})]}),m&&(0,W.jsxs)(`p`,{role:`alert`,className:`flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`seed-add-error`,children:[(0,W.jsx)(vn,{className:`size-3.5 mt-0.5 shrink-0`}),(0,W.jsx)(`span`,{children:m})]}),(0,W.jsx)(`div`,{className:`flex justify-end`,children:(0,W.jsxs)(K,{size:`sm`,onClick:()=>{w()},disabled:o!==null||!f.trim(),"data-testid":`seed-add-button`,className:`gap-2`,children:[(0,W.jsx)(En,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Add & Sync`})]})})]})]})]})}function H2({open:e,onOpenChange:t}){return(0,W.jsx)(E2,{open:e,onOpenChange:t,children:(0,W.jsxs)(k2,{className:`max-h-[85vh] w-full max-w-2xl overflow-y-auto`,"data-testid":`catalogs-manager-drawer`,children:[(0,W.jsxs)(A2,{children:[(0,W.jsx)(j2,{children:`Seed Subscriptions & Local Libraries`}),(0,W.jsx)(M2,{children:`Manage the seeds stored in your active data location — compare versions, sync updates, and subscribe, unsubscribe, or delete sources. One Subscribe imports every notebook a seed publishes. Your own notes are never touched.`})]}),(0,W.jsx)(V2,{})]})})}var U2={stream:`cards`,table:`rows`},W2=`wodwiki.viewSettings.v1`,G2={"/sessions":`/results`,"/feeds":`/collections`},K2=new _b(W2);function q2(e,t){return{level:e,layout:t??`cards`,visibleFields:sB(e),groupBy:void 0}}function J2(e,t,n=K2,r){let i=q2(t,r),a=e.startsWith(`/`)?e:`/${e}`,o=G2[a],s=n.get(a,{alias:o});if(!s)return i;let c=typeof s.layout==`string`?s.layout:``,l=c===`cards`||c===`rows`||c===`feed`?c:U2[c]??`cards`,u=new Set(oB(t).map(e=>e.id)),d=Array.isArray(s.visibleFields)?s.visibleFields.filter(e=>typeof e==`string`&&u.has(e)):i.visibleFields,f=typeof s.groupBy==`string`?s.groupBy:void 0;return{level:t,layout:l,visibleFields:d.length>0?d:i.visibleFields,groupBy:f}}function Y2(e,t,n=K2){let r=e.startsWith(`/`)?e:`/${e}`;n.set(r,{level:t.level,layout:t.layout,visibleFields:t.visibleFields,groupBy:t.groupBy})}function X2(e,t,n=K2){let r=e.startsWith(`/`)?e:`/${e}`,i=G2[r];return n.remove(r,i),q2(t)}function Z2(e,t,n){let[r,i]=(0,U.useState)(()=>J2(e,t,K2,n));(0,U.useEffect)(()=>{i(J2(e,t,K2,n))},[e,t,n]);let a=(0,U.useCallback)(t=>{i(n=>{let r=t(n);return Y2(e,r),r})},[e]);return{settings:r,setLayout:(0,U.useCallback)(e=>{a(t=>({...t,layout:e}))},[a]),toggleField:(0,U.useCallback)(e=>{a(t=>{let n=new Set(t.visibleFields);return n.has(e)?n.delete(e):n.add(e),{...t,visibleFields:Array.from(n)}})},[a]),setVisibleFields:(0,U.useCallback)(e=>{a(t=>({...t,visibleFields:e}))},[a]),setGroupBy:(0,U.useCallback)(e=>{a(t=>({...t,groupBy:e}))},[a]),resetSettings:(0,U.useCallback)(()=>{let n=X2(e,t);i(n)},[e,t])}}function Q2(e,t=200){let[n,r]=(0,U.useState)(t),i=(0,U.useRef)(null);(0,U.useEffect)(()=>{r(t)},[e,t]);let a=n<e.length,o=(0,U.useCallback)(t=>r(n=>Math.max(n,Math.min(Math.max(t,0),e.length))),[e.length]);return(0,U.useEffect)(()=>{let n=i.current;if(!n||!a)return;let o=new IntersectionObserver(n=>{n.some(e=>e.isIntersecting)&&r(n=>Math.min(n+t,e.length))},{rootMargin:`400px`});return o.observe(n),()=>o.disconnect()},[a,e.length,t]),{visible:e.slice(0,n),hasMore:a,sentinelRef:i,total:e.length,growTo:o}}function $2(e,t){let n=X(e);return n.error||!xm(n)?e:dh({...n,metric:t})}function e4(e){let t=X(e);return t.error?e:dh({...t,window:void 0})}function t4(e,t){let n=X(e);return n.error?e:dh({...n,groupBy:[t]})}function n4(e){return e.kind===`session`&&!e.sourceItem?!1:e.kind===`note`||e.kind===`session`||e.kind===`post`}async function r4(e){if(e.wodBlock?.content.trim())return e.wodBlock.content;let t=await BN.resolve(e.id),n=zV(t&&typeof t==`object`&&`rawContent`in t?String(t.rawContent??``):``),r=n.find(e=>e.dialect===`time`)??n[0];if(!r)throw Error(`No runnable workout block in this entry.`);return r.script}function i4(e,t){return{id:e.wodBlock?.blockId??e.block?.blockId??w(),contentId:e.wodBlock?.blockContentId??e.blockContentId,dialect:`time`,startLine:0,endLine:t.split(`
168
+ `).length,content:t,state:`idle`,widgetIds:{},version:1,createdAt:Date.now()}}async function a4(e,t){let n=await r4(e),r=i4(e,n),i=w();if(ZV(e)){let n=await BN.getById(e.id),a=e.wodBlock||e.block?n.blocks?.[r.id]:Object.values(n.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The selected saved workout is unavailable.`);d$.set(i,{block:{...r,id:a.id},noteId:e.id,origin:`playground`,returnTo:XV(e)}),t(KM(i));return}let a=await QQ({workoutName:e.title,category:e.sourceCatalog,sourceNoteLabel:e.subtitle??e.title,sourceNotePath:XV(e),wodContent:n}),o=Object.values(a.blocks??{}).find(e=>e.kind===`wod`);if(!o)throw Error(`The saved journal workout is unavailable.`);d$.set(i,{block:{...r,id:o.id},noteId:a.id}),t(HM(a.journalDate??``,i))}var o4={note:u,session:Xn,post:zt,effort:Ye,result:qe,segment:s,event:ze,dashboard:an,equipment:O},s4={note:`Note`,session:`Session`,post:`Post`,effort:`Effort`,result:`Result`,segment:`Segment`,event:`Event`,dashboard:`Dashboard`,equipment:`Equipment`},c4={note:`bg-primary/10 text-primary group-hover:bg-primary/20`,session:`bg-amber-500/10 text-amber-600 group-hover:bg-amber-500/20`,post:`bg-violet-500/10 text-violet-600 group-hover:bg-violet-500/20`,effort:`bg-emerald-500/10 text-emerald-600 group-hover:bg-emerald-500/20`,result:`bg-sky-500/10 text-sky-600 group-hover:bg-sky-500/20`,segment:`bg-indigo-500/10 text-indigo-600 group-hover:bg-indigo-500/20`,event:`bg-indigo-500/10 text-indigo-600 group-hover:bg-indigo-500/20`,dashboard:`bg-cyan-500/10 text-cyan-600 group-hover:bg-cyan-500/20`,equipment:`bg-orange-500/10 text-orange-600 group-hover:bg-orange-500/20`};function l4({entry:e,leading:t,actions:n,dateLabel:r,visibleFieldIds:i,tone:a=`secondary`,onAddToToday:o,onRunStart:s}){let c=ht(),l=e.kind===`note`?e.sourceCatalog:void 0,u=l===`playground`?Ae:l===`guides`?tr:o4[e.kind],d=l===`playground`?`Playground`:l===`guides`?`Guide`:s4[e.kind],f=a===`primary`,p=QV(e),m=XV(e),h=i?new Set(i):null,g=!h||h.has(`date`),_=!h||h.has(`catalog`)||h.has(`protocol`)||h.has(`elapsedTime`)||h.has(`splitDuration`)||h.has(`discipline`)||h.has(`met`)||h.has(`canonicalSlug`),v=!h||h.has(`excerpt`)||h.has(`movements`)||h.has(`tags`)||h.has(`aliases`);return(0,W.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:()=>c(XV(e)),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),c(XV(e)))},className:`flex items-center gap-4 px-6 py-3.5 hover:bg-muted/40 transition-colors text-left group w-full cursor-pointer ${f?`bg-primary/[0.025]`:``}`,"data-testid":`library-row-${e.kind}`,children:[t,(0,W.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl flex items-center justify-center transition-colors ${c4[e.kind]}`,children:(0,W.jsx)(u,{className:`size-4`})}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-bold text-foreground min-w-0 basis-full sm:basis-auto sm:truncate`,children:e.title}),e.block&&(0,W.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-sky-600 border border-sky-500/40 bg-sky-500/10 rounded-full px-1.5 py-0.5`,"data-testid":`library-row-block-type`,children:e.block.dataType}),(0,W.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-muted-foreground/60 border border-border rounded-full px-1.5 py-0.5`,children:d}),e.execution?.effortSlug&&(0,W.jsx)(Nt,{to:nN(e.execution.effortSlug),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),"data-testid":`library-row-effort-link`,className:`text-[9px] font-bold tracking-wide text-primary/80 hover:text-primary bg-primary/10 hover:bg-primary/20 border border-primary/20 rounded-full px-2 py-0.5 transition-colors shrink-0`,title:`View movement history for ${e.detail??e.execution.effortSlug}`,children:e.detail??e.execution.effortSlug}),p&&(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,onClick:e=>e.stopPropagation(),children:[(0,W.jsx)(Nt,{to:m,"data-testid":`library-row-details-link`,className:`text-[9px] font-bold tracking-wide text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted border border-border rounded-full px-2 py-0.5 transition-colors`,title:`View catalog details`,children:`Details`}),(0,W.jsx)(Nt,{to:p,"data-testid":`library-row-feed-link`,className:`text-[9px] font-bold tracking-wide text-primary/80 hover:text-primary bg-primary/10 hover:bg-primary/20 border border-primary/20 rounded-full px-2 py-0.5 transition-colors`,title:`View feed`,children:`Feed`})]}),e.subtitle&&_&&(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground/60 truncate`,children:e.subtitle})]}),v&&(e.block?(0,W.jsx)(`div`,{className:`mt-0.5`,"data-testid":`library-row-block-preview`,children:e.block.preview.map((e,t)=>(0,W.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate font-mono`,children:e},t))}):e.detail?(0,W.jsx)(`p`,{className:`text-[11px] text-muted-foreground truncate mt-0.5`,children:e.detail}):null)]}),r&&g&&(0,W.jsx)(`span`,{className:`flex-shrink-0 text-[10px] text-muted-foreground/70 tabular-nums`,"data-testid":`library-row-date`,children:r}),n??(0,W.jsx)(u4,{entry:e,onAddToToday:o,onRunStart:s})]})}function u4({entry:e,onAddToToday:t,onRunStart:n}){let r=ht(),i=$V(e),a=QV(e),o=eH(e)&&!!t,s=n4(e)&&!!n;return(0,W.jsxs)(`div`,{className:`flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity`,onClick:e=>e.stopPropagation(),children:[(0,W.jsx)(d4,{title:a?`Details`:`Open`,testId:`action-open`,onClick:()=>r(XV(e)),children:(0,W.jsx)(pn,{className:`size-3.5`})}),a&&(0,W.jsx)(d4,{title:`Feed`,testId:`action-feed`,onClick:()=>r(a),children:(0,W.jsx)(Xn,{className:`size-3.5`})}),o&&(0,W.jsx)(d4,{title:`Add to today`,testId:`action-add`,onClick:()=>t?.(e),children:(0,W.jsx)(En,{className:`size-3.5`})}),s&&(0,W.jsx)(d4,{title:`Run`,testId:`action-run`,onClick:()=>n?.(e),children:(0,W.jsx)(pn,{className:`size-3.5`})}),i&&(0,W.jsx)(d4,{title:`Compare`,testId:`action-compare`,onClick:()=>r(i),children:(0,W.jsx)(Et,{className:`size-3.5`})})]})}function d4({title:e,testId:t,onClick:n,children:r}){return(0,W.jsx)(`button`,{type:`button`,title:e,onClick:n,"data-testid":t,className:`size-8 rounded-lg flex items-center justify-center text-muted-foreground hover:text-primary hover:bg-primary/10 transition-colors`,children:r})}function f4({entries:e,level:t,visibleFieldIds:n,onRowClick:r,emptyMessage:i=`No entries to display`,className:a=``,stickyHeaderTop:o}){let s=ht(),c=(0,U.useMemo)(()=>t||(e.length>0?rB(e[0]):`note`),[t,e]),l=(0,U.useMemo)(()=>oB(c),[c]),u=(0,U.useMemo)(()=>{let e=new Set(n??sB(c));return l.filter(t=>e.has(t.id))},[l,n,c]),d=e=>{r?r(e):s(XV(e))},[f,p]=(0,U.useState)(null),[m,h]=(0,U.useState)(`asc`),g=e=>{f===e?h(e=>e===`asc`?`desc`:`asc`):(p(e),h(`asc`))},_=(0,U.useMemo)(()=>{if(!f)return e;let t=l.find(e=>e.id===f);return t?[...e].sort((e,n)=>{let r=t.getValue(e),i=t.getValue(n);if(r==null&&i==null)return 0;if(r==null)return m===`asc`?1:-1;if(i==null)return m===`asc`?-1:1;if(typeof r==`number`&&typeof i==`number`)return m===`asc`?r-i:i-r;if(Array.isArray(r)&&Array.isArray(i)){let e=r.join(`, `),t=i.join(`, `);return m===`asc`?e.localeCompare(t):t.localeCompare(e)}let a=String(r),o=String(i);return m===`asc`?a.localeCompare(o):o.localeCompare(a)}):e},[e,f,m,l]);return e.length===0?(0,W.jsx)(`div`,{className:`w-full py-16 text-center text-sm text-muted-foreground ${a}`,"data-testid":`property-table-empty`,children:i}):(0,W.jsx)(`div`,{className:`w-full border-y border-border bg-card/50 ${o===void 0?`overflow-x-auto`:`overflow-x-clip`} ${a}`,"data-testid":`property-table`,children:(0,W.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,W.jsx)(`thead`,{className:o===void 0?void 0:`sticky z-10`,style:o===void 0?void 0:{top:`${o}px`},children:(0,W.jsx)(`tr`,{className:`border-b border-border`,children:u.map(e=>{let t=e.align===`right`?`text-right`:e.align===`center`?`text-center`:`text-left`;return(0,W.jsx)(`th`,{scope:`col`,onClick:()=>g(e.id),className:`px-4 py-3 font-semibold uppercase tracking-wider text-[11px] text-muted-foreground whitespace-nowrap border-b border-border cursor-pointer select-none hover:text-foreground transition-colors group/th ${o===void 0?`bg-muted/30`:`bg-muted/95 backdrop-blur-sm`} ${t}`,"data-testid":`property-table-header-${e.id}`,children:(0,W.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 ${t===`text-right`?`justify-end`:t===`text-center`?`justify-center`:`justify-start`}`,children:[(0,W.jsx)(`span`,{children:e.label}),f===e.id?(0,W.jsx)(`span`,{className:`text-primary font-bold text-xs`,"aria-label":m===`asc`?`sorted ascending`:`sorted descending`,children:m===`asc`?`↑`:`↓`}):(0,W.jsx)(`span`,{className:`opacity-0 group-hover/th:opacity-40 text-muted-foreground text-[10px]`,"aria-hidden":`true`,children:`↕`})]})},e.id)})})}),(0,W.jsx)(`tbody`,{className:`divide-y divide-border/60`,children:_.map(e=>{let t=QV(e),n=XV(e);return(0,W.jsx)(`tr`,{role:`button`,tabIndex:0,onClick:()=>d(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),d(e))},className:`hover:bg-muted/40 transition-colors cursor-pointer group`,"data-testid":`property-table-row-${e.id}`,children:u.map(r=>{let i=r.getValue(e),a=r.formatValue(i,e),o=r.align===`right`?`text-right tabular-nums`:r.align===`center`?`text-center`:`text-left`;return(0,W.jsx)(`td`,{className:`px-4 py-3 whitespace-nowrap text-foreground/90 ${o}`,"data-testid":`property-table-cell-${r.id}`,children:r.id===`pacingTier`&&e.execution?.effortSlug?(0,W.jsx)(Nt,{to:nN(e.execution.effortSlug),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),"data-testid":`property-table-effort-link`,className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 transition-colors`,title:`View movement history for ${e.detail??e.execution.effortSlug}`,children:a}):r.id===`title`||r.id===`label`?(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`font-medium text-foreground group-hover:text-primary transition-colors`,children:a}),t&&(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 ml-auto`,onClick:e=>e.stopPropagation(),children:[(0,W.jsx)(Nt,{to:n,"data-testid":`property-table-details-link`,className:`rounded px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted border border-border transition-colors`,title:`View catalog details`,children:`Details`}),(0,W.jsx)(Nt,{to:t,"data-testid":`property-table-feed-link`,className:`rounded px-1.5 py-0.5 text-[10px] font-semibold bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 transition-colors`,title:`View feed`,children:`Feed`})]})]}):a},r.id)})},e.id)})})]})})}var p4={note:u,session:Xn,post:u,effort:Ye,result:qe,segment:s,event:ze,dashboard:an,equipment:O},m4={note:`Note`,session:`Session`,post:`Post`,effort:`Effort`,result:`Result`,segment:`Segment`,event:`Event`,dashboard:`Dashboard`,equipment:`Equipment`},h4=8;function g4({entry:e}){let t=e.execution;if(!t)return null;let n=[];return t.elapsedMs!=null&&n.push(bR(t.elapsedMs)),t.reps!=null&&n.push(`${t.reps} reps`),t.loadLbs!=null&&n.push(`${t.loadLbs} lb`),t.distanceMeters!=null&&n.push(`${(t.distanceMeters/1e3).toFixed(2)} km`),t.tis!=null&&n.push(`TIS ${t.tis}`),n.length===0?null:(0,W.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1.5`,"data-testid":`stream-feed-metrics`,children:n.map(e=>(0,W.jsx)(`span`,{className:`rounded-full bg-muted/70 border border-border/60 px-2 py-0.5 text-[10px] font-bold tabular-nums text-muted-foreground`,children:e},e))})}function _4({entry:e}){let[t,n]=(0,U.useState)(!1),r=e.wodBlock?.content.trim(),i=r?r.split(`
169
+ `):e.excerpt??e.block?.preview??[],a=i.length>h4,o=t||!a?i:i.slice(0,h4);return i.length===0&&!e.detail?null:(0,W.jsxs)(`div`,{className:`mt-1.5`,"data-testid":`stream-feed-preview`,children:[i.length>0&&(0,W.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-muted-foreground ${a&&!t?`max-h-40 overflow-hidden`:``}`,children:o.join(`
170
+ `)}),i.length===0&&e.detail&&(0,W.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.detail}),a&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>n(e=>!e),"data-testid":`stream-feed-preview-toggle`,className:`mt-1 min-h-[44px] px-2 -ml-2 text-[10px] font-black uppercase tracking-widest text-primary hover:text-primary/80 transition-colors`,children:t?`Show less`:`Show more (${i.length-h4} lines)`})]})}function v4({groups:e,batch:t,onRunEntry:n,onSendToPlayground:r,stickyOffset:i}){return(0,W.jsxs)(`div`,{className:`flex-1 divide-y divide-border/40`,"data-testid":`stream-feed`,children:[e.map(e=>(0,W.jsxs)(`section`,{id:e.id,"data-testid":`stream-feed-group-${e.key}`,children:[(0,W.jsx)(jz,{top:i,icon:(0,W.jsx)(zt,{className:`size-3 shrink-0 text-muted-foreground`}),label:e.label,badge:e.isToday?(0,W.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary`,children:`Today`}):void 0,meta:`${e.entries.length} ${e.entries.length===1?`entry`:`entries`}`}),(0,W.jsx)(`div`,{className:`divide-y divide-border/30`,children:e.entries.map(e=>{let t=e.kind===`note`?e.sourceCatalog:void 0,i=t===`playground`?Ae:t===`guides`?tr:p4[e.kind],a=t===`playground`?`Playground`:t===`guides`?`Guide`:m4[e.kind],o=XV(e),s=QV(e),c=!ZV(e)&&(e.kind===`note`||e.kind===`session`||e.kind===`post`);return(0,W.jsx)(`article`,{"data-testid":`stream-feed-item`,className:`px-6 py-4`,children:(0,W.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,W.jsx)(`div`,{className:`flex-shrink-0 size-9 rounded-xl bg-primary/10 flex items-center justify-center`,children:(0,W.jsx)(i,{className:`size-4 text-primary`})}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-bold text-foreground min-w-0 basis-full sm:basis-auto sm:truncate`,children:(0,W.jsx)(Nt,{to:o,className:`hover:text-primary transition-colors`,children:e.title})}),(0,W.jsx)(`span`,{className:`text-[9px] font-black uppercase tracking-widest text-muted-foreground/60 border border-border rounded-full px-1.5 py-0.5`,children:a}),e.subtitle&&(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground/70 truncate`,children:e.subtitle})]}),(0,W.jsx)(_4,{entry:e}),(0,W.jsx)(g4,{entry:e}),(0,W.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,W.jsx)(Nt,{to:o,"data-testid":`stream-feed-open`,className:`inline-flex min-h-[44px] items-center rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors`,children:s?`Details`:`Open`}),s&&(0,W.jsxs)(Nt,{to:s,"data-testid":`stream-feed-collection-feed`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-3 text-[10px] font-black uppercase tracking-widest text-primary hover:bg-primary/20 transition-colors`,children:[(0,W.jsx)(Xn,{className:`size-3`}),`Feed`]}),n4(e)&&(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(e),"data-testid":`stream-feed-run`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-3 text-[10px] font-black uppercase tracking-widest text-primary hover:bg-primary/20 transition-colors`,children:[(0,W.jsx)(pn,{className:`size-3`}),`Run`]}),c&&r&&(0,W.jsxs)(`button`,{type:`button`,onClick:()=>r(e),"data-testid":`stream-feed-playground`,className:`inline-flex min-h-[44px] items-center gap-1.5 rounded-full border border-border px-3 text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors`,children:[(0,W.jsx)(Ht,{className:`size-3`}),`Playground`]})]})]})]})},e.id)})})]},e.id)),t.hasMore&&(0,W.jsxs)(`div`,{ref:t.sentinelRef,className:`px-6 py-4 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-feed-load-more`,children:[`Loading more — `,t.total-t.visible.length,` remaining…`]})]})}function y4(e,t,n){return{journalDate:n,title:e.title,rawContent:t,sourceId:e.sourceId,type:`journal`}}var b4=/\[([^\]]*)\]\((:[^)]*)\)!/g;function x4(e){let t=e.trim();try{return decodeURIComponent(t)}catch{return t}}function S4(e){let t=x4(e);return t.startsWith(`:`)&&!X(t).error}function C4(e){let t=[],n=0;for(let r of e.matchAll(b4)){let i=r.index??0,a=x4(r[2]);S4(a)&&(i>n&&t.push({kind:`markdown`,text:e.slice(n,i)}),t.push({kind:`query`,query:a.trim(),heading:r[1]}),n=i+r[0].length)}n<e.length&&t.push({kind:`markdown`,text:e.slice(n)});let r=[];for(let e of t){let t=r[r.length-1];e.kind===`markdown`&&t?.kind===`markdown`?t.text+=e.text:r.push(e)}return r}function w4(e){return e.some(e=>e.kind===`query`)}var T4=`9999-12-31`;function E4(e,t){return(e.date??T4).localeCompare(t.date??T4)||e.title.localeCompare(t.title,void 0,{numeric:!0,sensitivity:`base`})}function D4(e){let t=new Date(`${e}T12:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(`en-US`,{weekday:`short`,month:`short`,day:`numeric`,year:`numeric`})}function O4({query:e,heading:t,onAddToToday:n,onRunStart:r}){let[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(null);(0,U.useEffect)(()=>{let t=!1;return a(null),s(null),jR.query(e).then(e=>{t||a([...e].sort(E4))}).catch(e=>{t||s(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let c=(0,U.useMemo)(()=>{if(!i)return null;let t=X(e);if(t.error||!(`groupBy`in t)||!t.groupBy?.includes(`date`))return null;let n=new Map;for(let e of i){let t=e.date??``,r=n.get(t);r?r.push(e):n.set(t,[e])}return[...n.entries()]},[i,e]);if(o)return(0,W.jsxs)(`p`,{className:`my-3 text-xs text-destructive`,"data-testid":`readme-query-error`,children:[`Query failed: `,o]});if(i===null)return(0,W.jsx)(`div`,{className:`my-3 text-xs text-muted-foreground/60`,"data-testid":`readme-query-loading`,children:`Loading…`});if(i.length===0)return(0,W.jsx)(`p`,{className:`my-3 text-xs text-muted-foreground/60`,"data-testid":`readme-query-empty`,children:`No entries match this query.`});let l=e=>(0,W.jsx)(l4,{entry:e,onAddToToday:n,onRunStart:r},e.id);return(0,W.jsxs)(`div`,{className:`my-3 not-prose`,"data-testid":`readme-query-block`,children:[t&&(0,W.jsx)(`p`,{className:`mt-4 mb-1 text-sm font-bold text-foreground`,"data-testid":`readme-query-heading`,children:t}),c?c.map(([e,t])=>(0,W.jsxs)(`div`,{className:`mt-3`,"data-testid":`readme-query-date-group`,children:[(0,W.jsx)(`p`,{className:`mb-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,children:e?D4(e):`Undated`}),(0,W.jsx)(`div`,{className:`divide-y divide-border/40`,children:t.map(l)})]},e||`undated`)):(0,W.jsx)(`div`,{className:`divide-y divide-border/40`,children:i.map(l)})]})}var k4=new YO;function A4({batch:e,testId:t=`stream-load-more`}){return e.hasMore?(0,W.jsxs)(`div`,{ref:e.sentinelRef,className:`px-6 py-4 text-center text-xs text-muted-foreground/60`,"data-testid":t,children:[`Loading more — `,e.total-e.visible.length,` remaining…`]}):null}var j4=150;function M4(e){switch(e.phase){case`checking`:return`Checking ${e.sourceLabel}…`;case`fetching`:return`Downloading ${e.chunkId??`library`}…`;case`applying`:return`Importing ${e.chunkId??`library`}…`;case`committed`:return`Committed ${e.chunkId??`chunk`}`;case`finalizing`:return`Finalizing checkpoints…`;case`finished`:return e.error??R2[e.outcome]}}function N4(e){return`${e.negate?`!`:``}${e.key}=${e.values.map(e=>`${e.wildcard?`*`:``}${e.value}`).sort().join(`|`)}`}function P4(e,t){let n={};for(let e of t){let t=N4(e);n[t]=(n[t]??0)+1}return e.filter(e=>{let t=N4(e),r=n[t]??0;return n[t]=r-1,r<=0})}function F4({error:e,target:t,matched:n,total:r,loading:i,applied:a,ignored:o,advisories:s,groupDims:c,groupingSource:l}){return(0,W.jsxs)(`div`,{role:`status`,"data-testid":`stream-query-status`,className:`flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground`,children:[e?(0,W.jsx)(`span`,{className:`font-semibold text-destructive`,children:`Invalid query — showing previous results`}):t?(0,W.jsxs)(`span`,{className:`font-mono`,children:[`:`,t]}):null,(0,W.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,W.jsxs)(`span`,{"data-testid":`stream-query-counts`,className:i?`motion-safe:animate-pulse`:void 0,children:[n,` of `,r]}),(0,W.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,W.jsxs)(`span`,{"data-testid":`stream-query-filters`,children:[a,` applied`,o>0?`, ${o} ignored`:``]}),(0,W.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,W.jsxs)(`span`,{children:[`by `,c.join(`, `),` `,(0,W.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`(`,l,`)`]})]}),s.map(e=>(0,W.jsx)(`p`,{className:`w-full break-words text-amber-700 dark:text-amber-400`,children:e},e))]})}function I4({profile:e,actions:t,queryEngine:n,onAddToToday:r,registerStreamDraft:i}){let a=ht(),o=Xt(),s=X0(),c=e2(),[l,u]=(0,U.useState)(!1),[d,f]=(0,U.useState)(!1),[p,m]=(0,U.useState)(null),[h,g]=(0,U.useState)(null),_=(0,U.useSyncExternalStore)(aA,()=>aj().filter(e=>e.autoImport===!1&&eA(e.id)).map(e=>e.id).join(`
171
+ `)),v=(0,U.useMemo)(()=>_?_.split(`
172
+ `):[],[_]),{query:y,setQuery:b,urlQueryError:x}=mM({defaultQuery:e.defaultWql,legacy:e.legacy});(0,U.useEffect)(()=>i?.(()=>y),[i,y]);let{settings:S,setLayout:C,toggleField:w,setGroupBy:T}=Z2(e.route,e.level,e.defaultLayout),E=m2(e.route),[D,O]=(0,U.useState)(!1),[k,A]=(0,U.useState)([]),[j,M]=(0,U.useState)(void 0),[N,P]=(0,U.useState)(null),[F,L]=(0,U.useState)(!0),[R,ee]=(0,U.useState)(!1),[te,ne]=(0,U.useState)(null),re=gB(),ie=Iz(),ae=e.route===`/catalogs`,oe=(0,U.useMemo)(()=>ae&&new URLSearchParams(o.search).get(`manage`)===`1`,[ae,o.search]),se=(0,U.useCallback)(e=>{let t=new URLSearchParams(o.search);e?t.set(`manage`,`1`):t.delete(`manage`);let n=t.toString();a({pathname:o.pathname,search:n?`?${n}`:``},{replace:!e})},[a,o.pathname,o.search]),ce=ae?(0,W.jsx)(H2,{open:oe,onOpenChange:se}):null,le=(0,U.useCallback)(()=>{ae?se(!0):a($.settingsSync)},[ae,se,a]),[z,ue]=(0,U.useState)(!1),de=(0,U.useCallback)(async(e,t,n)=>{let r=await hA.create(e,t,n);return await Z.saveNote(hA.createNotebookLandingNote(r)),De(e=>e+1),r},[]),fe=ae?(0,W.jsx)(n2,{open:z,onOpenChange:ue,onCreate:de}):null,B=(0,U.useMemo)(()=>X(y),[y]),pe=(0,U.useMemo)(()=>B.error||Sm(B)?!1:B.filters.some(e=>e.key===`source`&&!e.negate&&e.values.some(e=>e.value===`playground`)),[B]),me=(0,U.useMemo)(()=>{if(e.catalog)return e.catalog;if(e.route.startsWith(`/c/`)){let t=e.route.slice(3);if(t&&!t.includes(`/`))return t}if(!B.error&&bm(B)){let e=B.filters.find(e=>(e.key===`notebook`||e.key===`catalog`)&&!e.negate)?.values[0]?.value;if(e)return wa(e)}},[e,B]),he=GD(),[ge,_e]=(0,U.useState)(null),ve=(0,U.useMemo)(()=>ge?C4(ge):[],[ge]),ye=w4(ve);(0,U.useEffect)(()=>{if(!me){_e(null);return}let e=`markdown/collections/${me}/README.md`,t=he?.[e];t&&_e(t.replace(/\{\{workouts\}\}/g,``).trim());let n=!1;return zv(e).then(async e=>{try{let t=await k4.getEntry(e);!n&&t?.rawContent&&_e(t.rawContent.replace(/\{\{workouts\}\}/g,``).trim())}catch{}}),()=>{n=!0}},[me,he]);let be=(0,U.useMemo)(()=>{let e=n??jR;return S.layout===`feed`?e.withNoteBlockInfo():e},[n,S.layout]),xe=(0,U.useCallback)(async e=>{let t=WV(),n=``,r=e.kind===`result`||e.kind===`segment`?e.execution?.noteId:e.kind===`note`?e.sourceItem:e.id;if(r){if(e.kind===`segment`&&e.blockContentId){let t=(await $L.runFind({raw:`:block{note:${r}}`,target:`block`,filters:[{key:`note`,negate:!1,values:[{value:r,wildcard:!1}]}]})).blocks.find(t=>t.id===e.blockContentId);t?.rawContent&&(n=t.rawContent)}if(!n&&(e.kind===`note`||e.kind===`result`||e.kind===`segment`)){let e=await BN.getById(r);e&&typeof e==`object`&&`rawContent`in e&&typeof e.rawContent==`string`&&(n=e.rawContent)}if(!n&&e.kind!==`note`){let e=await $L.runFind({raw:`:block{note:${r}}`,target:`block`,filters:[{key:`note`,negate:!1,values:[{value:r,wildcard:!1}]}]});e.blocks.length>0&&(n=[...e.blocks].sort((e,t)=>(e.position??0)-(t.position??0)).filter(e=>e.rawContent.trim()!==``).map(e=>e.dataType===`frontmatter`?`---\n${e.rawContent}\n---`:e.rawContent).join(`
173
+
174
+ `))}}let i=y4(e,n,t);await BN.create(i)},[]),Se=r??xe,Ce=(0,U.useCallback)(async e=>{ne(null);try{await a4(e,a)}catch(e){ne(e instanceof Error?e.message:`Could not start the workout.`)}},[a]),we=(0,U.useCallback)(async e=>{ne(null);try{let t=await BN.resolve(e.id),{routeId:n}=await gK(t&&typeof t==`object`&&`rawContent`in t?String(t.rawContent??``):``,{title:e.title});a(RM(n.replace(/^playground\//,``)))}catch(e){ne(e instanceof Error?e.message:`Could not create the playground entry.`)}},[a]),Te=(0,U.useCallback)(e=>bm(e)?$L.runFind(e):$L.runQuery(e.raw),[]),[Ee,De]=(0,U.useState)(0);(0,U.useEffect)(()=>XW(()=>De(e=>e+1)),[]),(0,U.useEffect)(()=>{let e=Bb().result?.id??-1;return Vb(()=>{let t=Bb().result?.id??-1;t!==e&&(e=t,De(e=>e+1))})},[]);let Oe=(0,U.useCallback)(async()=>{let e=aj().filter(e=>e.autoImport===!1&&v.includes(e.id));if(e.length===0){le();return}f(!0),g(null),m(null);try{let t=0,n=0,r=[];for(let i of e){let e=await Ej(i.id,{onProgress:m});e===`imported`?(t+=1,u(!0),De(e=>e+1)):e===`current`||e===`server-stale`?(n+=1,u(!0)):r.push(`${i.label}: ${R2[e]}`)}r.length>0&&g(r.join(` — `)),t>0?Q({title:t===e.length?`Libraries synced`:`${t} of ${e.length} libraries synced`,description:`Content was imported from the published seeds. Your own edits were kept.`}):n>0&&r.length===0&&Q({title:`Everything is up to date`,description:`All your subscribed libraries already match their published versions.`})}finally{f(!1)}},[v,le]);(0,U.useEffect)(()=>{if(s===`preparing`)return;if(B.error){ee(!1);return}let e=!1,t=setTimeout(()=>{ee(!0),M(void 0),be.query(y,t=>{e||M(t)}).then(t=>{e||(A(t),P(o2(y,B)),cF({pathname:o.pathname,query:y,entries:t}))}).catch(()=>{e||(A([]),cF({pathname:o.pathname,query:y,entries:[]}))}).finally(()=>{e||ee(!1)})},j4);return()=>{e=!0,clearTimeout(t)}},[y,be,B,o.pathname,s,Ee]);let ke=(0,U.useMemo)(()=>{if(N?.length)return N;if(S.groupBy)return[S.groupBy];let t=am(B.error||!bm(B)?e.level===`effort`?`effort`:`note`:B.target,`find`);return[MP(e.groupByOptions,t,e.level===`effort`?`discipline`:`date`)]},[N,S.groupBy,e.level,e.groupByOptions,B]),Ae=N?.length?`query`:S.groupBy?`view`:e.groupByOptions?.length?`favorite`:`level`,je=(0,U.useMemo)(()=>new Set(B.error||!bm(B)?[]:im(B.target,`find`)),[B]),Me=B.error||Sm(B)?0:B.filters.filter(e=>je.has(e.key)).length,Ne=(B.error||Sm(B)?0:B.filters.length)-Me,Pe=e.shelfVisible&&!pe,Fe=(0,U.useMemo)(()=>c2(k,ke,{shelfVisible:Pe}),[k,ke,Pe]),Ie=Q2(k),{visible:Le,growTo:Re}=Ie,ze=(0,U.useMemo)(()=>c2(Le,ke,{shelfVisible:Pe}),[Le,ke,Pe]),Be=(0,U.useMemo)(()=>new Map(Fe.map(e=>[e.id,e.entries.length])),[Fe]),{setL3Items:Ve,scrollToSection:He,navState:Ue,setStreamControls:We}=lM();(0,U.useEffect)(()=>{if(Fe.length===0){Ve([]);return}let e=Fe.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return Ve(e),()=>Ve([])},[Fe,Ve]);let Ge=(0,U.useMemo)(()=>jP(am(B.error||!bm(B)?e.level===`effort`?`effort`:`note`:B.target,`find`),e.groupByOptions),[B,e.level,e.groupByOptions]),Ke=(0,U.useCallback)(e=>{let t=t4(y,e);t===y?T(e):b(t)},[y,b,T]),qe=(0,U.useCallback)(e=>{let t=ke.some(t=>t.toLowerCase()===e.toLowerCase()),n=kF(y,e,!t);b(n);let r=X(n);!r.error&&bm(r)&&Ke(r.groupBy?.[0]??``)},[ke,y,b,Ke]);(0,U.useEffect)(()=>(We?.({query:y,onQueryChange:b,groupDims:ke,onToggleGroupDim:qe,availableGroupDims:Ge,settings:S,onLayoutChange:C,onToggleField:w,level:e.level,...E?{onOpenQuerySettings:()=>O(!0)}:{}}),()=>We?.(null)),[y,b,ke,qe,Ge,We,S,C,w,e.level,E]);let Je=`activeL3Id`in Ue&&typeof Ue.activeL3Id==`string`?Ue.activeL3Id:null,Ye=(0,U.useRef)(null);(0,U.useEffect)(()=>{let e=Je;if(!e||Ye.current===e||document.getElementById(e))return;let t=Fe.find(t=>t.id===e);if(!t)return;Ye.current=e;let n=t.entries[t.entries.length-1],r=n?k.findIndex(e=>e.id===n.id):-1;Re(r>=0?r+1:k.length)},[Je,Fe,k,Re]),(0,U.useEffect)(()=>{let e=Ye.current;!e||!document.getElementById(e)||(Ye.current=null,He(e))},[ze,He]);let Xe=Az(104),Ze=B.error&&y!==e.defaultWql?B.error:null,Qe=x??Ze,et=(0,U.useMemo)(()=>{let t=X(e.defaultWql);return!t.error&&bm(t)?t.filters:[]},[e.defaultWql]),tt=e.seedNotice===!0&&c===!0&&!l,nt=(0,U.useMemo)(()=>{let e=[];if(tt)return e.push({id:`browse-libraries`,label:`Browse libraries`,apply:le}),e;if(!B.error&&B.advisories?.length&&e.push({id:`edit-query`,label:`Edit query`,apply:()=>i2(y,Te,b)}),!B.error&&B.window){let t=B.window,n=t.kind===`relative`?`last ${t.size}${t.unit}`:`from ${t.start}${t.end?` to ${t.end}`:``}`;e.push({id:`remove-window`,label:`Remove time window (${n})`,apply:()=>b(e4(y))})}if(!B.error&&bm(B)){let t=P4(B.filters,et);if(t.length>0){let n=new Set(t.map(N4)),r=B.filters.filter(e=>!n.has(N4(e)));e.push({id:`clear-filters`,label:t.length===1?`Clear filter`:`Clear filters (${t.length})`,apply:()=>b(dh({...B,filters:r}))})}}return e},[B,y,b,Te,et,tt,le]),rt=(0,W.jsxs)(`div`,{className:`px-6 py-16 text-center text-muted-foreground flex flex-col items-center justify-center gap-3`,"data-testid":`stream-empty-state`,children:[(0,W.jsx)(`p`,{className:`text-sm font-medium`,children:tt?`No ${e.title.toLowerCase()} are imported yet.`:e.emptyMessage??(B.window?`No entries found within the selected time window.`:`No entries match your search.`)}),nt.length>0&&(0,W.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2 mt-1`,children:nt.map(e=>(0,W.jsx)(K,{variant:`outline`,size:`sm`,onClick:e.apply,className:`text-xs`,children:e.label},e.id))})]}),it=!!B.error&&k.length>0;return s===`preparing`?(0,W.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,"data-testid":`stream-preparing`,role:`status`,"aria-busy":`true`,children:[ce,fe,(0,W.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-4 p-6`,children:[(0,W.jsxs)(`div`,{className:`w-full max-w-2xl space-y-3`,"aria-hidden":`true`,children:[(0,W.jsx)(`div`,{className:`h-4 w-2/3 animate-pulse rounded bg-muted`}),(0,W.jsx)(`div`,{className:`h-4 w-1/2 animate-pulse rounded bg-muted`}),(0,W.jsx)(`div`,{className:`h-4 w-3/4 animate-pulse rounded bg-muted`})]}),(0,W.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:`Loading library…`})]})]}):(0,W.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,"data-testid":`queriable-stream-view`,children:[ce,fe,E&&(0,W.jsx)(T2,{surface:E,open:D,onOpenChange:O}),(0,W.jsx)(wz,{className:`max-lg:hidden`,actions:(0,W.jsxs)(kB,{primary:e.route===`/efforts`?(0,W.jsxs)(K,{size:`sm`,onClick:()=>a(nN(`new`,void 0,{mode:`create`})),className:`h-9 px-2.5 text-xs gap-1.5`,"data-testid":`efforts-catalog-create-btn`,children:[(0,W.jsx)(En,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`New`})]}):ae?(0,W.jsxs)(K,{size:`sm`,onClick:()=>ue(!0),className:`h-9 px-2.5 text-xs gap-1.5`,"data-testid":`notebooks-create-button`,children:[(0,W.jsx)(En,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`New Notebook`})]}):void 0,label:`Stream actions`,children:[ae&&(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>se(!0),"data-testid":`manage-catalogs-button`,className:`h-9 gap-1.5 px-2.5 text-xs`,children:[(0,W.jsx)(Sn,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Manage Notebooks`})]}),t]}),queryBar:(0,W.jsx)(a2,{query:y,onQueryChange:b,scopeOptions:e.scopeOptions,execute:Te,defaultQuery:e.defaultWql,route:e.route})}),(0,W.jsx)(`div`,{className:`px-4 pt-2 sm:px-6 lg:px-8`,"data-testid":`stream-query-status-row`,children:(0,W.jsx)(F4,{error:Qe,target:B.error?null:bm(B)?B.target:B.family,matched:k.length,total:Math.max(j?.selected??0,k.length),loading:R,applied:Me,ignored:Ne,advisories:B.error?[]:B.advisories??[],groupDims:ke,groupingSource:Ae})}),e.scopeOptions.length===0&&(0,W.jsx)(`p`,{"data-testid":`route-wql-empty-options`,className:`px-4 pt-3 text-xs text-muted-foreground sm:px-6 lg:px-8`,children:`No source options are set for this route — pick a source by editing the query.`}),e.seedNotice&&c&&!l&&(0,W.jsx)(`div`,{className:`px-4 pt-3 sm:px-6 lg:px-8`,"data-testid":`seed-library-notice`,children:(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 flex flex-col sm:flex-row sm:items-center gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex-1 space-y-1`,children:[(0,W.jsxs)(`p`,{className:`text-sm font-medium text-foreground flex items-center gap-2`,children:[(0,W.jsx)($e,{className:`size-4 text-primary`}),`Only the core seed is imported`]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:v.length>0?`The content for this page comes from your subscribed libraries, which have not been imported yet. Sync now to import them — or open Sync settings to add more sources (mirrors, your own libraries).`:`The content for this page comes from library sources, and none are subscribed yet. Browse the library manager to subscribe — mirrors and your own libraries both work.`}),p&&(0,W.jsxs)(`div`,{className:`space-y-1.5 pt-1`,"data-testid":`seed-library-notice-progress`,children:[(0,W.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-xs text-muted-foreground`,children:M4(p)}),p.phase!==`checking`&&p.phase!==`finished`?(0,W.jsx)(r2,{value:p.completedChunks,max:p.totalChunks,label:`Library import progress`,className:`max-w-sm`}):d?(0,W.jsx)(`progress`,{"aria-label":`Checking library sources`,className:`h-2 max-w-sm w-full`}):null]}),(h??(p?.phase===`finished`?p.error:null))&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,"data-testid":`seed-library-notice-error`,children:h??(p?.phase===`finished`?p.error:null)})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,W.jsxs)(K,{size:`sm`,onClick:()=>void Oe(),disabled:d,"data-testid":`seed-library-notice-sync`,className:`gap-2`,children:[(0,W.jsx)(Rt,{className:`size-3.5 ${d?`animate-spin`:``}`}),(0,W.jsx)(`span`,{children:d?`Syncing…`:v.length>0?`Sync now`:`Browse libraries`})]}),(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>a($.settingsSync),"data-testid":`seed-library-notice-settings`,className:`gap-2`,children:[(0,W.jsx)(Sn,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Sync settings`})]})]})]})}),re&&ie&&(0,RS.createPortal)((0,W.jsx)(a2,{query:y,onQueryChange:b,scopeOptions:e.scopeOptions,execute:Te,defaultQuery:e.defaultWql,route:e.route,compact:!0}),ie),Qe&&(0,W.jsxs)(`div`,{role:`alert`,className:`mx-6 mt-4 flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive`,"data-testid":`stream-query-error`,children:[(0,W.jsx)(I,{className:`size-5 flex-shrink-0 mt-0.5`}),(0,W.jsxs)(`div`,{className:`flex-1 text-xs`,children:[(0,W.jsx)(`p`,{className:`font-bold`,children:`Query error`}),(0,W.jsx)(`p`,{className:`mt-1 font-mono text-[11px] opacity-90`,children:Qe})]})]}),te&&(0,W.jsxs)(`div`,{role:`alert`,className:`mx-6 mt-4 flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive`,"data-testid":`stream-action-error`,children:[(0,W.jsx)(I,{className:`size-5 flex-shrink-0 mt-0.5`}),(0,W.jsxs)(`div`,{className:`flex-1 text-xs`,children:[(0,W.jsx)(`p`,{className:`font-bold`,children:`Action failed`}),(0,W.jsx)(`p`,{className:`mt-1 text-[11px] opacity-90`,children:te})]}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>ne(null),className:`text-[11px] font-bold uppercase tracking-wider hover:opacity-80`,"data-testid":`stream-action-error-dismiss`,children:`Dismiss`})]}),ge&&(0,W.jsx)(`div`,{className:`border-b border-border/60 bg-card/20 px-6 py-4`,"data-testid":`collection-readme-note`,children:ve.map((e,t)=>e.kind===`markdown`?(0,W.jsx)(MZ,{prose:e.text},t):(0,W.jsx)(O4,{query:e.query,heading:e.heading,onAddToToday:Se,onRunStart:Ce},t))}),ye?null:S.layout===`rows`?(0,W.jsx)(`div`,{className:it?`flex-1 opacity-50 transition-opacity`:`flex-1`,children:(0,W.jsx)(f4,{entries:k,level:e.level,visibleFieldIds:S.visibleFields,stickyHeaderTop:Xe,emptyMessage:e.emptyMessage??`No matching records found.`})}):S.layout===`feed`?ze.length>0?(0,W.jsx)(v4,{groups:ze,batch:Ie,stickyOffset:Xe,onRunEntry:Ce,onSendToPlayground:we}):R&&k.length===0?(0,W.jsx)(`div`,{className:`py-16 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-loading`,children:`Loading…`}):k.length===0&&!R?rt:null:(0,W.jsx)(`div`,{className:it?`flex-1 divide-y divide-border/60 opacity-50 transition-opacity`:`flex-1 divide-y divide-border/60`,children:ze.length>0?(0,W.jsxs)(`div`,{className:`divide-y divide-border/40`,"data-testid":`stream-dated-content`,children:[ze.map(e=>{let t=Be.get(e.id)??e.entries.length;return e.key===`shelf`?(0,W.jsxs)(`div`,{id:e.id,className:`border-b border-border/60`,"data-testid":`stream-shelf`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:()=>L(e=>!e),className:`w-full flex items-center justify-between px-6 py-2.5 bg-muted/20 hover:bg-muted/40 transition-colors text-left`,children:(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[F?(0,W.jsx)(Cn,{className:`size-3.5 text-muted-foreground`}):(0,W.jsx)(Qt,{className:`size-3.5 text-muted-foreground`}),(0,W.jsx)(Rss,{className:`size-3.5 text-amber-500`}),(0,W.jsx)(`span`,{className:`text-xs font-bold text-foreground`,children:e.label}),(0,W.jsx)(`span`,{className:`text-[10px] font-bold text-muted-foreground/60 bg-muted px-1.5 py-0.5 rounded-full`,children:t})]})}),F&&(0,W.jsx)(`div`,{className:`divide-y divide-border/40`,children:e.entries.map(e=>(0,W.jsx)(l4,{entry:e,visibleFieldIds:S.visibleFields,onAddToToday:Se,onRunStart:Ce},e.id))})]},e.id):(0,W.jsxs)(`div`,{id:e.id,className:`group/date`,"data-testid":`date-group-${e.key}`,children:[(0,W.jsx)(jz,{top:Xe,icon:(0,W.jsx)(zt,{className:`size-3.5 shrink-0 text-muted-foreground`}),label:e.label,badge:e.isToday?(0,W.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary`,children:`Today`}):void 0,meta:`${t} ${t===1?`entry`:`entries`}`}),(0,W.jsx)(`div`,{className:`divide-y divide-border/30`,children:e.entries.map(t=>(0,W.jsx)(l4,{entry:t,visibleFieldIds:S.visibleFields,tone:e.isToday?`primary`:`secondary`,onAddToToday:Se,onRunStart:Ce},t.id))})]},e.id)}),(0,W.jsx)(A4,{batch:Ie})]}):R&&k.length===0?(0,W.jsx)(`div`,{className:`py-16 text-center text-xs text-muted-foreground/60`,"data-testid":`stream-loading`,children:`Loading…`}):k.length===0&&!R?rt:null})]})}function L4(){return(0,W.jsx)(w2,{surface:f2})}function R4({pageRoute:e,quests:t,challengeSectionMap:n,onScrollToSection:r}){let{quests:i,stepsComplete:a,totalSteps:o,isComplete:s}=OK(e,t),[c,l]=(0,U.useState)(!1),u=(0,U.useRef)(null),d=(0,U.useRef)(null),f=(0,U.useRef)(null);if(o===0)return null;let p=e=>{let t=n.get(e);t&&r?.(t),l(!1)};(0,U.useEffect)(()=>{if(!c)return;let e=e=>{e.key===`Escape`&&(l(!1),u.current?.focus())},t=e=>{let t=e.relatedTarget,n=u.current?.parentElement;n&&t&&!n.contains(t)&&l(!1)},n=e=>{let t=u.current?.parentElement;t&&!t.contains(e.target)&&l(!1)};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,n),document.addEventListener(`touchstart`,n),d.current?.addEventListener(`focusout`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,n),document.removeEventListener(`touchstart`,n),d.current?.removeEventListener(`focusout`,t)}},[c]),(0,U.useEffect)(()=>()=>{f.current&&=(window.clearTimeout(f.current),null)},[]);let m=()=>{f.current&&=(window.clearTimeout(f.current),null)},h=()=>{m(),f.current=window.setTimeout(()=>l(!1),150)};return(0,W.jsxs)(`div`,{className:`relative py-1.5 shrink-0`,onPointerEnter:e=>{e.pointerType===`mouse`&&(m(),l(!0))},onPointerLeave:e=>{e.pointerType===`mouse`&&h()},children:[(0,W.jsxs)(`button`,{ref:u,type:`button`,"aria-haspopup":`menu`,"aria-expanded":c,"aria-label":`${a} of ${o} challenges complete`,title:`${a} of ${o} challenges complete`,onClick:()=>l(!0),className:`flex items-center gap-1.5 cursor-pointer focus:outline-none select-none text-left rounded-full border border-border/70 bg-background px-3 py-1 hover:bg-muted/40 hover:border-border transition-colors shadow-sm`,children:[s?(0,W.jsx)(Vn,{className:`size-4 text-emerald-500`}):(0,W.jsx)(Pt,{className:`size-4 text-muted-foreground`}),(0,W.jsxs)(`span`,{className:G(`text-[10px] font-black uppercase tracking-wider`,s?`text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`),children:[a,`/`,o]})]}),c&&(0,W.jsxs)(`div`,{ref:d,role:`menu`,"aria-orientation":`vertical`,className:`absolute left-0 top-full mt-1.5 w-64 rounded-xl border border-border bg-popover text-popover-foreground shadow-2xl p-3 z-50 origin-top-left before:content-[''] before:absolute before:-top-1.5 before:left-0 before:right-0 before:h-1.5 before:bg-transparent`,children:[(0,W.jsxs)(`div`,{className:`mb-2.5 pb-2 border-b border-border/60 flex items-center justify-between gap-2`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h5`,{className:`text-[10px] font-black uppercase tracking-widest text-foreground`,children:`Syntax Challenges`}),(0,W.jsx)(`p`,{className:`text-[9px] text-muted-foreground mt-0.5`,children:`Click a challenge to jump to its section.`})]}),(0,W.jsxs)(`span`,{className:`text-[9px] font-black uppercase tracking-wider text-muted-foreground tabular-nums`,children:[a,`/`,o]})]}),(0,W.jsx)(`div`,{className:`flex flex-col gap-1`,children:i.map(e=>{let t=n.get(e.id);return(0,W.jsx)(YZ,{quest:e,onClick:t?()=>p(e.id):void 0,disabled:!t,compact:!0,className:`border-0 bg-transparent hover:bg-muted/40`},e.id)})})]})]})}function z4(e){return(0,W.jsx)(B4,{...e},e.entry.id)}function B4({entry:e,onChange:t,registerRun:n,...r}){let[i,a]=(0,U.useState)({blocks:e.blocks??{},sourceRevision:e.sourceRevision??0}),[o,s]=(0,U.useState)(null),c=(0,U.useRef)(i.sourceRevision),l=(0,U.useRef)({rawContent:e.rawContent,...i}),u=(0,U.useCallback)(e=>{c.current=e.sourceRevision;let t=l.current,n=t.rawContent===e.rawContent&&JSON.stringify(Object.values(t.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));a(t=>({blocks:n?e.blocks:t.blocks,sourceRevision:e.sourceRevision}))},[]),d=(0,U.useCallback)(async t=>{let n=await DN.saveNote({noteId:e.id,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:c.current}),r={rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??0};return u(r),r},[e.id,u]),f=c$({onSave:async e=>{await d(e)},getSnapshotKey:e=>JSON.stringify([e.rawContent,Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])])}),p=(0,U.useCallback)(e=>{let t=l.current.rawContent!==e.rawContent||JSON.stringify(Object.values(l.current.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));l.current=e,t&&f.onChange(e)},[f.onChange]);return(0,U.useEffect)(()=>(n?.(async(t,n)=>{await f.flush();let r=l.current,i=await yL({noteId:e.id,rawContent:r.rawContent,blocks:r.blocks,expectedSourceRevision:c.current},t,n);return u({rawContent:i.note.rawContent,blocks:i.note.blocks,sourceRevision:i.note.sourceRevision}),i}),()=>n?.(null)),[e.id,n,f.flush,u]),(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(OX,{...r,noteId:e.id,value:o??e.rawContent,noteBlocks:i.blocks,sourceRevision:i.sourceRevision,onIdentityChange:p,onSaved:u,beforeRun:async()=>(await f.flush(),c.current),onSaveRequest:f.flush,onChange:e=>{s(null),t(e)},onBlur:f.onBlur,onCursorPositionChange:f.onLineChange,onCommitChange:f.flush}),f.error?(0,W.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,f.error instanceof Error?f.error.message:String(f.error),` Your draft is kept.`]}):null,(0,W.jsx)(XI,{noteId:e.id,blocks:i.blocks,sourceRevision:i.sourceRevision,onRevert:async e=>{await f.flush();let n=YI({...l.current,sourceRevision:c.current},e),r=await d(n);l.current=r,s(n.rawContent),t(n.rawContent)}})]})}var V4=new YO;function H4({journalDate:e,theme:t,onViewCreated:n}){let[r,i]=(0,U.useState)(null),[a,o]=zn(),s=ht(),[c,l]=(0,U.useState)(!1),[u,d]=(0,U.useState)(!1),[f,p]=(0,U.useState)(null),[m,h]=(0,U.useState)(null),[g,_]=(0,U.useState)(null),[v,y]=(0,U.useState)(null),b=(0,U.useRef)(null);b.current=v;let x=(0,U.useRef)(null),S=(0,U.useRef)(!1),C=(0,U.useRef)(null),T=(0,U.useRef)(null),E=(0,U.useRef)(new Map),[D,O]=(0,U.useState)(null),k=(0,U.useCallback)(async()=>{let e=b.current;if(e)return e.block;let t=C.current;if(!t||!m)throw Error(`The pending workout is unavailable.`);return t.captured?(T.current=t.captured,t.captured.block):(T.current||=t.snapshot?await yL(t.snapshot,t.block,m,t.origin):await bL(t.noteId,t.block,m,t.origin),T.current.block)},[m]),[A,j]=(0,U.useState)({}),M=(0,U.useCallback)((e,t)=>{j(n=>n[e]===t?n:{...n,[e]:t})},[]),N=(0,U.useRef)(new Map),P=(0,U.useRef)(null),[F,I]=(0,U.useState)(null),L=(0,U.useCallback)((e,t)=>{N.current.set(e,t),P.current||(P.current=t,I(t),n?.(t))},[n]),R=a.get(`note`);(0,U.useEffect)(()=>{if(!R||!r)return;let e=document.getElementById(`note-${R}`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},[R,r]);let ee=a.toString();(0,U.useEffect)(()=>{let e=new URLSearchParams(ee).get(`autoStart`);if(!e)return;let t=d$.get(e);t&&(d$.delete(e),C.current=t,T.current=null,x.current={runtimeId:e,block:t.block,noteId:t.noteId,captured:t.captured},S.current=!1,p(t.block),h(e),_(t.noteId),d(!0)),o(e=>(e.delete(`autoStart`),e),{replace:!0})},[ee,o]),(0,U.useEffect)(()=>{if(u)return;let t=h$(e);t&&(y(t),C.current={block:t.block,noteId:t.noteId,captured:t.captured},T.current=t.captured??null,x.current={runtimeId:t.runtimeId,block:t.block,noteId:t.noteId,captured:t.captured},p(t.block),h(t.runtimeId),_(t.noteId),d(!0))},[e,u]);let te=(0,U.useCallback)((e,t)=>{i(n=>n?.map(n=>n.id===e?{...n,rawContent:t}:n)??n)},[]),ne=(0,U.useCallback)((e,t,n,r,i)=>{if(!t)return Promise.reject(Error(`This run produced no results to save.`));if(n)return Promise.resolve();let a=T.current;if(!a)return Promise.reject(Error(`The saved run pin is unavailable.`));S.current=!0,g$(a.session.id);let o=a.session.id,s=N.current.get(a.session.noteId);if(s&&!s.state.doc.toString().includes(wE(o))){let e=TE(s.state,a.session.blockId,o);e&&s.dispatch({changes:e})}return $W.record({blockId:a.session.blockId,noteId:a.session.noteId,resultId:o,data:t,createdAt:t.endTime})},[]);(0,U.useEffect)(()=>{let t=!1;return BN.listByDate(e).then(e=>{t||i(e)}).catch(()=>{t||i([])}),()=>{t=!0}},[e]);let re=/^\d{4}-\d{2}-\d{2}$/.test(e),ie=(0,U.useMemo)(()=>{if(!re)return null;let[t,n,r]=e.split(`-`).map(Number);return{prev:PN(new Date(t,n-1,r-1)),next:PN(new Date(t,n-1,r+1))}},[e,re]),{setL3Items:ae}=lM(),[oe,se]=(0,U.useState)({}),ce=r?.map(e=>e.id).join(`|`)??``,le=(0,U.useMemo)(()=>ce?ce.split(`|`):[],[ce]);(0,U.useEffect)(()=>{if(le.length===0)return;let e=!1;for(let t of le)Z.getSessionsForNote(t).then(n=>{e||se(e=>({...e,[t]:n}))}).catch(()=>{});return()=>{e=!0}},[le]),(0,U.useEffect)(()=>XW(e=>{Z.getSessionsForNote(e.noteId).then(t=>{se(n=>({...n,[e.noteId]:t}))}).catch(()=>{})}),[]);let z=r!==null&&r.length===1?r[0]:null,ue=z?oe[z.id]:void 0,de=(0,U.useCallback)(async(t,n)=>{try{let r=E.current.get(t);if(!r)throw Error(`The saved note editor is unavailable.`);let i=w(),a=await r(n,i);d$.set(i,{noteId:t,block:a.block,captured:a,returnTo:zM(e)}),s(KM(i))}catch(e){O(e instanceof Error?e.message:String(e))}},[e,s]),fe=(0,U.useCallback)(e=>{z&&de(z.id,e)},[z,de]);y$({content:z?.rawContent??``,scriptBlocks:z?A[z.id]??[]:[],onStartWorkout:fe,results:ue});let B=(0,U.useCallback)(e=>t=>{de(e,t)},[de]),pe=(0,U.useMemo)(()=>{if(!r||r.length<=1)return[];let e=[];for(let t of r){let n=t.title||`Untitled note`,r=v$(vH(t.rawContent),A[t.id]??[],B(t.id),oe[t.id]);for(let i of r)e.push(...yH([{...i,id:`note-${t.id}:${i.id}`,label:`${n} · ${i.label}`}]))}return e},[r,A,oe,B]),me=(0,U.useRef)(!1);return(0,U.useEffect)(()=>{if(pe.length!==0)return me.current=!0,ae(pe),()=>{me.current&&(me.current=!1,ae([]))}},[pe,ae]),r?R?(0,W.jsx)(Wn,{to:VM(R),replace:!0}):(0,W.jsxs)(OL,{notePersistence:DN,provider:V4,children:[(0,W.jsx)(Lz,{title:e,subtitle:`${r.length} ${r.length===1?`note`:`notes`}`,actions:(0,W.jsx)(kB,{primary:(0,W.jsxs)(K,{type:`button`,onClick:()=>l(!0),children:[(0,W.jsx)(En,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`New note`]})}),editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-8 px-4 py-6 sm:px-6`,children:[D&&(0,W.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,D,` Your draft is kept.`]}),(0,W.jsxs)(`nav`,{"aria-label":`Journal navigation`,className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:()=>_H()?s(-1):s(`/journal`),className:`rounded-pill border border-border px-2 py-0.5 hover:bg-accent hover:text-foreground transition-colors`,children:`‹ Journal`}),ie&&(0,W.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,W.jsxs)(Nt,{to:zM(ie.prev),"aria-label":`Previous day`,className:`hover:bg-accent hover:text-foreground rounded-pill border border-border px-2 py-0.5 transition-colors`,children:[`‹ `,ie.prev]}),(0,W.jsx)(`span`,{className:`font-semibold text-foreground`,children:e}),(0,W.jsxs)(Nt,{to:zM(ie.next),"aria-label":`Next day`,className:`hover:bg-accent hover:text-foreground rounded-pill border border-border px-2 py-0.5 transition-colors`,children:[ie.next,` ›`]})]})]}),r.length>1&&(0,W.jsx)(`nav`,{"aria-label":`Notes on this date`,className:`flex flex-wrap gap-2`,children:r.map(e=>(0,W.jsx)(Nt,{to:VM(e.id),className:`rounded-full border border-border px-3 py-1 text-xs text-muted-foreground hover:bg-muted`,children:e.title},e.id))}),r.length===0?(0,W.jsxs)(`div`,{className:`flex flex-col items-start gap-3 rounded-lg border border-dashed border-border p-6`,children:[(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No Notes on this date yet.`}),(0,W.jsxs)(K,{type:`button`,size:`lg`,onClick:()=>l(!0),children:[(0,W.jsx)(En,{className:`size-4 mr-1.5`,"aria-hidden":`true`}),`Create a note`]})]}):r.length===1?(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(`div`,{className:`flex items-center justify-between border-b border-border/40 pb-2`,children:(0,W.jsx)(Nt,{to:VM(r[0].id),className:`text-sm font-semibold hover:underline text-foreground`,"aria-label":`Open note page for ${r[0].title||`untitled note`}`,children:r[0].title||`Untitled note`})}),(0,W.jsx)(z4,{entry:r[0],registerRun:e=>{e?E.current.set(r[0].id,e):E.current.delete(r[0].id)},onChange:e=>te(r[0].id,e),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:e=>M(r[0].id,e),onCompleteWorkout:(e,t,n,i)=>ne(e,t,n,i,r[0].id),onViewCreated:e=>L(r[0].id,e)},r[0].id)]}):(0,W.jsx)(`div`,{className:`space-y-6`,children:r.map((e,n)=>(0,W.jsxs)(`div`,{id:`note-${e.id}`,className:`rounded-lg border border-border/60 p-4 space-y-2`,children:[(0,W.jsx)(`div`,{className:`flex items-center justify-between border-b border-border/40 pb-2`,children:(0,W.jsx)(Nt,{to:VM(e.id),className:`text-sm font-semibold hover:underline text-foreground`,children:e.title||`Note ${n+1}`})}),(0,W.jsx)(z4,{entry:e,registerRun:t=>{t?E.current.set(e.id,t):E.current.delete(e.id)},onChange:t=>te(e.id,t),readonly:!1,theme:t,showLineNumbers:!1,onBlocksChange:t=>M(e.id,t),onCompleteWorkout:(t,n,r,i)=>ne(t,n,r,i,e.id),onViewCreated:t=>L(e.id,t)})]},e.id))})]})}),(0,W.jsx)(JV,{open:c,onOpenChange:l,defaultDate:e,onCreated:t=>{BN.listByDate(e).then(i).catch(()=>{}),s(VM(t.id))}}),u&&f&&(0,W.jsx)(sX,{block:f,prepareRun:k,onClose:()=>{d(!1),h(null),_(null),y(null),S.current=!0;let e=x.current;e&&g$(e.runtimeId),x.current=null},resultId:m??void 0,onCompleteWorkout:(e,t)=>ne(e,t),autoStart:!0,adoptRuntime:v?.runtime??null,parkOnUnmount:!0,onPark:t=>{let n=x.current;if(!n||S.current){t.dispose();return}p$({runtimeId:n.runtimeId,block:n.block,noteId:n.noteId,captured:n.captured,runtime:t,journalDate:e})},onRuntimeReady:e=>{let t=x.current;if(!t)return;let n=m$(t.runtimeId);n&&n.runtime!==e&&n.runtime.dispose()}})]}):(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function U4({identity:e}){let t=ht();return(0,U.useEffect)(()=>{let n=!1;return BN.resolve(e).then(e=>{!n&&e.journalDate&&t(VM(e.id),{replace:!0})}).catch(()=>{n||t(`/journal`,{replace:!0})}),()=>{n=!0}},[e,t]),(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function W4(e){let t=window.location.pathname,n=QB(t);return n.kind===`date`?(0,W.jsx)(H4,{journalDate:n.journalDate,theme:e.theme,onViewCreated:e.onViewCreated}):n.kind===`note`?(0,W.jsx)(Wn,{to:VM(n.noteId),replace:!0}):n.kind===`uuid-alias`?(0,W.jsx)(U4,{identity:n.noteId}):n.kind===`slug-alias`?(0,W.jsx)(U4,{identity:n.slug}):(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Journal route not found.`})}var G4=()=>(0,W.jsxs)(`div`,{className:`relative my-3 flex items-start gap-3 rounded-lg border border-primary/30 bg-primary/5 px-4 py-3`,children:[(0,W.jsx)(`div`,{className:`mt-0.5 flex-shrink-0 text-primary`,children:(0,W.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,"aria-hidden":`true`,children:[(0,W.jsx)(`circle`,{cx:`9`,cy:`9`,r:`8`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,W.jsx)(`path`,{d:`M9 5v4.5M9 11.5v1`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}),(0,W.jsxs)(`div`,{className:`flex-1 text-sm leading-relaxed text-muted-foreground`,children:[(0,W.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Ready to try it?`}),` `,`Press the`,` `,(0,W.jsx)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary px-2 py-0.5 align-middle text-[11px] font-bold text-primary-foreground`,children:`▶ Run`}),` `,`button that appears on the workout block below to start the timer and track your rounds.`]}),(0,W.jsx)(`div`,{className:`pointer-events-none absolute -bottom-4 right-8 text-primary/50`,"aria-hidden":`true`,children:(0,W.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 20 20`,fill:`none`,children:[(0,W.jsx)(`path`,{d:`M3 3 L17 3 L17 17`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,W.jsx)(`path`,{d:`M11 11 L17 17 L23 11`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]});function K4({config:e,onAction:t}){return!e.headline||!e.subtitle||e.pillars.length===0?(0,W.jsxs)(`section`,{className:`rounded-3xl border border-amber-400/50 bg-amber-50 p-6 text-amber-900 dark:border-amber-500/40 dark:bg-amber-950/30 dark:text-amber-100`,children:[`Invalid `,(0,W.jsx)(`code`,{children:`attention`}),` widget config.`]}):(0,W.jsxs)(`section`,{className:`p-8`,children:[(0,W.jsx)(`p`,{className:`mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:`Playground`}),(0,W.jsx)(`h1`,{className:`text-3xl font-semibold tracking-tight text-zinc-950 dark:text-zinc-100 sm:text-4xl`,children:e.headline}),(0,W.jsx)(`p`,{className:`mt-4 max-w-3xl text-base leading-7 text-zinc-600 dark:text-zinc-300`,children:e.subtitle}),(0,W.jsx)(`div`,{className:`mt-7 grid gap-3 md:grid-cols-3`,children:e.pillars.map(e=>(0,W.jsxs)(`div`,{className:`rounded-2xl border border-zinc-200 bg-zinc-50/80 p-4 dark:border-zinc-800 dark:bg-zinc-900/70`,children:[(0,W.jsx)(`div`,{className:`mb-3 inline-flex size-8 items-center justify-center rounded-lg border border-zinc-200 bg-white text-zinc-700 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-200`,children:e.icon}),(0,W.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.label}),(0,W.jsx)(`p`,{className:`mt-1.5 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]},e.label))}),(0,W.jsx)(`div`,{className:`mt-7 flex flex-wrap gap-3`,children:e.actions.map(e=>(0,W.jsxs)(`button`,{type:`button`,onClick:()=>t(e.action),className:e.variant===`primary`?`inline-flex items-center gap-2 rounded-full bg-zinc-950 px-5 py-2.5 text-sm font-medium text-zinc-50 transition hover:opacity-90 dark:bg-zinc-100 dark:text-zinc-900`:`inline-flex items-center gap-2 rounded-full border border-zinc-300 px-5 py-2.5 text-sm font-medium text-zinc-700 transition hover:bg-zinc-100 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`,children:[e.label,(0,W.jsx)(lr,{className:`size-4`,"aria-hidden":`true`})]},`${e.action}-${e.label}`))})]})}function q4({config:e,isDarkMode:t,onRun:n}){let r=(0,U.useRef)(null),i=(0,U.useRef)(null),a=(0,U.useMemo)(()=>e.lines.map(e=>e.code).join(`
175
+ `),[e.lines]);return(0,U.useEffect)(()=>{if(r.current)return i.current?.destroy(),i.current=new Er({state:ri.create({doc:a,extensions:[Qr(),hi(),ri.readOnly.of(!1),Er.theme({"&":{fontSize:`13px`,borderRadius:`12px`,border:`1px solid var(--cm-border)`},".cm-scroller":{fontFamily:`JetBrains Mono, ui-monospace, SFMono-Regular, monospace`,lineHeight:`1.6`,minHeight:`180px`},".cm-content":{padding:`14px 0`},".cm-gutters":{backgroundColor:`transparent`,borderRight:`1px solid var(--cm-border)`}}),Er.theme({"&":{"--cm-border":t?`rgba(82, 82, 91, 0.7)`:`rgba(212, 212, 216, 0.9)`}},{dark:t}),...t?[ni]:[]]}),parent:r.current}),()=>{i.current?.destroy(),i.current=null}},[t,a]),e.lines.length===0?(0,W.jsxs)(`section`,{className:`rounded-2xl border border-amber-400/50 bg-amber-50 p-6 text-amber-900 dark:border-amber-500/40 dark:bg-amber-950/30 dark:text-amber-100`,children:[`Invalid `,(0,W.jsx)(`code`,{children:`code-example`}),` widget config.`]}):(0,W.jsxs)(`section`,{className:`p-5`,children:[(0,W.jsxs)(`div`,{className:`mb-4 flex items-center justify-between gap-3`,children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-zinc-900 dark:text-zinc-100`,children:`Code example`}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(i.current?.state.doc.toString()??a),className:`inline-flex items-center gap-2 rounded-full bg-emerald-600 px-4 py-2 text-xs font-semibold text-white transition hover:bg-emerald-500`,children:[(0,W.jsx)(pn,{className:`size-3.5`,"aria-hidden":`true`}),e.cta]})]}),(0,W.jsx)(`div`,{ref:r}),(0,W.jsx)(`ul`,{className:`mt-4 space-y-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.lines.map((e,t)=>(0,W.jsxs)(`li`,{className:`flex gap-2`,children:[(0,W.jsx)(`span`,{className:`mt-1 inline-block size-1.5 rounded-full bg-zinc-400`,"aria-hidden":`true`}),(0,W.jsxs)(`span`,{children:[(0,W.jsx)(`code`,{className:`rounded bg-zinc-200/70 px-1 py-0.5 text-[12px] dark:bg-zinc-800`,children:e.code}),` — `,e.annotation]})]},`${e.code}-${t}`))})]})}function J4({config:e,onOpenDocs:t}){return!e.category||!e.title||!e.docsPath?(0,W.jsxs)(`article`,{className:`rounded-2xl border border-amber-400/50 bg-amber-50 p-5 text-amber-900 dark:border-amber-500/40 dark:bg-amber-950/30 dark:text-amber-100`,children:[`Invalid `,(0,W.jsx)(`code`,{children:`syntax-group`}),` widget config.`]}):(0,W.jsxs)(`article`,{className:`p-5`,children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`p`,{className:`text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:e.category}),(0,W.jsxs)(`h3`,{className:`mt-2 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:[(0,W.jsx)(`span`,{className:`mr-2`,"aria-hidden":`true`,children:e.icon}),e.title]}),(0,W.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>t(e.docsPath),className:`inline-flex items-center gap-1.5 rounded-lg border border-zinc-300 px-2.5 py-1.5 text-xs font-semibold text-zinc-700 transition hover:bg-zinc-100 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`,children:[`Docs`,(0,W.jsx)(Ve,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,W.jsx)(`pre`,{className:`mt-4 overflow-x-auto rounded-xl border border-zinc-200 bg-white px-3 py-2 text-xs text-zinc-700 dark:border-zinc-700 dark:bg-zinc-950/70 dark:text-zinc-200`,children:(0,W.jsx)(`code`,{children:e.example})})]})}function Y4(e){return({config:t})=>(0,W.jsx)(K4,{config:t,onAction:e})}function X4(e,t){return({config:n})=>(0,W.jsx)(q4,{config:n,isDarkMode:e,onRun:t})}function Z4(e){return({config:t})=>(0,W.jsx)(J4,{config:t,onOpenDocs:e})}var Q4=[`visitedLanding`,`editedNote`,`ranWorkout`,`loggedEffort`,`openedReview`],$4=`wodwiki.onboarding.v1`,e3={visitedLanding:!1,editedNote:!1,ranWorkout:!1,loggedEffort:!1,openedReview:!1};function t3(){if(typeof window>`u`||!window.localStorage)return{...e3};try{let e=window.localStorage.getItem($4);if(!e)return{...e3};let t=JSON.parse(e),n={...e3};for(let e of Q4)n[e]=t[e]===!0;return n}catch{return{...e3}}}function n3(e){if(!(typeof window>`u`||!window.localStorage))try{window.localStorage.setItem($4,JSON.stringify(e))}catch{}}function r3(){let[e,t]=(0,U.useState)(t3);(0,U.useEffect)(()=>{let e=e=>{e.key===$4&&t(t3())};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]);let n=(0,U.useCallback)(e=>{t(t=>{if(t[e])return t;let n={...t,[e]:!0};return n3(n),n})},[]),r=Q4.length,i=Q4.reduce((t,n)=>t+ +!!e[n],0);return{progress:e,stepsComplete:i,totalSteps:r,isComplete:i===r,mark:n}}function i3(){let{mark:e}=r3();return{onEditNote:(0,U.useCallback)(()=>{e(`editedNote`)},[e]),onRunWorkout:(0,U.useCallback)(()=>{e(`ranWorkout`)},[e]),onLogEffort:(0,U.useCallback)(()=>{e(`loggedEffort`)},[e])}}var a3=new YO;function o3({theme:e,onViewCreated:t,onScrollToSection:n,onSearch:r}){let{id:i}=xn(),a=i??`playground`,o=MV(`playground`,a),s=(0,U.useMemo)(()=>i?ay(i):`Playground`,[i]),c=ht(),l=!i||i===`playground`,{content:u,loading:d,entryId:f,noteBlocks:p,sourceRevision:m,onIdentityChange:h,onSaved:g,error:_,onChange:v,onLineChange:y,onBlur:b,flush:x,committedSourceRevision:S,resetToOriginal:C}=u$({category:`playground`,name:a,mdContent:G$.content,seedOnMount:l}),T=f??o,{onEditNote:E,onRunWorkout:D,onLogEffort:O}=i3(),k=(0,U.useCallback)(e=>{E(),v(e)},[E,v]),[A,j]=(0,U.useState)([]),M=(0,U.useCallback)(()=>{Z.getSessionsForNote(T).then(e=>j(e.filter(e=>e.completed))).catch(()=>{})},[T]);(0,U.useEffect)(()=>{M()},[M]);let N=(0,U.useRef)(!1),P=(0,U.useRef)(null),F=(0,U.useCallback)(e=>{if(P.current=e,t?.(e),N.current)return;N.current=!0;let n=Math.min(G$.cursorOffset,e.state.doc.length);e.dispatch({selection:gi.cursor(n)})},[t]),I=(0,U.useCallback)(async e=>{try{await x();let t=w(),n=await bL(T,e,t,`playground`);g({rawContent:n.note.rawContent,blocks:n.note.blocks,sourceRevision:n.note.sourceRevision}),d$.set(t,{block:n.block,noteId:n.session.noteId,captured:n,origin:`playground`,returnTo:`/playground/${encodeURIComponent(a)}`}),D(),c(KM(t))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[T,a,c,D,x,g]),L=(0,U.useCallback)(async e=>{try{O();let t=await QQ({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content}),n=WO(new Date);Q({title:`Added to journal`,description:t.journalDate===n?`Added to today's journal`:`Added to ${t.journalDate}`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>c(BM(t.journalDate??n)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[s,a,c,O]),[R,ee]=(0,U.useState)(null),[te,ne]=(0,U.useState)(!1),re=(0,U.useCallback)(async e=>{let t=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`;try{await _K(T,t),Q({title:`Moved to journal`,description:`This playground now lives on ${t}.`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>c(BM(t)),children:`Open`})}),c(VM(T))}catch{Q({title:`Error`,description:`Could not move to journal`,variant:`destructive`})}},[T,c]),ie=(0,U.useCallback)(async(e,t)=>{let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await QQ({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content,date:t}),c(BM(n)),Q({title:`Scheduled`,description:`Added to journal for ${n}`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>c(BM(n)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[s,a,c]),[ae,oe]=(0,U.useState)([]),se=y$({content:u,scriptBlocks:ae,onStartWorkout:I,results:A}),ce=(0,U.useMemo)(()=>w$({id:T,type:`playground`}),[T]),le=A$({noteId:T,stamps:ce.stamps}),[z,ue]=(0,U.useState)(null);(0,U.useEffect)(()=>{let e=!1;return Z.getNote(T).then(t=>{if(e||!t?.sourceId)return;let n=T$(t.sourceId);n&&ue({noteId:T,link:n})}).catch(()=>{}),()=>{e=!0}},[T]);let de=(0,W.jsxs)(kB,{label:`Playground actions`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>ne(!0),title:`Move this playground to a journal date`,className:`inline-flex items-center gap-1 rounded-pill border border-border bg-card px-2.5 py-1 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,children:[(0,W.jsx)(Dn,{className:`size-3.5`,"aria-hidden":`true`}),`Move to journal`]}),(0,W.jsx)(K$,{mode:`playground`,currentWorkout:{name:s,content:u},index:se,onReset:C})]}),fe=M$(`playground`,{onPlay:I,onShare:R$,onAddToToday:L,onSchedule:ee}),B=(0,U.useCallback)(e=>{if(e===`scroll-to-workout`){let e=se.find(e=>e.type===`time`||e.type===`log`);e&&n?.(e.id)}else e===`open-search`&&r?.()},[se,n,r]),pe=(0,U.useCallback)(e=>{let t={id:`code-example-block`,line:0,endLine:e.split(`
176
+ `).length,content:e};I(t)},[I]),me=(0,U.useCallback)(e=>{e.startsWith(`/`)?window.open(e,`_blank`):c(e)},[c]),he=(0,U.useCallback)((e,t)=>{if(e===`route`&&t.route)c(t.route);else if(e===`start-workout`){let e=ae[0];e&&I(e)}else e===`new-note`&&c(`/playground`)},[c,ae,I]),ge=(0,U.useMemo)(()=>new Map([[`playground-run-tip`,G4],[`attention`,Y4(B)],[`code-example`,X4(e===`dark`,pe)],[`syntax-group`,Z4(me)]]),[B,pe,me,e]);return(0,U.useEffect)(()=>{document.title=`Wod.Wiki - ${s}`},[s]),d?(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(OL,{notePersistence:DN,provider:a3,children:(0,W.jsx)(Lz,{title:s,actions:de,editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,W.jsx)(j$,{data:le,up:ce.up,source:z?.noteId===T?z.link:null}),(0,W.jsx)(OX,{value:u,onChange:k,onCursorPositionChange:y,onBlur:b,noteId:T,noteBlocks:p,sourceRevision:m,onIdentityChange:e=>h({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:g,beforeRun:async()=>(await x(),S()),onSaveRequest:x,onCommitChange:x,commands:fe,enableInlineRuntime:!1,onViewCreated:F,theme:e,showLineNumbers:!1,onBlocksChange:oe,onButtonAction:he,widgetComponents:ge}),_?(0,W.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,_ instanceof Error?_.message:String(_),` Your draft is kept.`]}):null,(0,W.jsx)(XI,{noteId:T,blocks:p,sourceRevision:m,onRevert:async e=>{await x();let t=P.current?.state.field(Aw);if(!t)throw Error(`The current note editor is unavailable.`);let n=YI({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:S()},e);h({rawContent:n.rawContent,noteBlocks:n.blocks,sourceRevision:n.sourceRevision}),await x()}})]})})}),R&&(0,W.jsx)(HS,{open:!0,onClose:()=>ee(null),title:`Schedule workout`,children:(0,W.jsx)(s$,{selectedDate:null,onDateSelect:e=>{ie(R,e),ee(null)}})}),te&&(0,W.jsx)(HS,{open:!0,onClose:()=>ne(!1),title:`Move playground to Journal`,description:`Choose a date. This keeps the workout's existing results and attachments.`,children:(0,W.jsx)(s$,{selectedDate:null,onDateSelect:e=>{ne(!1),re(e)}})})]})}function s3({category:e,name:t,mdContent:n,theme:r,runMode:i,hidePlanningCommands:a,onViewCreated:o}){let s=i?i===`inline`:pH.has(e),c=!mH.has(e),l=MV(e,t),u=ht(),{content:d,loading:f,entryId:p,noteBlocks:m,sourceRevision:h,onIdentityChange:g,onSaved:_,error:v,onChange:y,onLineChange:b,onBlur:x,flush:S,committedSourceRevision:C}=u$({category:e,name:t,mdContent:n,seedOnMount:!c}),T=(0,U.useMemo)(()=>c?{label:`${e}-${t}`,path:GM(e,t)}:null,[e,c,t]),[E,D]=(0,U.useState)(null),O=(0,U.useCallback)(async n=>{let r=w();if(s){try{await S();let e=await yL({noteId:p??l,rawContent:d,blocks:m,expectedSourceRevision:C(),metadata:{title:t},noteType:`playground`},n,r);_({rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision}),d$.set(r,{block:e.block,noteId:e.session.noteId,captured:e}),u(KM(r))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}return}try{let i=await QQ({workoutName:t,category:e,sourceNoteLabel:T?.label,sourceNotePath:T?.path,wodContent:n.content}),a=Object.values(i.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The saved journal workout is unavailable.`);d$.set(r,{block:{...n,id:a.id},noteId:i.id}),u(HM(i.journalDate??``,r))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[s,l,p,t,e,T,u,d,m,S,C,_]),k=(0,U.useCallback)(async(n,r)=>{let i=zO(r),a;try{a=(await QQ({workoutName:t,category:e,sourceNoteLabel:T?.label,sourceNotePath:T?.path,wodContent:n.content,date:r,wrapInWod:!0})).journalDate??``}catch{Q({variant:`destructive`,title:`Could not save workout`,description:`Failed to add "${t}" to ${i}. Please try again.`});return}u(BM(a));let o=BM(a);Q({title:`Added to ${i}`,description:`"${t}" was added to your journal.`,action:(0,W.jsx)(Uj,{altText:`View journal entry`,onClick:()=>u(o),children:`View Note`}),duration:7e3})},[t,e,T,u]),A=M$(`collection-readonly`,{onPlay:O,onShare:R$,onAddToToday:a?void 0:e=>k(e,new Date),onSchedule:a?void 0:D,onOpenInPlayground:e=>F$(e,u)}),[j,M]=(0,U.useState)([]),N=(0,U.useCallback)(()=>{u(VM(l))},[u,l]),P=y$({content:d,scriptBlocks:j,onStartWorkout:O,onEditNote:c?N:void 0}),F=(0,U.useMemo)(()=>c?w$({id:l,type:`feed`}):null,[c,l]),I=A$({noteId:l,stamps:F?.stamps??[]}),L=(0,W.jsx)(kB,{children:(0,W.jsx)(K$,{mode:`collection-readonly`,currentWorkout:{name:l,content:d},index:P})});return f?(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(Lz,{title:t,actions:L,editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,W.jsx)(j$,{data:I,up:F?.up}),(0,W.jsx)(OX,{value:d,onChange:y,onCursorPositionChange:b,onBlur:x,noteId:l,noteBlocks:m,sourceRevision:h,onIdentityChange:e=>g({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:_,beforeRun:async()=>(await S(),C()),onSaveRequest:S,onCommitChange:S,readonly:!0,enableInlineRuntime:s,commands:A,onViewCreated:o,theme:r,showLineNumbers:!1,onBlocksChange:M}),v?(0,W.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,v instanceof Error?v.message:String(v),` Your draft is kept.`]}):null]})}),E&&(0,W.jsx)(HS,{open:!0,onClose:()=>D(null),title:`Schedule ${t}`,children:(0,W.jsx)(s$,{selectedDate:null,onDateSelect:e=>{e&&k(E,e),D(null)}})})]})}var c3=y(`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2`,{variants:{variant:{default:`border-transparent bg-primary text-primary-foreground hover:bg-primary/80`,secondary:`border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80`,destructive:`border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80`,outline:`text-foreground`}},defaultVariants:{variant:`default`}}),l3=U.memo(({className:e,variant:t,...n})=>(0,W.jsx)(`div`,{className:G(c3({variant:t}),e),...n})),u3=(0,U.forwardRef)(function({className:e,multiple:t,...n},r){return(0,W.jsxs)(`span`,{"data-slot":`control`,className:G(`group relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`has-data-[focus]:after:ring-2 has-data-[focus]:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:[(0,W.jsx)(D,{ref:r,multiple:t,...n,className:G(`relative block w-full appearance-none rounded-lg py-[calc(theme(spacing.2.5)-1px)]`,`sm:py-[calc(theme(spacing.1.5)-1px)]`,t?`px-[calc(theme(spacing.3.5)-1px)] sm:px-[calc(theme(spacing.3)-1px)]`:`pr-[calc(theme(spacing.10)-1px)] pl-[calc(theme(spacing.3.5)-1px)] sm:pr-[calc(theme(spacing.9)-1px)] sm:pl-[calc(theme(spacing.3)-1px)]`,`[&_optgroup]:font-semibold`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6 dark:[&>*]:text-white`,`border border-border/60 data-[hover]:border-border dark:border-white/10 dark:data-[hover]:border-white/20`,`bg-transparent dark:bg-white/5 dark:[&>*]:bg-muted`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 data-[disabled]:opacity-100 dark:data-[disabled]:border-white/15 dark:data-[disabled]:bg-white/2.5 dark:data-[hover]:data-[disabled]:border-white/15`,`dark:scheme-dark`,e)}),!t&&(0,W.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2`,children:(0,W.jsxs)(`svg`,{className:`size-5 stroke-muted-foreground group-has-data-[disabled]:stroke-muted-foreground/70 sm:size-4 forced-colors:stroke-[CanvasText]`,viewBox:`0 0 16 16`,"aria-hidden":`true`,fill:`none`,children:[(0,W.jsx)(`path`,{d:`M5.75 10.75L8 13L10.25 10.75`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,W.jsx)(`path`,{d:`M10.25 5.25L8 3L5.75 5.25`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]})}),d3={effort:`efforts`,equipment:`equipment`},f3=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`page`,`page_notes`,`note_tags`,`attachments`];async function p3(e){let t=e.kind===`effort`?Vc(e.rawContent):void 0,n=e.kind===`equipment`?Wc(e.rawContent):void 0,r=t?.effort??n?.equipment,i=[...t?.errors??n?.errors??[]],a=Y_(e.rawContent),o=typeof a.id==`string`?a.id.trim():``;if(o||i.push("Frontmatter must declare a stable `id` (the clone flow patches it into the source)"),r&&r.slug!==e.slug&&i.push(`Document slug "${r.slug}" does not match "${e.slug}"`),r&&r.label.trim()!==e.title.trim()&&i.push(`Document label "${r.label}" does not match title "${e.title}"`),i.length>0)throw Error(i.join(`
177
+ `));return Z.withTransaction([...f3],async i=>{let a=e.kind===`effort`?await i.getEffort(e.slug):await i.getEquipment(e.slug);if(a?.registrySource===`bundled`)throw Error(`"${e.slug}" is a bundled definition and cannot be saved over — clone it first`);if(a&&a.id!==o)throw Error(`Document id "${o}" does not match record id "${a.id}" — clone instead of re-keying`);let s=a?.ownerNoteId,c=e.noteId??s??`${e.kind}/${e.slug}`;if(s!==void 0&&c!==s)throw Error(`"${e.slug}" is owned by note ${s}; refusing to save against ${c}`);let l=new Date().toISOString();if(e.kind===`effort`){let n={...t.effort,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:d3.effort,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEffort(n)}else{let t={...n.equipment,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:d3.equipment,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEquipment(t)}return{id:c,sourceRevision:(await i.saveNoteSource({noteId:c,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:r.label,sourceId:d3[e.kind]},createdAt:Date.now()})).sourceRevision}})}async function m3(e,t){await Z.withTransaction([...f3],async n=>{let r=e===`effort`?await n.getEffort(t):await n.getEquipment(t);if(r?.registrySource!==`user`)throw Error(`"${t}" is not user-owned ${e}`);e===`effort`?await n.deleteEffort(t):await n.deleteEquipment(t);let i=r.ownerNoteId??`${e}/${t}`;await n.getNote(i)&&await n.deleteNote(i)})}function h3(e,t,n){let r=`effort-user-${crypto.randomUUID()}`,i=`${t}-custom`,a=`${n} (Custom)`,o=qa(e,[`id`],r);return o=qa(o,[`slug`],i),o=qa(o,[`label`],a),o=qa(o,[`registrySource`],`user`),o=qa(o,[`derivation`,`parentSlug`],t),{raw:o,id:r,slug:i,label:a}}function g3(e){let{registry:t,isReady:n,revision:r,refresh:i}=Fj(),[a,o]=(0,U.useState)(``),[s,c]=(0,U.useState)(!0),[l,u]=(0,U.useState)(null),[d,f]=(0,U.useState)(null),[p,m]=(0,U.useState)(!1),[h,g]=(0,U.useState)(!1),_=d?.registrySource===`user`,v=(0,U.useRef)(null),y=(0,U.useRef)(void 0);(0,U.useEffect)(()=>{if(!n){c(!1);return}if(!e){y.current=void 0,f(null),m(!1),g(!1),v.current=null,u(null),c(!1);return}let r=y.current!==e;y.current=e;let i=!1;r&&(v.current=null,c(!0),u(null),m(!1),f(null),o(``));async function a(){try{let n=t.resolve(e),a=n??t.resolveByAlias(e);if(!a){r&&!i&&(m(!0),c(!1));return}let s=a.ownerNoteId??`effort/${a.slug}`;if(!r&&v.current?.id===s){i||(f(a),g(!n));return}if(!r&&v.current)return;let l=await Z.getNote(s);if(i)return;f(a),g(!n),v.current={id:s,revision:l?.sourceRevision??0},o(l?.rawContent??Hc(a)),m(!1),c(!1)}catch(e){i||(u(e instanceof Error?e.message:`Failed to load effort.`),c(!1))}}return a(),()=>{i=!0}},[e,n,r,t]);let b=(0,U.useCallback)(async t=>{if(!e&&!d)return;let{effort:n,errors:r}=Vc(t,d??void 0);if(r.length>0)throw Q({title:`Invalid YAML`,description:r.join(`
178
+ `),variant:`destructive`}),Error(r.join(`
179
+ `));let a=t,o=n.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(o!==n.slug&&(n.slug=o,a=qa(a,[`slug`],o)),n.label.trim()!==n.label&&(n.label=n.label.trim(),a=qa(a,[`label`],n.label)),n.updatedAt=new Date().toISOString(),n.registrySource===`bundled`){let e=h3(a,n.slug,n.label);a=e.raw,n.id=e.id,n.slug=e.slug,n.label=e.label,n.registrySource=`user`,n.derivation={parentSlug:d?.slug,coefficients:{},hardOverrides:{}}}try{let e=n.ownerNoteId??v.current?.id??`effort/${n.slug}`,t=v.current?.id===e?v.current.revision:0,r=await p3({kind:`effort`,slug:n.slug,rawContent:a,title:n.label,expectedSourceRevision:t});v.current={id:r.id,revision:r.sourceRevision},await i(),f(n)}catch(e){throw Q({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`}),e}},[e,d,i]),{onChange:x,onLineChange:S,onBlur:C,flush:w}=c$({onSave:b});return{document:a,setDocument:(0,U.useCallback)(e=>{o(e),x(e)},[x]),isLoading:s,effort:d,isEditable:_,notFound:p,flush:w,onLineChange:S,onBlur:C,save:(0,U.useCallback)(e=>b(e??a),[b,a]),remove:(0,U.useCallback)(async()=>{let t=d?.slug??e;if(t)try{await m3(`effort`,t),v.current=null,f(null),await i()}catch(e){throw Q({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete effort.`,variant:`destructive`}),e}},[d,e,i]),cloneForEdit:(0,U.useCallback)(async()=>{if(!d||d.registrySource!==`bundled`)return null;let e=h3(a||Hc(d),d.slug,d.label),t={...d,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,derivation:{parentSlug:d.slug,coefficients:{},hardOverrides:{}},ownerNoteId:`effort/${e.slug}`,sourceId:`efforts`,sourcePath:`effort/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};f(t),o(e.raw);try{let t=await p3({kind:`effort`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});v.current={id:t.id,revision:t.sourceRevision},await i()}catch(e){throw Q({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[d,a,i]),error:l,isAliasMatch:h}}function _3({resolved:e,effort:t}){return(0,W.jsxs)(`div`,{className:`my-6 p-4 border rounded-lg bg-muted/30 space-y-4`,children:[(0,W.jsxs)(`h3`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,W.jsx)(P,{className:`size-4`}),`Effective Resolution`]}),(0,W.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Effective MET`}),(0,W.jsx)(`p`,{className:`text-xl font-bold`,children:e.met.toFixed(1)}),Math.abs(e.met-(t.baseAttributes.met||0))>.01&&(0,W.jsxs)(`span`,{className:`text-xs text-amber-600 dark:text-amber-400`,children:[`(base: `,t.baseAttributes.met.toFixed(1),`)`]})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Discipline Factor`}),(0,W.jsxs)(`p`,{className:`text-xl font-bold`,children:[e.disciplineFactor.toFixed(2),`×`]})]})]}),Object.keys(e.modifiers).length>0&&(0,W.jsxs)(`div`,{className:`border-t pt-3`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-2`,children:`Applied Modifiers`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Object.entries(e.modifiers).map(([e,t])=>(0,W.jsxs)(l3,{variant:`outline`,children:[e,`: `,t]},e))})]}),e.definition.derivation?.parentSlug&&(0,W.jsxs)(`div`,{className:`border-t pt-3 text-sm`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-1`,children:`Parent`}),(0,W.jsx)(`span`,{className:`font-mono text-primary`,children:e.definition.derivation.parentSlug})]})]})}function v3(){let{slug:e}=xn(),[t]=zn(),n=ht(),{theme:r}=ji(),i=r===`dark`?`dark`:`vs`,{registry:a,isReady:o,refresh:s}=Fj(),{document:c,setDocument:l,isLoading:u,effort:d,isEditable:f,notFound:p,cloneForEdit:m,error:h,onLineChange:g,onBlur:_,flush:v}=g3(e),[y,b]=(0,U.useState)([]),[x]=(0,U.useState)([]),[S,C]=(0,U.useState)(null),[T,E]=(0,U.useState)(!1),D=rN(t).mode===`create`,[O,k]=(0,U.useState)(()=>{let t=e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``,n=t?CD(t):``;return Hc({id:`effort-user-${crypto.randomUUID()}`,slug:t,label:n,aliases:t?[t.replace(/[-_]+/g,` `)]:[],baseAttributes:{met:5},registrySource:`user`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()})}),[A,j]=(0,U.useState)(!1),[M,F]=(0,U.useState)(``),I=(0,U.useMemo)(()=>a?[...a.list()].sort((e,t)=>e.label.localeCompare(t.label)):[],[a]),L=(0,U.useCallback)(async()=>{if(!(!e||!M||!a))try{await Qc(a,M,e),await s(),Q({title:`Alias Linked`,description:`Linked "${e}" as an alias to ${M}.`}),n(nN(M))}catch(e){Q({title:`Failed to link alias`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[e,M,a,s,n]),R=(0,U.useCallback)(async()=>{let{effort:e,errors:t}=Vc(O);if(t.length>0){Q({title:`Invalid YAML`,description:t.join(`
180
+ `),variant:`destructive`});return}let r=e.slug.trim();if(!r){Q({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(r)){Q({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${r}" in the document.`,variant:`destructive`});return}try{await p3({kind:`effort`,slug:r,rawContent:O,title:e.label.trim()||CD(r),expectedSourceRevision:0}),await s(),n(nN(r),{replace:!0})}catch(e){Q({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`})}},[O,s,n]),ee=(0,U.useMemo)(()=>new qc(a),[a]),te=(0,U.useMemo)(()=>!d||!o?null:ee.resolveEffort(d.slug),[d,o,ee]),ne=(0,U.useCallback)(async t=>{try{let r=await QQ({workoutName:d?.label??e??`Effort`,category:`effort`,sourceNotePath:nN(e??``),wodContent:t.content}),i=Object.values(r.blocks??{}).find(e=>e.kind===`wod`);if(!i)throw Error(`The saved journal workout is unavailable.`);let a=w();d$.set(a,{block:{...t,id:i.id},noteId:r.id}),n(`/run/${a}`)}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[e,d?.label,n]),re=(0,U.useCallback)(async(e,t)=>{if(!d)return;let r=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await QQ({workoutName:d.label,category:`effort`,sourceNoteLabel:d.label,sourceNotePath:nN(d.slug),wodContent:e.content,date:t}),n(BM(r)),Q({title:`Scheduled`,description:`Added to journal for ${r}`,action:(0,W.jsx)(Uj,{altText:`Open journal`,onClick:()=>n(BM(r)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[d,n]);y$({content:c,scriptBlocks:y,onStartWorkout:ne,results:x});let ie=d?.ownerNoteId??`effort/${e}`,ae=(0,U.useMemo)(()=>e?w$({id:ie,type:`collection`}):null,[e,ie]),oe=A$({noteId:ie,stamps:ae?.stamps??[],effortSlug:e}),se=M$(`collection-readonly`,{onPlay:ne,onShare:R$,onSchedule:C});(0,U.useEffect)(()=>{d&&(window.document.title=`Wod.Wiki - ${d.label}`)},[d]);let ce=(0,U.useCallback)(async()=>{if(d)try{let e=await m();e&&(n(nN(e.slug)),Q({title:`Cloned`,description:`Created a custom copy of "${d.label}". You can now edit it.`}))}catch(e){Q({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[m,d,n]);if(!o)return(0,W.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,W.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(D){let t=(0,W.jsx)(kB,{primary:(0,W.jsx)(K,{onClick:R,"data-testid":`effort-create-btn`,children:`Create Effort`}),children:(0,W.jsx)(K,{variant:`outline`,onClick:()=>n(ZM()),children:`Cancel`})});return(0,W.jsx)(`div`,{"data-testid":FH.EFFORT_DETAIL_ROOT,className:`contents`,children:(0,W.jsx)(Lz,{title:e&&e!==`new`?`New effort: ${e}`:`Create Custom Effort`,actions:t,editor:(0,W.jsx)(`div`,{className:`relative`,"data-testid":`effort-create-editor`,children:(0,W.jsx)(OX,{value:O,onChange:k,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:se,onBlocksChange:b})})})})}if(u)return(0,W.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,W.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(h)return(0,W.jsxs)(`div`,{"data-testid":`effort-load-error`,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Effort could not be loaded`}),(0,W.jsx)(`p`,{className:`text-sm text-destructive`,children:h})]}),(0,W.jsx)(K,{variant:`outline`,onClick:()=>n(ZM()),children:`Back to Catalog`})]});if(p||!d)return(0,W.jsxs)(`div`,{"data-testid":FH.EFFORT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Effort “`,e,`” not found`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This movement has not been populated in the effort catalog yet. You can create a new definition page for it or link it as an alias to an existing effort.`})]}),A?(0,W.jsxs)(`div`,{className:`w-full space-y-4 p-4 border rounded-lg bg-card text-left`,children:[(0,W.jsxs)(`div`,{className:`space-y-1`,children:[(0,W.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,children:[`Select target effort for “`,e,`”:`]}),(0,W.jsx)(u3,{value:M,onChange:e=>F(e.target.value),"data-testid":FH.EFFORT_NOT_FOUND_ALIAS_SELECT,children:I.map(e=>(0,W.jsxs)(`option`,{value:e.slug,children:[e.label,` (`,e.slug,`)`]},e.slug))})]}),(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(K,{variant:`ghost`,size:`sm`,onClick:()=>j(!1),children:`Cancel`}),(0,W.jsx)(K,{size:`sm`,onClick:L,disabled:!M,"data-testid":FH.EFFORT_NOT_FOUND_ALIAS_CONFIRM,children:`Confirm Link`})]})]}):(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,W.jsx)(K,{onClick:()=>n(nN(e,void 0,{mode:`create`})),"data-testid":FH.EFFORT_NOT_FOUND_CREATE_BTN,children:`Create Effort Page`}),(0,W.jsx)(K,{variant:`secondary`,onClick:()=>{j(!0),I.length>0&&!M&&F(I[0].slug)},"data-testid":FH.EFFORT_NOT_FOUND_ALIAS_BTN,children:`Link as Alias`}),(0,W.jsx)(K,{variant:`outline`,onClick:()=>n(ZM()),children:`Back to Catalog`})]})]});let le=(0,W.jsxs)(kB,{primary:f?void 0:(0,W.jsxs)(K,{variant:`outline`,onClick:ce,"data-testid":FH.EFFORT_DETAIL_CLONE_BTN,children:[(0,W.jsx)(xe,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,W.jsx)(K,{variant:`ghost`,size:`icon`,onClick:()=>_H()?n(-1):n(ZM()),"aria-label":`Back to catalog`,title:_H()?`Back`:`Back to catalog`,children:(0,W.jsx)(N,{className:`size-4`})}),(0,W.jsx)(l3,{"data-testid":FH.EFFORT_DETAIL_SOURCE,variant:d.registrySource===`bundled`?`secondary`:`default`,children:d.registrySource===`bundled`?`Bundled`:`Custom`}),te&&(0,W.jsxs)(K,{variant:T?`default`:`outline`,onClick:()=>E(e=>!e),children:[(0,W.jsx)(P,{className:`size-4 mr-1.5`}),T?`Hide Resolved`:`Show Resolved`]})]}),z=ie;return(0,W.jsxs)(`div`,{"data-testid":FH.EFFORT_DETAIL_ROOT,className:`contents`,children:[(0,W.jsx)(Lz,{title:d.label,titleTestId:FH.EFFORT_DETAIL_LABEL,actions:le,editor:(0,W.jsxs)(`div`,{className:`relative`,"data-testid":FH.EFFORT_DETAIL_NOTEBOOK_EDITOR,children:[T&&te&&(0,W.jsx)(`div`,{className:`px-6 lg:px-10 pt-4`,children:(0,W.jsx)(_3,{resolved:te,effort:d})}),(0,W.jsx)(OX,{noteId:z,value:c,onChange:l,onCursorPositionChange:g,onBlur:_,onSaveRequest:v,onCommitChange:v,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:se,onBlocksChange:b}),(0,W.jsx)(j$,{data:oe,up:ae?.up,relatedLabel:`Used in`})]})}),S&&(0,W.jsx)(HS,{open:!0,onClose:()=>C(null),title:`Schedule workout`,children:(0,W.jsx)(s$,{selectedDate:null,onDateSelect:e=>{re(S,e),C(null)}})})]})}function y3(e,t){let n=t??e.replace(/[-_]+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase());return Gc({id:`equipment-user-${crypto.randomUUID()}`,slug:e,label:n||e,aliases:[],registrySource:`user`})}function b3(e,t,n){let r=`equipment-user-${crypto.randomUUID()}`,i=`${t}-custom`,a=`${n} (Custom)`,o=qa(e,[`id`],r);return o=qa(o,[`slug`],i),o=qa(o,[`label`],a),o=qa(o,[`registrySource`],`user`),{raw:o,id:r,slug:i,label:a}}function x3(e){let{registry:t,isReady:n,refresh:r}=Rj(),[i,a]=(0,U.useState)(``),[o,s]=(0,U.useState)(!0),[c,l]=(0,U.useState)(null),[u,d]=(0,U.useState)(null),[f,p]=(0,U.useState)(!1),[m,h]=(0,U.useState)(!1),g=u?.registrySource===`user`,_=(0,U.useRef)(null);(0,U.useEffect)(()=>{if(!n){s(!1);return}if(!e){d(null),p(!1),h(!1),_.current=null,l(null),s(!1);return}let r=!1;s(!0),l(null),p(!1),d(null),a(``);async function i(){try{let n=t.resolve(e),i=n??t.resolveByAlias(e);if(!i){r||(p(!0),s(!1));return}let o=i.ownerNoteId??`equipment/${i.slug}`,c=await Z.getNote(o);if(r)return;d(i),h(!n),_.current={id:o,revision:c?.sourceRevision??0},a(c?.rawContent??Gc(i)),s(!1)}catch(e){r||(l(e instanceof Error?e.message:`Failed to load equipment.`),s(!1))}}return i(),()=>{r=!0}},[e,n,t]);let v=(0,U.useCallback)(async e=>{let{equipment:t,errors:n}=Wc(e,u??void 0);if(n.length>0)throw Q({title:`Invalid YAML`,description:n.join(`
181
+ `),variant:`destructive`}),Error(n.join(`
182
+ `));let i=e,a=t.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(a!==t.slug&&(t.slug=a,i=qa(i,[`slug`],a)),t.label.trim()!==t.label&&(t.label=t.label.trim(),i=qa(i,[`label`],t.label)),t.updatedAt=new Date().toISOString(),t.registrySource===`bundled`){let e=b3(i,t.slug,t.label);i=e.raw,t.id=e.id,t.slug=e.slug,t.label=e.label,t.registrySource=`user`}try{let e=t.ownerNoteId??_.current?.id??`equipment/${t.slug}`,n=_.current?.id===e?_.current.revision:0,a=await p3({kind:`equipment`,slug:t.slug,rawContent:i,title:t.label,expectedSourceRevision:n,noteId:e});_.current={id:a.id,revision:a.sourceRevision},await r(),d(t)}catch(e){throw Q({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save equipment.`,variant:`destructive`}),e}},[u,r]),{onChange:y,onLineChange:b,onBlur:x,flush:S}=c$({onSave:v});return{document:i,setDocument:(0,U.useCallback)(e=>{a(e),y(e)},[y]),isLoading:o,equipment:u,isEditable:g,notFound:f,flush:S,onLineChange:b,onBlur:x,save:(0,U.useCallback)(e=>v(e??i),[v,i]),remove:(0,U.useCallback)(async()=>{let e=u?.slug;if(e)try{await m3(`equipment`,e),_.current=null,d(null),await r()}catch(e){throw Q({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete equipment.`,variant:`destructive`}),e}},[u,r]),cloneForEdit:(0,U.useCallback)(async()=>{if(!u||u.registrySource!==`bundled`)return null;let e=b3(i||Gc(u),u.slug,u.label),t={...u,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,ownerNoteId:`equipment/${e.slug}`,sourceId:`equipment`,sourcePath:`equipment/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};d(t),a(e.raw);try{let t=await p3({kind:`equipment`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});_.current={id:t.id,revision:t.sourceRevision},await r()}catch(e){throw Q({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[u,i,r]),error:c,isAliasMatch:m}}function S3(e){let{isReady:t,registry:n}=Rj(),{isReady:r,revision:i,registry:a}=Fj(),[o,s]=(0,U.useState)({efforts:[],usedBy:[]});return(0,U.useEffect)(()=>{if(!t||!r||!e){s({efforts:[],usedBy:[]});return}let n=!1;async function i(){let t=a.list().filter(t=>t.equipment?.includes(e)??!1),r=await Z.getEquipmentUsage(e);n||s({efforts:t,usedBy:r})}return i(),()=>{n=!0}},[e,t,r,i,n,a]),o}function C3(){let{slug:e}=xn(),[t]=zn(),n=ht(),{theme:r}=ji(),i=r===`dark`?`dark`:`vs`,{isReady:a,refresh:o}=Rj(),{document:s,setDocument:c,isLoading:l,equipment:u,isEditable:d,notFound:f,cloneForEdit:p,error:m,onLineChange:h,onBlur:g,flush:_}=x3(e),[v,y]=(0,U.useState)([]),b=t.get(`mode`)===`create`,[x,S]=(0,U.useState)(()=>y3(e&&e!==`new`?e.trim().toLowerCase().replace(/\s+/g,`-`):``)),C=(0,U.useCallback)(async()=>{let{equipment:e,errors:t}=Wc(x);if(t.length>0){Q({title:`Invalid YAML`,description:t.join(`
183
+ `),variant:`destructive`});return}let r=e.slug.trim();if(!r){Q({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(r)){Q({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${r}" in the document.`,variant:`destructive`});return}try{await p3({kind:`equipment`,slug:r,rawContent:x,title:e.label.trim()||CD(r),expectedSourceRevision:0}),await o(),n(QM(r),{replace:!0})}catch(e){Q({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save equipment.`,variant:`destructive`})}},[x,o,n]);y$({content:b?x:s,scriptBlocks:v});let w=u?.ownerNoteId??(e?`equipment/${e}`:``),T=(0,U.useMemo)(()=>w?w$({id:w,type:`collection`}):null,[w]),E=A$({noteId:w,stamps:T?.stamps??[]}),D=S3(u?.slug),O=(0,U.useMemo)(()=>({efforts:D.efforts.map(e=>({id:e.slug,title:e.label,to:nN(e.slug)})),related:D.usedBy.map(e=>({id:e.noteId,title:e.title,to:x$(e.noteId)})),backlinks:E.backlinks}),[D,E.backlinks]);(0,U.useEffect)(()=>{u&&(window.document.title=`Wod.Wiki - ${u.label}`)},[u]);let k=(0,U.useCallback)(async()=>{if(u)try{let e=await p();e&&(n(QM(e.slug)),Q({title:`Cloned`,description:`Created a custom copy of "${u.label}". You can now edit it.`}))}catch(e){Q({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[p,u,n]);if(!a||l)return(0,W.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,W.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(b){let t=(0,W.jsx)(kB,{primary:(0,W.jsx)(K,{onClick:C,"data-testid":FH.EQUIPMENT_CREATE_BTN,children:`Create Equipment`}),children:(0,W.jsx)(K,{variant:`outline`,onClick:()=>n($.equipment),children:`Cancel`})});return(0,W.jsx)(`div`,{"data-testid":FH.EQUIPMENT_DETAIL_ROOT,className:`contents`,children:(0,W.jsx)(Lz,{title:e&&e!==`new`?`New equipment: ${e}`:`New equipment`,actions:t,editor:(0,W.jsx)(`div`,{className:`relative`,"data-testid":`equipment-create-editor`,children:(0,W.jsx)(OX,{value:x,onChange:S,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,onBlocksChange:y})})})})}if(m)return(0,W.jsxs)(`div`,{"data-testid":FH.EQUIPMENT_LOAD_ERROR,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Equipment could not be loaded`}),(0,W.jsx)(`p`,{className:`text-sm text-destructive`,children:m})]}),(0,W.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:(0,W.jsx)(K,{variant:`outline`,onClick:()=>n($.equipment),children:`Back to Equipment`})})]});if(f||!u)return(0,W.jsxs)(`div`,{"data-testid":FH.EQUIPMENT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Equipment “`,e,`” not found`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No equipment definition exists for this slug yet. You can create a new definition page for it.`})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,W.jsx)(K,{onClick:()=>n(`${QM(e??`new`)}?mode=create`),"data-testid":FH.EQUIPMENT_NOT_FOUND_CREATE_BTN,children:`Create Equipment Page`}),(0,W.jsx)(K,{variant:`outline`,onClick:()=>n($.equipment),children:`Back to Equipment`})]})]});let A=(0,W.jsxs)(kB,{primary:d?void 0:(0,W.jsxs)(K,{variant:`outline`,onClick:k,"data-testid":FH.EQUIPMENT_DETAIL_CLONE_BTN,children:[(0,W.jsx)(xe,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,W.jsx)(K,{variant:`ghost`,size:`icon`,onClick:()=>_H()?n(-1):n($.equipment),"aria-label":`Back to Equipment`,title:_H()?`Back`:`Back to Equipment`,children:(0,W.jsx)(N,{className:`size-4`})}),(0,W.jsx)(l3,{"data-testid":FH.EQUIPMENT_DETAIL_SOURCE,variant:u.registrySource===`bundled`?`secondary`:`default`,children:u.registrySource===`bundled`?`Bundled`:`Custom`})]});return(0,W.jsx)(`div`,{"data-testid":FH.EQUIPMENT_DETAIL_ROOT,className:`contents`,children:(0,W.jsx)(Lz,{title:u.label,titleTestId:FH.EQUIPMENT_DETAIL_LABEL,actions:A,editor:(0,W.jsxs)(`div`,{className:`relative`,"data-testid":FH.EQUIPMENT_DETAIL_NOTEBOOK_EDITOR,children:[(0,W.jsx)(OX,{noteId:w,value:s,onChange:c,onCursorPositionChange:h,onBlur:g,onSaveRequest:_,onCommitChange:_,theme:i,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,onBlocksChange:y}),(0,W.jsx)(j$,{data:O,up:T?.up,relatedLabel:`Used in`})]})})})}var w3=`wodwiki-user-calcs`,T3=1,E3=`calcs`,D3=`user-calc:`,O3;function k3(){return O3||=or(w3,T3,{upgrade(e){e.objectStoreNames.contains(E3)||e.createObjectStore(E3,{keyPath:`id`})}}),O3}var A3={scope:`segment`};async function j3(){return ik?(await fk(D3)).map(e=>e.value).sort((e,t)=>t.updatedAt-e.updatedAt):(await(await k3()).getAll(E3)).sort((e,t)=>t.updatedAt-e.updatedAt)}async function M3(e){if(ik){await pk(D3+e.id,{id:e.id,lineForm:e.lineForm,updatedAt:e.updatedAt??Date.now()});return}await(await k3()).put(E3,{...e,updatedAt:e.updatedAt??Date.now()})}async function N3(e){if(ik)return mk(D3+e);await(await k3()).delete(E3,e)}async function P3(){let e=await j3(),t=[],n=[];for(let r of e)try{let{defs:e}=sp(r.lineForm,A3);t.push(...e)}catch(e){n.push({id:r.id,message:e instanceof Error?e.message:String(e)})}return{defs:t,errors:n}}var F3={segment:`per record`,workout:`at workout end`},I3=new Set([`segment`,`workout`]);function L3(){let[e]=zn(),t=e.get(`tag`),[n,r]=(0,U.useState)([]),[i,a]=(0,U.useState)([]),[o,s]=(0,U.useState)([]),[c,l]=(0,U.useState)(null),[u,d]=(0,U.useState)(``),[f,p]=(0,U.useState)(``),[m,h]=(0,U.useState)([]),[g,_]=(0,U.useState)(``),[v,y]=(0,U.useState)(``),[b,x]=(0,U.useState)(``),[S,C]=(0,U.useState)(``),[w,T]=(0,U.useState)(null),[E,D]=(0,U.useState)(!1),O=(0,U.useCallback)(async()=>{let[e,t]=await Promise.all([Z.getAllTags(),Z.getAllTagTypes()]),n=await P3().catch(()=>({defs:[],errors:[]}));r(e),a(t);let i=xf.filter(e=>I3.has(e.scope)).map(e=>({name:e.id,grain:F3[e.scope]??e.scope}));for(let e of n.defs)I3.has(e.scope)&&i.push({name:e.id,grain:F3[e.scope]??e.scope});s(i)},[]);(0,U.useEffect)(()=>{O()},[O]),(0,U.useEffect)(()=>{if(!t||n.length===0)return;let e=n.find(e=>e.label===t);e&&l(e.id)},[t,n]);let k=n.find(e=>e.id===c)??null;(0,U.useEffect)(()=>{k&&(d(k.label),p(k.type??``),h(k.contributions??[]))},[k]);let A=fL(),j=(0,U.useMemo)(()=>So(A),[A]),M=async()=>{if(!k)return!1;let e=u.trim();return e.length===0?(T("A tag needs a name — that name is what `#slug` refers to."),!1):n.find(t=>t.id!==k.id&&t.label.trim()===e)?(T(`Another tag is already called "${e}".`),!1):(await Z.putTag({...k,label:e,type:f||void 0,contributions:m}),await UA(),await O(),T(null),D(!0),!0)},N=async()=>{let e=g.trim();if(e.length===0){T(`A tag needs a name.`);return}if(n.some(t=>t.label.trim()===e)){T(`A tag called "${e}" already exists.`);return}let t={id:`tag-${e}-${Date.now().toString(36)}`,label:e,type:v||void 0,contributions:[],createdAt:Date.now()};await Z.putTag(t),await UA(),await O(),l(t.id),_(``),T(null)},P=async()=>{k&&(await Z.deleteTag(k.id),await UA(),await O(),l(null))},F=(e,t)=>{D(!1),h(n=>n.map((n,r)=>r===e?t:n))},I=e=>{h(t=>t.filter((t,n)=>n!==e))},L=(0,U.useMemo)(()=>{let e=b.trim().toLowerCase();return n.filter(t=>!(e&&!t.label.toLowerCase().includes(e)||S&&(t.type??``)!==S))},[n,b,S]),R=(0,U.useMemo)(()=>{let e=new Set(i.map(e=>e.name));for(let t of n)t.type&&e.add(t.type);return f&&!e.has(f)&&e.add(f),[...e].sort()},[i,n,f]);return(0,W.jsxs)(`div`,{className:`max-w-4xl mx-auto p-6 space-y-8`,children:[(0,W.jsxs)(`section`,{className:`space-y-2`,children:[(0,W.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Tags`}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`A tag is a named bundle a script can point at:`,` `,(0,W.jsxs)(`code`,{className:`font-mono`,children:[`5 reps @ 100 kg `,`#heavy`]}),`. What the tag brings applies to the line it sits on. A tag can contribute a metric (a typed value with a unit), another tag, or a function — a named calculation that runs where the tag applies.`]}),j.length>0&&(0,W.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`These tags apply each other in a loop: `,j.map(e=>e.join(` → `)).join(`; `),`. A loop contributes nothing.`]})]}),(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`New tag`}),(0,W.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-3`,children:[(0,W.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),N()},className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex-1 min-w-[200px]`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Name`}),(0,W.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`,placeholder:`heavy`,value:g,onChange:e=>_(e.target.value)})]}),(0,W.jsxs)(`div`,{className:`w-40`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Kind`}),(0,W.jsxs)(`select`,{className:`w-full h-9 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`,value:v,onChange:e=>y(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:`—`}),R.map(e=>(0,W.jsx)(`option`,{value:e,children:e},e))]})]}),(0,W.jsxs)(K,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,W.jsx)(En,{className:`size-3.5 mr-1`}),` Add Tag`]})]}),w&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,children:w})]})]}),(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Tags`}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsx)(`input`,{"aria-label":`Filter tags`,className:`h-8 w-44 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`,placeholder:`Filter by name…`,value:b,onChange:e=>x(e.target.value)}),(0,W.jsxs)(`select`,{"aria-label":`Filter by kind`,className:`h-8 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`,value:S,onChange:e=>C(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:`All kinds`}),R.map(e=>(0,W.jsx)(`option`,{value:e,children:e},e))]})]})]}),n.length===0?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No tags yet.`}):L.length===0?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No tags match the filter.`}):(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:L.map(e=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>l(e.id),className:e.id===c?`px-2.5 py-1 rounded-md border border-primary bg-primary/10 font-mono text-xs text-foreground`:`px-2.5 py-1 rounded-md border border-border bg-card font-mono text-xs text-muted-foreground hover:text-foreground`,children:e.label},e.id))})]}),k&&(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground`,children:[`Edit `,k.label]}),(0,W.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Created `,new Date(k.createdAt).toLocaleDateString()]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex-1 min-w-[200px]`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Name`}),(0,W.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 font-mono text-xs outline-none focus:border-primary`,value:u,onChange:e=>d(e.target.value)})]}),(0,W.jsxs)(`div`,{className:`w-40`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Kind`}),(0,W.jsxs)(`select`,{className:`w-full h-9 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`,value:f,onChange:e=>p(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:`—`}),R.map(e=>(0,W.jsx)(`option`,{value:e,children:e},e))]})]})]}),(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`h3`,{className:`text-xs font-medium text-muted-foreground`,children:`Contributions`}),(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsxs)(K,{type:`button`,size:`sm`,variant:`outline`,className:`h-7 text-xs`,onClick:()=>h(e=>[...e,{kind:`metric`,type:``,value:``}]),children:[(0,W.jsx)(En,{className:`size-3 mr-1`}),` Metric`]}),(0,W.jsxs)(K,{type:`button`,size:`sm`,variant:`outline`,className:`h-7 text-xs`,onClick:()=>h(e=>[...e,{kind:`tag`,slug:``}]),children:[(0,W.jsx)(En,{className:`size-3 mr-1`}),` Tag`]}),(0,W.jsxs)(K,{type:`button`,size:`sm`,variant:`outline`,className:`h-7 text-xs`,onClick:()=>h(e=>[...e,{kind:`function`,name:``}]),children:[(0,W.jsx)(En,{className:`size-3 mr-1`}),` Function`]})]})]}),m.length===0?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`This tag contributes nothing yet.`}):(0,W.jsx)(`div`,{className:`space-y-2`,children:m.map((e,t)=>(0,W.jsx)(R3,{contribution:e,tagOptions:n.filter(e=>e.id!==k.id).map(e=>e.label.trim()),functionOptions:o,onChange:e=>F(t,e),onRemove:()=>I(t)},t))})]}),(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(K,{type:`button`,size:`sm`,className:`h-9`,onClick:()=>void M(),children:`Save`}),(0,W.jsxs)(K,{type:`button`,size:`sm`,variant:`outline`,className:`h-9`,onClick:()=>void P(),children:[(0,W.jsx)(Ue,{className:`size-3.5 mr-1`}),` Delete`]}),E&&(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground self-center`,children:`Saved`})]})]})]})]})}function R3({contribution:e,tagOptions:t,functionOptions:n,onChange:r,onRemove:i}){let a=`h-8 rounded-md border border-input bg-background px-2 text-xs outline-none focus:border-primary`;return(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e.kind===`metric`&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`input`,{"aria-label":`Metric type`,className:`${a} w-32 font-mono`,placeholder:`type`,value:e.type,onChange:t=>r({...e,type:t.target.value})}),(0,W.jsx)(`input`,{"aria-label":`Metric value`,className:`${a} w-32`,placeholder:`value`,value:String(e.value),onChange:t=>r({...e,value:t.target.value})}),(0,W.jsx)(`input`,{"aria-label":`Metric unit`,className:`${a} w-24`,placeholder:`unit`,value:e.unit??``,onChange:t=>r({...e,...t.target.value?{unit:t.target.value}:{unit:void 0}})})]}),e.kind===`tag`&&(0,W.jsx)(W.Fragment,{children:(0,W.jsxs)(`select`,{"aria-label":`Applied tag`,className:`${a} w-48 font-mono`,value:e.slug,onChange:t=>r({...e,slug:t.target.value}),children:[(0,W.jsx)(`option`,{value:``,children:`choose a tag…`}),t.map(e=>(0,W.jsx)(`option`,{value:e,children:e},e))]})}),e.kind===`function`&&(0,W.jsx)(W.Fragment,{children:(0,W.jsxs)(`select`,{"aria-label":`Function`,className:`${a} w-56 font-mono`,value:e.name,onChange:t=>r({...e,name:t.target.value}),children:[(0,W.jsx)(`option`,{value:``,children:`choose a function…`}),n.map(e=>(0,W.jsxs)(`option`,{value:e.name,children:[e.name,` — `,e.grain]},e.name))]})}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Remove contribution`,className:`text-muted-foreground hover:text-destructive`,onClick:i,children:(0,W.jsx)(Ue,{className:`size-3.5`})})]})}var z3=`h-11 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`;function B3({open:e,onOpenChange:t,entry:n,mode:r,provider:i,onSaved:a,onCloned:o}){let[s,c]=(0,U.useState)(``),[l,u]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[p,m]=(0,U.useState)([]),[h,g]=(0,U.useState)(!1),[_,v]=(0,U.useState)(null),y=(0,U.useRef)(!1),b=n.id,x=n.journalDate,S=n.slug,C=n.sourceId;(0,U.useEffect)(()=>{e&&(c(x??(r===`clone`?FN():``)),u(r===`clone`?``:S??``),f(C??``),v(null))},[e,r,b,x,S,C]),(0,U.useEffect)(()=>{if(!e||r!==`relationships`)return;let t=!1;return i.getEntries().then(e=>{t||m(e.filter(e=>e.id!==n.id&&!e.catalog))}).catch(()=>{}),()=>{t=!0}},[e,r,i,n.id]);let w=r===`clone`,T=`note-placement-sources-${n.id}`,E=()=>{y.current||t(!1)};return(0,W.jsx)(HS,{open:e,onClose:E,title:w?`Clone note`:`Note relationships`,description:w?`Independent copy. Results and attachments are not copied.`:void 0,presentation:`sheet`,footer:(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(K,{type:`button`,variant:`outline`,size:`lg`,onClick:E,disabled:h,children:`Cancel`}),(0,W.jsx)(K,{type:`submit`,form:`note-placement-form`,size:`lg`,disabled:h,children:h?`Saving…`:w?`Clone`:`Save`})]}),children:(0,W.jsxs)(`form`,{id:`note-placement-form`,onSubmit:async e=>{if(e.preventDefault(),!y.current){y.current=!0,g(!0),v(null);try{let e=s.trim(),r=l.trim(),c=d.trim(),u=e===``?null:LN(e);if(e&&!u){v(`Enter a valid date (YYYY-MM-DD).`);return}if(w){if(!e&&!r){v(`Choose a destination date or named page for the clone.`);return}let i=await BN.create({journalDate:e||void 0,slug:r||void 0,title:n.title,rawContent:n.rawContent,tags:n.tags,sourceId:n.id,type:`journal`});o?.(i),t(!1);return}let f={};if(c!==(C??``)){if(c===``)f.sourceId=null;else try{let e=await BN.resolve(c);if(!e||e.id===n.id)throw Error(`invalid source`);f.sourceId=e.id}catch{v(`Source note not found.`);return}}if(e!==(x??``)&&(f.journalDate=e===``?null:e,u&&(f.targetDate=u.date.getTime())),r!==(S??``)&&(f.slug=r===``?null:r),Object.keys(f).length===0){t(!1);return}let p=await i.updateEntry(n.id,f);a?.(p),t(!1)}catch{v(`Could not save — your fields are kept. Try again.`)}finally{y.current=!1,g(!1)}}},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`note-placement-date`,className:`text-sm font-medium`,children:`Journal date`}),(0,W.jsx)(`input`,{id:`note-placement-date`,type:`date`,className:z3,value:s,onChange:e=>c(e.target.value),disabled:h}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:w?`Defaults to the note’s date.`:`Leave empty to detach from the calendar.`})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`note-placement-slug`,className:`text-sm font-medium`,children:`Named page`}),(0,W.jsx)(`input`,{id:`note-placement-slug`,type:`text`,className:z3,value:l,onChange:e=>u(e.target.value),placeholder:`e.g. marathon-block`,autoCapitalize:`none`,spellCheck:!1,disabled:h}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Optional /p/<slug> link. Typing an existing page's slug shares that page with its notes — it does not create a unique copy.`})]}),w?null:(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`note-placement-source`,className:`text-sm font-medium`,children:`Source note`}),(0,W.jsx)(`input`,{id:`note-placement-source`,type:`text`,className:z3,value:d,onChange:e=>f(e.target.value),list:T,autoCapitalize:`none`,spellCheck:!1,disabled:h}),(0,W.jsx)(`datalist`,{id:T,children:p.map(e=>(0,W.jsx)(`option`,{value:e.id,children:e.title||`Untitled`},e.id))}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Leave empty to clear.`})]}),_&&(0,W.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:_})]})})}var V3=new YO;function H3({noteId:e,theme:t}){let n=ht(),r=Xt(),[i]=zn(),[a,o]=(0,U.useState)(null),[s,c]=(0,U.useState)(!1),l=(0,U.useRef)(0),u=(0,U.useRef)(null),d=(0,U.useRef)(async()=>{}),f=r.pathname.startsWith(`/p/`)||a!==null&&!Ea(a),[p,m]=(0,U.useState)(null),[h,g]=(0,U.useState)(null),[_,v]=(0,U.useState)(null),y=mZ();(0,U.useEffect)(()=>{JL().catch(()=>{})},[e]),(0,U.useEffect)(()=>{let t=!1;return o(null),c(!1),m(null),V3.getEntry(e).then(e=>{if(!t){if(!e){c(!0);return}o(e),l.current=e.sourceRevision??0,u.current={rawContent:e.rawContent,blocks:e.blocks??{},sourceRevision:e.sourceRevision??0}}}).catch(()=>{t||c(!0)}),()=>{t=!0}},[e,i]);let b=a?.sourceId;(0,U.useEffect)(()=>{if(v(null),!b)return;let e=!1;return V3.getEntry(b).then(t=>{e||v(t)}).catch(()=>{}),()=>{e=!0}},[b]);let x=(0,U.useMemo)(()=>a?w$(a):{zone:null,up:null,stamps:[]},[a]);uM(x.zone);let[S,C]=(0,U.useState)([]),[T,E]=(0,U.useState)([]),D=a?.id;(0,U.useEffect)(()=>{if(E([]),C([]),!D)return;let e=!1,t=()=>{Z.getSessionsForNote(D).then(t=>{e||E(t)}).catch(()=>{})};t();let n=XW(n=>{!e&&n.noteId===D&&t()});return()=>{e=!0,n()}},[D]);let O=(0,U.useCallback)(async t=>{if(a)try{await d.current();let e=u.current;if(!e)throw Error(`The note draft is unavailable.`);let r=w(),i=await yL({noteId:a.id,rawContent:e.rawContent,blocks:e.blocks,expectedSourceRevision:l.current},t,r);l.current=i.note.sourceRevision,d$.set(r,{block:i.block,noteId:a.id,captured:i,returnTo:VM(a.id)}),n(KM(r))}catch(t){m({noteId:e,message:`Workout not started. ${t instanceof Error?t.message:String(t)} Your draft is kept.`})}},[a,e,n]);y$({content:a?.rawContent??``,scriptBlocks:S,onStartWorkout:O,results:T});let k=A$(a?{noteId:a.id,stamps:x.stamps}:{noteId:``,stamps:[]}),A=(0,U.useCallback)(e=>{l.current=e.sourceRevision;let t=u.current,n=t?.rawContent===e.rawContent&&JSON.stringify(Object.values(t.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));o(t=>t&&{...t,...n?{blocks:e.blocks}:{},sourceRevision:e.sourceRevision})},[]),j=(0,U.useCallback)(async t=>{let n=await DN.saveNote({noteId:e,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:l.current});return A({rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??l.current}),m(null),o(e=>e?.id===n.id?{...e,title:n.title}:e),{rawContent:n.rawContent,blocks:n.blocks??{},sourceRevision:n.sourceRevision??0}},[e,A]),{onChange:M,onBlur:N,onLineChange:P,flush:F}=c$({onSave:async e=>{await j(e)},getSnapshotKey:e=>JSON.stringify([e.rawContent,Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])]),onError:t=>m({noteId:e,message:`Save failed. ${t instanceof Error?t.message:String(t)} Your draft is kept. Retry saving.`})});d.current=F;let I=(0,U.useCallback)(e=>{let t=u.current?.rawContent!==e.rawContent||JSON.stringify(Object.values(u.current?.blocks??{}).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));u.current=e,t&&M(e)},[M]),L=(0,U.useCallback)(e=>{o(t=>t&&{...t,rawContent:e})},[]),R=(0,U.useCallback)(async e=>{await F();let t=u.current;if(!t)throw Error(`The note draft is unavailable.`);let n=YI({...t,sourceRevision:l.current},e),r=await j(n);u.current=r,o(e=>e&&{...e,...r})},[F,j]),ee=(0,U.useCallback)(()=>Promise.resolve(),[]),te;if(s)te=(0,W.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 text-zinc-400`,children:[(0,W.jsx)(`p`,{children:`Note not found.`}),(0,W.jsx)(K,{variant:`outline`,onClick:()=>n(-1),children:`Go back`})]});else if(!a)te=(0,W.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-zinc-400`,children:`Loading…`});else{let r=`inline-flex min-h-11 items-center gap-1 rounded-pill border border-border bg-card px-2.5 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,i=(0,W.jsxs)(kB,{label:`Note actions`,children:[(0,W.jsxs)(`button`,{type:`button`,className:r,onClick:()=>g(`relationships`),children:[(0,W.jsx)(mn,{className:`size-3.5`,"aria-hidden":`true`}),`Note relationships`]}),(0,W.jsxs)(`button`,{type:`button`,className:r,onClick:()=>g(`clone`),children:[(0,W.jsx)(An,{className:`size-3.5`,"aria-hidden":`true`}),`Clone`]})]});te=(0,W.jsxs)(OL,{notePersistence:DN,provider:V3,children:[(0,W.jsx)(Lz,{title:a.title,subtitle:VM(a.id),actions:i,editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-4 px-4 py-6 sm:px-6 min-w-0 max-w-full`,children:[(0,W.jsx)(j$,{data:k,up:x.up}),(a.journalDate||a.slug||a.sourceId)&&(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[a.journalDate&&(0,W.jsx)(Nt,{to:zM(a.journalDate),className:`underline-offset-2 hover:underline`,children:a.journalDate}),a.slug&&(0,W.jsxs)(Nt,{to:YM(a.slug),className:`underline-offset-2 hover:underline`,children:[`/p/`,a.slug]}),a.sourceId&&(0,W.jsxs)(`span`,{children:[`Cloned from`,` `,_?(0,W.jsx)(Nt,{to:VM(_.id),className:`underline-offset-2 hover:underline`,children:_.title||_.id}):(()=>{let e=T$(a.sourceId);return e?(0,W.jsx)(Nt,{to:e.to,className:`underline-offset-2 hover:underline`,children:e.title}):a.sourceId})()]})]}),y?(0,W.jsx)(`div`,{className:`rounded-lg border border-border bg-card p-4 shadow-sm min-h-[240px] focus-within:border-accent/80 transition-colors`,children:(0,W.jsx)(OX,{value:a.rawContent,onChange:L,onBlur:N,noteId:a.id,noteBlocks:a.blocks,sourceRevision:a.sourceRevision,onIdentityChange:I,onSaved:A,beforeRun:async()=>(await F(),l.current),onSaveRequest:F,onCommitChange:F,onCursorPositionChange:P,readonly:f,theme:t,showLineNumbers:!1,onCompleteWorkout:ee,onBlocksChange:C,placeholder:`Write workout or notes here…`})}):(0,W.jsx)(`div`,{className:`flex items-center justify-center text-zinc-400 text-sm py-8`,children:`Loading…`}),(0,W.jsx)(XI,{noteId:a.id,blocks:a.blocks,sourceRevision:a.sourceRevision,onRevert:f?void 0:R}),p?.noteId===e&&(0,W.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p.message})]})}),h!==null&&(0,W.jsx)(B3,{open:!0,onOpenChange:e=>{e||g(null)},entry:a,mode:h,provider:V3,onSaved:e=>o(t=>t&&t.id===e.id?{...t,journalDate:e.journalDate,slug:e.slug,sourceId:e.sourceId}:t),onCloned:e=>n(`${VM(e.id)}?edit=1`)})]})}return te}var U3=new YO;function W3(e){let t=new Map;for(let n of e){let e=n.tags[0]?.toLowerCase()??`untagged`,r=t.get(e);r?r.push(n):t.set(e,[n])}return Array.from(t.entries()).map(([e,t])=>({id:`day-group-${e}`,label:e===`untagged`?`Untagged`:`#${e}`,entries:t}))}function G3(e){return PN(new Date(e.targetDate))}function K3({slug:e,date:t}){let[n,r]=(0,U.useState)(null);(0,U.useEffect)(()=>{let n=!1;return U3.getEntries().then(i=>{if(n)return;let a=i.filter(n=>n.catalog===e&&G3(n)===t);r(a.sort((e,t)=>t.createdAt-e.createdAt))}).catch(()=>{n||r([])}),()=>{n=!0}},[e,t]);let i=(0,U.useMemo)(()=>n?W3(n):[],[n]),{setL3Items:a}=lM();(0,U.useEffect)(()=>{if(i.length===0){a([]);return}let e=i.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return a(e),()=>a([])},[i,a]);let o=n===null?(0,W.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-zinc-400`,children:`Loading…`}):n.length===0?(0,W.jsxs)(`p`,{className:`rounded-lg border border-dashed border-border p-6 text-sm text-muted-foreground`,children:[`No notes in this collection for `,t,`.`]}):(0,W.jsx)(`div`,{className:`flex flex-col gap-6`,children:i.map(e=>(0,W.jsxs)(`section`,{id:e.id,className:`flex flex-col rounded-lg border border-border overflow-hidden`,children:[(0,W.jsxs)(`h3`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[e.label,` · `,e.entries.length]}),(0,W.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:e.entries.map(e=>(0,W.jsx)(`li`,{children:(0,W.jsxs)(Nt,{to:VM(e.id),className:`flex flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,children:[(0,W.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:new Date(e.createdAt).toLocaleTimeString()})]})},e.id))})]},e.id))});return(0,W.jsx)(Lz,{title:t,subtitle:e,editor:(0,W.jsx)(`div`,{className:`flex flex-col gap-6 px-4 py-6 sm:px-6`,children:o})})}var q3=`__new__`;function J3(e){return e.open?(0,W.jsx)(Y3,{...e},e.subsetQuery??`(whole-store)`):null}function Y3({onOpenChange:e,initialQuery:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a}){let o=ht(),{items:s,loading:c}=jN(),l=s.filter(e=>e.editable),[u,d]=(0,U.useState)(l[0]?.slug??q3),[f,p]=(0,U.useState)(``),[m,h]=(0,U.useState)(null),g=()=>e(!1);return(0,W.jsx)(i0,{open:!0,onClose:g,mode:`add`,initialWql:t,subsetQuery:n,rangeStart:r,rangeEnd:i,preferredUnit:a,onApply:async e=>{h(null);let t={title:e.title,question:e.question,type:e.type,spanCols:e.spanCols,spanFull:e.spanFull,wql:e.wql,attributes:e.attributes};try{if(u===q3){let e=f.trim()||`New Dashboard`,n=await HN.createDashboard(e);await BN.update(n,z_(n.rawContent,t)),g(),o(tN(j_(e)))}else{let e=await BN.resolve(u);await BN.update(e,z_(e.rawContent,t)),g(),o(tN(u))}}catch(e){let t=e instanceof Error?e.message:String(e);throw h(t),e}},applyLabel:`Add to dashboard`,destination:(0,W.jsxs)(`section`,{children:[(0,W.jsx)(`div`,{className:`text-[11px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5`,children:`Destination`}),c?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading dashboards…`}):(0,W.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[l.map(e=>(0,W.jsx)(`button`,{type:`button`,"aria-pressed":u===e.slug,onClick:()=>d(e.slug),className:`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${u===e.slug?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:e.title},e.slug)),(0,W.jsxs)(`button`,{type:`button`,"data-testid":`dashboard-dest-new`,"aria-pressed":u===q3,onClick:()=>d(q3),className:`flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${u===q3?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,W.jsx)(En,{className:`size-3`}),` New dashboard`]})]}),u===q3&&(0,W.jsx)(`input`,{type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`New Dashboard`,"data-testid":`dashboard-new-title`,className:`w-full sm:w-64 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-none focus:border-primary`})]}),m&&(0,W.jsxs)(`p`,{role:`alert`,"data-testid":`dashboard-save-error`,className:`mt-2 text-xs text-destructive font-mono`,children:[`Could not save: `,m]})]})})}function X3({catalog:e}){let[t,n]=(0,U.useState)([]),[r,i]=(0,U.useState)(!1),[a,o]=(0,U.useState)(``);return(0,U.useEffect)(()=>{let t=!1,r=()=>{e.listByPrefix(a,50).then(e=>{t||n(e)}).catch(()=>{})};r();let i=e.onChange?.(()=>r());return()=>{t=!0,i?.()}},[e,a]),(0,W.jsxs)(`section`,{className:`rounded-lg border p-3 text-sm`,"data-testid":`available-fields`,children:[(0,W.jsxs)(`button`,{type:`button`,className:`flex w-full items-center justify-between font-medium`,onClick:()=>i(e=>!e),children:[(0,W.jsxs)(`span`,{children:[`Available fields (`,t.length,`)`]}),(0,W.jsx)(`span`,{"aria-hidden":!0,children:r?`▾`:`▸`})]}),r&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`input`,{className:`mt-2 w-full rounded border px-2 py-1`,placeholder:`Filter fields…`,value:a,onChange:e=>o(e.target.value)}),(0,W.jsxs)(`ul`,{className:`mt-2 max-h-64 space-y-1 overflow-auto`,children:[t.map(e=>(0,W.jsxs)(`li`,{className:`flex items-baseline justify-between gap-2`,children:[(0,W.jsx)(`span`,{className:`font-mono`,children:e.path}),(0,W.jsxs)(`span`,{className:`text-xs opacity-70`,children:[e.kind,e.dimension?` · ${e.dimension}`:``,e.units.length?` · ${e.units.join(`/`)}`:``,e.spellings.length&&e.spellings[0]!==e.path?` · “${e.spellings[0]}”`:``]})]},e.id)),t.length===0&&(0,W.jsx)(`li`,{className:`opacity-60`,children:`No discovered fields for this prefix.`})]})]})]})}function Z3(e){return{id:e.id,path:e.path,kind:e.kind,...e.dimension?{dimension:e.dimension}:{},units:Object.keys(e.units??{}),spellings:Object.keys(e.spellings??{})}}var Q3=new class{storageInstance;listeners=new Set;constructor(e=DO){this.storageInstance=e}async listByPrefix(e,t=20){let n=e&&typeof IDBKeyRange<`u`?IDBKeyRange.bound(e,`${e}\uFFFF`,!1,!0):void 0;return(await this.storageInstance.readonly(`field_catalog`).getAllFromIndex(`by-path`,n,t)).map(Z3)}async lookup(e){return(await this.storageInstance.readonly(`field_catalog`).getAllFromIndex(`by-path`,e)).map(Z3)}async listValues(e,t,n=20){let r=await this.lookup(e),i=[];for(let e of r){if(i.length>=n)break;let r=t&&typeof IDBKeyRange<`u`?IDBKeyRange.bound([e.id,t],[e.id,`${t}\uFFFF`],!1,!0):void 0,a=await this.storageInstance.readonly(`field_values`).getAllFromIndex(`by-field`,r,n-i.length);for(let e of a)i.push({fieldId:e.fieldId,value:e.value})}return i}notifyChanged(){for(let e of this.listeners)e()}observeStore(e){}}(DO);function $3({label:e,value:t,className:n}){return(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 rounded border border-border bg-background/60 px-2 py-1`,children:[(0,W.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground`,children:e}),(0,W.jsx)(`span`,{className:G(`font-mono text-xs`,n??`text-foreground`),children:t})]})}function e6(e){return e.kind===`relative`?`last ${e.size}${e.unit}`:e.end?`from ${e.start} to ${e.end}`:`from ${e.start}`}function t6({parsed:e}){if(e.error)return(0,W.jsx)(`div`,{className:`text-sm text-destructive font-mono`,children:e.error});if(Sm(e)){let t=e.source.kind===`dataset`?(0,W.jsx)($3,{label:`source`,value:e.source.name,className:`text-blue-400 dark:text-blue-300`}):(0,W.jsx)($3,{label:`source`,value:`target`in e.source.query?`:${e.source.query.target}`:`:${e.source.query.agg}`,className:`text-blue-400 dark:text-blue-300`});return(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[t,e.transforms.map((e,t)=>(0,W.jsx)($3,{label:`fn ${t+1}`,value:`${e.agg}:${e.metric}`,className:`text-green-400 dark:text-green-300`},t)),e.sink&&(0,W.jsx)($3,{label:`sink`,value:`:${e.sink.head}`,className:`text-purple-400 dark:text-purple-300`})]})}let t=e.window&&(0,W.jsx)($3,{label:`window`,value:e6(e.window),className:`text-sky-400 dark:text-sky-300`}),n=e.filters.map((e,t)=>(0,W.jsx)($3,{label:e.negate?`exclude`:`filter`,value:`${e.key}:${e.values.map(e=>`${e.value}${e.wildcard?`*`:``}`).join(`|`)}`,className:`text-amber-400 dark:text-amber-300`},t));return xm(e)?(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,W.jsx)($3,{label:`aggregate`,value:e.agg,className:`text-blue-400 dark:text-blue-300`}),(0,W.jsx)($3,{label:`metric`,value:e.metric}),n,e.groupBy.map((e,t)=>(0,W.jsx)($3,{label:`group by`,value:e,className:`text-green-400 dark:text-green-300`},t)),e.rollup&&(0,W.jsx)($3,{label:`rollup`,value:`${e.rollup.size}${e.rollup.unit}`,className:`text-purple-400 dark:text-purple-300`}),e.displayUnit&&(0,W.jsx)($3,{label:`in`,value:e.displayUnit,className:`text-pink-400 dark:text-pink-300`}),t,e.join&&(0,W.jsx)($3,{label:`where`,value:`:${e.join.target}`,className:`text-teal-400 dark:text-teal-300`})]}):bm(e)?(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[(0,W.jsx)($3,{label:`target`,value:e.target,className:`text-blue-400 dark:text-blue-300`}),n,t,e.join&&(0,W.jsx)($3,{label:`where`,value:`${e.join.agg}:${e.join.metric}`,className:`text-teal-400 dark:text-teal-300`})]}):null}function n6({result:e}){let{parsed:t,stages:n}=e;if(t.error)return null;let r=t.groupBy.find(e=>e===`day`||e===`week`),i=r?`by ${r}`:t.rollup?`rollup ${t.rollup.size}${t.rollup.unit}`:`no rollup`,a=t.groupBy.length?`by {${t.groupBy.join(`, `)}}`:`single series`,o=[{n:1,name:`SELECT`,desc:`tag + time index scan`,count:n.selected,unit:`points`},{n:2,name:`BUCKET`,desc:i,count:n.buckets,unit:`buckets`},{n:3,name:`AGGREGATE`,desc:`${t.agg} per bucket`,count:n.aggregated,unit:`values`},{n:4,name:`GROUP`,desc:a,count:n.groups,unit:`series`}];return(0,W.jsx)(`div`,{className:`flex items-center gap-0 mt-4 overflow-x-auto`,children:o.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex items-center`,children:[(0,W.jsxs)(`div`,{className:`border border-border rounded-lg bg-background/60 px-3 py-2 min-w-[130px]`,children:[(0,W.jsxs)(`div`,{className:`text-[10px] font-bold tracking-wide`,style:{color:Ex[t%Ex.length]},children:[e.n,`. `,e.name]}),(0,W.jsx)(`div`,{className:`text-[11px] text-muted-foreground`,children:e.desc}),(0,W.jsxs)(`div`,{className:`text-sm font-semibold tabular-nums mt-0.5`,children:[e.count.toLocaleString(),` `,(0,W.jsx)(`span`,{className:`text-[10px] font-normal text-muted-foreground`,children:e.unit})]})]}),t<3&&(0,W.jsx)(Qt,{size:16,className:`text-muted-foreground mx-1 shrink-0`})]},e.n))})}function r6({matched:e,displayUnit:t}){let[n,r]=(0,U.useState)(!1);if(e.length===0)return null;let i=e=>{let t=[];return e.effortSlug&&t.push(`effort:${e.effortSlug}`),e.discipline&&t.push(`discipline:${e.discipline}`),e.intensityTier&&t.push(`intensity:${e.intensityTier}`),e.origin&&t.push(`origin:${e.origin}`),t},a=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};return(0,W.jsxs)(`div`,{className:`bg-card border border-border rounded-lg mt-3`,children:[(0,W.jsxs)(`button`,{onClick:()=>r(!n),className:`w-full flex items-center gap-2 px-4 py-2.5 text-sm text-muted-foreground hover:text-foreground`,children:[n?(0,W.jsx)(Cn,{size:14}):(0,W.jsx)(Qt,{size:14}),`Raw metric points behind this query (`,e.length,`)`,(0,W.jsx)(`span`,{className:`text-[11px] ml-auto`,children:`one row per fact from the analytics store`})]}),n&&(0,W.jsxs)(`div`,{className:`px-4 pb-3 overflow-x-auto`,children:[(0,W.jsxs)(`table`,{className:`w-full text-[11px] font-mono`,children:[(0,W.jsx)(`thead`,{children:(0,W.jsxs)(`tr`,{className:`text-muted-foreground text-left border-b border-border`,children:[(0,W.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`ts`}),(0,W.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`metric`}),(0,W.jsx)(`th`,{className:`py-1.5 pr-4 font-normal`,children:`value`}),(0,W.jsx)(`th`,{className:`py-1.5 font-normal`,children:`tags`})]})}),(0,W.jsx)(`tbody`,{children:e.slice(0,12).map(e=>{let n=e.unit??e.metricUnit,r=typeof e.value==`number`?e.value:void 0,o=t&&r!==void 0&&n&&Gh(n)===Gh(t)?Wh(r,n,t):void 0;return(0,W.jsxs)(`tr`,{className:`border-b border-border/40`,children:[(0,W.jsx)(`td`,{className:`py-1.5 pr-4 text-muted-foreground whitespace-nowrap`,children:a(e.timestamp)}),(0,W.jsx)(`td`,{className:`py-1.5 pr-4 text-primary whitespace-nowrap`,children:e.metricKey}),(0,W.jsxs)(`td`,{className:`py-1.5 pr-4 tabular-nums`,children:[String(e.value),n?` ${n}`:``,o!==void 0&&n!==t?` → ${o.toLocaleString()} ${t}`:``]}),(0,W.jsx)(`td`,{className:`py-1.5 text-muted-foreground`,children:i(e).map(e=>(0,W.jsx)(`span`,{className:`inline-block bg-background/80 rounded px-1.5 py-0.5 mr-1 mb-0.5`,children:e},e))})]},e.id)})})]}),e.length>12&&(0,W.jsxs)(`div`,{className:`text-[11px] text-muted-foreground pt-2`,children:[`… `,e.length-12,` more points`]})]})]})}var i6=[`totalVolume`,`tis`,`sessionLoad`,`totalReps`],a6=[`effort`,`discipline`,`intensity`,`tags`,`note`,`origin`];function o6(){let[e,t]=(0,U.useState)(i6);return(0,U.useEffect)(()=>{let e=!1;async function n(){try{let n=Date.now(),r=n-31536e6,i=await $L.getFactsByTimeRange(r,n);if(e)return;let a=new Set([...i6,...i.map(e=>e.metricKey)].filter(e=>e!==void 0));t(Array.from(a).sort())}catch{}}return n(),()=>{e=!0}},[]),{metricKeys:e,tagKeys:a6}}var s6=[4,8,16],c6=`sum:totalVolume{}`;function l6(e){let t=Number.parseInt(e??``,10);return s6.includes(t)?t:16}function u6(e={}){let{defaultQuery:t=c6,runOnLanding:n=!1}=e,[r,i]=zn(),a=r.get(`q`)??``,o=l6(r.get(`weeks`)),[s,c]=(0,U.useState)(()=>a&&!X(a).error?a:t),[l,u]=(0,U.useState)(a||(n?t:``)),d=(0,U.useRef)(s);d.current=s;let f=(0,U.useRef)(r);f.current=r;let p=(0,U.useRef)(!0),m=(0,U.useRef)(a);m.current=a;let h=(0,U.useRef)(a);(0,U.useEffect)(()=>{a!==h.current&&(h.current=a,d.current!==a&&(p.current=!0,c(a&&!X(a).error?a:t),u(a||(n?t:``))))},[a,t,n]);let g=(0,U.useRef)(t);return(0,U.useEffect)(()=>{t!==g.current&&(g.current=t,!a&&(c(t),u(n?t:``)))},[t,a,n]),{draft:s,setDraft:(0,U.useCallback)(e=>{if(e===d.current)return;let t=new URLSearchParams(f.current);t.set(`q`,e),i(t,{replace:!p.current}),p.current=!1,c(e)},[i]),submitted:l,submit:(0,U.useCallback)(e=>{let t=e??d.current;if(X(t).error)return;if(p.current&&m.current===t){u(t);return}let n=new URLSearchParams(f.current);n.set(`q`,t),i(n,{replace:!0}),p.current=!0,u(t)},[i]),weeks:o,setWeeks:(0,U.useCallback)(e=>{let t=new URLSearchParams(f.current);t.set(`weeks`,String(e)),i(t,{replace:!0})},[i])}}function d6({weeks:e,onWeeks:t,unitForced:n,onOpenQuerySettings:r}){let[i,a]=(0,U.useState)(!1),o=(0,U.useRef)(null),{unit:s,setUnit:c}=uS();(0,U.useEffect)(()=>{if(!i)return;let e=e=>{o.current?.contains(e.target)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[i]);let l=e=>()=>{e(),a(!1)};return(0,W.jsxs)(`div`,{ref:o,className:`relative`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),"data-testid":`explorer-options`,"aria-expanded":i,className:G(`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors`,i?`border-primary/60 text-primary bg-primary/10`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`),children:[(0,W.jsx)(_n,{className:`size-3.5`}),`Options`,(0,W.jsx)(Cn,{className:G(`size-3 transition-transform`,i&&`rotate-180`)})]}),i&&(0,W.jsxs)(`div`,{className:`absolute right-0 top-full z-40 mt-1 w-72 rounded-xl border border-border bg-card shadow-xl p-1.5`,"data-testid":`explorer-options-menu`,children:[(0,W.jsx)(`div`,{className:`px-2 pt-1.5 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:`Range`}),s6.map(n=>(0,W.jsxs)(`button`,{type:`button`,onClick:l(()=>t(n)),className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs text-foreground hover:bg-muted transition-colors`,children:[(0,W.jsx)(`span`,{className:`w-3.5 text-primary`,children:e===n?(0,W.jsx)(Vn,{className:`size-3.5`}):null}),`Past `,n,` weeks`]},n)),(0,W.jsxs)(`div`,{className:`mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:[`Units`,n?` — pinned by query`:``]}),[`kg`,`lb`].map(e=>(0,W.jsxs)(`button`,{type:`button`,disabled:n,onClick:l(()=>c(e)),className:G(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs transition-colors`,n?`text-muted-foreground/50 cursor-not-allowed`:`text-foreground hover:bg-muted`),children:[(0,W.jsx)(`span`,{className:`w-3.5 text-primary`,children:s===e?(0,W.jsx)(Vn,{className:`size-3.5`}):null}),e]},e)),r&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-[10px] font-black uppercase tracking-widest text-muted-foreground/70`,children:`This page`}),(0,W.jsxs)(`button`,{type:`button`,onClick:l(r),"data-testid":`explorer-query-settings`,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs text-foreground transition-colors hover:bg-muted`,children:[(0,W.jsx)(`span`,{className:`w-3.5 text-primary`}),`Query settings`]})]})]})]})}var f6=Z,p6=`sample`,m6=6048e5;function h6(e){return Math.round(e*10)/10}var g6={thruster:`high`,"pull-up":`high`,"push-up":`moderate`,"air-squat":`moderate`,"double-under":`high`,"sit-up":`low`,rowing:`moderate`,running:`moderate`,"recovery-run":`low`,"back-squat":`high`,deadlift:`high`},_6={fran:`high`,cindy:`moderate`,annie:`moderate`,rowing:`moderate`,running:`moderate`,strength:`high`,recoveryRun:`low`};function v6(e,t,n,r){return{effortSlug:n,discipline:r,reps:e,loadLbs:t,tisSeconds:h6(e*(n===`thruster`?2.2:1.6))}}function y6(e,t,n){let r=330-n*16,i=Math.max(180,h6(r+(Math.random()-.5)*20)),a=95+n*5;return{noteId:`sample-fran-${t}-${crypto.randomUUID()}`,title:`Sample — Fran (week ${16-t})`,workoutType:`fran`,timestamp:e-t*m6,durationSeconds:i,movements:[v6(45,a,`thruster`,`strength`),v6(45,0,`pull-up`,`gymnastics`)]}}function b6(e,t,n){let r=10+n+Math.round((Math.random()-.5)*2),i=Math.max(8,r);return{noteId:`sample-cindy-${t}-${crypto.randomUUID()}`,title:`Sample — Cindy (week ${16-t})`,workoutType:`cindy`,timestamp:e-t*m6,durationSeconds:1200,movements:[{effortSlug:`pull-up`,discipline:`gymnastics`,reps:i*5,loadLbs:0,tisSeconds:h6(i*5*1.5)},{effortSlug:`push-up`,discipline:`gymnastics`,reps:i*10,loadLbs:0,tisSeconds:h6(i*10*1.2)},{effortSlug:`air-squat`,discipline:`bodyweight`,reps:i*15,loadLbs:0,tisSeconds:h6(i*15*1.1)}]}}function x6(e,t,n){let r=540-n*22,i=Math.max(360,h6(r+(Math.random()-.5)*30));return{noteId:`sample-annie-${t}-${crypto.randomUUID()}`,title:`Sample — Annie (week ${16-t})`,workoutType:`annie`,timestamp:e-t*m6,durationSeconds:i,movements:[{effortSlug:`double-under`,discipline:`gymnastics`,reps:150,loadLbs:0,tisSeconds:h6(75)},{effortSlug:`sit-up`,discipline:`bodyweight`,reps:150,loadLbs:0,tisSeconds:h6(195)}]}}function S6(e,t,n){let r=135+n*5,i=185+n*5;return{noteId:`sample-strength-${t}-${crypto.randomUUID()}`,title:`Sample — Strength accessory (week ${16-t})`,workoutType:`strength`,timestamp:e-t*m6,durationSeconds:1800,movements:[{effortSlug:`back-squat`,discipline:`strength`,reps:25,loadLbs:r,tisSeconds:h6(62.5)},{effortSlug:`deadlift`,discipline:`strength`,reps:15,loadLbs:i,tisSeconds:h6(42)}]}}function C6(e,t,n){let r=2e3+n*250,i=h6(r/2+(Math.random()-.5)*30);return{noteId:`sample-rowing-${t}-${crypto.randomUUID()}`,title:`Sample — Rowing (week ${16-t})`,workoutType:`rowing`,timestamp:e-t*m6,durationSeconds:i,movements:[{effortSlug:`rowing`,discipline:`rowing`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function w6(e,t,n){let r=5e3+n*500,i=h6(r/2.8+(Math.random()-.5)*60);return{noteId:`sample-running-${t}-${crypto.randomUUID()}`,title:`Sample — Running (week ${16-t})`,workoutType:`running`,timestamp:e-t*m6,durationSeconds:i,movements:[{effortSlug:`running`,discipline:`running`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function T6(e,t,n){let r=3e3+n*50,i=h6(r/2.2+(Math.random()-.5)*60);return{noteId:`sample-recovery-run-${t}-${crypto.randomUUID()}`,title:`Sample — Recovery run (week ${16-t})`,workoutType:`recoveryRun`,timestamp:e-t*m6,durationSeconds:i,movements:[{effortSlug:`recovery-run`,discipline:`running`,reps:1,loadLbs:0,tisSeconds:i,distanceMeters:r}]}}function E6(e){let t=[];for(let n=0;n<16;n++){let r=Math.floor(n/4);t.push(S6(e,n,n)),n%4==0?t.push(y6(e,n,r)):n%4==1?t.push(b6(e,n,r)):n%4==2?t.push(x6(e,n,r)):n===3||n===11?t.push(C6(e,n,r)):(n===7||n===15)&&t.push(w6(e,n,r)),t.push(T6(e,n,n))}return t.sort((e,t)=>e.timestamp-t.timestamp)}function D6(e){let t=e.timestamp,n=_6[e.workoutType],r=e.movements.reduce((e,t)=>e+t.reps,0),i=e.movements.reduce((e,t)=>e+t.reps*t.loadLbs,0),a=e.movements.reduce((e,t)=>e+t.tisSeconds,0),o=e.movements.reduce((e,t)=>e+(t.distanceMeters??0),0),s=h6(i/100+r+e.durationSeconds/10),c=[],l=(e,n,r,i,a)=>{let o={canonicalKey:i};a?.effortSlug&&(o.effortSlug=a.effortSlug),a?.discipline&&(o.effortDiscipline=a.discipline),a?.intensityTier&&(o.effortIntensityTier=a.intensityTier);let s={id:c.length,outputType:`analytics`,timeSpan:{started:t},metrics:[{type:q.Label,value:e,origin:`analyzed`},{type:q.Metric,value:n,unit:r,metadata:o,origin:`analyzed`}],sourceBlockKey:``,stackLevel:0};c.push(s)};if(l(`Elapsed time`,e.durationSeconds,`s`,`elapsed`,{intensityTier:n}),l(`Total reps`,r,`reps`,`totalReps`,{intensityTier:n}),l(`Time in motion`,h6(a),`s`,`tis`,{intensityTier:n}),i>0&&l(`Total volume`,h6(i),`lb`,`totalVolume`,{intensityTier:n}),o>0){let t=e.movements.find(e=>e.distanceMeters&&e.distanceMeters>0)?.discipline;l(`Total distance`,h6(o),`m`,`totalDistance`,{discipline:t,intensityTier:n})}l(`Session load`,s,`AU`,`sessionLoad`,{intensityTier:n});for(let t of e.movements){let e=t.reps*t.loadLbs,n=g6[t.effortSlug]??`moderate`,r={effortSlug:t.effortSlug,discipline:t.discipline,intensityTier:n};l(`Total reps`,t.reps,`reps`,`totalReps`,r),l(`Time in motion`,t.tisSeconds,`s`,`tis`,r),e>0&&l(`Total volume`,h6(e),`lb`,`totalVolume`,r),l(`Session load`,h6(e/100+t.reps+t.tisSeconds/10),`AU`,`sessionLoad`,r)}return c}function O6(e,t){let n=`${`sample-${e.noteId}`}-result`,r=e.timestamp,i=r+e.durationSeconds*1e3;return{id:n,noteId:e.noteId,blockId:`sample-block`,blockVersion:1,blockContentId:t,origin:`journal`,status:`completed`,createdAt:Date.now(),startTime:r,endTime:i,duration:e.durationSeconds*1e3,completed:!0}}async function k6(){return(await f6.getTagByLabel(p6))?.id}async function A6(){return(await f6.getNotesForTag(p6)).map(e=>e.id)}async function j6(){let e=await A6();return e.length!==0&&(await f6.scanAll()).some(t=>e.includes(t.noteId))}async function M6(){if(await j6()){let e=await A6();return{facts:(await f6.scanAll()).filter(t=>t.grain===`summary`&&e.includes(t.noteId)).length}}let e=E6(Date.now()),t=0;for(let n of e){let e=n.movements.map(e=>`${e.distanceMeters?`${e.distanceMeters}m`:e.reps} ${e.effortSlug.replaceAll(`-`,` `)}${e.loadLbs?` ${e.loadLbs}lb`:``}`).join(`
184
+ `),r=`# ${n.title}\n\n\`\`\`log\n${e}\n\`\`\`\n`,i=Na(r,{sourceRevision:1,createId:()=>`sample-block`}),a=D6(n),o=O6(n,xa(e)),s={noteId:n.noteId,resultId:o.id,blockId:o.blockId,blockVersion:o.blockVersion,blockContentId:o.blockContentId,origin:o.origin,pageId:o.pageId,workoutTimestamp:n.timestamp};t+=await f6.withTransaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`],async e=>{await e.saveNoteSource({noteId:n.noteId,rawContent:r,blocks:i,expectedSourceRevision:0,metadata:{title:n.title},noteType:`playground`,createdAt:n.timestamp}),await e.setNoteTags(n.noteId,[p6]),await e.saveSession(o),await e.appendEvents(Eg(a,s));let t=Dg(a,s);return await e.finalizeSummaries(o.id,t),t.length})}return{facts:t}}async function N6(){let e=await A6();if(e.length!==0){for(let t of e)await f6.deleteEvents((await f6.getEventsForNote(t)).map(e=>e.id)),await f6.deleteNote(t);if((await f6.getNotesForTag(p6)).length===0){let e=await k6();e&&await f6.deleteTag(e)}}}function P6({result:e,onChanged:t,layout:n=`inline`,refreshKey:r}){let[i,a]=(0,U.useState)(void 0),[o,s]=(0,U.useState)(!1),c=(0,U.useCallback)(async()=>{a(await j6()),s(!1)},[]);(0,U.useEffect)(()=>{c()},[c,r]);let l=async()=>{await M6(),await c(),t?.()},u=(0,W.jsxs)(`div`,{className:`flex items-center justify-center gap-3 rounded-md border border-border bg-muted/50 px-3 py-2 text-xs text-foreground`,children:[(0,W.jsx)(`span`,{children:`Sample data loaded`}),(0,W.jsx)(`button`,{onClick:async()=>{await N6(),await c(),t?.()},className:`font-medium text-destructive hover:text-destructive/80 transition-colors`,children:`Purge sample data`}),(0,W.jsx)(`button`,{onClick:()=>s(!0),className:`text-muted-foreground hover:text-foreground transition-colors`,"aria-label":`Dismiss`,children:(0,W.jsx)(we,{size:14})})]});if(n===`banner`)return i&&!o?u:null;let d=i?o?null:u:(0,W.jsxs)(`div`,{className:`text-center`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2`,children:`Facts appear when you log or run workouts.`}),(0,W.jsxs)(`div`,{className:`flex items-center justify-center gap-3`,children:[(0,W.jsx)(`button`,{onClick:l,className:`text-xs font-medium rounded-md bg-primary text-primary-foreground px-3 py-1.5 hover:opacity-90 transition-opacity`,children:`Preview with sample data`}),(0,W.jsx)(Nt,{to:`/collections`,className:`text-xs text-primary underline-offset-2 hover:underline`,children:`Log your first workout`})]})]});return n===`card`?(0,W.jsxs)(`div`,{className:`bg-card border border-border rounded-lg p-6 flex flex-col items-center justify-center text-sm text-muted-foreground`,children:[e!==void 0&&(0,W.jsx)(yx,{result:e}),i!==void 0&&d&&(0,W.jsx)(`div`,{className:`mt-3`,children:d})]}):(0,W.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center`,children:[e!==void 0&&(0,W.jsx)(yx,{result:e}),i!==void 0&&d&&(0,W.jsx)(`div`,{className:`mt-3`,children:d})]})}var F6=`:dashboard{}`,I6=864e5,L6=`agg:metric{filters} by {dims} .rollup(period)`,R6=new Set([`tags`,`catalog`,`text`,`type`,`has`]);function z6(e){let t=e.find(e=>e.key===`source`&&!e.negate);return t?t.values.map(e=>e.value).join(`|`):null}function B6({entries:e,stickyOffset:t,idPrefix:n=``}){return(0,W.jsx)(`div`,{className:`-mx-4`,children:c2(e,`date`).map(e=>(0,W.jsxs)(`div`,{id:`${n}${e.id}`,className:`flex flex-col`,children:[(0,W.jsx)(jz,{top:t,icon:(0,W.jsx)(zt,{className:`size-3 shrink-0 text-muted-foreground`}),label:e.label,meta:(0,W.jsx)(`span`,{"data-testid":`library-group-count`,className:`font-bold tabular-nums`,children:e.entries.length})}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0 pb-1`,children:e.entries.map(e=>(0,W.jsx)(l4,{entry:e,dateLabel:e.date?GV(e.date):void 0},e.block?`${e.id}#${e.block.blockId}`:e.id))})]},e.id))})}function V6(e,t){if(e===t)return!0;let n=X(e),r=X(t);return!n.error&&!r.error&&dh(n)===dh(r)}function H6({actions:e}){(0,U.useEffect)(()=>{},[]);let t=ZP(`/dashboards`),{draft:n,setDraft:r,submitted:i,submit:a,weeks:o,setWeeks:s}=u6({defaultQuery:t.defaultWql??F6,runOnLanding:!0}),{unit:c}=uS(),{forced:l}=(0,U.useMemo)(()=>dS(i,c),[i,c]),[u,d]=(0,U.useState)(void 0),[f,p]=(0,U.useState)(void 0),[m,h]=(0,U.useState)(void 0),[g,_]=(0,U.useState)(void 0),[v,y]=(0,U.useState)(!1),[b,x]=(0,U.useState)(!1),[S,C]=(0,U.useState)(!1),[w,T]=(0,U.useState)(!0),E=o6(),D=t.typeOptions,O=(0,U.useMemo)(()=>X(n),[n]),k=z6(bm(O)?O.filters:[]),A=bm(O)&&O.window?e6(O.window):null,j=Az(104),M=!O.error&&n.trim().length>0,N=M&&w,P=(0,U.useMemo)(()=>{if(!M)return null;if(bm(O))return n;if(xm(O)&&O.join){let e=O.join;return dh({family:`find`,raw:``,target:e.target,filters:e.filters,window:e.last?{kind:`relative`,size:e.last.size,unit:e.last.unit}:void 0})}return null},[O,n,M]),F=(0,U.useMemo)(()=>{if(!i)return null;let e=X(i);if(bm(e)||e.error)return null;if(e.join){let t=e.join;return dh({family:`find`,raw:``,target:t.target,filters:t.filters,window:t.last?{kind:`relative`,size:t.last.size,unit:t.last.unit}:void 0})}return dh({family:`find`,raw:``,target:`note`,filters:e.filters.filter(e=>R6.has(e.key)&&!e.negate),window:{kind:`relative`,size:o,unit:`w`}})},[i,o]);(0,U.useEffect)(()=>{if(!F){h(void 0);return}let e=!1;return MR(F).then(t=>{e||h(t)}).catch(()=>{e||h(void 0)}),()=>{e=!0}},[F]);let[I,L]=(0,U.useState)(0),[R,ee]=(0,U.useState)(!1),[te,ne]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=!1;if(!i){d(void 0),p(void 0),_(void 0),y(!1);return}y(!0);let t=X(i);if(bm(t))d(void 0),t.target===`effort`?$L.runFind(t).then(t=>{e||(_(t.efforts??[]),p([]))}).catch(()=>{e||(_(void 0),p(void 0))}).finally(()=>{e||y(!1)}):MR(i).then(t=>{e||(p(t),_([]))}).catch(()=>{e||(p(void 0),_(void 0))}).finally(()=>{e||y(!1)});else{p(void 0),_(void 0);let t=Date.now(),n=t-o*7*I6;$L.runQuery(i,{rangeStart:n,rangeEnd:t,preferredUnit:c}).then(t=>{e||d(t)}).catch(()=>{e||d(void 0)}).finally(()=>{e||y(!1)})}return()=>{e=!0}},[i,o,I,c]);let re=vx(u),ie=e=>{let t=$2(n,e);r(t),a(t)},{setL3Items:ae}=lM(),oe=(0,U.useMemo)(()=>f!==void 0&&f.length>0?c2(f,`date`):[],[f]);(0,U.useEffect)(()=>{if(oe.length===0){ae([]);return}let e=oe.map(e=>({id:e.id,label:e.label,level:3,action:{type:`scroll`,sectionId:e.id}}));return ae(e),()=>ae([])},[oe,ae]);let se=UN.find(e=>e.query===i)?.question??`custom query`,ce=(0,U.useMemo)(()=>{let e=X(i);return e.error?i:dh(e)},[i]),le=u!==void 0&&(V6(u.parsed.raw,n)||u.parsed.raw===i&&n===ce),z=!i||!v&&re.kind===`empty`,ue=(0,W.jsxs)(`button`,{type:`button`,"data-testid":`inspect-pipeline`,"aria-expanded":R,onClick:()=>ee(e=>!e),className:`flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:[R?(0,W.jsx)(Cn,{size:12}):(0,W.jsx)(Qt,{size:12}),`Inspect pipeline`]});return(0,W.jsxs)(`div`,{className:`bg-card flex flex-col flex-1`,children:[(0,W.jsx)(X3,{catalog:Q3}),(0,W.jsx)(T2,{surface:d2,open:S,onOpenChange:C}),(0,W.jsx)(wz,{title:`Metric Explorer`,actions:(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(d6,{weeks:o,onWeeks:s,unitForced:l,onOpenQuerySettings:()=>C(!0)}),e]})}),(0,W.jsxs)(`div`,{className:`flex flex-col min-h-0 p-4`,children:[(0,W.jsx)(`div`,{className:`min-w-[280px]`,children:(0,W.jsx)(aw,{query:n,onQueryChange:r,onValidationChange:e=>T(e.valid),onSubmit:e=>a(e),actionLabel:`Run`,preferredChoices:D,showDiagnostics:!1,placeholder:L6,diagnosticsActions:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`save-query`,disabled:!N,onClick:()=>x(!0),title:`Save this query — decide where it lands (dashboard, …)`,className:`flex min-h-12 items-center gap-1.5 rounded-lg border border-primary/40 text-primary px-3 text-[11px] font-semibold hover:bg-primary/10 transition-all shrink-0 disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,W.jsx)(ln,{size:12}),` Save`]})})}),(0,W.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-x-1.5 gap-y-1`,"data-testid":`explorer-meta`,children:[n.trim().length>0&&(0,W.jsx)(`span`,{"data-testid":`draft-validity`,className:`mr-1 inline-flex items-center gap-1 text-[11px]`,children:O.error?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-mono text-red-600`,children:[(0,W.jsx)(vn,{size:11,className:`shrink-0`}),` `,O.error]}):(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-green-600`,children:[(0,W.jsx)(Ft,{size:11,className:`shrink-0`}),` valid`]})}),E.metricKeys.map(e=>(0,W.jsx)(`button`,{type:`button`,disabled:!N||!xm(O),title:M&&!xm(O)?`Metric shortcuts apply to measure queries — pivot the kind through the composer first`:void 0,onClick:()=>ie(e),className:G(`rounded-full border px-2 py-0.5 text-[11px] font-mono transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,n.includes(e)?`border-primary/60 bg-primary/10 text-primary`:`border-border text-muted-foreground hover:text-foreground hover:bg-muted`),children:e},e)),(0,W.jsx)(`span`,{className:`mx-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/50`,children:`filters`}),E.tagKeys.map(e=>(0,W.jsx)(`span`,{className:`rounded-full border border-border/60 px-2 py-0.5 text-[11px] font-mono text-muted-foreground/70`,children:e},e))]}),(0,W.jsx)(`section`,{className:`min-w-0`,children:bm(O)?(0,W.jsx)(`div`,{className:`mt-3`,children:(0,W.jsxs)(`div`,{className:`bg-card border border-border rounded-lg p-4`,children:[(0,W.jsxs)(`div`,{className:`text-[11px] uppercase tracking-wider text-muted-foreground mb-2`,children:[`Find `,O.target,k&&(0,W.jsxs)(`span`,{className:`ml-1`,children:[`in `,k]}),A&&(0,W.jsx)(`span`,{className:`ml-1`,children:A})]}),O.error?(0,W.jsx)(`div`,{className:`text-sm text-destructive font-mono`,children:O.error}):v?(0,W.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Searching…`}):g&&g.length>0?(0,W.jsx)(`div`,{className:`flex flex-col divide-y divide-border/50`,children:g.map(e=>(0,W.jsxs)(`div`,{className:`flex items-center gap-3 py-2.5`,children:[(0,W.jsx)(`span`,{className:`text-sm font-medium text-foreground`,children:e.label}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground font-mono`,children:e.slug}),e.baseAttributes.discipline&&(0,W.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground`,children:e.baseAttributes.discipline})]},e.slug))}):f&&f.length>0?(0,W.jsx)(B6,{entries:f,stickyOffset:j}):(0,W.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`No `,O.target,`s found.`]})]})}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`mt-3`,children:(0,W.jsx)(P6,{layout:`banner`,refreshKey:I,onChanged:()=>L(e=>e+1)})}),O.error&&i&&(0,W.jsx)(`div`,{"data-testid":`explorer-results-stale`,className:`mt-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs font-medium text-amber-700`,children:`Stale — showing the last run's results; the current draft is invalid and not applied.`}),(0,W.jsx)(`div`,{className:`mt-3`,children:(0,W.jsx)(hx,{title:`Query result`,question:se,query:i||`(empty)`,children:(0,W.jsx)(`div`,{className:`h-64`,children:i?v?(0,W.jsx)(yx,{result:void 0}):re.kind===`error`?(0,W.jsx)(`div`,{className:`h-full flex items-center justify-center text-sm text-destructive font-mono px-4 text-center`,children:re.message}):re.kind===`empty`?(0,W.jsxs)(`div`,{className:`h-full flex flex-wrap items-center justify-center gap-6`,children:[(0,W.jsx)(P6,{result:u,refreshKey:I,onChanged:()=>L(e=>e+1)}),ue]}):re.kind===`scalar`?(0,W.jsx)(bx,{result:u,label:`${u.parsed.agg}(${u.parsed.metric})`}):re.kind===`timeseries`?(0,W.jsx)(Dx,{result:u}):(0,W.jsx)(Ox,{result:u}):(0,W.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center gap-3`,children:[(0,W.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Enter a WQL query or choose an example to explore your data.`}),ue]})})})}),i&&(0,W.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[!v&&!z&&ue,F&&m!==void 0&&(0,W.jsxs)(`button`,{type:`button`,"data-testid":`records-toggle`,"aria-expanded":te,onClick:()=>ne(e=>!e),className:`flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,children:[te?(0,W.jsx)(Cn,{size:12}):(0,W.jsx)(Qt,{size:12}),`Records in this calculation`,(0,W.jsx)(`span`,{className:`text-[10px] font-bold text-muted-foreground/60 tabular-nums`,children:m.length})]})]}),R&&(0,W.jsx)(`div`,{className:`mt-3`,"data-testid":`pipeline-anatomy`,children:i?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(t6,{parsed:le?u.parsed:O}),le&&(0,W.jsx)(n6,{result:u})]}):(0,W.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Submit a query to see its anatomy.`})}),te&&F&&m!==void 0&&(0,W.jsxs)(`div`,{className:`mt-3`,children:[(0,W.jsx)(`code`,{className:`block mb-3 rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground`,"data-testid":`records-wql`,children:F}),m.length===0?(0,W.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No records match this calculation.`}):(0,W.jsx)(B6,{entries:m,stickyOffset:j,idPrefix:`records-`})]}),u&&(0,W.jsx)(r6,{matched:u.matched,displayUnit:u.unit})]})})]}),(0,W.jsx)(J3,{open:b,onOpenChange:x,initialQuery:n,subsetQuery:P,rangeStart:Date.now()-o*7*I6,rangeEnd:Date.now(),preferredUnit:c})]})}var U6=2.20462,W6=2.54,G6=`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`;function K6(e){if(!e)return;let t=new Date(e);if(Number.isNaN(t.getTime()))return;let n=new Date,r=n.getFullYear()-t.getFullYear(),i=n.getMonth()-t.getMonth();return(i<0||i===0&&n.getDate()<t.getDate())&&r--,r}function q6(e){let t=(e??``).trim().split(/\s+/).filter(Boolean);return t.length===0?`?`:t.slice(0,2).map(e=>e[0].toUpperCase()).join(``)}function J6({unit:e,other:t,onSwitch:n}){return(0,W.jsx)(`div`,{className:`flex rounded-md border border-input overflow-hidden shrink-0`,role:`group`,children:[e,t].map((e,t)=>(0,W.jsx)(`button`,{type:`button`,"aria-pressed":t===0,onClick:t===1?n:void 0,className:G(`px-2.5 h-9 text-xs font-medium transition-colors`,t===0?`bg-primary/10 text-primary`:`bg-background text-muted-foreground hover:bg-muted`),children:e},e))})}function Y6(){let[e,t]=(0,U.useState)(null),[n,r]=(0,U.useState)({displayName:``,birthDate:``,weight:``,height:``}),i=(0,U.useRef)(null);(0,U.useEffect)(()=>{let e=!0;return wO.current().then(n=>{e&&t(n)}).catch(console.error),()=>{e=!1}},[]),(0,U.useEffect)(()=>{e&&r({displayName:e.displayName?.trim()||`Anonymous`,birthDate:e.birthDate??``,weight:e.weight==null?``:String(e.weight),height:e.height==null?``:String(e.height)})},[e?.id]);let a=(0,U.useCallback)(async e=>{try{t(await wO.update(e))}catch(e){console.error(e)}},[]),o=(0,U.useCallback)(async e=>{if(e)try{await a({picture:await Tb(e)})}catch(e){console.error(e)}},[a]);if(!e)return(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,"data-testid":`profile-loading`,children:`Loading profile…`});let s=K6(e.birthDate),c=e.weightUnit??`kg`,l=e.heightUnit??`cm`;return(0,W.jsxs)(`div`,{className:`space-y-8`,children:[(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)(Me,{className:`size-4 text-primary`}),`Profile Picture`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Click the picture to choose an image — it is center-cropped and stored locally.`})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>i.current?.click(),"aria-label":`Change profile picture`,"data-testid":`profile-avatar`,className:`relative group size-20 rounded-full overflow-hidden border border-border bg-muted shrink-0 cursor-pointer`,children:[e.picture?(0,W.jsx)(`img`,{src:e.picture,alt:``,className:`size-full object-cover`}):(0,W.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center text-lg font-semibold text-muted-foreground`,children:q6(e.displayName)}),(0,W.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/45 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity`,children:(0,W.jsx)(jt,{className:`size-5 text-white`})})]}),(0,W.jsx)(`input`,{ref:i,type:`file`,accept:`image/*`,className:`hidden`,"aria-hidden":`true`,tabIndex:-1,onChange:e=>{o(e.target.files?.[0]),e.target.value=``}})]})]}),(0,W.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Details`}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Used by journal analytics (age from birth date, metric conversions). Changes are saved immediately.`})]}),(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`label`,{htmlFor:`profile-display-name`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Display Name`}),(0,W.jsx)(`input`,{id:`profile-display-name`,"data-testid":`profile-display-name`,className:G6,placeholder:`Anonymous`,value:n.displayName,onChange:e=>{r(t=>({...t,displayName:e.target.value})),a({displayName:e.target.value})}})]}),(0,W.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`label`,{htmlFor:`profile-birth-date`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:[`Birth Date`,s===void 0?``:` · Age ${s}`]}),(0,W.jsx)(`input`,{id:`profile-birth-date`,"data-testid":`profile-birth-date`,type:`date`,className:G6,value:n.birthDate,onChange:e=>{r(t=>({...t,birthDate:e.target.value})),a({birthDate:e.target.value||void 0})}})]}),(0,W.jsx)(`div`,{})]}),(0,W.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`label`,{htmlFor:`profile-weight`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Weight`}),(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(`input`,{id:`profile-weight`,"data-testid":`profile-weight`,type:`number`,inputMode:`decimal`,min:`0`,className:G6,placeholder:c===`kg`?`e.g. 75`:`e.g. 165`,value:n.weight,onChange:e=>{let t=e.target.value;r(e=>({...e,weight:t})),t===``?a({weight:void 0}):Number.isFinite(Number(t))&&a({weight:Number(t)})}}),(0,W.jsx)(J6,{unit:c,other:c===`kg`?`lb`:`kg`,onSwitch:()=>void a({weightUnit:c===`kg`?`lb`:`kg`,weight:e.weight==null?void 0:c===`kg`?e.weight*U6:e.weight/U6})})]})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`label`,{htmlFor:`profile-height`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Height`}),(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(`input`,{id:`profile-height`,"data-testid":`profile-height`,type:`number`,inputMode:`decimal`,min:`0`,className:G6,placeholder:l===`cm`?`e.g. 180`:`e.g. 71`,value:n.height,onChange:e=>{let t=e.target.value;r(e=>({...e,height:t})),t===``?a({height:void 0}):Number.isFinite(Number(t))&&a({height:Number(t)})}}),(0,W.jsx)(J6,{unit:l,other:l===`cm`?`in`:`cm`,onSwitch:()=>void a({heightUnit:l===`cm`?`in`:`cm`,height:e.height==null?void 0:l===`cm`?e.height/W6:e.height*W6})})]})]})]})]})]})]})}function X6(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:`The pairing file is not valid JSON.`}}if(!t||typeof t!=`object`||Array.isArray(t))return{ok:!1,error:`The pairing file has an unexpected shape.`};let n=t;if(n.wodWikiPairing!==1)return{ok:!1,error:`Not a wod.wiki database pairing file (missing "wodWikiPairing": 1).`};if(n.kind!==`turso`)return{ok:!1,error:`Unsupported pairing kind "${String(n.kind)}" — only Turso databases can be paired here.`};let{url:r,authToken:i}=n;return typeof r!=`string`||!r.trim()||typeof i!=`string`||!i.trim()?{ok:!1,error:`The pairing file is missing the database URL or auth token.`}:{ok:!0,pairing:{url:r,authToken:i,database:typeof n.database==`string`&&n.database.trim()?n.database:void 0,schemaVersion:typeof n.schemaVersion==`number`&&Number.isSafeInteger(n.schemaVersion)?n.schemaVersion:void 0,createdAt:typeof n.createdAt==`string`?n.createdAt:void 0}}}async function Z6(e){let t=dO(e.url,e.authToken);if(t)return{state:`unreachable`,reason:t};let n;try{n=Ub(g({url:e.url.trim(),authToken:e.authToken}))}catch(t){return{state:`unreachable`,reason:fO(t,e.authToken).message}}try{let e=await ky(n);return e===`empty`?{state:`empty`,reason:`The database is empty — nothing to restore. Use Enable Sync to back up to it instead.`}:e.kind===`unknown`?{state:`unknown`,reason:`The database contains foreign tables — refusing to touch it.`}:e.kind===`legacy`||e.schemaVersion<32?{state:`older`,schemaVersion:e.schemaVersion,reason:`The database uses schema v${e.schemaVersion}, this app needs v32. Migrate it with the CLI to a fresh target, then pair that target.`}:e.schemaVersion>32?{state:`newer`,schemaVersion:e.schemaVersion,reason:`The database uses schema v${e.schemaVersion}, newer than this app supports (v32). Update the app first.`}:{state:`current`,schemaVersion:e.schemaVersion,rev:e.rev}}catch(t){return{state:`unreachable`,reason:fO(t,e.authToken).message}}finally{await n.close().catch(()=>void 0)}}var Q6=[`wodwiki.seedSources`,`wodwiki.seedSources.hidden`,`wodwiki.seedSubscriptions`,`wodwiki.seedAutoSync`];function $6(e){if(typeof e!=`string`)return!1;try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&!t.username&&!t.password&&!t.search&&!t.hash}catch{return!1}}function e8(){let e=[];for(let t of Q6){let n=null;try{n=localStorage.getItem(t)}catch{n=null}if(n!==null)try{let r=JSON.parse(n);if(t===`wodwiki.seedSources`){let n=(Array.isArray(r)?r:[]).flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e;if(typeof t.id!=`string`||typeof t.label!=`string`||!$6(t.url))return[];let n={id:t.id,label:t.label,url:t.url};return typeof t.repositoryUrl==`string`&&$6(t.repositoryUrl)&&(n.repositoryUrl=t.repositoryUrl),[n]});e.push({key:t,value:n})}else if(t===`wodwiki.seedSources.hidden`)e.push({key:t,value:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]});else{let n=r&&typeof r==`object`&&!Array.isArray(r)?Object.entries(r).filter(([,e])=>typeof e==`boolean`):[];e.push({key:t,value:Object.fromEntries(n)})}}catch{}}return e}function t8(e){let t=(e,t)=>JSON.parse(py(t,e===`attachments`?`data`:void 0));return JSON.stringify({format:`wod-wiki-safe-export`,version:1,...e,rows:e.rows.map(({store:e,rows:n})=>({store:e,rows:n.map(n=>t(e,n))})),pendingGroups:e.pendingGroups.map(e=>({...e,ops:e.ops.map(e=>e&&typeof e==`object`&&`op`in e&&e.op===`put`&&`store`in e&&typeof e.store==`string`&&`value`in e?{...e,value:t(e.store,e.value)}:e)}))},null,2)}async function n8(){let[e,t]=await Promise.all([IO(),LO()]),n=t8({pendingGroups:e.map(e=>({id:e.id,at:e.at,ops:e.ops})),rows:t,contentSources:e8(),exportedAt:new Date().toISOString()}),r=`wodwiki-safe-export-${new Date().toISOString().slice(0,10)}.json`,i=URL.createObjectURL(new Blob([n],{type:`application/json`})),a=document.createElement(`a`);return a.href=i,a.download=r,a.click(),setTimeout(()=>URL.revokeObjectURL(i),1e3),r}async function r8(){let e=await FO();try{return await n8()}finally{e&&PO()}}function i8(e){let t=globalThis.indexedDB;if(!t)return Promise.resolve();let{promise:n,resolve:r}=Promise.withResolvers(),i=t.deleteDatabase(e);return i.onsuccess=()=>r(),i.onerror=()=>r(),i.onblocked=()=>r(),n}async function a8(e,t){let n=mO();if(n.state===`turso`&&cO(n.url,e.url))throw Error(`This database is already the active sync target. Restore needs the URL of a different database.`);t?.(`Checking the target database…`);let r=await Z6(e);if(r.state!==`current`)throw Error(r.reason);t?.(`Pausing background sync…`);let i=await FO(),a=`wodwiki-restore-${crypto.randomUUID().slice(0,8)}`,o=new nb({dbName:a}),s=new aO(o,{url:e.url.trim(),authToken:e.authToken});try{t?.(`Exporting your current data and unsent edits…`),await n8(),t?.(`Replaying the remote database into an isolated local copy…`),await s.restoreNow(),await s.stop(),await o.close(),t?.(`Saving the restored database as your data…`),yO(a)}catch(t){throw await s.stop().catch(()=>void 0),await o.close().catch(()=>void 0),await i8(a),i&&PO(),fO(t,e.authToken)}return{localDbName:a}}function o8({idPrefix:e,onPair:t}){let[n,r]=(0,U.useState)(null),i=async e=>{if(!e?.length)return;let n=X6(await e[0].text());n.ok?(r(null),t(n.pairing)):r(n.error)};return(0,W.jsxs)(`div`,{className:`space-y-1`,children:[(0,W.jsxs)(`label`,{htmlFor:`${e}-pairing`,className:`block text-xs font-medium text-muted-foreground`,children:[`Pair from provisioning file (from `,(0,W.jsx)(`code`,{className:`font-mono`,children:`wod db`}),`)`]}),(0,W.jsx)(`input`,{id:`${e}-pairing`,type:`file`,accept:`application/json,.json`,onChange:e=>void i(e.target.files),"data-testid":`${e}-pairing-input`,className:`block w-full text-xs text-muted-foreground file:mr-2 file:cursor-pointer file:rounded-md file:border-0 file:bg-muted file:px-2 file:py-1 file:text-xs file:font-medium`}),n&&(0,W.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`${e}-pairing-error`,children:n})]})}function s8({saved:e,onConnected:t}){let[n,r]=(0,U.useState)(e?.url??``),[i,a]=(0,U.useState)(``),[o,s]=(0,U.useState)(null),[c,l]=(0,U.useState)(null),[u,d]=(0,U.useState)(null),[f,p]=(0,U.useState)(null),h=t??(typeof window<`u`?()=>window.location.reload():void 0),g=()=>{let t=n.trim();return t?i.trim()?i.trim():e&&t===e.url&&e.authToken?e.authToken:(d(e?.authToken?`The URL differs from the saved connection — enter the auth token for this database.`:`An auth token is required.`),null):(d(`A database URL is required.`),null)};return(0,W.jsxs)(`div`,{className:`space-y-3`,"data-testid":`turso-connect-form`,children:[(0,W.jsx)(o8,{idPrefix:`turso`,onPair:e=>{r(e.url),a(e.authToken),d(null),p(null),s([e.database,e.schemaVersion===void 0?void 0:`file schema v${e.schemaVersion}`].filter(Boolean).join(` · `)||null)}}),o&&(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`turso-pairing-label`,children:[`Provisioned database: `,(0,W.jsx)(`span`,{className:`font-mono`,children:o}),` — verify with Test Connection, then Enable Sync. The live database is checked again before anything is saved.`]}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsxs)(`div`,{className:`sm:col-span-2`,children:[(0,W.jsx)(`label`,{htmlFor:`turso-url`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Database URL`}),(0,W.jsx)(`input`,{id:`turso-url`,type:`text`,autoComplete:`off`,spellCheck:!1,placeholder:`libsql://your-db.turso.io`,className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,value:n,onChange:e=>r(e.target.value),disabled:c!==null})]}),(0,W.jsxs)(`div`,{className:`sm:col-span-2`,children:[(0,W.jsx)(`label`,{htmlFor:`turso-token`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Auth token`}),(0,W.jsx)(`input`,{id:`turso-token`,type:`password`,autoComplete:`off`,placeholder:e?`•••••••• (saved token — reused only for the same URL)`:``,className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,value:i,onChange:e=>a(e.target.value),disabled:c!==null})]})]}),(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-xs text-muted-foreground leading-relaxed`,"data-testid":`turso-token-warning`,children:[(0,W.jsx)(m,{className:`size-3.5 mt-0.5 shrink-0`}),(0,W.jsx)(`span`,{children:`The token is saved in this browser's localStorage, so any code on this site can read it. Use a token scoped to this one database, and never a token with write access elsewhere.`})]}),u&&(0,W.jsxs)(`p`,{role:`alert`,className:`flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`turso-connect-error`,children:[(0,W.jsx)(vn,{className:`size-3.5 mt-0.5 shrink-0`}),(0,W.jsx)(`span`,{children:u})]}),f&&(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-xs text-emerald-600`,"data-testid":`turso-test-ok`,children:[(0,W.jsx)(Ft,{className:`size-3.5 mt-0.5 shrink-0`}),(0,W.jsx)(`span`,{children:f})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:async()=>{let e=g();if(e){l(`test`),d(null),p(null);try{await vO({url:n.trim(),authToken:e}),p(`Connection verified — the database is reachable and writable. Nothing was saved.`)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(null)}}},disabled:c!==null,"data-testid":`turso-test-button`,className:`gap-2`,children:[c===`test`?(0,W.jsx)(Rt,{className:`size-3.5 animate-spin`}):(0,W.jsx)(Tt,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:c===`test`?`Testing…`:`Test Connection`})]}),(0,W.jsxs)(K,{size:`sm`,onClick:async()=>{let e=g();if(e){l(`connect`),d(null),p(null);try{await _O({url:n.trim(),authToken:e}),Q({title:`Turso Sync enabled`,description:`Reloading… Your local data will sync in the background.`}),h?.()}catch(e){d(e instanceof Error?e.message:String(e)),l(null)}}},disabled:c!==null,"data-testid":`turso-connect-button`,className:`gap-2`,children:[c===`connect`?(0,W.jsx)(Rt,{className:`size-3.5 animate-spin`}):(0,W.jsx)(Vn,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:c===`connect`?`Enabling…`:e?`Update Connection`:`Enable Sync`})]}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sync merges and backs up your local data in the background. Your local copy stays the one you edit.`})]})]})}function c8({status:e}){let t={current:{label:`Compatible`,className:`text-emerald-600`},older:{label:`Older schema`,className:`text-amber-600`},newer:{label:`Newer schema`,className:`text-destructive`},empty:{label:`Empty database`,className:`text-amber-600`},unknown:{label:`Foreign database`,className:`text-destructive`},unreachable:{label:`Unreachable`,className:`text-destructive`}}[e.state],n=e.state===`current`?`Canonical schema v${e.schemaVersion}, up to date at rev ${e.rev}.`:e.reason;return(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-xs leading-relaxed`,"data-testid":`restore-status-${e.state}`,children:[e.state===`current`?(0,W.jsx)(Ft,{className:`size-3.5 mt-0.5 shrink-0 text-emerald-600`}):(0,W.jsx)(vn,{className:G(`size-3.5 mt-0.5 shrink-0`,t.className)}),(0,W.jsxs)(`span`,{className:t.className,children:[(0,W.jsxs)(`span`,{className:`font-semibold`,children:[t.label,`.`]}),` `,(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:n})]})]})}function l8(){let[e,t]=(0,U.useState)(``),[n,r]=(0,U.useState)(``),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(null),[c,l]=(0,U.useState)(null),[u,d]=(0,U.useState)(!1),[f,p]=(0,U.useState)(null),[m,h]=(0,U.useState)(null),[g,_]=(0,U.useState)(null);(0,U.useEffect)(()=>{let e=!0;return IO().then(t=>{e&&_(t.length)}).catch(()=>void 0),()=>{e=!1}},[]);let v=e.trim()!==``&&n.trim()!==``,y=async()=>{h(`probe`),p(null),a(null);try{a(await Z6({url:e.trim(),authToken:n}))}finally{h(null)}},b=async()=>{h(`export`),p(null);try{let e=await r8();l(`Exported ${e} — unsent edits, a full local snapshot, and content-source settings. No tokens included.`);let t=await IO();_(t.length)}catch(e){p(e instanceof Error?e.message:String(e))}finally{h(null)}},x=async()=>{h(`restore`),d(!1),p(null);try{await a8({url:e.trim(),authToken:n},s),Q({title:`Restore complete`,description:`The restored database is now your data. Reloading…`}),setTimeout(()=>window.location.reload(),600)}catch(e){p(e instanceof Error?e.message:String(e)),s(null),h(null)}};return(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 sm:p-5 space-y-4`,"data-testid":`restore-section`,children:[(0,W.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,W.jsx)(`div`,{className:`p-2 rounded-lg bg-muted text-foreground shrink-0`,children:(0,W.jsx)(ar,{className:`size-5`})}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Restore from a backup database`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:[`Point this at a different, already-provisioned database (for example one retained by`,` `,(0,W.jsx)(`code`,{className:`font-mono`,children:`wod db backup`}),`) to replace this browser's data with its contents. The remote database is never modified, and your current data is kept in a separate local database that stays on disk.`]})]})]}),(0,W.jsx)(o8,{idPrefix:`restore`,onPair:e=>{t(e.url),r(e.authToken),a(null),p(null),l(null)}}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsxs)(`div`,{className:`sm:col-span-2`,children:[(0,W.jsx)(`label`,{htmlFor:`restore-url`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Backup database URL`}),(0,W.jsx)(`input`,{id:`restore-url`,type:`text`,autoComplete:`off`,spellCheck:!1,placeholder:`libsql://your-restore-target.turso.io`,className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,value:e,onChange:e=>{t(e.target.value),a(null)},disabled:m!==null})]}),(0,W.jsxs)(`div`,{className:`sm:col-span-2`,children:[(0,W.jsx)(`label`,{htmlFor:`restore-token`,className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Auth token`}),(0,W.jsx)(`input`,{id:`restore-token`,type:`password`,autoComplete:`off`,placeholder:`Database-scoped token for the backup database`,className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,value:n,onChange:e=>{r(e.target.value),a(null)},disabled:m!==null})]})]}),f&&(0,W.jsxs)(`p`,{role:`alert`,className:`flex items-start gap-1.5 text-xs text-destructive`,"data-testid":`restore-error`,children:[(0,W.jsx)(vn,{className:`size-3.5 mt-0.5 shrink-0`}),(0,W.jsx)(`span`,{children:f})]}),i&&(0,W.jsx)(c8,{status:i}),o&&(0,W.jsx)(`p`,{"aria-live":`polite`,className:`text-xs text-muted-foreground`,"data-testid":`restore-phase`,children:o}),c&&(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`restore-export-note`,children:c}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>void y(),disabled:!v||m!==null,"data-testid":`restore-check-button`,className:`gap-2`,children:[m===`probe`?(0,W.jsx)(Rt,{className:`size-3.5 animate-spin`}):(0,W.jsx)(Tt,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:m===`probe`?`Checking…`:`Check database`})]}),(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>void b(),disabled:m!==null,"data-testid":`restore-export-button`,className:`gap-2`,children:[m===`export`?(0,W.jsx)(Rt,{className:`size-3.5 animate-spin`}):(0,W.jsx)(A,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:g===null||g===0?`Export data (safe file)`:`Export data — ${g} unsent ${g===1?`edit`:`edits`}`})]}),u?(0,W.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground max-w-72`,children:`Your current data is exported and kept locally. The restored copy opens with sync disabled so the archive stays unchanged.`}),(0,W.jsxs)(K,{variant:`destructive`,size:`sm`,autoFocus:!0,onClick:()=>void x(),disabled:m!==null,"data-testid":`restore-confirm-button`,children:[m===`restore`?(0,W.jsx)(Rt,{className:`size-3.5 animate-spin`}):(0,W.jsx)(Vn,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:m===`restore`?`Restoring…`:`Confirm restore`})]}),(0,W.jsx)(K,{variant:`ghost`,size:`sm`,onClick:()=>d(!1),disabled:m!==null,"data-testid":`restore-cancel-button`,children:`Cancel`})]}):(0,W.jsxs)(K,{variant:`destructive`,size:`sm`,onClick:()=>{d(!0),p(null)},disabled:!v||m!==null,"data-testid":`restore-button`,className:`gap-2`,children:[(0,W.jsx)(ar,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Restore this database…`})]})]})]})}function u8(){let[e]=(0,U.useState)(mO),t=e?.state===`turso`,n=CO===`api`;return(0,W.jsx)(`div`,{className:`space-y-8`,children:(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Storage`}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Notes, results, workouts, and queries stay in this browser. Optional Turso Sync backs up your data and syncs other browsers in the background.`})]}),n?(0,W.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,"data-testid":`storage-option-api`,children:`This deployment stores data on its server; storage is managed by the deployment.`}):(0,W.jsxs)(W.Fragment,{children:[e?.state===`invalid`&&(0,W.jsxs)(`div`,{role:`alert`,className:`rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive flex items-start gap-2`,"data-testid":`data-settings-invalid-banner`,children:[(0,W.jsx)(vn,{className:`size-4 mt-0.5 shrink-0`}),(0,W.jsxs)(`div`,{className:`space-y-1`,children:[(0,W.jsx)(`div`,{className:`font-semibold`,children:`Turso Sync settings are invalid; sync is off`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.error,` Fix the connection below or turn off Turso Sync to keep working from your local copy. Neither copy was deleted.`]}),(0,W.jsx)(K,{variant:`outline`,size:`sm`,onClick:()=>{bO(),window.location.reload()},"data-testid":`data-settings-invalid-disable`,className:`mt-1`,children:`Turn off Turso Sync`})]})]}),(0,W.jsxs)(`div`,{"data-testid":`storage-option-browser`,className:`rounded-xl border border-primary ring-2 ring-primary/20 bg-primary/5 p-4 sm:p-5 space-y-4 text-left`,children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,W.jsx)(`div`,{className:`p-2 rounded-lg bg-primary text-primary-foreground shrink-0`,children:(0,W.jsx)(se,{className:`size-5`})}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:`This Browser`}),(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:`Private local storage (IndexedDB). Everything is stored in this browser and reads and writes are local — Turso Sync, when enabled, backs it up to your database in the background.`})]})]}),(0,W.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-primary text-primary-foreground shrink-0`,children:`Always on`})]}),(0,W.jsx)(`div`,{"aria-hidden":`true`,className:`border-t border-border`}),(0,W.jsxs)(`div`,{"data-testid":`storage-option-turso`,className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Turso Sync`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5 leading-relaxed font-mono break-all`,children:e?.state===`turso`?`Backing up to ${e.url} in the background.`:`Off — fill out the form below to back up your local data to your own Turso database in the background.`})]}),(0,W.jsx)(`span`,{className:G(`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded shrink-0`,t?`bg-primary text-primary-foreground`:`bg-muted text-muted-foreground`),children:t?`Sync on`:`Sync off`})]}),t&&(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 rounded-md border border-border bg-muted/30 p-3`,children:[(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>{t&&(bO(),window.location.reload())},"data-testid":`turso-sync-disable`,className:`gap-2`,children:[(0,W.jsx)(rt,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Turn off Turso Sync`})]}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Turning off sync keeps everything in this browser. Nothing is deleted from your Turso database.`})]}),(0,W.jsx)(s8,{saved:e?.state===`turso`?{url:e.url,authToken:e.authToken}:void 0})]})]}),(0,W.jsx)(l8,{}),(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground`,"data-testid":`storage-option-self-hosted`,children:[(0,W.jsx)(Bn,{className:`mb-2 size-5`,"aria-hidden":`true`}),(0,W.jsx)(`p`,{className:`font-medium text-foreground`,children:`API server mode`}),(0,W.jsx)(`p`,{className:`mt-1 text-xs`,children:`Run the API deployment with your local or cloud-hosted database. This browser build uses IndexedDB; API deployments run storage and queries on their server.`})]})]})]})})}var d8=`sound`,f8=`wodwiki.soundProfiles.v1`,p8=`profiles`,m8=new _b(f8,ik?ck:void 0);function h8(e){return`${NA}${e}`}function g8(e){return[{kind:`metric`,type:`sound`,value:e}]}function _8(e=m8){let t=e.get(p8);if(!Array.isArray(t))return[];let n=[],r=new Set;for(let e of t){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.id!=`string`||t.id.length===0||r.has(t.id))continue;r.add(t.id);let i=[];if(Array.isArray(t.rules))for(let e of t.rules){if(!e||typeof e!=`object`)continue;let t=e;typeof t.trigger==`string`&&typeof t.sound==`string`&&i.push({trigger:t.trigger,sound:t.sound})}n.push({id:t.id,name:typeof t.name==`string`&&t.name.length>0?t.name:t.id,rules:i})}return n}async function v8(e,t=m8){let n=e.map(e=>({id:e.id,name:e.name,rules:e.rules.map(e=>({trigger:e.trigger,sound:e.sound}))})),r=JSON.stringify(n);if(ik){try{await uk(t.qualify(p8),r)}catch(e){return console.error(`[soundProfiles] server write failed:`,e),!1}return T8(),!0}return t.set(p8,n),t.getRaw(p8)===r&&(T8(),!0)}var y8=Promise.resolve();async function b8(e,t=m8){let n=y8.then(async()=>v8(e(_8(t)),t));return y8=n.catch(()=>!1),n}async function x8(e,t){let n=h8(e),r=(await t.getAllTags()).find(e=>e.label===n);if(r){let n=g8(e),i=r.contributions?.[0];if(r.contributions?.length===1&&i?.kind===`metric`&&i.type===n[0].type&&i.value===n[0].value)return;await t.putTag({...r,contributions:n,type:d8});return}await t.putTag({id:`sound-profile-${e}`,label:n,type:d8,contributions:g8(e),createdAt:Date.now()})}async function S8(e,t){let n=h8(e),r=(await t.getAllTags()).find(e=>e.label===n);r&&await t.deleteTag(r.id)}var C8=new Set,w8=0;function T8(){w8+=1;for(let e of C8)e()}function E8(e){return C8.add(e),()=>{C8.delete(e)}}function D8(){return w8}function O8(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}var k8=`:00, -:03, :05:00`;function A8(){(0,U.useSyncExternalStore)(E8,D8);let e=_8(),[t,n]=(0,U.useState)(``),[r,i]=(0,U.useState)(null),[a,o]=(0,U.useState)(null),[s,c]=(0,U.useState)(null),[l,u]=(0,U.useState)(``),d=async e=>{i(null);let t=await b8(e);return t||i(`Could not save — storage rejected the write; your change was not kept.`),t},f=async r=>{r.preventDefault();let a=t.trim();if(!a){i(`Profile name is required`);return}let o=O8(a);if(!o){i(`Profile name needs at least one letter or number`);return}if(e.some(e=>e.id===o)){i(`A profile with id "${o}" already exists`);return}await d(e=>[...e,{id:o,name:a,rules:[]}])&&(n(``),await x8(o,Z),await UA())},p=async e=>{let t=l.trim();c(null),!(!t||t===e.name)&&await d(n=>n.map(n=>n.id===e.id?{...n,name:t}:n))},m=async e=>{o(null),await d(t=>t.filter(t=>t.id!==e.id)),await S8(e.id,Z),await UA()},h=(e,t)=>d(n=>n.map(n=>n.id===e.id?{...n,rules:[...n.rules,t]}:n)),g=(e,t,n)=>d(r=>r.map(r=>r.id===e.id?{...r,rules:r.rules.map((e,r)=>r===t?n:e)}:r)),_=(e,t)=>d(n=>n.map(n=>n.id===e.id?{...n,rules:n.rules.filter((e,n)=>n!==t)}:n));return(0,W.jsx)(`div`,{className:`space-y-8`,children:(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Sound Profiles`}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`A profile is a named set of sound rules. Each rule fires a sound at a trigger point relative to a block's own duration: `,(0,W.jsx)(`code`,{className:`font-mono`,children:`:00`}),` starts it,`,` `,(0,W.jsx)(`code`,{className:`font-mono`,children:`-:00`}),` ends it, `,(0,W.jsx)(`code`,{className:`font-mono`,children:`-:03`}),` `,`is three seconds before the end, `,(0,W.jsx)(`code`,{className:`font-mono`,children:`:05:00`}),` is five minutes elapsed. Tag a note`,` `,(0,W.jsx)(`code`,{className:`font-mono`,children:h8(`classic`)}),` to apply that profile to the whole note;`,` `,(0,W.jsxs)(`code`,{className:`font-mono`,children:[`sound: `,`#sound-classic`]}),` on a line applies it to that block only.`]})]}),(0,W.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,W.jsxs)(`form`,{onSubmit:f,className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex-1 min-w-[200px]`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Profile Name`}),(0,W.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`,placeholder:`New profile (e.g. Classic beeps)`,value:t,onChange:e=>n(e.target.value)})]}),(0,W.jsxs)(K,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,W.jsx)(En,{className:`size-3.5 mr-1`}),` Add Profile`]})]}),r&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,children:r}),e.length===0?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No sound profiles created yet.`}):(0,W.jsx)(`div`,{className:`space-y-3`,children:e.map(e=>(0,W.jsxs)(`div`,{className:`p-3 rounded-lg border border-border/70 bg-background/50 space-y-3`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s===e.id?(0,W.jsx)(`input`,{autoFocus:!0,"aria-label":`Rename profile ${e.name}`,className:`h-7 max-w-[220px] rounded border border-primary bg-background px-2 font-mono text-xs outline-none`,value:l,onChange:e=>u(e.target.value),onKeyDown:t=>{t.key===`Enter`?p(e):t.key===`Escape`&&c(null)},onBlur:()=>void p(e)}):(0,W.jsx)(`button`,{type:`button`,className:`font-semibold text-sm text-foreground hover:underline text-left`,title:`Click to rename`,onClick:()=>{c(e.id),u(e.name)},children:e.name}),(0,W.jsxs)(`span`,{className:`font-mono text-[11px] text-muted-foreground`,children:[`(`,e.id,`)`]}),(0,W.jsx)(`button`,{type:`button`,title:`Click to copy`,"aria-label":`Copy tag ${h8(e.id)}`,onClick:()=>{navigator.clipboard?.writeText(h8(e.id))},className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-foreground hover:bg-accent`,children:h8(e.id)}),(0,W.jsx)(`div`,{className:`ml-auto flex items-center gap-2`,children:a===e.id?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`text-xs text-destructive`,children:`Delete this profile?`}),(0,W.jsx)(K,{variant:`destructive`,size:`sm`,className:`h-7`,onClick:()=>void m(e),children:`Confirm`}),(0,W.jsx)(K,{variant:`outline`,size:`sm`,className:`h-7`,onClick:()=>o(null),children:`Cancel`})]}):(0,W.jsx)(`button`,{type:`button`,"aria-label":`Delete profile ${e.name}`,className:`p-1 rounded text-muted-foreground hover:text-destructive transition`,onClick:()=>o(e.id),children:(0,W.jsx)(Ue,{className:`size-3.5`})})})]}),(0,W.jsx)(j8,{profile:e,onAdd:t=>void h(e,t),onUpdate:(t,n)=>void g(e,t,n),onRemove:t=>void _(e,t)})]},e.id))})]})]})})}function j8({profile:e,onAdd:t,onUpdate:n,onRemove:r}){return(0,W.jsxs)(`div`,{className:`space-y-2`,children:[e.rules.length===0?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No rules yet — this profile is silent.`}):(0,W.jsx)(`div`,{className:`space-y-1`,children:e.rules.map((e,t)=>(0,W.jsx)(N8,{index:t,rule:e,onCommit:n,onRemove:r},`${t}:${e.trigger}:${e.sound}`))}),(0,W.jsx)(P8,{onAdd:t})]})}function M8({value:e,onChange:t,label:n}){return(0,W.jsx)(`select`,{"aria-label":n,className:`h-7 rounded border border-input bg-background px-2 text-xs outline-none cursor-pointer focus:border-primary`,value:e,onChange:e=>t(e.target.value),children:QO.map(e=>(0,W.jsx)(`option`,{value:e,children:e},e))})}function N8({index:e,rule:t,onCommit:n,onRemove:r}){let[i,a]=(0,U.useState)(t.trigger),[o,s]=(0,U.useState)(null),c=()=>{let r=i.trim();if(r===t.trigger){s(null);return}if(!ku(r)){s(`"${r}" is not a trigger — use ${k8} …`);return}s(null),n(e,{trigger:r,sound:t.sound})};return(0,W.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsx)(`input`,{"aria-label":`Trigger for rule ${e+1}`,className:`h-7 w-24 rounded border border-input bg-background px-2 font-mono text-xs outline-none focus:border-primary`,placeholder:k8,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&c()},onBlur:c}),(0,W.jsx)(M8,{label:`Sound for rule ${e+1}`,value:t.sound,onChange:r=>n(e,{trigger:t.trigger,sound:r})}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Delete rule ${e+1}`,className:`p-1 rounded text-muted-foreground hover:text-destructive transition`,onClick:()=>r(e),children:(0,W.jsx)(Ue,{className:`size-3.5`})})]}),o&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,children:o})]})}function P8({onAdd:e}){let[t,n]=(0,U.useState)(``),[r,i]=(0,U.useState)(QO[0]),[a,o]=(0,U.useState)(null);return(0,W.jsxs)(`form`,{onSubmit:a=>{a.preventDefault();let s=t.trim();if(!ku(s)){o(`"${s}" is not a trigger — use ${k8} …`);return}o(null),e({trigger:s,sound:r}),n(``),i(QO[0])},className:`flex items-center gap-2`,children:[(0,W.jsx)(`input`,{"aria-label":`New rule trigger`,className:`h-7 w-24 rounded border border-input bg-background px-2 font-mono text-xs outline-none focus:border-primary`,placeholder:k8,value:t,onChange:e=>n(e.target.value)}),(0,W.jsx)(M8,{label:`New rule sound`,value:r,onChange:i}),(0,W.jsxs)(K,{type:`submit`,size:`sm`,variant:`outline`,className:`h-7`,children:[(0,W.jsx)(En,{className:`size-3 mr-1`}),` Add Rule`]}),a&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,children:a})]})}var F8=[{id:`appearance`,content:(0,W.jsx)(R8,{})},{id:`profile`,content:(0,W.jsx)(Y6,{})},{id:`storage`,content:(0,W.jsx)(u8,{})},{id:`sync`,content:(0,W.jsx)(V2,{})},{id:`tags`,content:(0,W.jsx)(B8,{})},{id:`sound-profiles`,content:(0,W.jsx)(A8,{})},{id:`routes`,content:(0,W.jsx)(L8,{})},{id:`system`,content:(0,W.jsx)(z8,{})}];function I8(){let e=Xt(),t=e.pathname.endsWith(`/system`)?`system`:e.pathname.endsWith(`/profile`)?`profile`:e.pathname.endsWith(`/storage`)?`storage`:e.pathname.endsWith(`/sync`)?`sync`:e.pathname.endsWith(`/tags`)?`tags`:e.pathname.endsWith(`/sound-profiles`)?`sound-profiles`:e.pathname.endsWith(`/routes`)?`routes`:`appearance`;return(0,W.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0 bg-background`,children:[(0,W.jsx)(wz,{title:`Settings`,subtitle:`Manage profile, appearance, audio, and system preferences`}),(0,W.jsx)(`main`,{className:`flex-1 overflow-y-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8`,children:(0,W.jsx)(`div`,{className:`max-w-4xl mx-auto space-y-8`,children:F8.find(e=>e.id===t)?.content})})]})}function L8(){let[e,t]=(0,U.useState)([]);return(0,U.useEffect)(()=>{let e=!0;return DO.readonly(`page`).getAll().then(n=>{e&&t(n)}).catch(console.error),()=>{e=!1}},[]),(0,W.jsxs)(`section`,{className:`space-y-6`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`text-lg font-medium`,children:`Route Review`}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:"All page routes (`/p/:slug`, `/c/:slug`, `/journal/:date`) currently registered in storage."})]}),(0,W.jsx)(`div`,{className:`border rounded-md`,children:(0,W.jsxs)(`table`,{className:`w-full text-sm text-left`,children:[(0,W.jsx)(`thead`,{className:`bg-muted/50 border-b`,children:(0,W.jsxs)(`tr`,{children:[(0,W.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Route`}),(0,W.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Title`}),(0,W.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`ID`})]})}),(0,W.jsx)(`tbody`,{className:`divide-y`,children:e.length===0?(0,W.jsx)(`tr`,{children:(0,W.jsx)(`td`,{colSpan:3,className:`px-4 py-4 text-center text-muted-foreground`,children:`No pages found.`})}):e.map(e=>(0,W.jsxs)(`tr`,{children:[(0,W.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs`,children:e.slug?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold bg-primary/10 text-primary`,children:`SLUG`}),e.slug]}):e.date?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold bg-secondary/10 text-secondary`,children:`DATE`}),e.date]}):`—`}),(0,W.jsx)(`td`,{className:`px-4 py-2`,children:e.title??`—`}),(0,W.jsx)(`td`,{className:`px-4 py-2 font-mono text-[10px] text-muted-foreground`,children:e.id})]},e.id))})]})})]})}function R8(){let{theme:e,setTheme:t}=ji(),[n,r]=CB(),i={right:fr,left:bt};return(0,W.jsxs)(`div`,{className:`space-y-8`,children:[(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Interface Theme`}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select your preferred color theme. Changes are saved and applied immediately.`})]}),(0,W.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4`,children:[{id:`system`,label:`System`,description:`Follows your operating system color scheme preferences`,icon:tn,isDefault:!0},{id:`light`,label:`Light`,description:`Crisp light background with dark text for high daytime readability`,icon:ae},{id:`dark`,label:`Dark`,description:`Relaxed dark background for lower eye strain in low-light settings`,icon:Pe}].map(n=>{let r=e===n.id,i=n.icon;return(0,W.jsxs)(`button`,{type:`button`,"data-testid":`theme-option-${n.id}`,onClick:()=>t(n.id),className:G(`relative flex flex-col items-start p-4 rounded-xl border text-left transition-all`,r?`border-primary ring-2 ring-primary/20 bg-primary/5 text-foreground shadow-xs`:`border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted/40`),children:[(0,W.jsxs)(`div`,{className:`w-full flex items-center justify-between mb-3`,children:[(0,W.jsx)(`div`,{className:G(`p-2 rounded-lg`,r?`bg-primary text-primary-foreground`:`bg-muted text-foreground`),children:(0,W.jsx)(i,{className:`size-5`})}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[n.isDefault&&(0,W.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`Default`}),(0,W.jsx)(`div`,{className:G(`size-4 rounded-full border flex items-center justify-center transition-colors`,r?`border-primary bg-primary text-primary-foreground`:`border-muted-foreground/40`),children:r&&(0,W.jsx)(Vn,{className:`size-2.5 stroke-[3]`})})]})]}),(0,W.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:n.label}),(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:n.description})]},n.id)})})]}),(0,W.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)(Tt,{className:`size-4 text-primary`}),`Actions Button Position`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`On phones, search and page actions float as a button cluster at the bottom of the screen. Place the cluster near your dominant thumb.`})]}),(0,W.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4`,children:vB.map(e=>{let t=n===e.id,a=i[e.id];return(0,W.jsxs)(`button`,{type:`button`,"data-testid":`fab-alignment-${e.id}`,onClick:()=>r(e.id),className:G(`relative flex flex-col items-start p-4 rounded-xl border text-left transition-all`,t?`border-primary ring-2 ring-primary/20 bg-primary/5 text-foreground shadow-xs`:`border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted/40`),children:[(0,W.jsxs)(`div`,{className:`w-full flex items-center justify-between mb-3`,children:[(0,W.jsx)(`div`,{className:G(`p-2 rounded-lg`,t?`bg-primary text-primary-foreground`:`bg-muted text-foreground`),children:(0,W.jsx)(a,{className:`size-5`})}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[e.id===`right`&&(0,W.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`Default`}),(0,W.jsx)(`div`,{className:G(`size-4 rounded-full border flex items-center justify-center transition-colors`,t?`border-primary bg-primary text-primary-foreground`:`border-muted-foreground/40`),children:t&&(0,W.jsx)(Vn,{className:`size-2.5 stroke-[3]`})})]})]}),(0,W.jsx)(`div`,{className:`font-semibold text-foreground text-sm`,children:e.label}),(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 leading-relaxed`,children:e.description})]},e.id)})})]})]})}function z8(){let{isEnabled:e,toggleAudio:t,playTestSound:n}=DA(),{isDebugMode:r,toggleDebugMode:i}=Jv(),{consent:a,setConsent:o}=cK(),[s,c]=(0,U.useState)(!1),[l,u]=(0,U.useState)(!1),[d,f]=(0,U.useState)(null),p=mO(),m=p.state===`turso`?`your Turso database (${p.url})`:null;return(0,U.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),c(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,W.jsxs)(`div`,{className:`space-y-8`,children:[(0,W.jsxs)(`section`,{className:`space-y-4`,"data-testid":`settings-about`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)(pe,{className:`size-4 text-primary`}),`About`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Build version and release information for this playground.`})]}),(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,W.jsxs)(`p`,{className:`text-sm font-medium text-foreground font-mono`,children:[`v`,WR]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Wod Wiki playground build`})]}),(0,W.jsx)(K,{asChild:!0,variant:`outline`,size:`sm`,className:`gap-2`,children:(0,W.jsxs)(`a`,{href:KR(WR),target:`_blank`,rel:`noopener noreferrer`,"data-testid":`settings-release-link`,children:[(0,W.jsx)(Ve,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Release notes`})]})})]})]}),(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[e?(0,W.jsx)(fe,{className:`size-4 text-primary`}):(0,W.jsx)(te,{className:`size-4 text-muted-foreground`}),`Audio Feedback`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Configure sound effects for workout timers, interval countdowns, and completion cues.`})]}),(0,W.jsxs)(`div`,{className:`rounded-xl border border-border bg-card p-4 space-y-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,W.jsx)(`label`,{htmlFor:`sound-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Workout Sound Effects`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Play countdown beeps, interval alerts, and workout finish chimes`})]}),(0,W.jsx)(h2,{id:`sound-switch`,"data-testid":`sound-toggle`,checked:e,onChange:t})]}),(0,W.jsxs)(`div`,{className:`pt-3 border-t border-border/50 flex items-center justify-between`,children:[(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Test audio output device`}),(0,W.jsxs)(K,{variant:`outline`,size:`sm`,onClick:n,disabled:!e,"data-testid":`play-test-sound-btn`,className:`gap-2`,children:[(0,W.jsx)(fe,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Play Test Chime`})]})]})]})]}),(0,W.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)(qt,{className:`size-4 text-primary`}),`Developer Diagnostics`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Logging and runtime inspection tools for Whiteboard scripts and execution trees.`})]}),(0,W.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4`,children:(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,W.jsx)(`label`,{htmlFor:`debug-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Debug Mode`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Output verbose AST compilation and runtime execution traces to browser console`})]}),(0,W.jsx)(h2,{id:`debug-switch`,"data-testid":`debug-mode-toggle`,checked:r,onChange:i})]})})]}),(0,W.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,"data-testid":`settings-telemetry`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-foreground flex items-center gap-2`,children:[(0,W.jsx)(ze,{className:`size-4 text-primary`}),`Anonymous Telemetry`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Anonymous usage telemetry is internal to Wod Wiki only. It helps us improve timer accuracy, workout execution, and query reliability. Your data will never be sold or shared with third parties.`})]}),(0,W.jsx)(`div`,{className:`rounded-xl border border-border bg-card p-4`,children:(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,W.jsx)(`label`,{htmlFor:`telemetry-switch`,className:`text-sm font-medium text-foreground cursor-pointer`,children:`Share Anonymous Usage Statistics`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends anonymous feature usage events. Turn off to opt out at any time.`})]}),(0,W.jsx)(h2,{id:`telemetry-switch`,"data-testid":`telemetry-toggle`,checked:a,onChange:o})]})})]}),(0,W.jsxs)(`section`,{className:`space-y-4 pt-4 border-t border-border/50`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`h2`,{className:`text-base font-semibold text-destructive flex items-center gap-2`,children:[(0,W.jsx)(I,{className:`size-4 text-destructive`}),`Data & Cache (Danger Zone)`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Manage your local database storage and reset client state.`})]}),(0,W.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 p-4 sm:p-5 space-y-4`,children:[(0,W.jsxs)(`div`,{className:`space-y-1`,children:[(0,W.jsx)(`div`,{className:`font-semibold text-sm text-foreground`,children:`Reset & Clear Cache`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:m?(0,W.jsxs)(W.Fragment,{children:[`Wipes ALL data stored in `,m,`: notes, workouts, custom efforts, recorded results, and attachments, plus this browser's localStorage preferences. Your separate IndexedDB copy is kept. Bundled core content re-imports automatically on the next launch; community and custom libraries must be re-synced from Settings > Sync. Your connection settings are preserved.`]}):(0,W.jsx)(W.Fragment,{children:`Wipes all durable data stores including IndexedDB (notes, workouts, custom efforts, recorded results, and attachments) and resets all localStorage preferences. The application returns to a fresh first-run state: the core playground content re-imports automatically on the next launch, and community/custom libraries wait for you in Settings > Sync.`})})]}),(0,W.jsx)(`div`,{children:(0,W.jsxs)(K,{variant:`destructive`,size:`sm`,onClick:()=>c(!0),"data-testid":`reset-cache-button`,className:`gap-2`,children:[(0,W.jsx)(At,{className:`size-4`}),(0,W.jsx)(`span`,{children:`Reset & Clear Cache`})]})})]})]}),s&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-150`,onClick:e=>{e.target===e.currentTarget&&!l&&c(!1)},"data-testid":`reset-confirmation-modal`,children:(0,W.jsxs)(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl flex flex-col gap-4`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`reset-modal-title`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 text-destructive font-semibold text-base`,id:`reset-modal-title`,children:[(0,W.jsx)(I,{className:`size-5`}),`Reset All Application Data?`]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed`,children:m?(0,W.jsxs)(W.Fragment,{children:[`This permanently deletes every note, result, cached effort, and local setting stored in `,m,`. It cannot be undone.`]}):(0,W.jsx)(W.Fragment,{children:`This action will permanently wipe every note, result, cached effort, and local setting from your browser storage. This returns Wod Wiki to its first-run state and cannot be undone.`})}),d&&(0,W.jsxs)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`reset-error`,children:[`Reset failed: `,d,` — your data and connection were left untouched; try again.`]}),(0,W.jsxs)(`div`,{className:`flex items-center justify-end gap-2 pt-2`,children:[(0,W.jsx)(K,{variant:`outline`,onClick:()=>c(!1),disabled:l,children:`Cancel`}),(0,W.jsx)(K,{variant:`destructive`,onClick:async()=>{u(!0),f(null);try{await _1(),window.location.reload()}catch(e){f(e instanceof Error?e.message:String(e)),u(!1)}},disabled:l,"data-testid":`confirm-reset-button`,className:`gap-2`,children:l?(0,W.jsx)(`span`,{children:`Resetting…`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(At,{className:`size-4`}),(0,W.jsx)(`span`,{children:`Yes, Reset Everything`})]})})]})]})})]})}function B8(){let[e,t]=(0,U.useState)([]),[n,r]=(0,U.useState)([]),[i,a]=(0,U.useState)(``),[o,s]=(0,U.useState)(``),[c,l]=(0,U.useState)(`#3b82f6`),[u,d]=(0,U.useState)(null),f=(0,U.useCallback)(async()=>{try{let[e,n]=await Promise.all([Z.getAllTagTypes(),Z.getAllTags()]);t(e),r(n)}catch{}},[]);(0,U.useEffect)(()=>{f()},[f]);let p=async t=>{t.preventDefault();let n=i.trim().toLowerCase().replace(/[^a-z0-9_-]/g,`-`),r=o.trim();if(!n||!r){d(`Both type name and display label are required`);return}if(e.some(e=>e.name.toLowerCase()===n)){d(`Tag type "${n}" already exists`);return}d(null);let l={id:typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,name:n,label:r,color:c,createdAt:Date.now()};await Z.putTagType(l),a(``),s(``),await f()},m=async e=>{if(n.some(t=>t.type?.toLowerCase()===e.name.toLowerCase())){d(`Cannot delete tag type "${e.label}" while tags are assigned to it`);return}d(null),await Z.deleteTagType(e.id),await f()};return(0,W.jsx)(`div`,{className:`space-y-8`,children:(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:`Tag Types`}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`The kinds of tag that exist. A tag picks one as its kind, and note frontmatter properties matching a type name provide typeahead suggestions. The tags themselves — and what they contribute — are authored on the`,` `,(0,W.jsx)(`span`,{className:`font-mono`,children:`/tags`}),` page.`]})]}),(0,W.jsxs)(`div`,{className:`p-4 sm:p-5 rounded-xl border border-border bg-card shadow-xs space-y-4`,children:[(0,W.jsxs)(`form`,{onSubmit:p,className:`flex flex-wrap items-end gap-3`,children:[(0,W.jsxs)(`div`,{className:`flex-1 min-w-[160px]`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Type Name`}),(0,W.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary font-mono`,placeholder:`Type name (e.g. discipline)`,value:i,onChange:e=>a(e.target.value)})]}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-[160px]`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Display Label`}),(0,W.jsx)(`input`,{className:`w-full h-9 rounded-md border border-input bg-background px-3 text-xs outline-none focus:border-primary`,placeholder:`Display label (e.g. Discipline)`,value:o,onChange:e=>s(e.target.value)})]}),(0,W.jsxs)(`div`,{className:`w-24`,children:[(0,W.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Color`}),(0,W.jsx)(`input`,{type:`color`,className:`w-full h-9 p-1 rounded-md border border-input bg-background cursor-pointer`,value:c,onChange:e=>l(e.target.value)})]}),(0,W.jsxs)(K,{type:`submit`,size:`sm`,className:`h-9`,children:[(0,W.jsx)(En,{className:`size-3.5 mr-1`}),` Add Type`]})]}),u&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,children:u}),(0,W.jsxs)(`div`,{className:`border-t border-border pt-3`,children:[(0,W.jsx)(`h3`,{className:`text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2`,children:`Registered Types`}),e.length===0?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground italic`,children:`No custom tag types created yet.`}):(0,W.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2`,children:e.map(e=>{let t=n.filter(t=>t.type?.toLowerCase()===e.name.toLowerCase()).length;return(0,W.jsxs)(`div`,{className:`flex items-center justify-between p-2.5 rounded-lg border border-border/70 bg-background/50 text-xs`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,W.jsx)(`span`,{className:`size-2.5 rounded-full shrink-0`,style:{backgroundColor:e.color||`#3b82f6`}}),(0,W.jsx)(`span`,{className:`font-semibold truncate`,children:e.label}),(0,W.jsxs)(`span`,{className:`text-muted-foreground font-mono text-[11px] truncate`,children:[`(`,e.name,`)`]}),(0,W.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.2 text-[10px] text-muted-foreground`,children:t})]}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Delete tag type ${e.label}`,disabled:t>0,title:t>0?`Cannot delete type while ${t} tag(s) are assigned`:`Delete unused tag type`,className:G(`p-1 rounded transition`,t>0?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground hover:text-destructive cursor-pointer`),onClick:()=>m(e),children:(0,W.jsx)(Ue,{className:`size-3.5`})})]},e.id)})})]})]})]})})}var V8=`dashboard-title`;function H8(){let{slug:e}=xn(),t=ht(),[n]=e0(),{unit:r}=uS(),i=Date.now()-n*7*864e5,a=Date.now(),[o,s]=(0,U.useState)(0),[c,l]=(0,U.useState)(null);(0,U.useEffect)(()=>{let e=!1;return Z.countEvents().then(t=>{e||l(t>0)}),()=>{e=!0}},[o]);let{source:u,loading:d}=AN(e,o),f=(0,U.useMemo)(()=>{if(!u?.rawContent)return null;let{meta:e,sections:t}=k_(u.rawContent);return{doc:C_(t,e),sections:t}},[u]),p=f?.doc??null,{setL3Items:m,registerScrollFn:h}=lM(),g=(0,U.useMemo)(()=>{if(!f)return{headings:[],items:[]};let{doc:e,sections:t}=f,n=new Set;t.forEach((e,r)=>{if(e.type!==`query`)return;let i=t[r-1];if(i?.type===`markdown`&&i.subtype===`paragraph`){let e=t[r-2];e?.type===`markdown`&&e.subtype===`heading`&&n.add(r-2)}else i?.type===`markdown`&&i.subtype===`heading`&&n.add(r-1)});let r=[],i=[];e.title&&i.push({id:V8,label:e.title,level:3,action:{type:`scroll`,sectionId:V8}});let a=0;return t.forEach((t,o)=>{if(t.type===`markdown`&&t.subtype===`heading`){if(n.has(o)||/^#\s/.test(t.content))return;let e=`note-h${o}`,s=t.content.replace(/^#+\s*/,``);r.push({id:e,level:/^#+/.exec(t.content)?.[0].length??2,text:s,beforeWidget:a}),i.push({id:e,label:s,level:3,action:{type:`scroll`,sectionId:e}});return}if(t.type!==`query`)return;let s=e.widgets[a];if(!s)return;a++;let c=`widget-${s.key}`;i.push({id:c,label:s.title||s.body,level:3,action:{type:`scroll`,sectionId:c}})}),{headings:r,items:i}},[f]),_=g.items;(0,U.useEffect)(()=>(m(_),()=>m([])),[_,m]),(0,U.useEffect)(()=>(h(e=>{let t=globalThis.document.getElementById(e);t&&(window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-80,behavior:`smooth`}),typeof t.animate==`function`&&t.animate([{boxShadow:`0 0 0 3px hsl(var(--primary))`},{boxShadow:`0 0 0 3px transparent`}],{duration:1500,easing:`ease-out`}))}),()=>h(e=>{let t=globalThis.document.getElementById(e);t&&window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-80,behavior:`smooth`})})),[h]);let[v,y]=(0,U.useState)(!1),[b,x]=(0,U.useState)(null),[S,C]=(0,U.useState)(null),w=(0,U.useCallback)(async(e,t)=>{if(!u?.editable||!u.noteId)return;let n=await BN.getById(u.noteId);if(n.rawContent!==e)throw s(e=>e+1),Error(`The dashboard changed elsewhere — this edit was not saved.`);let r=t(n.rawContent);if(r==null)throw s(e=>e+1),Error(`The widget changed on disk — this edit was not saved.`);await BN.update(n,typeof r==`string`?r:r.note,typeof r==`string`?void 0:r),s(e=>e+1)},[u]),T=(0,U.useCallback)(async(e,t)=>{if(!u?.editable||!u.noteId)return;let n=await BN.getById(u.noteId),{meta:r,body:i}=tx(n.rawContent),a=`---\n${ax(v_(r,e,t))}\n---\n${i}`;await BN.update(n,a),s(e=>e+1)},[u]),E=(0,U.useCallback)((e,t)=>{C(null),w(e,e=>{let n=t(e);if(!n.ok){let e=n.reason;throw Error(e===`stale-body`?`Widget changed since you opened this page — reload and retry.`:`Widget no longer exists — reload the dashboard.`)}return n}).catch(e=>{C(e instanceof Error?e.message:String(e))})},[w]),D=(0,U.useCallback)(async e=>{if(!(!b||b.mode===`inspect`)){if(b.mode===`add`)await w(b.expectedRaw,t=>z_(t,e));else{let t=b.widget;await w(b.expectedRaw,n=>{let r=H_(n,t.key,t.body,e);if(!r.ok){let e=r.reason;throw Error(e===`stale-body`?`Widget changed since you opened this page — reload and retry.`:`Widget no longer exists — reload the dashboard.`)}return r})}}},[b,w]),O=(0,U.useCallback)(async()=>{!u||u.editable||(await HN.cloneDashboard(u.slug,u.rawContent,u.title),s(e=>e+1))},[u]),k=u!=null&&u.slug===e;if(d&&!k)return(0,W.jsx)(`div`,{className:`p-8 text-sm text-muted-foreground`,children:`Loading dashboard…`});if(!k||!u)return(0,W.jsxs)(`div`,{className:`p-8`,"data-testid":`dashboard-not-found`,children:[(0,W.jsx)(`h1`,{className:`text-lg font-bold text-foreground mb-2`,children:`Dashboard not found`}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground mb-4`,children:[`No dashboard named `,(0,W.jsx)(`code`,{children:e}),`. It may have been removed.`]}),(0,W.jsx)(`button`,{onClick:()=>t(`/dashboard`),className:`px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90`,children:`Back to explorer`})]});let A=u.editable;return(0,W.jsxs)(`div`,{className:`min-h-screen bg-background flex flex-col`,children:[(0,W.jsx)(wz,{id:V8,title:p?.title||u.title,subtitle:A?`Editable dashboard note.`:`Prebuilt — read-only until cloned to your vault.`,actions:(0,W.jsxs)(kB,{label:`Dashboard actions`,primary:A?(0,W.jsxs)(`button`,{type:`button`,"data-testid":`dashboard-edit-toggle`,"aria-pressed":v,onClick:()=>y(e=>!e),className:`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors ${v?`bg-primary text-primary-foreground`:`border border-border text-muted-foreground hover:text-foreground hover:bg-muted`}`,children:[(0,W.jsx)(Kt,{size:12}),` `,v?`Done`:`Edit`]}):void 0,children:[(0,W.jsx)(tS,{}),(0,W.jsx)(fS,{})]})}),(0,W.jsxs)(`div`,{className:`max-w-[1500px] w-full mx-auto p-4 md:p-6 lg:p-8 flex-1`,children:[S&&(0,W.jsxs)(`div`,{role:`alert`,"data-testid":`dashboard-action-error`,className:`mb-4 flex items-center justify-between rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2 text-xs text-destructive`,children:[(0,W.jsx)(`span`,{children:S}),(0,W.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,onClick:()=>C(null),className:`font-medium hover:opacity-70 transition-opacity`,children:`×`})]}),!A&&(0,W.jsxs)(`div`,{className:`mb-4 flex items-center justify-between rounded-lg border border-primary/30 bg-primary/5 px-4 py-2 text-xs`,children:[(0,W.jsx)(`span`,{className:`text-foreground`,children:`This is a read-only prebuilt. Clone it to edit widgets and tokens.`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`clone-dashboard`,onClick:O,className:`font-medium text-primary hover:text-primary/80 transition-colors`,children:`Clone to vault`})]}),A&&v&&(0,W.jsxs)(`button`,{type:`button`,"data-testid":`add-widget`,onClick:()=>x({mode:`add`,expectedRaw:u.rawContent}),className:`mb-4 flex items-center gap-1.5 rounded-lg border border-dashed border-primary/50 px-4 py-2 text-xs font-semibold text-primary hover:bg-primary/5 transition-colors`,children:[(0,W.jsx)(En,{size:13}),` Add widget`]}),c===!1?(0,W.jsx)(P6,{layout:`card`,refreshKey:o,onChanged:()=>s(e=>e+1)}):(0,W.jsx)(`div`,{className:`mb-4`,children:(0,W.jsx)(P6,{layout:`banner`,refreshKey:o,onChanged:()=>s(e=>e+1)})}),p&&(0,W.jsx)(eS,{document:p,headings:g.headings,executor:$L,onTokenChange:A?T:void 0,editMode:A&&v,onEditWidget:A?e=>x({mode:`edit`,widget:e,expectedRaw:u.rawContent}):void 0,onDuplicateWidget:A?e=>E(u.rawContent,t=>U_(t,e.key,e.body)):void 0,onRemoveWidget:A?e=>E(u.rawContent,t=>W_(t,e.key,e.body)):void 0,onMoveWidget:A?(e,t)=>E(u.rawContent,n=>G_(n,e.key,e.body,t)):void 0,onResizeWidget:A?(e,t)=>E(u.rawContent,n=>K_(n,e.key,e.body,t)):void 0,onInspectWidget:A?void 0:e=>x({mode:`inspect`,widget:e,expectedRaw:u.rawContent}),onOpenInExplorer:(e,n)=>t($M({q:n})),rangeStart:i,rangeEnd:a,preferredUnit:r})]}),(0,W.jsx)(i0,{open:b!==null,onClose:()=>x(null),mode:b?.mode??`add`,initialWql:b&&b.mode!==`add`?b.widget.body:`sum:totalVolume{}`,initial:b&&b.mode!==`add`?{title:b.widget.title,question:b.widget.question,type:b.widget.type,spanCols:b.widget.spanCols,spanFull:b.widget.spanFull,attributes:b.widget.attributes}:void 0,executor:$L,rangeStart:i,rangeEnd:a,preferredUnit:r,tokenValues:p?__(p.tokens):void 0,onApply:b?.mode===`inspect`?void 0:D,footerExtra:b?.mode===`inspect`?(0,W.jsx)(`button`,{type:`button`,"data-testid":`inspect-clone`,onClick:()=>{O().then(()=>{x(null),y(!0)})},className:`px-3 py-1.5 text-xs font-medium text-primary hover:text-primary/80 rounded-lg border border-primary/40 hover:bg-primary/10 transition-colors`,children:`Clone to vault to edit`}):void 0})]})}function U8({sessionId:e}){let[t,n]=(0,U.useState)(null),[r,i]=(0,U.useState)(null),[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(``);return(0,U.useEffect)(()=>{let t=!1;return n(null),i(null),(async()=>{let r=await DN.getSessionById?.(e);if(!r)throw Error(`Session not found.`);let i=await DN.getBlockRevision(r.noteId,r.blockId,r.blockVersion);if(!i)throw Error(`The pinned saved workout is unavailable.`);t||n({session:r,revision:i})})().catch(e=>{t||i(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]),(0,W.jsxs)(`section`,{"aria-label":`Pinned workout source`,className:`space-y-3 border-b p-4`,children:[(0,W.jsx)(`h2`,{className:`font-semibold`,children:`Saved workout used by this session`}),r&&(0,W.jsx)(`p`,{role:`alert`,children:r}),t?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`p`,{className:`break-all text-sm`,children:[`Block `,t.session.blockId,` · v`,t.revision.version,` · `,t.revision.dialect,t.revision.sport?` · ${t.revision.sport}`:``]}),(0,W.jsx)(`pre`,{className:`max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-3 text-xs`,children:t.revision.rawContent}),(0,W.jsx)(`button`,{type:`button`,disabled:a,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:async()=>{o(!0),i(null);try{await new EN().rederiveResultAnalytics(e),c(`Analytics replayed from the pinned saved workout. Reload the results to view them.`)}catch(e){i(e instanceof Error?e.message:String(e))}finally{o(!1)}},children:a?`Replaying…`:`Replay saved analytics`}),(0,W.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`text-sm`,children:s}),(0,W.jsx)(XI,{noteId:t.session.noteId})]}):r?null:(0,W.jsx)(`p`,{role:`status`,children:`Loading saved workout…`})]})}function W8({searchHandlerRef:e}){let t=ht(),n=Xt(),{theme:r}=ji(),i=GD()??GB,a=WB(),o=zI(),s=sV(),c=oV(),{workout:l,nav:u}=s,[d,f]=(0,U.useState)(!1),[p,m]=(0,U.useState)(`blank`),h=(0,U.useCallback)(e=>{m(e?.mode??`blank`),f(!0)},[]),g=(0,U.useMemo)(()=>/^\/journal\/(\d{4}-\d{2}-\d{2})\/?$/.exec(n.pathname)?.[1],[n.pathname]),_=(0,U.useCallback)(e=>{t(`${VM(e.id)}?edit=1`)},[t]),{tree:v,navState:y,setL3Items:b,setSecondarySpec:x,registerCreateJournal:S}=lM(),C=y?.activeL1Id??null,w=(v??[]).find(e=>e?.id===C)??null,T=s.shell.title??l.name,E=$P((0,U.useMemo)(()=>s.page===`library`?FM(n.pathname):void 0,[s.page,n.pathname])),D=s.shell.secondary;(0,U.useEffect)(()=>(x(D),()=>x(void 0)),[D,x]),(0,U.useEffect)(()=>S(h),[S,h]),(0,U.useEffect)(()=>{let e=new URLSearchParams(n.search);if(e.get(`create`)===`1`||e.get(`new`)===`1`){let r=e.get(`mode`)===`source`?`source`:`blank`;h({mode:r}),e.delete(`create`),e.delete(`new`),e.delete(`mode`);let i=e.toString()?`?${e.toString()}`:``;t(`${n.pathname}${i}`,{replace:!0})}},[n.pathname,n.search,h,t]),(0,U.useEffect)(()=>{if(!(!s.shell.withIndex||u.length===0))return b(yH(u)),()=>b([])},[s.shell.withIndex,u,b]);let O=(0,U.useRef)(()=>null),k=(0,U.useCallback)(e=>(O.current=e,()=>{O.current===e&&(O.current=()=>null)}),[]),A=(0,U.useCallback)(()=>{gV.getState().open({wql:{initialQuery:O.current()??lH(),execute:dH,preferredChoices:uH(),settings:{panel:(0,W.jsx)(L4,{})}},sources:[oH(),cH(RV(o)),cH(jV())]}).then(e=>{e.dismissed||fH(e.item,t)})},[t,o]);(0,U.useEffect)(()=>{e.current=A},[A,e]),(0,U.useEffect)(()=>{let e=e=>{e.key===`/`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.stopPropagation(),A())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[A]);let[j,M]=(0,U.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches),{handleViewCreated:N,scrollToSection:P}=bH(u);(0,U.useEffect)(()=>{if(r!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>M(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let F=(0,U.useMemo)(()=>r===`system`?j?`vs-dark`:`vs`:r===`dark`?`vs-dark`:`vs`,[r,j]),I={feedDetail:()=>(0,W.jsx)(t$,{feedSlug:decodeURIComponent(s.feedDetailMatch)}),feedItem:()=>(0,W.jsx)(q$,{feedSlug:decodeURIComponent(s.feedItemMatch[0]),feedDate:decodeURIComponent(s.feedItemMatch[1]),feedItem:decodeURIComponent(s.feedItemMatch[2]),theme:F,onViewCreated:N,onScrollToSection:P}),effortDetail:()=>(0,W.jsx)(v3,{}),equipmentDetail:()=>(0,W.jsx)(C3,{}),tags:()=>(0,W.jsx)(L3,{}),analyticsExplorer:()=>(0,W.jsx)(H6,{actions:(0,W.jsx)(K$,{mode:`collection-readonly`,currentWorkout:l,index:[]})}),dashboardExplorer:()=>(0,W.jsx)(H6,{actions:(0,W.jsx)(K$,{mode:`collection-readonly`,currentWorkout:l,index:[]})}),dashboardView:()=>(0,W.jsx)(H8,{}),canvas:()=>s.canvasPage.route===`/`?(0,W.jsx)(I0,{wodFiles:i,theme:F}):s.canvasPage.scroll?(0,W.jsx)(ZQ,{page:s.canvasPage,wodFiles:i,theme:F,workoutItems:a,onSelect:c,onScrollToSection:P}):(0,W.jsx)(NQ,{page:s.canvasPage,wodFiles:i,theme:F,workoutItems:a,onSelect:c,onScrollToSection:P}),playground:()=>(0,W.jsx)(o3,{theme:F,onViewCreated:N,onScrollToSection:P,onSearch:A},s.effectivePlaygroundId),journalEntry:()=>(0,W.jsx)(W4,{theme:F,onViewCreated:N,onScrollToSection:P,onSearch:A},s.journalEntryId),note:()=>(0,W.jsx)(H3,{noteId:s.noteById,theme:F},s.noteById),collectionDate:()=>(0,W.jsx)(K3,{slug:s.collectionDate.slug,date:s.collectionDate.date,theme:F},`${s.collectionDate.slug}/${s.collectionDate.date}`),workout:()=>(0,W.jsx)(s3,{category:s.workout.category,name:s.workout.name,mdContent:s.workout.content,theme:F,onViewCreated:N},`${s.workout.category}/${s.workout.name}`),library:()=>{let e=E??QP(FM(n.pathname));return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(G8,{pathname:n.pathname}),(0,W.jsx)(I4,{profile:e,registerStreamDraft:k,actions:(0,W.jsx)(K$,{mode:`collection-readonly`,currentWorkout:l,index:[]})},e.route)]})},settings:()=>(0,W.jsx)(I8,{})},L=s.page===`canvas`?s.canvasPage?.route:void 0,R=L===`/`||!!L?.startsWith(`/guide/`),ee=s.page===`canvas`&&s.canvasPage?(0,W.jsx)(W.Fragment,{children:s.canvasPage.quests.length>0&&(0,W.jsx)(R4,{pageRoute:s.canvasPage.route,quests:s.canvasPage.quests,challengeSectionMap:dI(s.canvasPage),onScrollToSection:P})}):void 0;return(0,W.jsxs)(RB,{navbar:(0,W.jsxs)(VI,{children:[(0,W.jsxs)(`nav`,{"aria-label":`Breadcrumb`,className:`flex items-center gap-1.5 min-w-0 shrink-2 truncate text-sm`,children:[w&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>w?.action?.type===`route`&&t(w.action.to),className:`shrink-0 text-muted-foreground hover:text-foreground transition-colors`,children:w.label}),w&&!!T&&T.toLowerCase()!==w.label.toLowerCase()&&(0,W.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/50 shrink-0`,children:`›`}),T&&T.toLowerCase()!==w?.label.toLowerCase()&&(0,W.jsx)(`span`,{className:`text-sm font-semibold text-zinc-950 dark:text-white truncate`,children:T}),ee]}),(0,W.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1`,children:[(0,W.jsx)(lV,{}),(0,W.jsx)(jB,{}),(0,W.jsx)(rX,{})]})]}),sidebar:(0,W.jsx)(UR,{navSpec:s.shell.nav}),hideDesktopSidebar:R,secondary:D,pageAction:l.content===``?void 0:(0,W.jsx)(V$,{currentWorkout:l}),onSearch:A,onCreate:h,children:[(0,W.jsx)(JV,{open:d,onOpenChange:f,defaultDate:g,defaultMode:p,onCreated:_}),(0,W.jsx)(`div`,{className:`flex flex-col h-full min-h-[calc(100vh-theme(spacing.20))]`,children:(0,W.jsx)(`div`,{className:`flex-1 flex flex-col min-h-0`,children:(e=>{if(s.shell.wrap===`bare`)return e;let t=s.shell.subheader===`filter-collection-workouts`?(0,W.jsx)(sZ,{placeholder:`Filter notebook notes… Press / to start filtering`}):void 0;return(0,W.jsx)(Ez,{title:s.shell.title,titleAccessory:ee,subheader:t,index:s.shell.withIndex?u:void 0,actions:s.shell.actionsMode?(0,W.jsx)(K$,{mode:s.shell.actionsMode,currentWorkout:l,index:u}):void 0,children:e})})(I[s.page]())})}),(0,W.jsx)(kV,{}),(0,W.jsx)(mV,{})]})}function G8({pathname:e}){let t=/^\/results\/([^/]+)\/?$/.exec(e);return t?(0,W.jsx)(U8,{sessionId:decodeURIComponent(t[1])}):null}function K8(){let{name:e}=xn();return(0,W.jsx)(Wn,{to:RM(e),replace:!0})}function q8(){let{category:e,name:t}=xn();return(0,W.jsx)(Wn,{to:GM(e,t),replace:!0})}function J8(){let{slug:e,target:t}=xn(),{search:n}=Xt();return t==null?(0,W.jsx)(Wn,{to:{pathname:WM(e),search:n},replace:!0}):YB(decodeURIComponent(t))?(0,W.jsx)(Wn,{to:{pathname:VM(decodeURIComponent(t)),search:n},replace:!0}):(0,W.jsx)(Wn,{to:{pathname:GM(e,decodeURIComponent(t)),search:n},replace:!0})}function Y8(){let{search:e}=Xt();return(0,W.jsx)(Wn,{to:{pathname:`/feeds`,search:e},replace:!0})}function X8(){let{slug:e}=xn();return(0,W.jsx)(Wn,{to:nN(e),replace:!0})}function Z8(){let{search:e}=Xt();return(0,W.jsx)(Wn,{to:{pathname:`/sessions`,search:e},replace:!0})}function Q8(){return(0,W.jsx)(Wn,{to:`/sessions?q=%3Asegment%7B%7D%20last%208w`,replace:!0})}function $8(){let{search:e}=Xt();return(0,W.jsx)(Wn,{to:{pathname:`/dashboards`,search:e},replace:!0})}function e5(){let{runtimeId:e}=xn();return(0,W.jsx)(Wn,{to:KM(e),replace:!0})}function t5(){let{runtimeId:e,noteId:t,resultId:n}=xn(),r=n??e;return r?(0,W.jsx)(Wn,{to:JM(r),replace:!0}):t?(0,W.jsx)(Wn,{to:`/sessions?q=${encodeURIComponent(`:session{note:${t}}`)}`,replace:!0}):(0,W.jsx)(Wn,{to:`/sessions`,replace:!0})}function n5(){let e=Xt().search,t=e&&e.startsWith(`?`)?`${e}&mode=plan`:`?mode=plan`;return(0,W.jsx)(Wn,{to:`/journal${t}`,replace:!0})}function r5(){let{search:e}=Xt();return(0,W.jsx)(Wn,{to:{pathname:`/dashboards`,search:e},replace:!0})}var i5=`G-PROD-ID`,a5=!1;function o5(){if(a5||typeof document>`u`)return;a5=!0,window.dataLayer=window.dataLayer??[],window.gtag=function(){window.dataLayer.push(arguments)};let e=document.createElement(`script`);e.async=!0,e.src=`https://www.googletagmanager.com/gtag/js?id=${i5}`,document.head.appendChild(e),window.gtag(`js`,new Date),window.gtag(`config`,i5,{send_page_view:!1})}function s5(e,t){typeof window>`u`||!oK.consent||window.gtag?.(`event`,`page_view`,{page_title:e??document.title,page_location:window.location.href,page_path:t??window.location.pathname+window.location.search,engagement_time_msec:aK()})}oK.setForwarder(e=>{window.gtag?.(`event`,e.name,e.payload??{})}),oK.consent?o5():oK.subscribeConsent(e=>{e&&(o5(),s5())});function c5(){let e=Xt();return(0,U.useEffect)(()=>{let t=e.pathname;if(!t.startsWith(`/effort/`)&&!t.startsWith(`/e/`)&&!t.startsWith(`/playground/`)&&!t.startsWith(`/equipment/`)){let e=`Wod.Wiki`;t.startsWith(`/journal`)?e=`Wod.Wiki - Journal`:t.startsWith(`/catalogs`)?e=`Wod.Wiki - Notebooks`:t.startsWith(`/feeds`)||t.startsWith(`/feed`)||t.startsWith(`/collections`)||t.startsWith(`/c/`)?e=`Wod.Wiki - Notes`:t.startsWith(`/efforts`)?e=`Wod.Wiki - Efforts`:t.startsWith(`/equipment`)?e=`Wod.Wiki - Equipment`:t.startsWith(`/sessions`)||t.startsWith(`/session/`)||t.startsWith(`/results`)?e=`Wod.Wiki - Sessions`:t.startsWith(`/dashboards`)||t===`/dashboard`||t.startsWith(`/dashboard/`)||t.startsWith(`/d/`)?e=`Wod.Wiki - Dashboards`:t.startsWith(`/playgrounds`)?e=`Wod.Wiki - Playgrounds`:t.startsWith(`/syntax`)?e=`Wod.Wiki - Syntax`:t.startsWith(`/analytics`)&&(e=`Wod.Wiki - Analytics`),document.title=e}let n=setTimeout(()=>{s5(document.title,e.pathname+e.search)},0);return()=>clearTimeout(n)},[e.pathname]),null}function l5(e,t){let n=e.match(RegExp(`^${t}:\\s*"([^"]+)"`,`m`));if(!n?.[1])throw Error(`Guide example is missing frontmatter field: ${t}`);return n[1]}function u5(e){let t=e.match(/```time\n([\s\S]*?)\n```/);if(!t)throw Error("Guide example is missing a ```time fenced block.");return t[1]}function d5(e,t){let n=l5(e,`title`),r=l5(e,`subtitle`),i=u5(e);return{title:n,subtitle:r,docsPath:t,workout:i,storyContent:[`# `+n,``,r,``,"```time",i,"```"].join(`
185
+ `)}}var f5={coreRules:{path:`markdown/canvas/syntax/core-rules.md`,docsPath:`/guide/start?h=first-workout`},measurements:{path:`markdown/canvas/syntax/measurements.md`,docsPath:`/guide/start?h=measurements`},timerModifiers:{path:`markdown/canvas/syntax/timer-modifiers.md`,docsPath:`/guide/protocols?h=countdown-countup`},simpleRounds:{path:`markdown/canvas/syntax/groups-1.md`,docsPath:`/guide/structure?h=rounds`},repSchemes:{path:`markdown/canvas/syntax/groups-2.md`,docsPath:`/guide/structure?h=rep-schemes`},timersAndRest:{path:`markdown/canvas/syntax/timers-rest.md`,docsPath:`/guide/protocols?h=required-rest`},classicAmrap:{path:`markdown/canvas/syntax/classic-amrap.md`,docsPath:`/guide/protocols?h=amrap`},basicEmom:{path:`markdown/canvas/syntax/basic-emom.md`,docsPath:`/guide/protocols?h=emom`},standardTabata:{path:`markdown/canvas/syntax/protocols-4.md`,docsPath:`/guide/protocols?h=tabata-intervals`},mixedSections:{path:`markdown/canvas/syntax/mixed-sections.md`,docsPath:`/guide/structure?h=named-sections`},complexNestedProtocols:{path:`markdown/canvas/syntax/complex-nested-protocols.md`,docsPath:`/guide/sessions?h=nested`}};function p5(e){let t={};for(let[n,{path:r,docsPath:i}]of Object.entries(f5)){let a=e[r];if(!a){t[n]=void 0;continue}try{t[n]=d5(a,i)}catch{t[n]=void 0}}return t}function m5({actionsSlot:e,heroSlot:t,children:n,className:r}){return(0,W.jsxs)(`main`,{className:G(`mx-auto w-full max-w-7xl px-6 py-10 sm:px-8 lg:px-12 lg:py-14`,r),children:[e&&(0,W.jsx)(`div`,{className:`mb-6 flex justify-end`,children:e}),t,n]})}var h5={headline:`Build and preview widget-driven workout pages.`,subtitle:`Phase 2.2 integrates the attention, code-example, and syntax-group widgets into one interactive playground surface.`,pillars:[{icon:(0,W.jsx)(Pt,{className:`size-4`,"aria-hidden":`true`}),label:`Attention widget`,description:`High-signal hero block with actionable CTAs.`},{icon:(0,W.jsx)(er,{className:`size-4`,"aria-hidden":`true`}),label:`Code example widget`,description:`Editable CodeMirror sample with runnable workout output.`},{icon:(0,W.jsx)(ye,{className:`size-4`,"aria-hidden":`true`}),label:`Syntax group widget`,description:`Grouped syntax cards linked to docs.`}],actions:[{label:`Jump to workout`,action:`scroll-to-workout`,variant:`primary`},{label:`Open search`,action:`open-search`,variant:`secondary`}]};function g5(){let e=ht(),{theme:t,setTheme:n}=ji(),r=(0,U.useRef)(null),i=GD(),a=(0,U.useMemo)(()=>i?p5(i):null,[i]),o=(0,U.useMemo)(()=>(a?.classicAmrap?.workout??`20:00 AMRAP
186
+ 5 Pullups
187
+ 10 Pushups
188
+ 15 Air Squats`).split(`
189
+ `),[a]),s=(0,U.useMemo)(()=>({lines:[{code:o[0]??`20:00 AMRAP`,annotation:`Classic AMRAP from the guide — fixed time window with unbounded rounds.`},{code:o[1]??` 5 Pullups`,annotation:`Start each round with five pullups.`},{code:o[2]??` 10 Pushups`,annotation:`Then move into ten pushups.`},{code:o[3]??` 15 Air Squats`,annotation:`Finish the round with fifteen air squats before looping.`}],cta:`Run this example`}),[o]),c=(0,U.useMemo)(()=>{let e=a?.simpleRounds,t=a?.timersAndRest,n=a?.repSchemes;return[{category:`Structure`,icon:`🔁`,title:e?.title??`Simple Rounds`,description:e?.subtitle??`Rounds repeated for time or reps.`,example:e?.workout??`3 rounds
190
+ 10 Air Squats`,docsPath:e?.docsPath??`/guide/structure?h=rounds`},{category:`Timing`,icon:`⏱️`,title:t?.title??`Timers And Rest`,description:t?.subtitle??`Timed windows with rest periods.`,example:t?.workout??`10:00
191
+ 5 Burpees
192
+ rest 1:00`,docsPath:t?.docsPath??`/guide/protocols?h=required-rest`},{category:`Structure`,icon:`🏋️`,title:`Rep Schemes`,description:n?.subtitle??`Rep counts per movement.`,example:n?.workout??`21-15-9
193
+ Thrusters`,docsPath:n?.docsPath??`/guide/structure?h=rep-schemes`}]},[a]),l=(0,U.useMemo)(()=>t===`dark`||t!==`light`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches,[t]),u=zI(),d=(0,U.useCallback)(async()=>{let t=await gV.getState().open({wql:{initialQuery:lH(),execute:dH,preferredChoices:uH()},sources:[oH(),cH(RV(u))]});t.dismissed||fH(t.item,e)},[e,u]),f=(0,U.useCallback)(e=>{if(e===`scroll-to-workout`){r.current?.scrollIntoView({behavior:`smooth`,block:`start`});return}e===`open-search`&&d()},[d]),p=(0,U.useCallback)(async t=>{let n=await hK([`# Playground Widget Example`,``,"```time",t,"```",``,`[▶ Run Workout]{.button action=start-workout}`,``].join(`
194
+ `));e(RM(n))},[e]),m=(0,U.useCallback)(t=>{if(/^https?:\/\//i.test(t)){window.open(t,`_blank`,`noopener,noreferrer`);return}e(t)},[e]);return(0,W.jsxs)(m5,{actionsSlot:(0,W.jsxs)(`div`,{className:`flex items-center gap-3 rounded-2xl border border-zinc-200 bg-zinc-50/80 px-4 py-3 dark:border-zinc-700 dark:bg-zinc-900/70`,children:[(0,W.jsx)(ae,{className:`size-4 text-zinc-500`,"aria-hidden":`true`}),(0,W.jsx)(h2,{checked:l,onChange:e=>n(e?`dark`:`light`),"aria-label":`Toggle dark mode`}),(0,W.jsx)(Pe,{className:`size-4 text-zinc-500`,"aria-hidden":`true`})]}),heroSlot:(0,W.jsx)(K4,{config:h5,onAction:f}),children:[(0,W.jsxs)(`section`,{ref:r,id:`workout-widget-surface`,className:`mt-8 grid grid-cols-1 gap-4 xl:grid-cols-3`,children:[(0,W.jsx)(`div`,{className:`xl:col-span-2`,children:(0,W.jsx)(q4,{config:s,isDarkMode:l,onRun:p})}),(0,W.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,W.jsx)(J4,{config:e,onOpenDocs:m},e.title))})]}),(0,W.jsx)(M1,{})]})}function _5(e){let[t,n]=(0,U.useState)(!1),[r,i]=(0,U.useState)({});(0,U.useEffect)(()=>{i(SK()),n(!0);let e=e=>{e.key===`wodwiki.quests.v1`&&i(SK())};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]);let a=e=>{for(let t in r)if(r[t]?.[e])return!0;return!1};return{chapters:e.map(e=>{let t=(e.questIds??[]).map(e=>({id:e,isComplete:a(e)})),n=t.filter(e=>e.isComplete).length;return{chapter:e,completedCount:n,totalCount:t.length,isComplete:t.length>0&&n===t.length,quests:t}}),isHydrated:t}}function v5({activeIndex:e,onCommand:t,captions:n}){return(0,W.jsx)(`div`,{className:`relative h-full w-full`,"data-testid":`tour-captions`,children:n.map((n,r)=>(0,W.jsx)(`div`,{"data-scroll-pane":!0,className:`absolute inset-0 overflow-y-auto transition-opacity duration-300`,style:{opacity:+(r===e),pointerEvents:r===e?`auto`:`none`},"aria-hidden":r!==e,inert:r!==e,children:(0,W.jsx)(y5,{cap:n,onCommand:t})},n.id))})}function y5({cap:e,onCommand:t}){return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`h3`,{className:`mb-3.5 xl:mb-5 text-[clamp(22px,2vw,32px)] font-extrabold leading-[1.12] tracking-[-0.03em]`,children:[(0,W.jsx)(`span`,{className:`mr-2 align-[0.2em] font-mono text-[0.5em] font-semibold tracking-[0.08em] text-muted-foreground/50`,children:e.num}),e.title]}),(0,W.jsx)(`p`,{className:`text-[14.5px] sm:text-base xl:text-[17px] leading-[1.7] xl:leading-[1.75] text-muted-foreground`,children:e.body}),e.bullets&&e.bullets.length>0&&(0,W.jsx)(`ul`,{className:`mt-3 space-y-1.5 text-sm xl:text-[15px] leading-relaxed text-foreground/85`,children:e.bullets.map((e,t)=>(0,W.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,W.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,W.jsx)(`span`,{children:e})]},t))}),e.foot&&(0,W.jsx)(`div`,{className:`mt-4 xl:mt-6 border-t border-border pt-3 xl:pt-4 font-mono text-[10px] xl:text-[11px] tracking-[0.06em] text-muted-foreground/60`,children:e.foot}),e.extra&&(0,W.jsx)(`div`,{className:`mt-3`,children:e.extra}),e.commands&&e.commands.length>0&&t&&(0,W.jsx)(`div`,{className:`mt-4 xl:mt-6 flex flex-wrap items-center gap-2`,"data-testid":`tour-caption-commands-${e.id}`,children:e.commands.map(n=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>t(e.id,n.key),className:`inline-flex items-center rounded-full border border-border px-3.5 py-1.5 text-[13px] font-medium text-foreground transition-colors hover:border-primary/40 hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`,"data-testid":`tour-caption-command-${e.id}-${n.key}`,children:n.label},n.key))}),e.actions&&e.actions.length>0&&(0,W.jsx)(`div`,{className:`mt-4 xl:mt-6 flex flex-wrap items-center gap-3`,children:e.actions.map((e,t)=>{let n=t===0;return(0,W.jsx)(Nt,{to:e.href,onClick:()=>oK.record(e.event,e.data),"data-testid":e.testId,className:n?`inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90`:`text-sm text-primary underline-offset-2 hover:underline`,children:e.label},e.label)})})]})}function b5({visible:e,children:t}){return(0,W.jsx)(`div`,{className:`absolute inset-0 transition-opacity duration-500`,style:{opacity:+!!e,pointerEvents:e?`auto`:`none`},"aria-hidden":!e,inert:!e,children:t})}var x5=(0,U.forwardRef)(function({id:e,heightVh:t,header:n,stages:r,captions:i,onActiveStageChange:a,onViewportChange:o,onReachedChange:s,onCommand:c,editor:l},u){let d=(0,U.useRef)(null),f=(0,U.useRef)(null),[p,m]=(0,U.useState)(null),h=(0,U.useCallback)(e=>{f.current=e,m(e)},[]),{slice:g,subscribe:_,resync:v,runwayReached:y}=$X(d,!1,r,e),b=C5(d);(0,U.useEffect)(()=>{o?.(b)},[b,o]),(0,U.useEffect)(()=>{s?.(y)},[y,s]);let[x,S]=(0,U.useState)(!1),C=S5(d);(0,U.useEffect)(()=>{(C||y)&&S(!0)},[C,y]);let w=g.stage?.screen??`editor`,T=(0,U.useRef)(null);return(0,U.useEffect)(()=>{x&&T.current!==g.stage?.id&&(T.current=g.stage?.id??null,g.stage?.id&&a?.(g.stage.id))},[g.stage?.id,a,x]),(0,U.useImperativeHandle)(u,()=>({scrollToStage:e=>{let t=d.current,n=r.find(t=>t.id===e);!t||!n||QX(t,Math.min(n.range[0]+.02,n.range[1]-.005))},subscribe:_,resync:v}),[r,_,v]),(0,W.jsxs)(`section`,{id:`tour-section-${e}`,"data-testid":`tour-section-${e}`,children:[n,(0,W.jsx)(XX,{trackRef:d,height:t,stages:r,activeIndex:g.index,segmentId:e,testId:`tour-runway`,pane:(0,W.jsx)(`div`,{ref:h,className:`absolute inset-0 flex flex-col justify-center`,children:(0,W.jsxs)(s1,{children:[(0,W.jsx)(u1,{ringKey:`editor.window`,el:p}),(0,W.jsx)(PK,{title:aQ[w],className:`relative h-full max-h-[760px]`,children:(0,W.jsx)(YX,{gateId:`${e}-pane`,segmentId:e,className:`relative h-full`,children:l&&(0,W.jsx)(b5,{visible:w===`editor`,children:(0,W.jsx)(N1,{doc:l.doc,onDocChange:l.onDocChange,onBlocksChange:l.onBlocksChange,onRun:l.onRun,theme:l.theme,withRingTargets:!0})})})}),(0,W.jsx)(d1,{target:g.ring?.key?{key:g.ring.key}:null,accent:g.stage.accent??iQ.editor,canvasRef:f})]})}),captions:(0,W.jsx)(v5,{activeIndex:g.index,captions:i,onCommand:c})})]})});function S5(e){let[t,n]=(0,U.useState)(!1);return(0,U.useEffect)(()=>{let t=e.current;if(!t||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(([e])=>{e.isIntersecting&&(n(!0),r.disconnect())},{threshold:.05});return r.observe(t),()=>r.disconnect()},[e]),t}function C5(e){let[t,n]=(0,U.useState)(()=>typeof IntersectionObserver>`u`);return(0,U.useEffect)(()=>{let t=e.current;if(!t||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(([e])=>n(e.isIntersecting),{threshold:.05});return r.observe(t),()=>r.disconnect()},[e]),t}var w5={basics:`wods/examples/syntax/single-movement.md`,protocols:`wods/examples/syntax/timers-rest.md`,structure:`wods/examples/syntax/groups-1.md`,"custom-metrics":`wods/syntax/custom-metrics-1.md`,dialects:`wods/examples/syntax/dialect-climb-bouldering.md`,complex:`wods/examples/syntax/complex-swimming.md`},T5={basics:{summary:`Statements and metrics — how a workout line reads, from movement names to reps, loads, and timed rests.`,bullets:["Freeform Markdown + fenced ```time blocks",`Single movements: 10 Pushups, 15 Air Squats`,`Inline resistance: 225lb, 100kg, 24kg`]},protocols:{summary:`Time-capped and paced protocols: AMRAP, EMOM, Tabata intervals, and required rest that paces the room.`,bullets:[`20:00 AMRAP (As Many Rounds As Possible)`,`(10) :60 EMOM (Every Minute on the Minute)`,`*:30 Rest (required, unskippable recovery)`]},structure:{summary:`Rounds, rep ladders, and nested grouping — how blocks compose into multi-part workout schemes.`,bullets:[`(3 Rounds) and (5 Sets) block repetition`,`Ladders & schemes: 21-15-9, 10-8-6-4-2`,`Section labels: (Warmup) and // Strength`]},"custom-metrics":{summary:`Capture typed data points right inline: effort intensity, heart rate, RPE, and custom JSON metrics.`,bullets:[`Inline JSON metrics: {"intensity": 80}`,`Capture prompts: :? time, ? reps, ?lb load`,`Session-level RPE & custom dimensions`]},dialects:{summary:`Dialect fences for specialized domains: workout, log, plan, and climbing session notes.`,bullets:["```time for workouts, ```log for recorded efforts","Sport dialect suffixes like ```log:climbing",`Discipline tags and session intent`]},complex:{summary:`Multi-set training sessions that chain intervals, strength, and conditioning into one complete program.`,bullets:[`Multi-set swimming and track intervals`,`Strength blocks paired with conditioned finishers`,`Full training session flow`]}},E5=[{id:`basics`,title:`Basics`,badge:`trophy`,questIds:[],sectionIds:[]},{id:`protocols`,title:`Protocols`,badge:`timer`,questIds:[],sectionIds:[]},{id:`structure`,title:`Structure`,badge:`dumbbell`,questIds:[],sectionIds:[]},{id:`custom-metrics`,title:`Custom Metrics`,badge:`trophy`,questIds:[],sectionIds:[]},{id:`dialects`,title:`Dialects`,badge:`trophy`,questIds:[],sectionIds:[]},{id:`complex`,title:`Complex Workouts`,badge:`dumbbell`,questIds:[],sectionIds:[]}];function D5({chapters:e=[],allQuests:t=[],theme:n,wodFiles:r={},onRun:i}){let a=(0,U.useMemo)(()=>{let t=(e??[]).filter(e=>e.id!==`home-tour`);return t.length>0?t:E5},[e]),o=jK(`(prefers-reduced-motion: reduce)`),{markComplete:s}=OK(`/`,t),{chapters:c}=_5(a),[l,u]=(0,U.useState)(()=>a[0]?.id??`basics`),[d,f]=(0,U.useState)(``),p=(0,U.useRef)([]),m=(0,U.useRef)(l);m.current=l;let h=(0,U.useMemo)(()=>Object.fromEntries(a.map(e=>[e.id,pB(w5[e.id]??``,r)])),[a,r]);(0,U.useEffect)(()=>{p.current=[],f(h[l]??``)},[l,h]);let g=(0,U.useCallback)(e=>{p.current=e},[]),_=(0,U.useCallback)(()=>{let e=m.current;s(`${e}-run`),i?.(e,p.current[0]??null,d)},[d,s,i]),v=(0,U.useMemo)(()=>a.map((e,t)=>{let n=Math.max(1,a.length);return{id:e.id,range:[t/n,(t+1)/n],screen:`editor`,accent:`hsl(var(--primary))`,label:e.title,source:h[e.id]}}),[a,h]),y=(0,U.useMemo)(()=>Object.fromEntries(c.map(e=>[e.chapter.id,e])),[c]),b=(0,U.useMemo)(()=>a.map((e,t)=>{let n=T5[e.id],r=y[e.id];return{id:e.id,num:`05${String.fromCharCode(97+t)}`,title:e.title,body:n?.summary??e.title,bullets:n?.bullets,accent:`hsl(var(--primary))`,extra:r&&(0,W.jsx)(`span`,{"data-testid":`chapter-picker-progress-${e.id}`,className:G(`font-mono text-[11px] font-semibold tabular-nums`,r.isComplete?`font-bold text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`),children:r.isComplete?`done ✓`:`${r.completedCount}/${r.totalCount}`}),actions:[{label:`Read guide →`,href:oQ[e.id]??`/guide/start`,event:sK.chapterGuideClicked,data:{chapter:e.id},testId:`chapter-picker-guide-${e.id}`}]}}),[a,y]);return(0,W.jsxs)(`section`,{id:`tour-chapter-picker`,"data-testid":`tour-chapter-picker`,className:`flex flex-col`,children:[(0,W.jsx)(nQ,{index:`05`,before:`Learning with `,accentText:`Examples`,after:``,accent:`hsl(var(--primary))`,blurb:`Six chapters on the syntax, each with a runnable example and quests to earn. Scroll into each section to load its example code into the editor.`}),o?(0,W.jsx)(O5,{chapters:a,selectedId:l,onSelect:u,doc:d,onDocChange:f,theme:n,onBlocksChange:g,onRun:_,progressByChapter:y}):(0,W.jsx)(x5,{id:`learn`,heightVh:`600vh`,stages:v,captions:b,onActiveStageChange:u,editor:{doc:d,theme:n,onDocChange:f,onBlocksChange:g,onRun:_}})]})}function O5({chapters:e,selectedId:t,onSelect:n,doc:r,onDocChange:i,theme:a,onBlocksChange:o,onRun:s,progressByChapter:c}){return(0,W.jsx)(`div`,{className:`relative mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px] px-6 py-8 lg:px-12 xl:px-16`,children:(0,W.jsxs)(`div`,{className:`flex flex-col gap-10 lg:flex-row lg:items-start lg:gap-12 xl:gap-16`,children:[(0,W.jsx)(`div`,{className:`w-full lg:w-[58%] xl:w-[60%] lg:sticky lg:top-[110px] z-10 flex-none`,children:(0,W.jsx)(`div`,{className:`h-[420px] sm:h-[480px] lg:h-[calc(100dvh-150px)] max-h-[700px] w-full rounded-2xl border border-border shadow-2xl overflow-hidden bg-background`,children:(0,W.jsx)(PK,{title:oQ[t]?.split(`/`).pop()??`example.md`,subtitle:`Lesson: ${e.find(e=>e.id===t)?.title??t}`,className:`h-full`,children:(0,W.jsx)(N1,{doc:r,onDocChange:i,onBlocksChange:o,onRun:s,theme:a,withRingTargets:!1})})})}),(0,W.jsx)(`div`,{className:`w-full lg:w-[42%] xl:w-[40%] flex flex-col gap-16 lg:py-6`,"data-testid":`chapter-picker-list`,children:e.map((e,r)=>{let i=c[e.id],a=qZ(e.badge),o=e.id===t,s=T5[e.id];return(0,W.jsxs)(`div`,{"data-testid":`chapter-picker-row-${e.id}`,className:G(`rounded-2xl border p-6 sm:p-8 transition-all duration-300 min-h-[340px] flex flex-col justify-between`,o?`border-primary bg-primary/5 ring-1 ring-primary/30 shadow-lg dark:bg-primary/10`:`border-border/70 bg-card hover:border-primary/40`),children:[(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,W.jsxs)(`span`,{className:`font-mono text-xs font-bold uppercase tracking-wider text-primary`,children:[`Chapter 0`,r+1]}),a&&(0,W.jsx)(a,{className:`size-4 text-primary`})]}),(0,W.jsx)(`span`,{className:G(`font-mono text-xs font-semibold tabular-nums`,i?.isComplete?`text-emerald-600 dark:text-emerald-400 font-bold`:`text-muted-foreground`),children:i?.isComplete?`done ✓`:`${i?.completedCount??0}/${i?.totalCount??e.questIds.length}`})]}),(0,W.jsx)(`h3`,{className:`mt-3 text-2xl font-bold tracking-tight text-foreground sm:text-3xl`,children:e.title}),(0,W.jsx)(`p`,{className:`mt-3 text-sm sm:text-base leading-relaxed text-muted-foreground`,children:s?.summary??e.title}),s?.bullets&&(0,W.jsx)(`ul`,{className:`mt-4 space-y-1.5 text-xs sm:text-sm text-foreground/80 font-mono`,children:s.bullets.map((e,t)=>(0,W.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,W.jsx)(`span`,{className:`text-primary font-bold`,children:`›`}),(0,W.jsx)(`span`,{children:e})]},t))})]}),(0,W.jsxs)(`div`,{className:`mt-6 flex flex-wrap items-center gap-3 pt-4 border-t border-border/50`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(e.id),"data-testid":`chapter-picker-select-${e.id}`,"aria-pressed":o,className:G(`inline-flex items-center gap-2 rounded-lg px-4 py-2 text-xs sm:text-sm font-semibold transition-colors shadow-xs`,o?`bg-primary text-primary-foreground hover:bg-primary/90`:`border border-border bg-background text-foreground hover:bg-muted`),children:[(0,W.jsx)(pn,{className:`size-3.5 fill-current`}),(0,W.jsx)(`span`,{children:o?`Loaded in editor`:`Load example`})]}),(0,W.jsxs)(Nt,{to:oQ[e.id]??`/guide/start`,"data-testid":`chapter-picker-guide-${e.id}`,"aria-label":`Read guide for ${e.title}`,onClick:()=>oK.record(sK.chapterGuideClicked,{chapter:e.id}),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-background/80 px-3.5 py-2 text-xs sm:text-sm font-medium text-muted-foreground transition-colors hover:border-primary/50 hover:bg-background hover:text-primary`,children:[(0,W.jsx)(pr,{className:`size-3.5`}),(0,W.jsx)(`span`,{children:`Read guide →`})]})]})]},e.id)})})]})})}function k5({chapters:e}){let t=()=>oK.record(sK.lessonStarted),n=()=>oK.record(sK.cheatsheetOpened),{chapters:r}=_5(e),i=r.filter(e=>e.chapter.id!==`home-tour`);return(0,W.jsxs)(`section`,{"data-testid":`tour-learn`,className:`mx-auto max-w-5xl px-6 py-16 border-b border-border/60`,children:[(0,W.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-bold tracking-tight`,children:`Learn the Language`}),(0,W.jsx)(`p`,{className:`mt-2 text-muted-foreground leading-relaxed max-w-xl`,children:`Six chapters, each with a runnable example and quests to earn — progress shows on the chapter cards above.`})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,W.jsx)(Nt,{to:`/guide/start`,onClick:t,className:`inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90`,children:`Start Lesson 1`}),(0,W.jsx)(Nt,{to:`/guide/start?h=reference`,onClick:n,className:`text-sm font-semibold text-primary underline-offset-2 hover:underline`,children:`Cheat sheet →`})]})]}),(0,W.jsx)(`div`,{className:`mt-8 flex flex-wrap items-center gap-2`,children:i.map(({chapter:e,completedCount:t,totalCount:n,isComplete:r})=>{let i=oQ[e.id]??`/guide/start`,a=qZ(e.badge);return(0,W.jsxs)(Nt,{to:i,"data-testid":`learn-progress-chip-${e.id}`,className:G(`group inline-flex items-center gap-2 rounded-full border px-3 py-1.5 transition-colors hover:border-primary/40`,r?`border-emerald-500/30 bg-emerald-500/5`:`border-border bg-card`),children:[a&&(0,W.jsx)(a,{className:`size-3.5 text-muted-foreground`}),(0,W.jsx)(`span`,{className:`text-[12px] font-semibold text-foreground`,children:e.title}),(0,W.jsx)(`span`,{className:G(`font-mono text-[10px] font-bold tabular-nums`,r?`text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`),children:r?`done ✓`:`${t}/${n}`})]},e.id)})})]})}var A5=k5;function j5(){let e=GD()??GB,{theme:t}=ji(),[n,r]=(0,U.useState)(()=>typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches);(0,U.useEffect)(()=>{if(t!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=e=>r(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[t]);let i=(0,U.useMemo)(()=>t===`system`?n?`vs-dark`:`vs`:t===`dark`?`vs-dark`:`vs`,[t,n]),a=BI(`/`),o=zI(),s=a?.chapters??[],c=a?.quests??[],l=(0,U.useMemo)(()=>{let e={};for(let{page:t}of o)for(let n of t.quests)e[n.id]=n.label;return e},[o]),u=cK()?.track,{run:d,start:f,finalize:p,end:m}=vK(),[h,g]=(0,U.useState)(null),[_,v]=(0,U.useState)(0),[y,b]=(0,U.useState)(!1),x=(0,U.useCallback)(()=>{g(null),b(!1)},[]),S=(0,U.useCallback)(async(e,t,n)=>{if(t){u?.(sK.chapterExampleRun,{chapter:e});try{let r=await f(n,t,{pageTitle:`Syntax`,sectionTitle:`Chapter ${e}`});g(r.block),v(e=>e+1),b(!0)}catch(e){console.error(`[SyntaxView] failed to persist playground run note:`,e),x(),Q({title:`Could not start workout`,variant:`destructive`})}}},[x,f,u]),C=(0,U.useCallback)(async(e,t)=>{try{(t.logs??[]).length===0?(await m(),x()):await p(t,t.completed)}catch(e){throw console.error(`[SyntaxView] failed to save session:`,e),Q({title:`Session not saved`,variant:`destructive`}),e}},[x,m,p]);return(0,W.jsx)(s1,{children:(0,W.jsxs)(`div`,{"data-testid":`syntax-view`,children:[(0,W.jsx)(nQ,{index:`S`,before:`Syntax `,accentText:`Learning with Examples`,after:``,accent:`hsl(var(--primary))`,blurb:`Six chapters on the syntax, each with a runnable example. Press run to start a timed workout from any chapter.`}),(0,W.jsx)(D5,{wodFiles:e,chapters:s,allQuests:c,theme:i,onRun:S}),(0,W.jsx)(A5,{quests:c,chapters:s,questLabels:l}),(0,W.jsx)(lQ,{}),(0,W.jsx)(g1,{}),h&&y&&d&&(0,W.jsx)(sX,{block:d.block,resultId:d.resultId,autoStart:!0,onClose:x,onCompleteWorkout:C},_)]})})}function M5(){let e=ht();return(0,W.jsxs)(`div`,{className:`h-full flex flex-col items-center justify-center gap-6 p-8 text-center`,children:[(0,W.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-muted`,children:(0,W.jsx)(Ge,{className:`w-8 h-8 text-muted-foreground`})}),(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(`h1`,{className:`text-2xl font-bold tracking-tight`,children:`Page not found`}),(0,W.jsx)(`p`,{className:`text-muted-foreground max-w-sm`,children:`The page you are looking for does not exist or has been moved.`})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>e(`/`),className:`inline-flex items-center gap-2 px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors`,children:[(0,W.jsx)(ge,{className:`w-4 h-4`}),`Go home`]})]})}var N5=(e=0,t=0,n=0,r=0,i=0)=>[e,t,n,r,i],P5=(e,t)=>e.map((e,n)=>e+t[n]),F5=(e,t)=>e.map((e,n)=>e-t[n]),I5=(e,t)=>e.every((e,n)=>e===t[n]),L5=N5(),R5=[`length`,`mass`,`time`,`count`,`energy`];function z5(e){if(I5(e,L5))return`dimensionless`;let t=[];return e.forEach((e,n)=>{e!==0&&t.push(`${R5[n]}${e===1?``:`^`+e}`)}),t.join(` · `)}var B5={m:{dim:N5(1),toBase:1},km:{dim:N5(1),toBase:1e3},mi:{dim:N5(1),toBase:1609.34},kg:{dim:N5(0,1),toBase:1},lb:{dim:N5(0,1),toBase:.4536},ms:{dim:N5(0,0,1),toBase:.001},s:{dim:N5(0,0,1),toBase:1},min:{dim:N5(0,0,1),toBase:60},h:{dim:N5(0,0,1),toBase:3600},reps:{dim:N5(0,0,0,1),toBase:1},cal:{dim:N5(0,0,0,0,1),toBase:1},MET:{dim:L5,toBase:1},pts:{dim:L5,toBase:1},AU:{dim:L5,toBase:1},ratio:{dim:L5,toBase:1},"MET-min":{dim:N5(0,0,1),toBase:60},"reps/min":{dim:F5(N5(0,0,0,1),N5(0,0,1)),toBase:1/60},"m/s":{dim:F5(N5(1),N5(0,0,1)),toBase:1},"min/km":{dim:F5(N5(0,0,1),N5(1)),toBase:60/1e3},"sec/km":{dim:F5(N5(0,0,1),N5(1)),toBase:1/1e3},"min/mi":{dim:F5(N5(0,0,1),N5(1)),toBase:60/1609.34},"km/h":{dim:F5(N5(1),N5(0,0,1)),toBase:1e3/3600},"kg/s":{dim:F5(P5(N5(0,1),N5(0,0,0,1)),N5(0,0,1)),toBase:1},"lb/s":{dim:F5(P5(N5(0,1),N5(0,0,0,1)),N5(0,0,1)),toBase:.4536}},V5=[{dim:F5(N5(0,0,1),N5(1)),name:`pace`,units:[`min/km`,`sec/km`,`min/mi`]},{dim:F5(N5(1),N5(0,0,1)),name:`speed`,units:[`m/s`,`km/h`]},{dim:P5(N5(0,1),N5(0,0,0,1)),name:`volume`,units:[`kg`,`lb`]},{dim:F5(P5(N5(0,1),N5(0,0,0,1)),N5(0,0,1)),name:`power`,units:[`kg/s`,`lb/s`]},{dim:N5(0,0,1),name:`time`,units:[`min`,`s`,`MET-min`]},{dim:N5(0,0,0,1),name:`count`,units:[`reps`]},{dim:N5(1),name:`length`,units:[`m`,`km`,`mi`]},{dim:N5(0,1),name:`mass`,units:[`kg`,`lb`]},{dim:L5,name:`dimensionless`,units:[`pts`,`AU`,`MET`]}],H5=e=>V5.find(t=>I5(t.dim,e)),U5=(e,t=L5)=>({v:e,dim:t}),W5={thruster:{met:6,discipline:`strength`,disciplineFactor:1.2,intensityTier:`high`,resolvedFrom:`bundled`},"pull-up":{met:5,discipline:`gymnastics`,disciplineFactor:1.2,intensityTier:`moderate`,resolvedFrom:`bundled`},run:{met:9.8,discipline:`running`,disciplineFactor:1,intensityTier:`high`,resolvedFrom:`bundled`},squat:{met:5,discipline:`strength`,disciplineFactor:1.2,intensityTier:`moderate`,resolvedFrom:`bundled`}},G5={met:N5(0,0,0,0,0),disciplineFactor:L5},K5={easy:3,moderate:5,hard:7,"all-out":10,max:10},q5={effort:{fields:[`met`,`discipline`,`disciplineFactor`,`intensityTier`,`resolvedFrom`],get:(e,t)=>{let n=W5[e];if(!n)return t===`resolvedFrom`?U5(NaN):void 0;let r=n[t];return typeof r==`number`?{v:r,dim:G5[t]??L5}:void 0}},"rpe-labels":{fields:[`rpe`],get:e=>K5[e]===void 0?void 0:U5(K5[e])}},J5={min:e=>U5(Math.min(...e.map(e=>e.v)),e[0]?.dim??L5),max:e=>U5(Math.max(...e.map(e=>e.v)),e[0]?.dim??L5),abs:e=>U5(Math.abs(e[0].v),e[0].dim),round:e=>U5(e.length>1?+e[0].v.toFixed(e[1].v):Math.round(e[0].v),e[0].dim),floor:e=>U5(Math.floor(e[0].v),e[0].dim),ceil:e=>U5(Math.ceil(e[0].v),e[0].dim),clamp:e=>U5(Math.min(Math.max(e[0].v,e[1].v),e[2].v),e[0].dim),convert:e=>{let t=e[1].unit??``,n=B5[t];if(!n||!I5(n.dim,e[0].dim))throw Error(`convert: ${t} dimension ≠ value dimension`);return{v:e[0].v/n.toBase,dim:e[0].dim}}},Y5=Object.keys(J5).concat([`has`,`lookup`]);function X5(e){let t=[],n=/\s*("(?:[^"]*)"|\d+\.?\d*|[a-zA-Z_][\w.-]*(?::[\w.:*!|,-]+(?:\{[^}]*\})?(?:\s+by\s+\{[^}]*\})?)?|[-+*/(),<>!=]=?|>=|<=|==)/y,r,i=0;for(;i<e.length;){if(n.lastIndex=i,r=n.exec(e),!r||r.index!==i){/\S/.test(e[i])&&t.push({t:`err`,s:e[i]}),i+=1;continue}i=n.lastIndex;let a=r[1];/^".*"$/.test(a)?t.push({t:`str`,s:a.slice(1,-1)}):/^\d/.test(a)?t.push({t:`num`,s:a}):/^[-+*/(),]$/.test(a)||[`>=`,`<=`,`==`,`!=`,`>`,`<`,`=`].includes(a)?t.push({t:`op`,s:a}):t.push({t:`id`,s:a})}return t}function Z5(e){let t=0,n=()=>e[t];function r(i){let a,o=e[t++];if(!o)throw Error(`unexpected end`);if(o.t===`num`)a={k:`num`,v:parseFloat(o.s)};else if(o.t===`str`)a={k:`str`,s:o.s};else if(o.s===`-`)a={k:`neg`,e:r(70)};else if(o.s===`(`){if(a=r(0),n()?.s!==`)`)throw Error(`missing )`);t++}else if(o.t===`id`){if(n()?.s===`(`){t++;let e=[];if(n()?.s!==`)`)for(;;){if(e.push(r(0)),n()?.s===`,`){t++;continue}break}if(n()?.s!==`)`)throw Error(`missing )`);t++,a={k:`call`,f:o.s,args:e}}else a={k:`id`,s:o.s}}else throw Error(`unexpected "${o.s}"`);for(;;){let e=n()?.s,o=e===`*`||e===`/`?60:e===`+`||e===`-`?50:[`<`,`<=`,`>`,`>=`,`==`,`!=`].includes(e)?40:e===`and`?30:e===`or`?20:0;if(!o||o<i)break;t++;let s=r(o+1);a={k:`bin`,op:e,l:a,r:s}}return a}let i=r(0);if(t<e.length)throw Error(`trailing "${e[t].s}"`);return i}function Q5(e,t,n){switch(e.k){case`num`:return U5(e.v);case`str`:return{v:NaN,dim:L5,unit:e.s};case`neg`:{let r=Q5(e.e,t,n);return U5(-r.v,r.dim)}case`id`:{if(/^(sum|avg|max|min|count|last):/.test(e.s)){let t=n(e.s);if(!t)throw Error(`no data for ${e.s}`);return t}let r=t[e.s];if(r===void 0)throw Error(`unknown or absent: ${e.s}`);return r}case`bin`:{if(e.op===`and`)return U5(Q5(e.l,t,n).v&&Q5(e.r,t,n).v?1:0);if(e.op===`or`)return U5(Q5(e.l,t,n).v||Q5(e.r,t,n).v?1:0);let r=Q5(e.l,t,n),i=Q5(e.r,t,n);switch(e.op){case`+`:if(!I5(r.dim,i.dim))throw Error(`+ : ${z5(r.dim)} vs ${z5(i.dim)}`);return U5(r.v+i.v,r.dim);case`-`:if(!I5(r.dim,i.dim))throw Error(`- : ${z5(r.dim)} vs ${z5(i.dim)}`);return U5(r.v-i.v,r.dim);case`*`:return U5(r.v*i.v,P5(r.dim,i.dim));case`/`:return U5(r.v/i.v,F5(r.dim,i.dim));case`<`:return U5(+(r.v<i.v));case`<=`:return U5(+(r.v<=i.v));case`>`:return U5(+(r.v>i.v));case`>=`:return U5(+(r.v>=i.v));case`==`:return U5(+(r.v===i.v));case`!=`:return U5(r.v===i.v?0:1)}throw Error(e.op)}case`call`:{if(e.f===`has`){let r=e.args[0];return r.k===`id`?U5(t[r.s]!==void 0||/^(sum|avg|max|min|count|last):/.test(r.s)&&n(r.s)!==void 0?1:0):U5(0)}if(e.f===`lookup`){let[n,r,i]=e.args,a=n.k===`str`?n.s:``,o=r.k===`str`?r.s:r.k===`id`?String(t[r.s]?.v??r.s):``,s=i.k===`str`?i.s:``,c=q5[a];if(!c)throw Error(`unknown table "${a}"`);if(!c.fields.includes(s))throw Error(`table "${a}" has no field "${s}"`);if(a===`effort`&&s===`resolvedFrom`)return U5(+!!W5[o]);let l=c.get(o,s);if(!l)throw Error(`lookup miss: ${a}/${o}/${s}`);return l}let r=J5[e.f];if(!r)throw Error(`unknown function ${e.f}`);return r(e.args.map((r,i)=>e.f===`convert`&&i>0&&r.k===`id`?{v:NaN,dim:L5,unit:r.s}:Q5(r,t,n)))}}}var $5=[{effort:`thruster`,label:`hard`,reps:21,resistanceKg:43,elapsedMs:95e3},{effort:`pull-up`,reps:21,elapsedMs:6e4},{effort:`thruster`,reps:15,resistanceKg:43,elapsedMs:7e4},{effort:`pull-up`,reps:15,elapsedMs:5e4},{effort:`sled-push`,reps:9,resistanceKg:43,elapsedMs:45e3},{effort:`pull-up`,reps:9,elapsedMs:3e4}],e7=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function t7(e){let t=W5[e.effort]?.met??4,n=!W5[e.effort];return{segmentVolume:e.reps&&e.resistanceKg?U5(e.reps*e.resistanceKg,P5(N5(0,1),N5(0,0,0,1))):void 0,metMinutes:U5(t*(e.elapsedMs/6e4),N5(0,0,1)),metMinutesEstimated:n?U5(1):void 0,effortRpe:e.label?U5(K5[e.label]??0):void 0}}function n7(e){let t={name:``,exprSrc:``,alternates:[],library:!1,bindings:[]};try{let n=e.trim(),r=/\s+when\s+/.exec(n);r&&(t.whenSrc=n.slice(r.index+r[0].length).trim(),n=n.slice(0,r.index));let i=/\s+where\s+/.exec(n);if(i){let e=n.slice(i.index+i[0].length).trim();n=n.slice(0,i.index);for(let n of e.split(/,\s*(?=[a-zA-Z_][\w]*\s*=)/)){let e=n.indexOf(`=`);e>0&&t.bindings.push({name:n.slice(0,e).trim(),src:n.slice(e+1).trim()})}}let a=/\s*->\s*/.exec(n);a&&(t.unit=n.slice(a.index+a[0].length).trim().replace(/\s+(key|grouped).*$/,``),n=n.slice(0,a.index)),/\(library\)/.test(n)&&(t.library=!0,n=n.replace(`(library)`,``));let o=n.indexOf(`=`);if(o<0)throw Error(`expected name = expression`);t.name=n.slice(0,o).trim();let s=n.slice(o+1).trim().split(`|`).map(e=>e.trim());return t.exprSrc=s[0],t.alternates=s.slice(1).map(e=>({src:e.replace(/\s*estimated\s*$/,``),estimated:/\bestimated\b/.test(e)})),t}catch(e){return t.error=e instanceof Error?e.message:String(e),t}}function r7(e,t,n,r){let i=t7(e);return{elapsed:U5(e.elapsedMs/1e3,N5(0,0,1)),reps:e.reps===void 0?void 0:U5(e.reps,N5(0,0,0,1)),resistance:e.resistanceKg===void 0?void 0:U5(e.resistanceKg,N5(0,1)),distance:e.distanceM===void 0?void 0:U5(e.distanceM,N5(1)),effort:U5(NaN),effortLabel:e.label?U5(NaN):void 0,segmentVolume:i.segmentVolume,metMinutes:i.metMinutes,effortRpe:i.effortRpe,sessionRpe:n===void 0?void 0:U5(n),"profile.vo2max":r===void 0?void 0:U5(r),...t}}var i7=e=>e.effort;function a7(e,t,n,r){let i=n7(e),a=[];if(i.error)return{calc:i,diagnostics:[i.error]};let o={calc:i,diagnostics:a},s=e=>e instanceof Error?e.message:String(e);if(t!==`store`){try{Z5(X5(i.exprSrc))}catch(e){a.push(`expression: ${s(e)}`)}for(let e of i.bindings)for(let t of e.src.split(`|`))try{Z5(X5(t.replace(/\s*estimated\s*$/,``)))}catch(t){a.push(`${e.name}: ${s(t)}`)}if(i.whenSrc)try{Z5(X5(i.whenSrc))}catch(e){a.push(`when: ${s(e)}`)}}let c=$5,l=(e,t=c.length)=>{let i=/^(sum|avg|max|min|count|last):([\w.]+)/.exec(e);if(!i)return;let[,a,o]=i,s=c.slice(0,t),l=[];for(let e of s){let t=r7(e,{},n,r)[o];t!==void 0&&!Number.isNaN(t.v)&&l.push(t)}if(o===`sessionLoad`&&e.includes(`by {day}`))return U5(NaN);if(!l.length)return;let u=l[0].dim,d=l.map(e=>e.v);if(a===`sum`)return U5(d.reduce((e,t)=>e+t,0),u);if(a===`avg`)return U5(d.reduce((e,t)=>e+t,0)/d.length,u);if(a===`max`)return U5(Math.max(...d),u);if(a===`min`)return U5(Math.min(...d),u);if(a===`count`)return U5(d.length,N5(0,0,0,1));if(a===`last`)return l[l.length-1]},u=(e,t,n)=>{let r={...t};for(let e of i.bindings){let t=e.src.split(`|`).map(e=>e.replace(/\s*estimated\s*$/,``).trim()),i;for(let e of t)try{i=d(e,r,n);break}catch{}if(i===void 0)throw Error(`${e.name}: no applicable variant`);r[e.name]=i}return d(e,r,n)},d=(e,t,n)=>Q5(Z5(X5(e)),t,e=>l(e,n));try{if(t===`segment`){let e=[],t;c.forEach((a,o)=>{try{let s=r7(a,{},n,r);if(s.effort=void 0,i.whenSrc&&!d(i.whenSrc,s,o+1).v){e.push(null);return}let c=i.exprSrc.replace(/lookup\("effort",\s*effort\s*,/g,`lookup("effort", "${i7(a)}",`).replace(/lookup\("rpe-labels",\s*effortLabel\s*,/g,`lookup("rpe-labels", "${a.label??``}",`),l=u(c,s,o+1);t||=l.dim;let f=i.unit&&i.unit!==`auto`?` ${i.unit}`:t?` [${z5(l.dim)}]`:``;e.push(`${Math.round(l.v*100)/100}${f}`)}catch(t){e.push(`∅ ${s(t)}`)}}),o.perSegment=e,o.dim=t}else if(t===`workout`){let e=[],t;for(let a=1;a<=c.length;a++)try{let s=c[a-1],l=r7(s,{"session.duration":U5(c.slice(0,a).reduce((e,t)=>e+t.elapsedMs,0)/1e3,N5(0,0,1))},n,r);if(i.whenSrc&&!d(i.whenSrc,l,a).v){e.push(null);continue}let f=i.exprSrc.replace(/lookup\("effort",\s*effort\s*,/g,`lookup("effort", "${i7(s)}",`),p,m=`primary`;try{p=u(f,l,a)}catch(e){for(let e of i.alternates)try{p=u(e.src,l,a),m=e.estimated?`estimated`:`alternate`;break}catch{}if(p===void 0)throw e}t=p.dim,e.push(`${Math.round(p.v*100)/100}${i.unit&&i.unit!==`auto`?` `+i.unit:``}${m===`estimated`?` (est.)`:``}`),o.variantUsed=m}catch(t){e.push(`∅ ${s(t)}`)}o.running=e,o.dim=t}else{let e=e7,t=(e,t,n)=>e.map((r,i)=>i+1>=t?n(e.slice(i+1-t,i+1)):NaN),n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=e=>{let t=n(e);return Math.sqrt(n(e.map(e=>(e-t)**2)))},a=i.name,s=[];if(a.includes(`acwr`)){let r=t(e,7,n),i=t(e,28,n);s=e.map((e,t)=>r[t]/i[t])}else if(a.includes(`monotony`)){let i=t(e,7,n),a=t(e,7,r);s=e.map((e,t)=>i[t]/a[t])}else if(a.includes(`strain`)){let i=t(e,7,n),a=t(e,7,r),o=t(e,7,e=>e.reduce((e,t)=>e+t,0));s=e.map((e,t)=>i[t]/a[t]*o[t])}else s=t(e,7,n);o.perSegment=s.slice(-7).map(e=>Number.isNaN(e)?null:String(Math.round(e*100)/100)),o.dim=L5}}catch(e){a.push(s(e))}if(o.dim&&i.unit&&i.unit!==`auto`){let e=B5[i.unit];e?!I5(e.dim,o.dim)&&!I5(e.dim,L5)&&a.push(`unit "${i.unit}" is ${z5(e.dim)} but expression computes ${z5(o.dim)}`):a.push(`unknown unit "${i.unit}"`)}return o}function o7(e,t){let n=/([a-zA-Z_][\w.:-]*|"[\w-]*|)$/.exec(e)[1],r=e.length-n.length,i=e.slice(0,r),a=[],o=(e,t,n)=>a.push({label:e,insert:t,detail:n}),s=/lookup\("([\w-]*)",?\s*("[\w-]*",?\s*)?"?([\w-]*)$/.exec(e);if(s){if(s[2]===void 0&&!e.endsWith(`"`))q5&&Object.keys(q5).forEach(e=>o(e,`"${e}"`,`lookup table`));else{let t=s[1];(e.split(`"`).length<=5&&s[3]!==void 0||/,\s*"[\w-]*$/.test(e))&&(q5[t]?.fields??[]).forEach(e=>o(e,`"${e}"`,`${t} field`)),t===`effort`&&/,\s*$/.test(e)&&Object.keys(W5).concat([`effort`]).forEach(e=>o(e,e===`effort`?`effort`:`"${e}"`,`key`))}return{items:a.filter(e=>e.label.startsWith(n.replace(/"/g,``))),from:r}}return/^(sum|avg|max|min|count|last):[\w.]*$/.test(n)?((t===`segment`?[]:[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`,`sessionLoad`]).forEach(e=>o(e,e,`metric key`)),{items:a.filter(e=>e.label.startsWith(n.split(`:`)[1]??``)),from:r+n.indexOf(`:`)+1}):/->\s*[\w/]*$/.test(i+n)?(Object.keys(B5).forEach(e=>o(e,e,`unit`)),{items:a.filter(e=>e.label.startsWith(n)),from:r}):((t===`segment`?[`elapsed`,`reps`,`resistance`,`distance`,`effort`,`effortLabel`,`segmentVolume`,`metMinutes`,`effortRpe`,`sessionRpe`]:[`sessionRpe`,`session.duration`,`profile.vo2max`]).forEach(e=>o(e,e,t===`segment`?`segment metric / context`:`context node`)),Y5.forEach(e=>o(`${e}()`,`${e}()`,`function`)),[`sum:`,`avg:`,`max:`,`count:`,`last:`].forEach(e=>o(`${e}{}`,e,`WQL atom`)),i.includes(`=`)&&o(`estimated`,`estimated`,`variant origin`),[`when `,`-> `,`where `,`| `,` key `,`(library)`].forEach(e=>o(e.trim(),e,`clause`)),{items:a.filter(e=>e.label.startsWith(n)).slice(0,9),from:r})}var s7={background:`#18181b`,border:`1px solid #3f3f46`,borderRadius:8,padding:12},c7={fontFamily:`ui-monospace, monospace`,fontSize:13};function l7({r:e}){let t=H5(e.dim??L5);return(0,W.jsxs)(`div`,{style:{marginTop:8,fontSize:12},children:[e.dim&&(0,W.jsxs)(`div`,{style:{color:`#a1a1aa`,marginBottom:4},children:[`computes `,(0,W.jsx)(`b`,{style:{color:`#e4e4e7`},children:z5(e.dim)}),t&&t.name!==`dimensionless`&&(0,W.jsxs)(W.Fragment,{children:[` → `,(0,W.jsx)(`span`,{style:{color:`#c084fc`},children:t.name}),` — units: `,t.units.map(t=>(0,W.jsx)(u7,{u:t,active:e.calc.unit===t},t))]})]}),e.diagnostics.map((e,t)=>(0,W.jsxs)(`div`,{style:{color:`#f87171`},children:[`⚠ `,e]},t)),!e.diagnostics.length&&(0,W.jsxs)(`div`,{style:{color:`#34d399`},children:[`✓ valid`,e.variantUsed===`estimated`?` — estimated variant in use`:``]})]})}var u7=({u:e,active:t})=>(0,W.jsx)(`span`,{style:{border:`1px solid ${t?`#c084fc`:`#52525b`}`,borderRadius:4,padding:`0 5px`,marginRight:4,color:t?`#c084fc`:`#a1a1aa`},children:e});function d7({r:e,scope:t,sessionRpe:n,vo2max:r}){return(0,W.jsxs)(`div`,{style:{...s7,minWidth:320},children:[(0,W.jsxs)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:6},children:[`LIVE PREVIEW — `,t===`store`?`last 7 of 28 days (fixture)`:`Fran, 2026-07-28 (fixture)${r?` · VO₂max ${r}`:` · VO₂max unknown`}${n?` · sRPE ${n}`:``}`]}),t===`segment`&&$5.map((t,n)=>(0,W.jsxs)(`div`,{style:{...c7,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,W.jsxs)(`span`,{style:{color:`#71717a`},children:[t.effort,t.reps?` ×${t.reps}`:``,t.resistanceKg?` ${t.resistanceKg}kg`:``]}),(0,W.jsx)(`span`,{style:{color:e.perSegment?.[n]?.startsWith(`∅`)?`#f87171`:`#7dd3fc`},children:e.perSegment?.[n]??`—`})]},n)),t===`workout`&&$5.map((t,n)=>(0,W.jsxs)(`div`,{style:{...c7,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,W.jsxs)(`span`,{style:{color:`#71717a`},children:[`after line `,n+1]}),(0,W.jsx)(`span`,{style:{color:e.running?.[n]?.startsWith(`∅`)?`#f87171`:`#7dd3fc`},children:e.running?.[n]??`—`})]},n)),t===`store`&&(e.perSegment??[]).map((e,t)=>(0,W.jsxs)(`div`,{style:{...c7,display:`flex`,justifyContent:`space-between`,color:`#d4d4d8`},children:[(0,W.jsxs)(`span`,{style:{color:`#71717a`},children:[`D-`,6-t]}),(0,W.jsx)(`span`,{style:{color:`#7dd3fc`},children:e??`—`})]},t))]})}function f7({scope:e,onSrc:t}){let[n,r]=(0,U.useState)(`power`),[i,a]=(0,U.useState)(`reps * resistance / convert(elapsed, s)`),[o,s]=(0,U.useState)(`kg/s`),[c,l]=(0,U.useState)(`has(reps) and has(resistance) and elapsed > 0`),[u,d]=(0,U.useState)(null),f=`${n} = ${i}${o?` -> ${o}`:``}${c?` when ${c}`:``}`,p=(0,U.useMemo)(()=>a7(f,e,void 0,void 0),[f,e]);(0,U.useEffect)(()=>t(f),[f]);let m=[{id:`name`,label:`name`,value:n,set:r,hint:`calc id`},{id:`expr`,label:`=`,value:i,set:a,hint:`expression — metrics, lookups, functions`},{id:`unit`,label:`->`,value:o,set:s,hint:`output unit (auto allowed)`},{id:`when`,label:`when`,value:c,set:l,hint:`applicability predicate`}];return(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`div`,{style:{display:`flex`,gap:6,flexWrap:`wrap`,alignItems:`center`},children:m.map(e=>(0,W.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4},children:[(0,W.jsx)(`span`,{style:{color:`#71717a`,fontSize:12},children:e.label}),(0,W.jsx)(`button`,{onClick:()=>d(u===e.id?null:e.id),style:{...c7,fontSize:12,background:u===e.id?`#3b0764`:`#27272a`,border:`1px solid ${u===e.id?`#c084fc`:`#3f3f46`}`,borderRadius:6,color:`#e4e4e7`,padding:`4px 10px`,cursor:`pointer`,maxWidth:340,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.value||(0,W.jsx)(`span`,{style:{color:`#52525b`},children:`∅`})})]},e.id))}),u&&(0,W.jsxs)(`div`,{style:{...s7,marginTop:8},children:[(0,W.jsx)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:4},children:m.find(e=>e.id===u)?.hint}),(0,W.jsx)(`input`,{autoFocus:!0,value:m.find(e=>e.id===u).value,onChange:e=>m.find(e=>e.id===u).set(e.target.value),style:{...c7,width:`100%`,background:`#09090b`,border:`1px solid #3f3f46`,borderRadius:6,color:`#e4e4e7`,padding:`4px 8px`,outline:`none`}}),(0,W.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`,marginTop:6},children:o7(m.find(e=>e.id===u).value,e).items.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>m.find(e=>e.id===u).set(e.insert),style:{...c7,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:e.label},t))})]}),(0,W.jsx)(`div`,{style:{...c7,marginTop:8,color:`#52525b`,fontSize:12},children:f}),(0,W.jsx)(l7,{r:p})]})}function p7({scope:e,onSrc:t}){let[n,r]=(0,U.useState)(`power`),[i,a]=(0,U.useState)([`reps`,`*`,`resistance`,`/`,`convert(elapsed, s)`]),o=[{group:`metrics`,items:e===`segment`?[`elapsed`,`reps`,`resistance`,`distance`]:[`sum:reps{}`,`sum:distance{}`,`sum:metMinutes{}`,`sum:elapsed{}`]},{group:`functions`,items:[`convert(·, min)`,`convert(·, km)`,`convert(·, s)`,`min(·, 100)`,`round(·)`]},{group:`lookups`,items:[`lookup("effort", effort, "met")`,`lookup("effort", effort, "disciplineFactor")`,`lookup("rpe-labels", effortLabel, "rpe")`]},{group:`operators`,items:[`+`,`-`,`*`,`/`,`(`,`)`]}],s=`${n} = ${i.join(` `)} -> auto`,c=(0,U.useMemo)(()=>a7(s,e,void 0,void 0),[s,e]);(0,U.useEffect)(()=>t(s),[s]);let l=H5(c.dim??L5);return(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`div`,{style:{display:`flex`,gap:8,marginBottom:8,alignItems:`center`},children:[(0,W.jsx)(`span`,{style:{fontSize:12,color:`#71717a`},children:`name`}),(0,W.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),style:{...c7,background:`#09090b`,border:`1px solid #3f3f46`,borderRadius:6,color:`#e4e4e7`,padding:`3px 8px`}})]}),o.map(e=>(0,W.jsxs)(`div`,{style:{marginBottom:6},children:[(0,W.jsx)(`div`,{style:{fontSize:11,color:`#71717a`,marginBottom:3},children:e.group}),(0,W.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`},children:e.items.map(e=>(0,W.jsx)(`button`,{onClick:()=>a(t=>[...t,e]),style:{...c7,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:e},e))})]},e.group)),(0,W.jsxs)(`div`,{style:{...s7,...c7,marginTop:8,color:`#d4d4d8`,minHeight:34},children:[i.map((e,t)=>(0,W.jsx)(`span`,{onClick:()=>a(e=>e.filter((e,n)=>n!==t)),title:`click to remove`,style:{cursor:`pointer`,background:`#27272a`,borderRadius:4,padding:`1px 6px`,marginRight:4,display:`inline-block`},children:e},t)),!i.length&&(0,W.jsx)(`span`,{style:{color:`#52525b`},children:`click palette items to build the formula…`})]}),(0,W.jsxs)(`div`,{style:{fontSize:12,color:`#71717a`,marginTop:6},children:[`unit: `,(0,W.jsx)(`b`,{style:{color:`#c084fc`},children:l?l.units.join(` / `):`—`}),` (derived)`]}),(0,W.jsx)(`div`,{style:{...c7,marginTop:6,color:`#52525b`,fontSize:12},children:s}),(0,W.jsx)(l7,{r:c})]})}var m7={segment:`power = reps * resistance / convert(elapsed, s) -> kg/s when has(reps) and has(resistance) and elapsed > 0`,workout:`sessionLoad = round(rpe * convert(session.duration, min)) -> AU where rpe = sessionRpe | max:effortRpe{} | 5 estimated`,store:`acwr = windowMean(daily, 7d) / windowMean(daily, 28d) -> ratio`};function h7(){let[e,t]=zn(),n=e.get(`v`)??`text`,[r,i]=(0,U.useState)(`segment`),[a,o]=(0,U.useState)(void 0),[s,c]=(0,U.useState)(void 0),[l,u]=(0,U.useState)(m7.segment),[d,f]=(0,U.useState)(``),p=n===`text`?l:d||l,m=(0,U.useMemo)(()=>a7(p,r,a,s),[p,r,a,s]),h=[[`text`,`A · text + completion`],[`slots`,`B · token slots`],[`guided`,`C · guided builder`]];return(0,W.jsxs)(`div`,{style:{background:`#09090b`,minHeight:`100vh`,color:`#e4e4e7`,padding:24,fontFamily:`system-ui`},children:[(0,W.jsxs)(`div`,{style:{maxWidth:1100,margin:`0 auto`},children:[(0,W.jsx)(`div`,{style:{fontSize:11,color:`#f59e0b`,marginBottom:4},children:`PROTOTYPE — throwaway · issue #863`}),(0,W.jsx)(`h1`,{style:{fontSize:20,fontWeight:700,marginBottom:12},children:`Calc-line guided authoring`}),(0,W.jsxs)(`div`,{style:{display:`flex`,gap:12,marginBottom:16,alignItems:`center`,fontSize:13},children:[[`segment`,`workout`,`store`].map(e=>(0,W.jsxs)(`button`,{onClick:()=>{i(e),u(m7[e])},style:{padding:`3px 12px`,borderRadius:6,border:`1px solid ${r===e?`#7dd3fc`:`#3f3f46`}`,background:`none`,color:r===e?`#7dd3fc`:`#a1a1aa`,cursor:`pointer`},children:[e,` scope`]},e)),(0,W.jsx)(`span`,{style:{color:`#3f3f46`},children:`|`}),(0,W.jsxs)(`label`,{style:{color:`#71717a`},children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:!!a,onChange:e=>o(e.target.checked?8:void 0)}),` sRPE captured`]}),(0,W.jsxs)(`label`,{style:{color:`#71717a`},children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:!!s,onChange:e=>c(e.target.checked?42:void 0)}),` VO₂max known`]})]}),(0,W.jsxs)(`div`,{style:{display:`flex`,gap:16,alignItems:`flex-start`},children:[(0,W.jsxs)(`div`,{style:{flex:1},children:[n===`text`&&(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),style:{...s7,...c7,width:`100%`,color:`#e4e4e7`,outline:`none`},placeholder:`name = expression -> unit when predicate`}),(0,W.jsx)(g7,{src:l,scope:r,onApply:e=>u(e)}),(0,W.jsx)(l7,{r:m})]}),n===`slots`&&(0,W.jsx)(f7,{scope:r,onSrc:f}),n===`guided`&&(0,W.jsx)(p7,{scope:r,onSrc:f})]}),(0,W.jsx)(d7,{r:m,scope:r,sessionRpe:a,vo2max:s})]})]}),(0,W.jsx)(`div`,{style:{position:`fixed`,bottom:16,left:`50%`,transform:`translateX(-50%)`,display:`flex`,gap:6,background:`#18181b`,border:`1px solid #3f3f46`,borderRadius:10,padding:6},children:h.map(([e,r])=>(0,W.jsx)(`button`,{onClick:()=>t({v:e}),style:{padding:`4px 14px`,borderRadius:7,border:`none`,background:n===e?`#7dd3fc`:`transparent`,color:n===e?`#09090b`:`#a1a1aa`,cursor:`pointer`,fontSize:13},children:r},e))})]})}function g7({src:e,scope:t,onApply:n}){let r=(0,U.useMemo)(()=>o7(e,t),[e,t]);return r.items.length?(0,W.jsx)(`div`,{style:{display:`flex`,gap:4,flexWrap:`wrap`,marginTop:6},children:r.items.map((t,i)=>(0,W.jsxs)(`button`,{onClick:()=>n(e.slice(0,r.from)+t.insert),style:{...c7,fontSize:12,background:`#27272a`,border:`1px solid #3f3f46`,borderRadius:5,color:`#7dd3fc`,padding:`2px 8px`,cursor:`pointer`},children:[t.label,` `,(0,W.jsx)(`span`,{style:{color:`#52525b`},children:t.detail})]},i))}):null}var _7=`01a09d45-885a-738d-ab1e-be31d44fe919`,v7=`:session{result:${_7}}`,y7=`## Morning session
195
+
196
+ Fran went unbroken until round three. Throat on fire.
197
+
198
+ \`\`\`time
199
+ (21-15-9)
200
+ Thruster 43kg
201
+ Pull-up
202
+ \`\`\``,b7=`Should have paced the first round. Next time: breathing ladder on thrusters.`,x7=[{effort:`Thruster`,round:1,reps:21,load:`43kg`,elapsed:`0:48`},{effort:`Pull-up`,round:1,reps:21,load:`bw`,elapsed:`1:12`},{effort:`Thruster`,round:2,reps:15,load:`43kg`,elapsed:`1:05`},{effort:`Pull-up`,round:2,reps:15,load:`bw`,elapsed:`1:31`},{effort:`Thruster`,round:3,reps:9,load:`43kg`,elapsed:`1:22`},{effort:`Pull-up`,round:3,reps:9,load:`bw`,elapsed:`1:47`}];function S7(e){if(!/:session/.test(e))return{rows:[],note:`no :session head — block would render chart/value instead`};let t=/text:"?([\w-]+)"?/.exec(e)?.[1];return{rows:t?x7.filter(e=>e.effort.toLowerCase().includes(t.toLowerCase())):x7}}function C7({wql:e}){let{rows:t,note:n}=(0,U.useMemo)(()=>S7(e),[e]);return(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-card overflow-hidden`,children:[(0,W.jsxs)(`div`,{className:`flex items-baseline justify-between px-3 py-2 border-b border-border/60 bg-muted/30`,children:[(0,W.jsx)(`span`,{className:`text-xs font-medium text-foreground`,children:`Fran — 2026-09-13`}),(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-mono`,children:n??`${t.length} rows`})]}),t.length===0?(0,W.jsx)(`div`,{className:`px-3 py-4 text-xs text-muted-foreground italic`,children:n??`no rows match`}):(0,W.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,W.jsx)(`thead`,{children:(0,W.jsxs)(`tr`,{className:`text-left text-muted-foreground border-b border-border/40`,children:[(0,W.jsx)(`th`,{className:`px-3 py-1.5 font-medium`,children:`Effort`}),(0,W.jsx)(`th`,{className:`px-3 py-1.5 font-medium`,children:`Rd`}),(0,W.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Reps`}),(0,W.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Load`}),(0,W.jsx)(`th`,{className:`px-3 py-1.5 font-medium text-right`,children:`Split`})]})}),(0,W.jsx)(`tbody`,{children:t.map((e,t)=>(0,W.jsxs)(`tr`,{className:`border-b border-border/20 last:border-0`,children:[(0,W.jsx)(`td`,{className:`px-3 py-1.5`,children:e.effort}),(0,W.jsx)(`td`,{className:`px-3 py-1.5 text-muted-foreground`,children:e.round}),(0,W.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.reps}),(0,W.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.load}),(0,W.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono`,children:e.elapsed})]},t))})]})]})}function w7({children:e}){return(0,W.jsx)(`p`,{className:`text-sm text-foreground/80 whitespace-pre-wrap leading-relaxed`,children:e})}function T7(){return(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-card px-3 py-2`,children:[(0,W.jsx)(`div`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground mb-1`,children:`time · 3 rounds`}),(0,W.jsx)(`div`,{className:`text-xs font-mono text-foreground/90`,children:`21-15-9 · Thruster 43kg · Pull-up`})]})}function E7({wql:e}){return(0,W.jsxs)(`div`,{className:`rounded-lg border border-dashed border-amber-500/40 bg-muted/20 p-3`,children:[(0,W.jsx)(`div`,{className:`text-[10px] text-amber-500 mb-2 font-mono`,children:`note.md — live fence state`}),(0,W.jsxs)(`pre`,{className:`text-[11px] font-mono text-muted-foreground whitespace-pre-wrap leading-relaxed`,children:[y7.split("```time")[0],(0,W.jsx)(`span`,{className:`opacity-50`,children:"```time … ```"}),`
203
+
204
+ `,(0,W.jsxs)(`span`,{className:`text-sky-400 bg-sky-400/10 rounded px-1 -mx-1`,children:["```query:table\n",e,"\n```"]}),`
205
+
206
+ `,b7]})]})}var D7=`✎`;function O7({wql:e,setWql:t}){let[n,r]=(0,U.useState)(!1),[i,a]=(0,U.useState)(e);return(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`relative`,children:[(0,W.jsx)(C7,{wql:e}),!n&&(0,W.jsx)(`button`,{onClick:()=>{a(e),r(!0)},className:`absolute top-2 right-2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted`,children:D7})]}),n&&(0,W.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-card p-3 space-y-2 shadow-lg shadow-sky-500/5`,children:[(0,W.jsx)(`div`,{className:`text-[10px] text-sky-400 font-mono`,children:`editing query:table — Apply writes the fence`}),(0,W.jsx)(aw,{query:i,onQueryChange:a,autoFocus:!0,placeholder:`:session…`}),(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(`button`,{onClick:()=>r(!1),className:`px-3 py-1 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground`,children:`Cancel`}),(0,W.jsx)(`button`,{onClick:()=>{t(i),r(!1)},className:`px-3 py-1 text-xs rounded-md bg-sky-500 text-zinc-950 font-medium`,children:`Apply to fence`})]})]})]})}function k7({wql:e,setWql:t}){let[n,r]=(0,U.useState)(!1);return(0,W.jsxs)(`div`,{className:`space-y-3 pb-24`,children:[(0,W.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left rounded-lg transition-shadow ${n?`ring-2 ring-sky-500/70`:`hover:ring-1 hover:ring-border`}`,children:(0,W.jsx)(C7,{wql:e})}),(0,W.jsxs)(`div`,{className:`sticky bottom-20 rounded-xl border p-3 space-y-2 shadow-xl backdrop-blur transition-colors ${n?`border-sky-500/60 bg-card/95`:`border-border bg-card/80 opacity-70`}`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-mono ${n?`text-sky-400`:`text-muted-foreground`}`,children:n?`◉ bound: query:table · ${_7.slice(0,8)}…`:`○ click a query block to bind the composer`}),n&&(0,W.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-muted-foreground hover:text-foreground`,children:`Done`})]}),n&&(0,W.jsx)(aw,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`})]})]})}function A7({wql:e,setWql:t}){let[n,r]=(0,U.useState)(!1);return(0,U.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&r(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),n?(0,W.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-muted/60 shadow-lg shadow-sky-500/5`,children:[(0,W.jsx)(`div`,{className:`px-3 pt-2 text-[10px] font-mono text-muted-foreground select-none`,children:"```query:table"}),(0,W.jsx)(`div`,{className:`px-3 py-2`,children:(0,W.jsx)(aw,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`,className:`bg-transparent border-0 shadow-none`})}),(0,W.jsxs)(`div`,{className:`px-3 pb-2 flex items-center justify-between`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-mono text-muted-foreground select-none`,children:"```"}),(0,W.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-sky-400 hover:text-sky-300 font-mono`,children:`Esc / leave fence ↩`})]})]}):(0,W.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left hover:ring-1 hover:ring-border rounded-lg`,children:(0,W.jsx)(C7,{wql:e})})}var j7=[[`inline`,`A · in-flow expansion`],[`dock`,`B · bound dock`],[`fence`,`C · fence-as-composer`]];function M7(){let[e,t]=zn(),n=e.get(`v`)??`inline`,[r,i]=(0,U.useState)(v7),a=e=>{let r=j7[(j7.findIndex(([e])=>e===n)+e+j7.length)%j7.length][0];t({v:r})};return(0,U.useEffect)(()=>{let e=e=>{e.target.closest(`input, textarea, [contenteditable]`)||(e.key===`ArrowLeft`&&a(-1),e.key===`ArrowRight`&&a(1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),(0,W.jsxs)(`div`,{className:`min-h-screen bg-background text-foreground p-6`,children:[(0,W.jsxs)(`div`,{className:`max-w-5xl mx-auto grid grid-cols-[1fr_320px] gap-6 items-start`,children:[(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`div`,{className:`text-[11px] text-amber-500 mb-1`,children:`PROTOTYPE — throwaway · query:table editing via WqlComposer`}),(0,W.jsx)(`h1`,{className:`text-xl font-bold`,children:`Journal — 2026-09-13`})]}),(0,W.jsx)(w7,{children:y7.split("```time")[0].trim()}),(0,W.jsx)(T7,{}),n===`inline`&&(0,W.jsx)(O7,{wql:r,setWql:i}),n===`dock`&&(0,W.jsx)(k7,{wql:r,setWql:i}),n===`fence`&&(0,W.jsx)(A7,{wql:r,setWql:i}),(0,W.jsx)(w7,{children:b7})]}),(0,W.jsx)(`div`,{className:`sticky top-6`,children:(0,W.jsx)(E7,{wql:r})})]}),(0,W.jsxs)(`div`,{className:`fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 rounded-xl border border-border bg-card/95 backdrop-blur px-2 py-1.5 shadow-2xl z-50`,children:[(0,W.jsx)(`button`,{onClick:()=>a(-1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`←`}),j7.map(([e,r])=>(0,W.jsx)(`button`,{onClick:()=>t({v:e}),className:`px-3 py-1 rounded-lg text-xs transition-colors ${n===e?`bg-sky-400 text-zinc-950 font-medium`:`text-muted-foreground hover:text-foreground`}`,children:r},e)),(0,W.jsx)(`button`,{onClick:()=>a(1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`→`})]})]})}function N7(e,t,n=`absent`){return{id:e,fields:t,missPolicy:n,get:()=>void 0}}function P7(){let e=new yf;return e.register(N7(`effort`,{met:{dimension:nd,type:`number`},disciplineFactor:{dimension:nd,type:`number`},discipline:{dimension:nd,type:`string`},intensityTier:{dimension:nd,type:`string`},resolvedFrom:{dimension:nd,type:`string`}},`default-row`)),e.register(N7(`rpe-labels`,{rpe:{dimension:nd,type:`number`}})),e.register(N7(`profile`,{vo2max:{dimension:nd,type:`number`}})),e.register(N7(`disciplines`,{disciplineFactor:{dimension:nd,type:`number`}},`default-row`)),e}function F7(e,t){for(let n of t)try{e.register(n)}catch{}}function I7(e,t=`segment`){let n=[],r=[];try{let i=sp(e,{scope:t});r=i.defs;for(let e of i.warnings)n.push({severity:`warning`,message:e})}catch(e){return{defs:r,diagnostics:[{severity:`error`,message:e instanceof Error?e.message:String(e)}],dim:void 0,compound:void 0}}let i=new nf(P7());F7(i,[...xf,...Tf]);let a;for(let e of r){try{i.register(e)}catch(e){n.push({severity:`error`,message:e instanceof Error?e.message:String(e)});continue}let t=xp(e)??(e.kind===`library`?Object.keys(e.variants[0]?.nodes??{})[0]:void 0),r=[...e.variants].sort((e,t)=>t.priority-e.priority)[0],o=t&&r.nodeDims?.[t];o&&(a=o)}let o;return a&&(o=hd(a)),r.length===0&&n.push({severity:`warning`,message:`No calc line parsed.`}),{defs:r,diagnostics:n,dim:a,compound:o}}var L7=[`segment`,`workout`,`store`],R7=[`when`,`where`,`key`,`grouped`,`label`,`emit`,`meta`,`estimated`,`library`,`on`,`by`,`without`,`and`,`or`,`not`],z7=[`convert`,`lookup`,`has`,`round`,`floor`,`ceil`,`abs`,`clamp`,`min`,`max`,`sum`,`avg`,`count`,`last`,`windowMean`,`windowSum`,`windowSd`,`mean`],B7=[{name:`elapsed`,dim:gd.elapsed.dim,detail:`s (time)`},{name:`reps`,dim:gd.reps.dim,detail:`count`},{name:`resistance`,dim:gd.resistance.dim,detail:`kg (mass)`},{name:`distance`,dim:gd.distance.dim,detail:`m (length)`},{name:`effort`,dim:_d.effort,detail:`resolved effort slug`},{name:`effortLabel`,dim:_d.effortLabel,detail:`raw effort label`}],V7=[{name:`sessionRpe`,dim:_d.sessionRpe,detail:`captured session RPE`},{name:`session.duration`,dim:_d[`session.duration`],detail:`workout duration`},{name:`profile.vo2max`,dim:_d[`profile.vo2max`],detail:`user VO₂max (mL/kg/min)`}],H7=Object.keys(gd),U7=Object.keys(vd),W7=[{name:`effort`,detail:`effort catalog`,fields:[`met`,`disciplineFactor`,`discipline`,`intensityTier`,`resolvedFrom`]},{name:`rpe-labels`,detail:`effort label → RPE`,fields:[`rpe`]},{name:`profile`,detail:`user profile`,fields:[`vo2max`]},{name:`disciplines`,detail:`canonical disciplines`,fields:[`disciplineFactor`]}],G7=Object.keys(Sd),K7=Object.keys(vd);function q7(e){if(!e)return G7;let t=G7.filter(t=>{let n=Sd[t];return n?n.dim.every((t,n)=>t===e[n]):!1});return t.length?t:G7}var J7=new Set([...R7,...L7,`lookup`]),Y7=new Set(z7),X7=new Set([...B7.map(e=>e.name),...V7.map(e=>e.name),...H7,...W7.map(e=>e.name)]),Z7=/^\d*\.?\d+(?:d)?/,Q7=/^[A-Za-z_][\w.]*/,$7=wr.define({name:`calcLine`,token(e){if(e.eatSpace())return null;if(e.match(`#`,!1))return e.skipToEnd(),`comment`;if(e.match(/^"([^"]*)"/)||e.match(/^'([^']*)'/))return`string`;if(e.match(/^(->|==|!=|<=|>=)/)||e.match(/^[+\-*/=<>(),:{}[\]]/))return`operator`;if(e.match(Z7))return`number`;if(e.match(Q7)){let t=e.current();return J7.has(t)?`keyword`:Y7.has(t)?`function`:(X7.has(t),`variableName`)}return e.next(),null}}),e9=jr.define([{tag:H.keyword,color:`#c084fc`},{tag:H.function(H.variableName),color:`#60a5fa`},{tag:H.variableName,color:`#e4e4e7`},{tag:H.number,color:`#fbbf24`},{tag:H.string,color:`#34d399`},{tag:H.operator,color:`#a1a1aa`},{tag:H.comment,color:`#71717a`,fontStyle:`italic`}]);function t9(){return new Pr($7,[Ar(e9)])}var n9=[`effort`,`thruster`,`push-press`,`front-squat`,`wall-ball`,`row`,`run`];function r9(e={}){let t=e.scope??`segment`;return e=>{let n=e.state.sliceDoc(0,e.pos),r=e.matchBefore(/[\w./"]*/);if(!r)return null;if(/lookup\(\s*/.test(n)){let t=n.lastIndexOf(`lookup(`),r=n.slice(t+7);if(!/,/.test(r)&&/^"?[\w.-]*"?$/.test(r.replace(/"/g,``).trim()||``)){let t=r.replace(/"/g,``).trim(),n=W7.filter(e=>e.name.startsWith(t)).map(e=>({label:e.name,insert:`"${e.name}"`,detail:e.detail}));if(n.length)return{from:e.pos-t.length,options:n,validFor:/^[\w.-]*$/}}let i=/lookup\(\s*"[^"]+"\s*,\s*[^,]+,\s*"?([\w-]*)"?$/.exec(n);if(i){let t=/lookup\(\s*"([^"]+)"/.exec(n)?.[1],r=(W7.find(e=>e.name===t)?.fields??[]).filter(e=>e.startsWith(i[1])).map(e=>({label:e,insert:`"${e}"`,detail:`${t} field`}));return{from:e.pos-i[1].length,options:r,validFor:/^[\w-]*$/}}let a=/lookup\(\s*"(effort)"\s*,\s*"?([\w.-]*)"?$/.exec(n);if(a){let t=n9.filter(e=>e.startsWith(a[2])).map(e=>({label:e,insert:e===`effort`?e:`"${e}"`,detail:`effort key`}));return{from:e.pos-a[2].length,options:t,validFor:/^[\w.-]*$/}}}let i=/->\s*([\w/]*)$/.exec(n);if(i){let n=e.state.doc.lineAt(e.pos).text,r=I7(n,t),a=r.diagnostics.length===0?r.dim:void 0,o=q7(a).filter(e=>e.startsWith(i[1])).map(e=>({label:e,detail:a?`matches inferred dimension`:`unit`}));return{from:e.pos-i[1].length,options:o,validFor:/^[\w/]*$/}}if(t===`store`){let e=/^(sum|avg|max|min|count|last):([\w.]*)$/.exec(r.text);if(e){let t=H7.filter(t=>t.startsWith(e[2])).map(e=>({label:e,detail:`metric key`}));return{from:r.from+r.text.indexOf(`:`)+1,options:t,validFor:/^[\w.]*$/}}}let a=[];if(t===`segment`)a.push(...B7.map(e=>({label:e.name,insert:e.name,detail:e.detail})));else if(a.push(...V7.map(e=>({label:e.name,insert:e.name,detail:e.detail}))),t===`workout`){for(let e of U7)for(let t of[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`])a.push({label:`${e}(${t})`,insert:`${e}(${t})`,detail:`aggregate`});a.push({label:`sum(reps, without: rest)`,insert:`sum(reps, without: rest)`,detail:`exclusion aggregate`})}a.push(...z7.map(e=>({label:`${e}()`,insert:`${e}()`,detail:`function`}))),t===`store`&&a.push(...K7.map(e=>({label:`${e}:{}`,insert:`${e}:`,detail:`WQL atom`}))),a.push(...R7.map(e=>({label:e,insert:e===`when`?`when `:e,detail:`clause`}))),a.push({label:`estimated`,insert:`estimated`,detail:`variant origin`}),a.push({label:`(library)`,insert:`(library)`,detail:`library calc`});let o=a.filter(e=>e.label.startsWith(r.text)).slice(0,20);return o.length?{from:r.from,options:o,validFor:/^[\w./]*$/}:null}}function i9(e){return Jr({override:[r9(e)]})}function a9({value:e,onChange:t,scope:n=`segment`,placeholder:r,readOnly:i=!1,autoFocus:a=!1,className:o}){let s=(0,U.useRef)(null),c=(0,U.useRef)(null),l=(0,U.useRef)(t);return l.current=t,(0,U.useEffect)(()=>{let t=s.current;if(!t)return;c.current?.destroy();let r=Er.updateListener.of(e=>{e.docChanged&&l.current(e.state.doc.toString())}),o=new Er({state:ri.create({doc:e,extensions:[t9(),i9({scope:n}),Qr(),pi(),yr.of([ti,...$r,...ci]),Er.lineWrapping,ri.readOnly.of(i),r,Er.theme({"&":{height:`auto`,minHeight:`120px`,fontSize:`13px`,border:`1px solid rgb(63 63 70)`,borderRadius:`8px`},".cm-scroller":{fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,lineHeight:`1.55`},".cm-content":{padding:`8px 4px`},".cm-gutters":{borderRight:`1px solid rgb(63 63 70)`,minWidth:`28px`},"&.cm-focused":{outline:`2px solid rgb(139 92 246 / 0.5)`,outlineOffset:`1px`}})]}),parent:t});return a&&requestAnimationFrame(()=>o.focus()),c.current=o,()=>o.destroy()},[n,i]),(0,U.useEffect)(()=>{let t=c.current;if(!t)return;let n=t.state.doc.toString();n!==e&&t.dispatch({changes:{from:0,to:n.length,insert:e}})},[e]),(0,W.jsx)(`div`,{ref:s,className:`calc-line-editor ${o??``}`,"data-testid":`calc-line-editor`})}function o9({analysis:e}){let{dim:t,compound:n,diagnostics:r}=e,i=r.filter(e=>e.severity===`error`),a=r.filter(e=>e.severity===`warning`),o=i.length===0&&a.length===0&&t!==void 0;return(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 px-3 py-2 text-xs`,"data-testid":`calc-diagnostics`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[t?(0,W.jsxs)(`div`,{className:`text-muted-foreground`,children:[`computes `,(0,W.jsx)(`b`,{className:`text-foreground`,children:c9(t)}),n&&(0,W.jsxs)(`span`,{className:`text-purple-400 dark:text-purple-300`,children:[` → `,n]})]}):!o&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`dimension unknown`}),o&&(0,W.jsx)(`span`,{className:`text-signal-positive`,children:`✓ valid`})]}),i.map((e,t)=>(0,W.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e.message]},`e-${t}`)),a.map((e,t)=>(0,W.jsxs)(`div`,{className:`text-signal-caution`,children:[`⚠ `,e.message]},`w-${t}`)),i.length===0&&a.length===0&&t===void 0&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`Type a calc line to see diagnostics.`})]})}var s9=[[`L`,`length`],[`M`,`mass`],[`T`,`time`],[`C`,`count`],[`E`,`energy`]];function c9(e){let t=[];return e.forEach((e,n)=>{e!==0&&t.push(e===1?s9[n][1]:`${s9[n][1]}${e}`)}),t.length?t.join(`·`):`dimensionless`}function l9(e){return new ga({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function u9(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function d9(e){return e.output?.emitType??e.output?.key??e.id}function f9(e,t){for(let n of e){if(n.outputType!==`analytics`||!(n.metrics.find(e=>e.type?.toLowerCase()===`label`&&String(e.value)===t)??n.metrics.find(e=>String(e.value)===t)))continue;let e=n.metrics.find(e=>typeof e.value==`number`);if(e)return{value:e.value,unit:e.unit,origin:e.origin}}}function p9(e){return String(Number.isInteger(e)?e:Math.round(e*100)/100)}function m9(e,t,n){return If(e,{userProfile:t.vo2max===void 0?void 0:{vo2max:t.vo2max},calcs:n}).engine}function h9(e){let t=[],n=e.defs[0];if(!n)return{rows:[],errors:[`No calc line to preview.`]};let r=d9(n),i=e.logs.filter(e=>e.outputType===`segment`);if(e.scope===`segment`){let n=m9(e.block,e,e.defs),a=[];for(let e of i){let t=n.run(l9(u9(e))).metrics.rawMetrics.find(e=>e.type===r);if(!t){a.push(null);continue}let i=typeof t.value==`number`?t.value:NaN;if(!Number.isFinite(i)){a.push(null);continue}a.push({label:e.metrics.find(e=>e.type===`effort-data`)?.value?.label??`segment`,text:p9(i),unit:t.unit,estimated:t.origin===`analyzed-estimated`,raw:i})}return{rows:a,errors:t}}if(e.scope===`workout`){let n=i.map(u9),a=[];for(let t=1;t<=n.length;t++){let i=m9(e.block,e,e.defs);for(let e=0;e<t;e++)i.run(l9(n[e]));let o=f9(i.finalize(),r),s=o&&typeof o.value==`number`?o.value:NaN;o&&Number.isFinite(s)?a.push({label:`after line ${t}`,text:p9(s),unit:o.unit,estimated:o.origin===`analyzed-estimated`,raw:s}):a.push(null)}return{rows:a,errors:t}}return _9(n,t)}var g9=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function _9(e,t){let n=[],r=e.variants[0]?.nodes[xp(e)??`value`]?.expression??``,i=e=>e.reduce((e,t)=>e+t,0)/e.length,a=e=>{let t=i(e);return Math.sqrt(i(e.map(e=>(e-t)**2)))},o=(e,t)=>g9.map((n,r)=>r+1>=e?t(g9.slice(r+1-e,r+1)):NaN),s=o(7,i),c=o(28,i),l=o(7,a),u=o(7,e=>e.reduce((e,t)=>e+t,0)),d=r.includes(`windowSd`)||r.length===0?s.map((e,t)=>e/l[t]):s.map((e,t)=>e/c[t]);return v9(r.includes(`windowSum`)||r.includes(` * sum`)?u:d,n),{rows:[],series:n,errors:t}}function v9(e,t){for(let n of e.slice(-7))t.push(Number.isNaN(n)?null:Number(Math.round(n*100)/100))}var y9=[{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:21,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:21,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:15,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:15,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:9,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:9,resistanceKg:0}];function b9(e){return{type:`effort-data`,origin:`analyzed`,value:{slug:e.slug,label:e.label,aliases:[],baseAttributes:{met:e.met,discipline:e.discipline},registrySource:`bundled`}}}function x9(e,t){let n=[b9(e)];return n.push({type:`elapsed`,value:e.elapsedMs,origin:`runtime`}),e.reps!==void 0&&n.push({type:`rep`,value:e.reps,origin:`runtime`}),e.resistanceKg!==void 0&&n.push({type:`resistance`,value:e.resistanceKg,origin:`runtime`}),fN(new ga({outputType:`segment`,timeSpan:{started:t*1e3,ended:t*1e3+e.elapsedMs},sourceBlockKey:`preview-block`,stackLevel:1,metrics:n}))}function S9(){return{id:`preview-block`,dialect:`time`,startLine:0,endLine:10,content:"```time\nFran preview\n```",state:`idle`,widgetIds:{},version:1,createdAt:0}}var C9=y9.map((e,t)=>x9(e,t+1)),w9=S9();function T9(e){return e==null?`—`:String(e)}function E9({scope:e,analysis:t,vo2max:n}){let r=(0,U.useMemo)(()=>t.defs.filter(()=>t.diagnostics.length===0),[t]),i=r[0],a=(0,U.useMemo)(()=>{if(i)return h9({logs:C9,block:w9,defs:r,scope:e,vo2max:n})},[i,e,n]);return(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 p-3 text-xs`,"data-testid":`calc-preview`,children:[(0,W.jsxs)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wide text-muted-foreground`,children:[`Live preview — `,e===`store`?`last 7 of 28 fixture days`:`Fran (fixture)`]}),!i&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`Enter a valid calc line to see live results.`}),i&&a?.rows&&(0,W.jsxs)(`div`,{className:`space-y-1 font-mono`,children:[a.rows.length===0&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`No applicable segments.`}),a.rows.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:e?e.label:`segment ${t+1}`}),(0,W.jsx)(`span`,{className:e?`text-sky-300 dark:text-sky-400`:`text-muted-foreground`,children:e?`${e.text}${e.unit?` ${e.unit}`:``}${e.estimated?` (est.)`:``}`:`—`})]},t))]}),i&&a?.series&&(0,W.jsx)(`div`,{className:`space-y-1 font-mono`,children:a.series.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,W.jsxs)(`span`,{className:`text-muted-foreground`,children:[`D-`,6-t]}),(0,W.jsx)(`span`,{className:`text-sky-300 dark:text-sky-400`,children:T9(e)})]},t))}),a?.errors?.length?a.errors.map((e,t)=>(0,W.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e]},`e-${t}`)):null]})}var D9=[`segment`,`workout`,`store`];function O9(e,t){let n=e[0]?.id;if(n)return n;let r=/^[\s\S]*?^\s*([A-Za-z_][\w.-]*)\s*=.*$/m.exec(t);return r?r[1]:`custom-${Date.now().toString(36)}`}function k9({defaultScope:e=`segment`,initialId:t}){let[n,r]=(0,U.useState)(`# ${e} calc line
207
+ segmentVolume = reps * resistance (library) when has(reps) and has(resistance)
208
+ `),[i,a]=(0,U.useState)(e),[o,s]=(0,U.useState)([]),[c,l]=(0,U.useState)(),u=(0,U.useMemo)(()=>I7(n,i),[n,i]),d=O9(u.defs,n),f=u.diagnostics.every(e=>e.severity!==`error`)&&u.defs.length>0,p=async()=>{s(await j3())};(0,U.useEffect)(()=>{p()},[]),(0,U.useEffect)(()=>{t&&(async()=>{let e=(await j3()).find(e=>e.id===t);e&&(r(e.lineForm),l(`Loaded "${e.id}".`))})()},[t]);let m=async()=>{if(!f){l(`Cannot save: fix the errors first.`);return}try{await M3({id:d,lineForm:n,updatedAt:Date.now()}),await p(),l(`Saved "${d}".`)}catch(e){console.error(`[CalcAuthoringPanel] save failed:`,e),l(`Save failed: ${e instanceof Error?e.message:String(e)}`)}},h=async e=>{try{await N3(e),await p(),l(`Deleted "${e}".`)}catch(e){console.error(`[CalcAuthoringPanel] delete failed:`,e),l(`Delete failed: ${e instanceof Error?e.message:String(e)}`)}},g=e=>{let t=/^\s*(segment|workout|store)\b/.exec(e.lineForm);t&&a(t[1]),r(e.lineForm),l(`Loaded "${e.id}".`)};return(0,W.jsxs)(`div`,{className:`space-y-3`,"data-testid":`calc-authoring-panel`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Scope`}),(0,W.jsx)(`div`,{className:`flex gap-1`,children:D9.map(e=>(0,W.jsx)(`button`,{onClick:()=>a(e),className:`rounded px-2.5 py-1 text-xs font-medium transition-colors ${i===e?`bg-purple-600 text-white dark:bg-purple-700 dark:text-white`:`bg-muted text-muted-foreground hover:bg-muted/80`}`,children:e},e))}),(0,W.jsx)(`div`,{className:`ml-auto flex gap-2`,children:(0,W.jsx)(`button`,{onClick:m,disabled:!f,className:`rounded bg-signal-positive px-3 py-1 text-xs font-medium text-white dark:text-white disabled:opacity-40`,children:`Save`})})]}),(0,W.jsx)(a9,{value:n,onChange:r,scope:i,autoFocus:!0}),(0,W.jsx)(o9,{analysis:u}),(0,W.jsx)(E9,{scope:i,analysis:u}),c&&(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:c}),o.length>0&&(0,W.jsxs)(`div`,{className:`mt-2`,children:[(0,W.jsx)(`div`,{className:`mb-1 text-[11px] uppercase tracking-wide text-muted-foreground`,children:`Saved user calcs`}),(0,W.jsx)(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,children:o.map(e=>(0,W.jsxs)(`li`,{className:`flex items-center justify-between px-3 py-2 text-sm`,children:[(0,W.jsx)(`button`,{onClick:()=>g(e),className:`text-left font-mono text-purple-300 dark:text-purple-400 hover:underline`,children:e.id}),(0,W.jsx)(`button`,{onClick:()=>h(e.id),className:`text-xs text-muted-foreground hover:text-destructive`,children:`delete`})]},e.id))})]})]})}function A9(){let e=ht(),[t]=Gt(`zip`),[n]=Gt(`z`),[r]=(0,U.useState)(()=>{let e=window.location.search;return e.includes(`zip=`)||e.includes(`z=`)});return(0,U.useEffect)(()=>{!t&&!n&&!r&&e(`/`,{replace:!0})},[t,n,e,r]),(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}async function j9(e){try{let t=e.replace(/-/g,`+`).replace(/_/g,`/`);for(;t.length%4!=0;)t+=`=`;let n=atob(t),r=Uint8Array.from(n,e=>e.charCodeAt(0));try{let e=new DecompressionStream(`gzip`),t=e.writable.getWriter(),n=e.readable.getReader();t.write(r),t.close();let i=[];for(;;){let{done:e,value:t}=await n.read();if(e)break;i.push(t)}let a=i.reduce((e,t)=>e+t.length,0),o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.length;return new TextDecoder().decode(o)}catch{return new TextDecoder().decode(r)}}catch{return null}}function M9(){let e=ht(),t=Xt(),{date:n}=xn(),[r]=Gt(`zip`),[i,a]=(0,U.useState)({state:`loading`});return(0,U.useEffect)(()=>{if(!(t.pathname===`/load/journal`||t.pathname.startsWith(`/load/journal/`)))return;if(!r){e($.journal,{replace:!0});return}let i=!1,o=async()=>{try{a({state:`loading`});let t;try{t=await j9(r)}catch(e){console.error(`Failed to decode zip:`,e),a({state:`error`,error:`Failed to decode the journal entry`,onRetry:()=>{o()}}),Q({title:`Error`,description:`Failed to decode the journal entry. Please check the link.`,variant:`destructive`});return}if(i)return;let c;if(n){let t=LN(n);if(!t){a({state:`error`,error:`Invalid date format`}),Q({title:`Error`,description:`Invalid date format. Expected YYYY-MM-DD.`,variant:`destructive`}),e($.journal,{replace:!0});return}c=t.dateKey}else c=FN();if(i)return;if(IN(c)){a({state:`pending-confirmation`,content:t,dateKey:c,onConfirmBackdate:async()=>{i||await s(t,c)}});return}await s(t,c)}catch(e){console.error(`Unexpected error in journal zip processor:`,e),i||(a({state:`error`,error:`An unexpected error occurred`,onRetry:()=>{o()}}),Q({title:`Error`,description:`An unexpected error occurred.`,variant:`destructive`}))}},s=async(t,n)=>{if(!i)try{a({state:`creating`});let r=await BN.create({journalDate:n,title:n,rawContent:t});i||(a({state:`success`,content:t,dateKey:n}),e(VM(r.id),{replace:!0}))}catch(e){console.error(`Failed to create journal entry:`,e),i||(a({state:`error`,error:`Failed to create journal entry`,onRetry:()=>{s(t,n)}}),Q({title:`Error`,description:`Failed to create journal entry.`,variant:`destructive`}))}};return o(),()=>{i=!0}},[r,n,e]),i}var N9=({selectedDate:e,onImportToday:t,onDateSelect:n,entryDates:r,isLoading:i=!1,className:a})=>{let[o,s]=(0,U.useState)(!1),[c,l]=(0,U.useState)(!1),{triggerRef:u,align:d,recompute:f}=z$(`end`),p=async()=>{l(!0);try{await t()}finally{l(!1)}},m=async e=>{l(!0),s(!1);try{await n(e)}finally{l(!1)}},h=e=>{e&&f(),s(e)},g=e?BO(e):`Date`,_=i||c;return(0,W.jsxs)(`div`,{className:G(`inline-flex items-stretch rounded-lg overflow-hidden border border-border/70`,`bg-muted text-muted-foreground shadow-sm hover:shadow-md transition-shadow font-medium`,`text-xs`,a),children:[(0,W.jsxs)(`button`,{type:`button`,title:`Import to today's journal`,onClick:p,disabled:_,className:G(`flex items-center gap-2 px-3 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,_&&`opacity-60 cursor-not-allowed`),children:[c?(0,W.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}):(0,W.jsx)(Ft,{className:`h-4 w-4 shrink-0`}),(0,W.jsx)(`span`,{children:`Import Today`})]}),(0,W.jsx)(`div`,{className:`w-px bg-border/60 self-stretch`}),(0,W.jsxs)(Hz,{open:o,onOpenChange:h,children:[(0,W.jsx)(Uz,{asChild:!0,children:(0,W.jsxs)(`button`,{ref:e=>{u.current=e},type:`button`,title:`Select a date to plan for the future`,className:G(`flex items-center gap-1.5 px-2.5 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,e&&`text-primary`,_&&`opacity-60 cursor-not-allowed`),disabled:_,children:[(0,W.jsx)(mn,{className:`h-4 w-4 shrink-0`}),e&&(0,W.jsx)(`span`,{className:`leading-none text-xs`,children:g})]})}),(0,W.jsx)(Wz,{align:d,className:`p-0 w-auto`,children:(0,W.jsx)(s$,{selectedDate:e||null,onDateSelect:m,entryDates:r})})]})]})},P9=({dateKey:e,onConfirm:t,onCancel:n,isLoading:r=!1})=>{let[i,a]=U.useState(!1),o=zO(new Date(`${e}T00:00:00`));return(0,W.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-50 flex items-center justify-center`,onKeyDown:e=>{e.key===`Escape`&&n()},onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,W.jsx)(`div`,{className:`absolute inset-0 bg-black/50 animate-in fade-in`}),(0,W.jsx)(`div`,{className:`relative z-10 w-full max-w-sm mx-auto px-4 animate-in zoom-in-95 fade-in`,children:(0,W.jsxs)(`div`,{className:`bg-background rounded-lg border border-border shadow-lg`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border`,children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold`,children:`Backdate Journal Entry`}),(0,W.jsx)(`button`,{onClick:n,className:`p-1 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors`,"aria-label":`Close modal`,children:(0,W.jsx)(we,{className:`h-4 w-4`})})]}),(0,W.jsxs)(`div`,{className:`px-6 py-4 space-y-4`,children:[(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The date you selected is in the past.`}),(0,W.jsxs)(`p`,{className:`text-sm`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Import to: `}),(0,W.jsx)(`span`,{className:`font-medium text-foreground`,children:o})]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This will create a journal entry for the selected date. Are you sure you want to proceed?`})]}),(0,W.jsxs)(`div`,{className:`px-6 py-4 border-t border-border flex gap-2 justify-end`,children:[(0,W.jsx)(K,{variant:`outline`,onClick:n,disabled:r||i,children:`Cancel`}),(0,W.jsx)(K,{onClick:async()=>{a(!0);try{await t()}finally{a(!1)}},disabled:r||i,className:G(r||i?`opacity-70`:``),children:i?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`inline-block animate-spin mr-2`,children:`⏳`}),`Importing...`]}):`Confirm & Import`})]})]})})]})},F9={h1:({children:e})=>(0,W.jsx)(`h1`,{className:`text-3xl font-bold mt-8 mb-4 first:mt-0 text-foreground`,children:e}),h2:({children:e})=>(0,W.jsx)(`h2`,{className:`text-2xl font-bold mt-6 mb-3 text-foreground`,children:e}),h3:({children:e})=>(0,W.jsx)(`h3`,{className:`text-xl font-semibold mt-5 mb-2 text-foreground`,children:e}),h4:({children:e})=>(0,W.jsx)(`h4`,{className:`text-lg font-semibold mt-4 mb-2 text-foreground`,children:e}),h5:({children:e})=>(0,W.jsx)(`h5`,{className:`text-base font-semibold mt-3 mb-1 text-foreground`,children:e}),h6:({children:e})=>(0,W.jsx)(`h6`,{className:`text-sm font-semibold mt-2 mb-1 text-muted-foreground`,children:e}),p:({children:e})=>(0,W.jsx)(`p`,{className:`text-sm leading-relaxed mb-4 text-muted-foreground`,children:e}),strong:({children:e})=>(0,W.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,W.jsx)(`em`,{className:`italic text-muted-foreground`,children:e}),ul:({children:e})=>(0,W.jsx)(`ul`,{className:`list-disc list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),ol:({children:e})=>(0,W.jsx)(`ol`,{className:`list-decimal list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),li:({children:e})=>(0,W.jsx)(`li`,{className:`ml-2`,children:e}),code:({children:e,className:t})=>t?null:(0,W.jsx)(`code`,{className:`px-1.5 py-0.5 rounded bg-muted text-primary font-mono text-xs`,children:e}),pre:({children:e})=>(0,W.jsx)(`pre`,{className:`bg-muted rounded-lg p-4 overflow-x-auto mb-4 text-xs font-mono text-muted-foreground border border-border`,children:e}),blockquote:({children:e})=>(0,W.jsx)(`blockquote`,{className:`border-l-4 border-primary/30 pl-4 py-2 mb-4 italic text-muted-foreground text-sm`,children:e}),a:({href:e,children:t})=>(0,W.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary hover:underline font-medium`,children:t}),table:({children:e})=>(0,W.jsx)(`div`,{className:`my-4 overflow-x-auto rounded border border-border`,children:(0,W.jsx)(`table`,{className:`w-full text-xs`,children:e})}),thead:({children:e})=>(0,W.jsx)(`thead`,{className:`bg-muted/50`,children:e}),tbody:({children:e})=>(0,W.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e}),tr:({children:e})=>(0,W.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e}),th:({children:e})=>(0,W.jsx)(`th`,{className:`px-3 py-2 text-left font-semibold text-foreground text-xs`,children:e}),td:({children:e})=>(0,W.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:e}),hr:()=>(0,W.jsx)(`hr`,{className:`my-6 border-border/50`})};function I9(){let e=ht(),t=M9(),[n,r]=(0,U.useState)(!1),[i,a]=(0,U.useState)(null),{state:o,content:s,dateKey:c,error:l,onConfirmBackdate:u,onRetry:d}=t;return(0,W.jsxs)(`div`,{className:`flex flex-col h-screen bg-background`,children:[(0,W.jsxs)(`div`,{className:`border-b border-border/50 bg-muted/30 px-6 py-4 flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(`button`,{onClick:()=>{e(-1)},className:`p-1.5 rounded hover:bg-muted transition-colors text-muted-foreground hover:text-foreground`,title:`Go back`,children:(0,W.jsx)(Fe,{className:`h-5 w-5`})}),(0,W.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Journal Entry`})]}),o===`loading`?(0,W.jsxs)(`div`,{className:`text-xs text-muted-foreground flex items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}),`Preparing preview...`]}):o===`error`?(0,W.jsx)(K,{variant:`outline`,size:`sm`,onClick:d,children:`Retry`}):o===`pending-confirmation`||o===`creating`?null:(0,W.jsx)(N9,{selectedDate:i,onImportToday:async()=>{u&&await u()},onDateSelect:async e=>{a(e);let t=new Date;t.setHours(0,0,0,0);let n=new Date(e);n.setHours(0,0,0,0),n<t?r(!0):u&&await u()},isLoading:o===`creating`})]}),(0,W.jsxs)(`div`,{className:`flex-1 overflow-auto px-6 py-6`,children:[o===`loading`&&(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,W.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading preview...`})]}),o===`error`&&(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,W.jsx)(`div`,{className:`bg-destructive/10 border border-destructive/50 rounded-lg p-4 max-w-md`,children:(0,W.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,W.jsx)(vn,{className:`h-5 w-5 text-destructive mt-0.5 shrink-0`}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`font-semibold text-foreground`,children:`Error Loading Preview`}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:l||`Failed to decode the zip content`})]})]})}),(0,W.jsx)(K,{onClick:d,variant:`outline`,children:`Try Again`})]}),o===`pending-confirmation`&&(0,W.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,W.jsxs)(`div`,{className:`text-center`,children:[(0,W.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`Backdate Confirmation Required`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm mb-4`,children:`This date is in the past. Please confirm to proceed.`})]})}),o===`creating`&&(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,W.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Creating journal entry...`})]}),o===`success`&&(0,W.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,W.jsxs)(`div`,{className:`text-center`,children:[(0,W.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`✓ Entry Created`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Redirecting...`})]})}),o===`loading`||o===`error`||o===`pending-confirmation`||o===`creating`||o===`success`?null:s?(0,W.jsx)(`article`,{className:`prose prose-sm max-w-2xl mx-auto`,children:(0,W.jsx)(gn,{remarkPlugins:[Un],components:F9,children:s})}):null]}),n&&c&&(0,W.jsx)(P9,{dateKey:c,onConfirm:async()=>{u&&(r(!1),await u())},onCancel:()=>r(!1),isLoading:o===`creating`})]})}function L9(){let e=Xt(),t=ht(),[n,r]=(0,U.useState)({kind:`loading`}),[i,a]=(0,U.useState)(!1),[o,s]=(0,U.useState)(!1),[c,l]=(0,U.useState)(null);(0,U.useEffect)(()=>{let n=!0,i=new URLSearchParams(e.search).get(`source`);if(!i){t($.catalogs,{replace:!0});return}return r({kind:`loading`}),a(!1),l(null),(async()=>{try{let e=new URL(i);if(e.protocol!==`https:`||e.username||e.password||e.search||e.hash)throw Error(`Enter an HTTPS seed directory URL without credentials, query parameters, or a fragment.`);e.pathname.endsWith(`/`)||(e.pathname+=`/`);let t=await new kA(e.href).fetchManifest();n&&r({kind:`ready`,url:e.href,manifest:t})}catch(e){n&&r({kind:`error`,message:e instanceof Error?e.message:`Unable to read the seed manifest.`})}})(),()=>{n=!1}},[e.search,t]);let u=async e=>{if(!(n.kind!==`ready`||o)){s(!0),l(null);try{let r=aj().find(e=>_k(new URL(e.url,window.location.href).href)===n.url)??wk(n.manifest.name?.trim()||new URL(n.url).hostname,n.url,{repositoryUrl:n.manifest.repositoryUrl}),a=await Ej(r.id,{subscribe:!1});if(a!==`imported`&&a!==`current`)throw Error(`Seed import did not complete (${a}). Your existing content was kept.`);if(e){let e=cA(r.id,i),t=tA(r.id,!0);if(!e||!t)throw Error(`Content imported, but subscription preferences could not be saved. Browser storage is unavailable; these choices last this session only.`)}t(`${$.catalogs}?manage=1`,{replace:!0})}catch(e){l(e instanceof Error?e.message:`Seed import failed. Your existing content was kept.`)}finally{s(!1)}}};return(0,W.jsxs)(`main`,{className:`mx-auto flex min-h-dvh w-full max-w-2xl flex-col justify-center gap-5 p-6`,"data-testid":`catalog-subscription-intake`,children:[n.kind===`loading`&&(0,W.jsx)(`p`,{role:`status`,children:`Checking the seed manifest…`}),n.kind===`error`&&(0,W.jsx)(`p`,{role:`alert`,className:`break-words text-destructive`,children:n.message}),n.kind===`ready`&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`h1`,{className:`text-xl font-semibold`,children:[`Subscribe to `,n.manifest.name?.trim()||new URL(n.url).hostname,`?`]}),(0,W.jsx)(`a`,{href:n.url,target:`_blank`,rel:`noopener noreferrer`,className:`break-all text-sm underline`,children:n.url}),n.manifest.description&&(0,W.jsx)(`p`,{children:n.manifest.description}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Opening this link has not added any content or source. Choose whether to import once or subscribe for future update checks.`}),(0,W.jsxs)(`dl`,{className:`grid grid-cols-2 gap-2 text-sm`,children:[(0,W.jsx)(`dt`,{children:`Published version`}),(0,W.jsxs)(`dd`,{children:[`v`,n.manifest.version]}),(0,W.jsx)(`dt`,{children:`Published at`}),(0,W.jsx)(`dd`,{children:new Date(n.manifest.builtAt).toLocaleString()}),(0,W.jsx)(`dt`,{children:`Schema`}),(0,W.jsxs)(`dd`,{children:[`v`,n.manifest.schema]}),(0,W.jsx)(`dt`,{children:`Chunks`}),(0,W.jsx)(`dd`,{children:n.manifest.chunks.length}),(0,W.jsx)(`dt`,{children:`Catalog items`}),(0,W.jsx)(`dd`,{children:n.manifest.chunks.reduce((e,t)=>e+t.count,0)}),(0,W.jsx)(`dt`,{children:`Download size`}),(0,W.jsxs)(`dd`,{children:[(n.manifest.chunks.reduce((e,t)=>e+t.bytes,0)/1024).toFixed(1),` KB`]})]}),n.manifest.repositoryUrl&&(0,W.jsx)(`a`,{href:n.manifest.repositoryUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-sm underline`,children:`Git source directory`}),(0,W.jsxs)(`label`,{className:`flex items-start gap-3 rounded-lg border border-border p-4`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked),disabled:o,"aria-label":`Auto-sync this seed`,className:`mt-1 size-4 shrink-0`}),(0,W.jsxs)(`span`,{children:[(0,W.jsx)(`span`,{className:`font-medium`,children:`Auto-sync this seed`}),(0,W.jsx)(`span`,{className:`mt-1 block text-sm text-muted-foreground`,children:`When subscribed, apply new versions in the background on page load. Off keeps updates manual. Import Once ignores this preference and creates no subscription.`})]})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,W.jsx)(K,{variant:`outline`,disabled:o,onClick:()=>void u(!1),children:`Import Once`}),(0,W.jsx)(K,{disabled:o,onClick:()=>void u(!0),children:o?`Importing…`:`Import & Subscribe`})]})]}),c&&(0,W.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:c}),(0,W.jsx)(K,{variant:`ghost`,disabled:o,onClick:()=>t($.catalogs,{replace:!0}),children:`Decline & Dismiss`})]})}async function R9(e,t,n){let r=await Z.getNote(e);if(!r)return;let i=`:session{result:${n}}`;if(r.rawContent.includes(i))return;let a=Object.values(r.blocks??{}).find(e=>e.id===t);if(!a||a.to==null)return;let o=`${r.rawContent.slice(0,a.to)}\n\n\`\`\`query:table\n${i}\n\`\`\`${r.rawContent.slice(a.to)}`;await new YO().updateEntry(r.id,{rawContent:o,expectedSourceRevision:r.sourceRevision})}function z9(){let{runtimeId:e}=xn(),t=ht(),n=(0,U.useRef)(e?d$.get(e):void 0),r=(0,U.useRef)(null),i=(0,U.useCallback)(async()=>{let t=n.current;if(!t||!e)throw Error(`The pending workout is unavailable.`);return t.captured?(r.current=t.captured,t.captured.block):(r.current||=t.snapshot?await yL(t.snapshot,t.block,e,t.origin):await bL(t.noteId,t.block,e,t.origin),r.current.block)},[e]);(0,U.useEffect)(()=>{e&&d$.delete(e)},[e]);let a=n.current,o=(0,U.useRef)(!1),s=(0,U.useCallback)((t,n)=>!n||!e||!a?Promise.reject(Error(`Run cannot be saved — its session data or runtime id is missing.`)):(o.current=n.completed,$W.record({runBlock:a.block,blockId:a.block.id,noteId:a.noteId,resultId:e,data:n,createdAt:n.endTime||Date.now(),...a.origin?{origin:a.origin}:{}}).then(async()=>{if(n.completed)try{await R9(a.noteId,a.block.id,e)}catch{}})),[e,a]),c=(0,U.useCallback)(()=>{if(!a){t(`/`);return}if(o.current){t(JM(e),{replace:!0});return}if(a.returnTo){t(a.returnTo,{replace:!0});return}t(b$(eR(a.noteId)),{replace:!0})},[e,a,t]);return a?(0,W.jsx)(sX,{block:a.block,prepareRun:i,onClose:c,onCompleteWorkout:s,resultId:e,autoStart:!0}):(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-red-400`,children:`Runtime not found. Please start the workout from the editor.`})}var B9=null;async function V9(e){(!B9||B9.attempt!==e)&&(B9={attempt:e,promise:hK(G$.content)});try{return await B9.promise}finally{B9?.attempt===e&&(B9=null)}}function H9(){let e=ht(),[t,n]=(0,U.useState)(!1),[r,i]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await V9(r);t||e(RM(n),{replace:!0})}catch{t||n(!0)}})(),()=>{t=!0}},[e,r]),t?(0,W.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-3 text-zinc-300 px-4 text-center`,children:[(0,W.jsx)(`p`,{role:`alert`,children:`Unable to create a new playground note.`}),(0,W.jsx)(`button`,{type:`button`,className:`rounded border border-zinc-600 px-3 py-1 text-sm hover:bg-zinc-800`,onClick:()=>{n(!1),i(e=>e+1)},children:`Try again`})]}):(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function U9(){let e=ht(),t=Xt(),[n]=Gt(`zip`),[r]=Gt(`z`),[i]=Gt(`by`),[a]=Gt(`src`);(0,U.useEffect)(()=>{if(t.pathname!==`/load`&&!(t.pathname===`/`&&r))return;if(r){let t=!1;return(async()=>{try{let e=await j9(r);if(e===null)throw Error(`Invalid workout link`);if(t)return;let n=J$(e,i??void 0);if(await gK(n,{reuseKey:`home`,title:`Home playground`}),t)return;Z$({content:n,by:i??void 0})}catch(e){console.error(`Failed to decode zip:`,e),t||Q({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`})}t||e(`/`,{replace:!0})})(),()=>{t=!0}}if(!n)return;let o=!1,s=a&&a.startsWith(`/`)?a:void 0;return(async()=>{try{let t=await j9(n);if(t===null)throw Error(`Invalid workout link`);if(o)return;let r=s?await hK(t,{sourcePath:s}):await hK(t);o||e(RM(r),{replace:!0})}catch(t){console.error(`Failed to decode zip:`,t),o||(Q({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`}),e($.home,{replace:!0}))}})(),()=>{o=!0}},[n,r,i,a,e,t.pathname])}function W9(){let{pathname:e,hash:t}=Xt(),{scrollToSection:n}=lM();return(0,U.useEffect)(()=>{if(t){let e=t.slice(1);n(e);let r=setTimeout(()=>{n(e)},50);return()=>clearTimeout(r)}window.scrollTo(0,0)},[e,t]),null}function G9(){return U9(),M9(),(0,U.useEffect)(()=>{wO.current().catch(console.error),qD(),Q0(),HA().catch(()=>{})},[]),null}function K9({settling:e}){return e?(0,W.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Loading library…`}):(0,W.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:`The library's routed content failed to load.`}),(0,W.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:`The seed corpus is missing the root page. Re-running the seed import usually restores it.`}),(0,W.jsx)(K,{variant:`outline`,size:`sm`,"data-testid":`root-reseed`,onClick:()=>{Cj().then(()=>HD())},children:`Re-seed library`})]})}function q9(){let e=(0,U.useRef)(()=>{}),t=zI(),n=X0(),r=(0,U.useMemo)(()=>cI(()=>e.current(),t),[t]);return(0,W.jsx)(Ai,{defaultTheme:`system`,storageKey:`wod-wiki-playground-theme`,children:(0,W.jsx)(qv,{children:(0,W.jsx)(Pj,{children:(0,W.jsx)(Lj,{children:(0,W.jsx)(TA,{children:(0,W.jsx)(i,{children:(0,W.jsxs)(De,{children:[(0,W.jsx)(G9,{}),(0,W.jsx)(iM,{}),(0,W.jsxs)(dM,{tree:r,children:[(0,W.jsx)(W9,{}),(0,W.jsxs)(Pn,{children:[(0,W.jsx)(V,{path:`*`,element:t.some(({route:e})=>e===$.home)?(0,W.jsx)(M5,{}):(0,W.jsx)(K9,{settling:n===`preparing`})}),(0,W.jsx)(V,{path:`/proto/calc-authoring`,element:(0,W.jsx)(h7,{})}),(0,W.jsx)(V,{path:`/proto/query-block-composer`,element:(0,W.jsx)(M7,{})}),(0,W.jsx)(V,{path:`/settings`,element:(0,W.jsx)(Wn,{to:`/settings/appearance`,replace:!0})}),(0,W.jsx)(V,{path:`/settings/appearance`,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.settingsProfile,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.settingsData,element:(0,W.jsx)(Wn,{to:$.settingsStorage,replace:!0})}),(0,W.jsx)(V,{path:$.settingsDatabase,element:(0,W.jsx)(Wn,{to:$.settingsStorage,replace:!0})}),(0,W.jsx)(V,{path:$.settingsStorage,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.settingsSync,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:`/settings/system`,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.settingsQueries,element:(0,W.jsx)(Wn,{to:$.journal,replace:!0})}),(0,W.jsx)(V,{path:$.settingsTags,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.settingsSoundProfiles,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:`/settings/library/calcs`,element:(0,W.jsx)(`div`,{className:`p-6`,children:(0,W.jsx)(k9,{})})}),(0,W.jsx)(V,{path:`/legacy`,element:(0,W.jsx)(g5,{})}),(0,W.jsx)(V,{path:`/syntax`,element:(0,W.jsx)(j5,{})}),(0,W.jsx)(V,{path:`/chapters/basics`,element:(0,W.jsx)(Wn,{to:`/guide/start`,replace:!0})}),(0,W.jsx)(V,{path:`/chapters/sequences`,element:(0,W.jsx)(Wn,{to:`/guide/start`,replace:!0})}),(0,W.jsx)(V,{path:`/chapters/protocols`,element:(0,W.jsx)(Wn,{to:`/guide/protocols`,replace:!0})}),(0,W.jsx)(V,{path:`/challenge`,element:(0,W.jsx)(Wn,{to:`/`,replace:!0})}),(0,W.jsx)(V,{path:$.plan,element:(0,W.jsx)(n5,{})}),(0,W.jsx)(V,{path:$.feeds,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.feed,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.feedDetail,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.feedItem,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.catalogs,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.subscribe,element:(0,W.jsx)(L9,{})}),(0,W.jsx)(V,{path:$.collections,element:(0,W.jsx)(Y8,{})}),(0,W.jsx)(V,{path:`/collections/:slug`,element:(0,W.jsx)(J8,{})}),(0,W.jsx)(V,{path:`/collections/:slug/:target`,element:(0,W.jsx)(J8,{})}),(0,W.jsx)(V,{path:$.collection,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.collectionTarget,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.load,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(A9,{})})}),(0,W.jsx)(V,{path:$.loadJournal,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(I9,{})})}),(0,W.jsx)(V,{path:$.loadJournalDate,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(I9,{})})}),(0,W.jsx)(V,{path:$.playgroundRoot,element:(0,W.jsx)(H9,{})}),(0,W.jsx)(V,{path:$.playground,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.playgrounds,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.notePlaygroundAlias,element:(0,W.jsx)(K8,{})}),(0,W.jsx)(V,{path:$.note,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.journalNote,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.journalEntry,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.noteById,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.journal,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.pages,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.run,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(z9,{})})}),(0,W.jsx)(V,{path:$.tracker,element:(0,W.jsx)(e5,{})}),(0,W.jsx)(V,{path:`/results`,element:(0,W.jsx)(Z8,{})}),(0,W.jsx)(V,{path:`/results/segments`,element:(0,W.jsx)(Q8,{})}),(0,W.jsx)(V,{path:$.sessionDetail,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.sessions,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.sessionDate,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:`/review/:runtimeId`,element:(0,W.jsx)(t5,{})}),(0,W.jsx)(V,{path:`/note/:noteId/review`,element:(0,W.jsx)(t5,{})}),(0,W.jsx)(V,{path:`/note/:noteId/review/:sectionId`,element:(0,W.jsx)(t5,{})}),(0,W.jsx)(V,{path:`/note/:noteId/review/:sectionId/:resultId`,element:(0,W.jsx)(t5,{})}),(0,W.jsx)(V,{path:`/workout/:category/:name`,element:(0,W.jsx)(q8,{})}),(0,W.jsx)(V,{path:$.efforts,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.effort,element:(0,W.jsx)(X8,{})}),(0,W.jsx)(V,{path:$.effortSlug,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.equipment,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.tags,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.equipmentSlug,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.dashboard,element:(0,W.jsx)($8,{})}),(0,W.jsx)(V,{path:$.dashboards,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.dashboardView,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.dashboardSlug,element:(0,W.jsx)(W8,{searchHandlerRef:e})}),(0,W.jsx)(V,{path:$.analytics,element:(0,W.jsx)(Wn,{to:`/dashboards`,replace:!0})}),(0,W.jsx)(V,{path:$.analyticsExplorer,element:(0,W.jsx)(r5,{})}),t.map(({route:t})=>(0,W.jsx)(V,{path:t,element:(0,W.jsx)(W8,{searchHandlerRef:e})},t))]}),(0,W.jsx)(c5,{})]})]})})})})})})})}function J9({error:e,onRetry:t}){let n=e instanceof Error?e.message:String(e),r=mO();return(0,W.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-4 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:`The local database could not be opened.`}),(0,W.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground font-mono break-all`,"data-testid":`boot-recovery-error`,children:n}),(0,W.jsxs)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:[`Your stored data has not been cleared. Retry after resolving the error above.`,r.state!==`indexed-db`&&` Turn off Turso Sync to skip backup comparison. Settings → Storage has the full controls once the app loads.`]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:t,"data-testid":`boot-recovery-retry`,className:`rounded-md border border-border bg-card px-3 py-1.5 text-xs font-medium hover:bg-accent`,children:`Retry`}),r.state!==`indexed-db`&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>{bO(),window.location.reload()},"data-testid":`boot-recovery-local`,className:`rounded-md border border-border bg-card px-3 py-1.5 text-xs font-medium hover:bg-accent`,children:`Turn off Turso Sync`})]}),r.state!==`indexed-db`&&(0,W.jsxs)(`details`,{className:`w-full max-w-md rounded-xl border border-border bg-card p-4 text-left`,children:[(0,W.jsx)(`summary`,{className:`cursor-pointer text-xs font-medium`,children:`Fix Turso credentials`}),(0,W.jsx)(`div`,{className:`pt-3`,children:(0,W.jsx)(s8,{saved:r.state===`turso`?{url:r.url,authToken:r.authToken}:void 0})})]})]})}function Y9(){let e=(0,U.useSyncExternalStore)(Jb,qb),t=e.phase===`updating`;return(0,W.jsxs)(`div`,{role:`status`,"aria-live":`polite`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:t?`Updating local database…`:`Checking for storage updates…`}),t&&e.fromVersion!==null&&(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Schema v`,e.fromVersion,` → v`,e.toVersion]}),e.message&&(0,W.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:e.message})]})}var X9=(0,Oi.createRoot)(document.getElementById(`root`));function Z9(){let[e,t]=(0,U.useState)(!1),[n,r]=(0,U.useState)(null),[i,a]=(0,U.useState)(0),o=(0,U.useSyncExternalStore)(Jb,qb);return(0,U.useEffect)(()=>{let e=!1,n;return AO().then(()=>ik?lk():void 0).then(()=>{e||(n=PO(),t(!0))}).catch(t=>{e||r(t)}),()=>{e=!0,n?.()}},[i]),n?(0,W.jsx)(J9,{error:n,onRetry:()=>{r(null),a(e=>e+1)}}):o.phase===`checking`||o.phase===`updating`?(0,W.jsx)(Y9,{}):e?(0,W.jsx)(q9,{}):(0,W.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Loading…`})}X9.render((0,W.jsx)(U.StrictMode,{children:(0,W.jsx)(Z9,{})}));export{gV as t};
209
+ //# sourceMappingURL=main-DyocvczK.js.map